file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
// SPDX-License-Identifier: MIT
//** LFG MasterChef Contract */
//** Author Alex Hong : LFG Platform 2021.9 */
pragma solidity 0.6.6;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
// MasterChef is the master of LFG. He can make LFG and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once LFGs is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
contract LFGMasterChef is OwnableUpgradeable, ReentrancyGuardUpgradeable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
uint256 rewardLockedUp; // Reward locked up.
uint256 nextHarvestUntil; // When can the user harvest again.
//
// We do some fancy math here. Basically, any point in time, the amount of LFGs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accLFGPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accLFGPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. LFGs to distribute per block.
uint256 lastRewardBlock; // Last block number that LFGs distribution occurs.
uint256 accLFGPerShare; // Accumulated LFGs per share, times 1e12. See below.
uint16 depositFeeBP; // Deposit fee in basis points
uint256 harvestInterval; // Harvest interval in seconds
}
// The LFG TOKEN!
IERC20 public lfg;
// Deposit Fee address
address public feeAddress;
// Reward tokens holder address
address public rewardHolder;
// LFGs tokens created per block. 0.5 LFG per block. 10% to lfg charity ( address )
uint256 public lfgPerBlock;
// Bonus muliplier for early lfg makers.
uint256 public constant BONUS_MULTIPLIER = 1;
// Max harvest interval: 14 days.
uint256 public constant MAXIMUM_HARVEST_INTERVAL = 10 days;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
// The block number when LFGs mining starts.
uint256 public startBlock;
// Total locked up rewards
uint256 public totalLockedUpRewards;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event Compound(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
event EmissionRateUpdated(
address indexed caller,
uint256 previousAmount,
uint256 newAmount
);
event RewardLockedUp(
address indexed user,
uint256 indexed pid,
uint256 amountLockedUp
);
function initialize(
address _lfg,
address _feeAddress,
address _rewardHolder,
uint256 _startBlock,
uint256 _lfgPerBlock
) public initializer {
lfg = IERC20(_lfg);
rewardHolder = _rewardHolder;
startBlock = _startBlock;
lfgPerBlock = _lfgPerBlock;
feeAddress = _feeAddress;
totalAllocPoint = 0;
__Ownable_init();
__ReentrancyGuard_init();
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(
uint256 _allocPoint,
IERC20 _lpToken,
uint16 _depositFeeBP,
uint256 _harvestInterval,
bool _withUpdate
) public onlyOwner {
require(_depositFeeBP <= 500, "add: invalid deposit fee basis points");
require(
_harvestInterval <= MAXIMUM_HARVEST_INTERVAL,
"add: invalid harvest interval"
);
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock
? block.number
: startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accLFGPerShare: 0,
depositFeeBP: _depositFeeBP,
harvestInterval: _harvestInterval
})
);
}
// Update the given pool's LFGs allocation point and deposit fee. Can only be called by the owner.
function set(
uint256 _pid,
uint256 _allocPoint,
uint16 _depositFeeBP,
uint256 _harvestInterval,
bool _withUpdate
) public onlyOwner {
require(_depositFeeBP <= 500, "set: invalid deposit fee basis points");
require(
_harvestInterval <= MAXIMUM_HARVEST_INTERVAL,
"set: invalid harvest interval"
);
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
poolInfo[_pid].depositFeeBP = _depositFeeBP;
poolInfo[_pid].harvestInterval = _harvestInterval;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to)
public
pure
returns (uint256)
{
return _to.sub(_from).mul(BONUS_MULTIPLIER);
}
// View function to see pending LFGs on frontend.
function pendingLFG(uint256 _pid, address _user)
external
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accLFGPerShare = pool.accLFGPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(
pool.lastRewardBlock,
block.number
);
uint256 lfgReward = multiplier
.mul(lfgPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
accLFGPerShare = accLFGPerShare.add(
lfgReward.mul(1e12).div(lpSupply)
);
}
uint256 pending = user.amount.mul(accLFGPerShare).div(1e12).sub(
user.rewardDebt
);
return pending.add(user.rewardLockedUp);
}
// View function to see if user can harvest LFGs.
function canHarvest(uint256 _pid, address _user)
public
view
returns (bool)
{
UserInfo storage user = userInfo[_pid][_user];
return block.timestamp >= user.nextHarvestUntil;
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0 || pool.allocPoint == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 lfgReward = multiplier
.mul(lfgPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
pool.accLFGPerShare = pool.accLFGPerShare.add(
lfgReward.mul(1e12).div(lpSupply)
);
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for LFGs allocation.
function deposit(uint256 _pid, uint256 _amount) public nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
payOrLockupPendingLFG(_pid);
if (_amount > 0) {
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
if (pool.depositFeeBP > 0) {
uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000);
pool.lpToken.safeTransfer(feeAddress, depositFee);
user.amount = user.amount.add(_amount).sub(depositFee);
} else {
user.amount = user.amount.add(_amount);
}
}
user.rewardDebt = user.amount.mul(pool.accLFGPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
payOrLockupPendingLFG(_pid);
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accLFGPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
// Compound tokens to LFG pool.
function compound(uint256 _pid) public nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(
address(pool.lpToken) == address(lfg),
"compound: not able to compound"
);
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accLFGPerShare).div(1e12).sub(
user.rewardDebt
);
safeLFGTransferFrom(rewardHolder, address(this), pending);
user.amount = user.amount.add(pending);
user.rewardDebt = user.amount.mul(pool.accLFGPerShare).div(1e12);
emit Compound(msg.sender, _pid, pending);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
user.rewardLockedUp = 0;
user.nextHarvestUntil = 0;
pool.lpToken.safeTransfer(address(msg.sender), amount);
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
// Pay or lockup pending LFGs.
function payOrLockupPendingLFG(uint256 _pid) internal {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if (user.nextHarvestUntil == 0) {
user.nextHarvestUntil = block.timestamp.add(pool.harvestInterval);
}
uint256 pending = user.amount.mul(pool.accLFGPerShare).div(1e12).sub(
user.rewardDebt
);
if (canHarvest(_pid, msg.sender)) {
if (pending > 0 || user.rewardLockedUp > 0) {
uint256 totalRewards = pending.add(user.rewardLockedUp);
// reset lockup
totalLockedUpRewards = totalLockedUpRewards.sub(
user.rewardLockedUp
);
user.rewardLockedUp = 0;
user.nextHarvestUntil = block.timestamp.add(
pool.harvestInterval
);
// send rewards
safeLFGTransferFrom(rewardHolder, msg.sender, totalRewards);
}
} else if (pending > 0) {
user.rewardLockedUp = user.rewardLockedUp.add(pending);
totalLockedUpRewards = totalLockedUpRewards.add(pending);
emit RewardLockedUp(msg.sender, _pid, pending);
}
}
// Safe LFG transfer function, just in case if rounding error causes pool to not have enough LFGs.
function safeLFGTransferFrom(
address _from,
address _to,
uint256 _amount
) internal {
uint256 lfgBal = lfg.balanceOf(rewardHolder);
if (_amount > lfgBal) {
revert("Not enough balance");
} else {
lfg.transferFrom(_from, _to, _amount);
}
}
function setFeeAddress(address _feeAddress) public {
require(msg.sender == feeAddress, "setFeeAddress: FORBIDDEN");
require(_feeAddress != address(0), "setFeeAddress: ZERO");
feeAddress = _feeAddress;
}
function setRewardHolder(address _rewardHolder) public {
require(msg.sender == rewardHolder, "setRewardHolder: FORBIDDEN");
require(_rewardHolder != address(0), "setRewardHolder: ZERO");
rewardHolder = _rewardHolder;
}
// Pancake has to add hidden dummy pools in order to alter the emission, here we make it simple and transparent to all.
function updateEmissionRate(uint256 _lfgPerBlock) public onlyOwner {
massUpdatePools();
emit EmissionRateUpdated(msg.sender, lfgPerBlock, _lfgPerBlock);
lfgPerBlock = _lfgPerBlock;
}
}
| Safe LFG transfer function, just in case if rounding error causes pool to not have enough LFGs. | function safeLFGTransferFrom(
address _from,
address _to,
uint256 _amount
) internal {
uint256 lfgBal = lfg.balanceOf(rewardHolder);
if (_amount > lfgBal) {
revert("Not enough balance");
lfg.transferFrom(_from, _to, _amount);
}
}
| 14,084,399 |
// File: localhost/base/InitializableOwnable.sol
//SPDX-License-Identifier: SimPL-2.0
pragma solidity ^0.6.0;
contract InitializableOwnable {
address public _OWNER_;
address public _NEW_OWNER_;
bool internal _INITIALIZED_;
event OwnershipTransferPrepared(address indexed previousOwner, address indexed newOwner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
modifier notInitialized() {
require(!_INITIALIZED_, "INITIALIZED");
_;
}
modifier onlyOwner() {
require(msg.sender == _OWNER_, "NOT_OWNER");
_;
}
function initOwner(address newOwner) public notInitialized {
_INITIALIZED_ = true;
_OWNER_ = newOwner;
}
function transferOwnership(address newOwner) public onlyOwner {
emit OwnershipTransferPrepared(_OWNER_, newOwner);
_NEW_OWNER_ = newOwner;
}
function claimOwnership() public {
require(msg.sender == _NEW_OWNER_, "INVALID_CLAIM");
emit OwnershipTransferred(_OWNER_, _NEW_OWNER_);
_OWNER_ = _NEW_OWNER_;
_NEW_OWNER_ = address(0);
}
}
// File: localhost/token/createToken/ERC20FactoryV1.sol
//SPDX-License-Identifier: SimPL-2.0
pragma solidity ^0.6.0;
abstract contract ERC20FactoryV1 {
function getTokenByUser(address user) virtual external view returns (address[] memory tokens);
}
// File: localhost/interface/IYouSwapFactory.sol
//SPDX-License-Identifier: SimPL-2.0
pragma solidity ^0.6.0;
interface IYouSwapFactory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
function setFeeToRate(uint256) external;
function feeToRate() external view returns (uint256);
}
// File: localhost/token/createToken/MoonProxy.sol
//SPDX-License-Identifier: SimPL-2.0
pragma solidity ^0.6.0;
contract MoonProxy is InitializableOwnable {
using SafeMath for uint256;
IERC20 public TOKENMOON;
IERC20 public TOKENB;
bool private _pairCreated;
IYouSwapRouter public youSwapRouter;
address private _youSwapPair;
bool inSwapAndLiquify;
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
event SwapAndLiquify(
uint256 moonTokensSwapped,
uint256 tokenBReceived,
uint256 moonTokensIntoLiqudity
);
event LiquifySkipped(
uint256 tokenMoonAmount,
uint256 tokenBAmount
);
function youSwapPair() external view returns (address){
return _youSwapPair;
}
modifier onlyMoon() {
require(msg.sender == address(TOKENMOON), "ONLY_CALLABLE_FOR_MOON_CONTRACT");
_;
}
function createPairs(address creator, address router, address tokenMoon, address tokenB) external returns (address, address){
require(!_pairCreated, "PAIR_CREATED");
require(msg.sender == tokenMoon, "ONLY_CALLABLE_FOR_MOON_CONTRACT");
TOKENMOON = IERC20(tokenMoon);
TOKENB = IERC20(tokenB);
initOwner(creator);
youSwapRouter = IYouSwapRouter(router);
IYouSwapFactory factory = IYouSwapFactory(youSwapRouter.factory());
// Create YouSwap pairs for this new token
_youSwapPair = factory.createPair(tokenMoon, tokenB);
address ethPair = factory.createPair(tokenMoon, youSwapRouter.WETH());
_pairCreated = true;
return (_youSwapPair, ethPair);
}
function swapAndLiquify(uint256 contractTokenBalance) onlyMoon lockTheSwap external returns (bool) {
// split the contract balance into halves
uint256 half = contractTokenBalance.div(2);
uint256 otherHalf = contractTokenBalance.sub(half);
// capture the contract's current TOKENB balance.
// this is so that we can capture exactly the amount of TOKENB that the
// swap creates, and not make the liquidity event include any TOKENB that
// has been manually sent to the contract
uint256 initialBalance = TOKENB.balanceOf(address(this));
// swap tokens for TOKENB
swapTokensForTOKENB(half);
// how much TOKENB did we just swap into?
uint256 newBalance = TOKENB.balanceOf(address(this)).sub(initialBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
if (otherHalf == 0 || newBalance == 0) {
LiquifySkipped(otherHalf, newBalance);
}
else {
// add liquidity to YouSwap
addLiquidity(otherHalf, newBalance);
}
}
function swapTokensForTOKENB(uint256 tokenMoonAmount) private {
// generate the YouSwap pair path of TOKENMOON -> TOKENB
address[] memory path = new address[](2);
path[0] = address(TOKENMOON);
path[1] = address(TOKENB);
TOKENMOON.approve(address(youSwapRouter), tokenMoonAmount);
// make the swap
youSwapRouter.swapExactTokensForTokensSupportingFeeOnTransferTokens(
tokenMoonAmount,
0, // accept any amount of TOKENB
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenMoonAmount, uint256 tokenBAmount) private {
// approve token transfer to cover all possible scenarios
TOKENMOON.approve(address(youSwapRouter), tokenMoonAmount);
TOKENB.approve(address(youSwapRouter), tokenBAmount);
// add the liquidity
youSwapRouter.addLiquidity(
address(TOKENMOON),
address(TOKENB),
tokenMoonAmount,
tokenBAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
_OWNER_,
block.timestamp
);
}
}
// File: localhost/token/createToken/templates/MoonERC20Template.sol
//SPDX-License-Identifier: SimPL-2.0
pragma solidity ^0.6.0;
contract MoonERC20Template is InitializableOwnable {
using SafeMath for uint256;
using Address for address;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
mapping(address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal;
uint256 private _rTotal;
uint256 private _tFeeTotal;
string private _name;
string private _symbol;
uint8 private _decimals;
uint8 public _taxFee;
uint8 private _previousTaxFee = _taxFee;
uint8 public _liquidityFee;
uint8 private _previousLiquidityFee = _liquidityFee;
bool public swapAndLiquifyEnabled;
uint256 public _maxTxAmount;
uint256 private _numTokensSellToAddToLiquidity;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event Transfer(address indexed sender, address indexed recipient, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
event Mint(address indexed account, uint256 amount);
event Burn(address indexed account, uint256 amount);
bool public initialized;
MoonProxy public moonProxy;
IERC20 public YOU;
bool inSwapAndLiquify;
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
function init(
address creator,
address tokenYou,
address router,
uint256 initSupply,
string memory name,
string memory symbol,
uint8 decimals,
uint8 taxFee,
uint8 liquidityFee,
address cloneFactory,
address moonProxyTemplate
) public {
require(!initialized, "TOKEN_INITIALIZED");
require((taxFee + liquidityFee) < 100, "INVALID_FEE_RATE");
initOwner(creator);
YOU = IERC20(tokenYou);
_name = name;
_symbol = symbol;
_decimals = decimals;
_taxFee = taxFee;
_liquidityFee = liquidityFee;
_tTotal = initSupply * 10 ** uint256(decimals);
_rTotal = (MAX - (MAX % _tTotal));
_maxTxAmount = _tTotal.div(200);
_numTokensSellToAddToLiquidity = _maxTxAmount.div(10);
_rOwned[creator] = _rTotal;
emit Transfer(address(0), creator, _tTotal);
moonProxy = MoonProxy(ICloneFactory(cloneFactory).clone(moonProxyTemplate));
(address youPair,address ethPair) = moonProxy.createPairs(creator, router, address(this), address(YOU));
_isExcludedFromFee[youPair] = true;
_isExcludedFromFee[ethPair] = true;
//exclude owner and the proxy contract from fee
_isExcludedFromFee[creator] = true;
_isExcludedFromFee[address(moonProxy)] = true;
swapAndLiquifyEnabled = true;
initialized = true;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) public {
address sender = msg.sender;
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns (uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns (uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeFromReward(address account) public onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if (_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function setTaxFeePercent(uint8 taxFee) external onlyOwner {
require((_liquidityFee + taxFee) < 100, "INVALID_FEE_RATE");
_taxFee = taxFee;
}
function setNumTokensSellToAddToLiquidity(uint256 numTokensSellToAddToLiquidity) external onlyOwner {
_numTokensSellToAddToLiquidity = numTokensSellToAddToLiquidity;
}
function getNumTokensSellToAddToLiquidity() external view returns (uint256) {
return _numTokensSellToAddToLiquidity;
}
function setLiquidityFeePercent(uint8 liquidityFee) external onlyOwner() {
require((_taxFee + liquidityFee) < 100, "INVALID_FEE_RATE");
_liquidityFee = liquidityFee;
}
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() {
_maxTxAmount = _tTotal.mul(maxTxPercent).div(
10 ** 2
);
}
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity);
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) {
uint256 tFee = calculateTaxFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity);
return (tTransferAmount, tFee, tLiquidity);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(moonProxy)] = _rOwned[address(moonProxy)].add(rLiquidity);
if (_isExcluded[address(moonProxy)])
_tOwned[address(moonProxy)] = _tOwned[address(moonProxy)].add(tLiquidity);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(
10 ** 2
);
}
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_liquidityFee).div(
10 ** 2
);
}
function removeAllFee() private {
if (_taxFee == 0 && _liquidityFee == 0) return;
_previousTaxFee = _taxFee;
_previousLiquidityFee = _liquidityFee;
_taxFee = 0;
_liquidityFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_liquidityFee = _previousLiquidityFee;
}
function isExcludedFromFee(address account) public view returns (bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != _OWNER_ && to != _OWNER_)
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
// is the token balance of this contract address over the min number of
// tokens that we need to initiate a swap + liquidity lock?
// also, don't get caught in a circular liquidity event.
// also, don't swap & liquify if sender is YouSwap pair.
uint256 contractTokenBalance = balanceOf(address(moonProxy));
if (contractTokenBalance >= _maxTxAmount) {
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != moonProxy.youSwapPair() &&
swapAndLiquifyEnabled
) {
contractTokenBalance = _numTokensSellToAddToLiquidity;
//add liquidity
swapAndLiquify(contractTokenBalance);
}
//indicates if fee should be deducted from transfer
bool takeFee = true;
//if any account belongs to _isExcludedFromFee account then remove the fee
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
//transfer amount, it will take tax, burn, liquidity fee
_tokenTransfer(from, to, amount, takeFee);
}
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
moonProxy.swapAndLiquify(contractTokenBalance);
}
//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private {
if (!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if (!takeFee)
restoreAllFee();
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
}
// File: localhost/lib/Address.sol
//SPDX-License-Identifier: SimPL-2.0
pragma solidity ^0.6.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
function isNotZero(address account) internal pure returns (bool) {
return account != address(0);
}
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly {size := extcodesize(account)}
return size > 0;
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{value : amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value : weiValue}(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: localhost/token/createToken/templates/MintableERC20Template.sol
//SPDX-License-Identifier: SimPL-2.0
pragma solidity ^0.6.0;
contract MintableERC20Template is InitializableOwnable {
using SafeMath for uint256;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _totalSupply;
mapping(address => uint256) private _balanceOf;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => uint8) private _minters;
event Transfer(address indexed sender, address indexed recipient, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
bool public initialized;
function init(
address creator,
uint256 initSupply,
string memory name,
string memory symbol,
uint8 decimals
) public {
require(!initialized, "TOKEN_INITIALIZED");
initialized = true;
initOwner(creator);
_name = name;
_symbol = symbol;
_decimals = decimals;
_totalSupply = initSupply * 10 ** uint256(decimals);
_balanceOf[creator] = _totalSupply;
_minters[creator] = 1;
emit Transfer(address(0), creator, _totalSupply);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balanceOf[account];
}
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "DECREASED_ALLOWANCE_BELOW_ZERO"));
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "TRANSFER_FROM_THE_ZERO_ADDRESS");
require(recipient != address(0), "TRANSFER_TO_THE_ZERO_ADDRESS");
require(amount > 0, "TRANSFER_ZERO_AMOUNT");
_balanceOf[sender] = _balanceOf[sender].sub(amount, "TRANSFER_AMOUNT_EXCEEDS_BALANCE");
_balanceOf[recipient] = _balanceOf[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _burn(address account, uint256 amount) internal {
require(account != address(0), "BURN_FROM_THE_ZERO_ADDRESS");
require(_balanceOf[account] > 0, "INSUFFICIENT_FUNDS");
_balanceOf[account] = _balanceOf[account].sub(amount, "BURN_AMOUNT_EXCEEDS_BALANCE");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "APPROVE_FROM_THE_ZERO_ADDRESS");
require(spender != address(0), "APPROVE_TO_THE_ZERO_ADDRESS");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function burn(uint256 amount) external {
_burn(msg.sender, amount);
}
function burnFrom(address account, uint256 amount) external {
uint256 newAllowance = allowance(account, msg.sender).sub(amount, "BURN_AMOUNT_EXCEEDS_ALLOWANCE");
_approve(account, msg.sender, newAllowance);
_burn(account, amount);
}
modifier isMinter() {
require(_minters[msg.sender] == 1, "IS_NOT_A_MINTER");
_;
}
function mint(address recipient, uint256 amount) external isMinter {
_totalSupply = _totalSupply.add(amount);
_balanceOf[recipient] = _balanceOf[recipient].add(amount);
emit Transfer(address(0), recipient, amount);
}
function addMinter(address account) external onlyOwner {
require(Address.isNotZero(account), "ZERO_ADDRESS");
_minters[account] = 1;
}
function removeMinter(address account) external onlyOwner {
_minters[account] = 0;
}
}
// File: localhost/lib/SafeMath.sol
//SPDX-License-Identifier: SimPL-2.0
pragma solidity ^0.6.0;
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;
}
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = x / 2 + 1;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
// File: localhost/token/createToken/templates/ERC20Template.sol
//SPDX-License-Identifier: SimPL-2.0
pragma solidity ^0.6.0;
contract ERC20Template {
using SafeMath for uint256;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _totalSupply;
mapping(address => uint256) private _balanceOf;
mapping(address => mapping(address => uint256)) private _allowances;
event Transfer(address indexed sender, address indexed recipient, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
bool public initialized;
function init(
address creator,
uint256 initSupply,
string calldata name,
string calldata symbol,
uint8 decimals
) external {
require(!initialized, "TOKEN_INITIALIZED");
_name = name;
_symbol = symbol;
_decimals = decimals;
_totalSupply = initSupply * 10 ** uint256(decimals);
_balanceOf[creator] = _totalSupply;
initialized = true;
emit Transfer(address(0), creator, _totalSupply);
}
function name() external view returns (string memory) {
return _name;
}
function symbol() external view returns (string memory) {
return _symbol;
}
function decimals() external view returns (uint8) {
return _decimals;
}
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) external view returns (uint256) {
return _balanceOf[account];
}
function transfer(address recipient, uint256 amount) external returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender) external view returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) external returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool) {
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE"));
_transfer(sender, recipient, amount);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) external returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "DECREASED_ALLOWANCE_BELOW_ZERO"));
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "TRANSFER_FROM_THE_ZERO_ADDRESS");
require(recipient != address(0), "TRANSFER_TO_THE_ZERO_ADDRESS");
require(amount > 0, "TRANSFER_ZERO_AMOUNT");
_balanceOf[sender] = _balanceOf[sender].sub(amount, "TRANSFER_AMOUNT_EXCEEDS_BALANCE");
_balanceOf[recipient] = _balanceOf[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "APPROVE_FROM_THE_ZERO_ADDRESS");
require(spender != address(0), "APPROVE_TO_THE_ZERO_ADDRESS");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
// File: localhost/interface/ICloneFactory.sol
//SPDX-License-Identifier: SimPL-2.0
pragma solidity ^0.6.0;
interface ICloneFactory {
function clone(address prototype) external returns (address proxy);
}
// File: localhost/interface/IERC20.sol
//SPDX-License-Identifier: SimPL-2.0
pragma solidity ^0.6.0;
interface IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
/**
* @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 `amount` tokens are moved from one account (`sender`) to
* another (`recipient`).
*
* Note that `amount` may be zero.
*/
event Transfer(address indexed sender, address indexed recipient, uint256 amount);
/**
* @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);
}
// File: localhost/interface/IYouSwapRouter.sol
//SPDX-License-Identifier: SimPL-2.0
pragma solidity ^0.6.0;
interface IYouSwapRouter {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function swapMining() 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);
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// File: localhost/base/Context.sol
//SPDX-License-Identifier: SimPL-2.0
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 { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: localhost/base/Ownable.sol
//SPDX-License-Identifier: SimPL-2.0
pragma solidity ^0.6.0;
contract Ownable is Context{
address internal _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), msg.sender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "CALLER_IS_NOT_THE_OWNER");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0), "NEW_OWNER_IS_THE_ZERO_ADDRESS");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: localhost/token/createToken/ERC20FactoryV2.sol
//SPDX-License-Identifier: SimPL-2.0
pragma solidity ^0.6.0;
interface IERC20USDT {
function decimals() external view returns (uint8);
function balanceOf(address account) external view returns (uint);
function approve(address spender, uint amount) external returns (bool);
function transferFrom(address sender, address recipient, uint amount) external returns (bool);
}
contract ERC20FactoryV2 is Ownable {
address public _CLONE_FACTORY_;
address public _ERC20_TEMPLATE_;
address public _MINTABLE_ERC20_TEMPLATE_;
address public _MOON_ERC20_TEMPLATE_;
address public _MOON_PROXY_TEMPLATE_;
uint256 public usdtFeeForStd;
uint256 public youFeeForStd;
uint256 public usdtFeeForMintable;
uint256 public youFeeForMintable;
uint256 public usdtFeeForMoon;
uint256 public youFeeForMoon;
mapping(address => bool) private _isExcludedFromFee;
event NewERC20(address tokenAddress, address creator, bool isMintable, uint8 tokenType);
IYouSwapRouter public youSwapRouter;
IERC20 public YOU;
IERC20USDT public USDT;
// ============ Registry ============
// creator -> token address list
mapping(address => address[]) public _USER_REGISTRY_;
// creator -> token type list
mapping(address => uint8[]) public _USER_REGISTRY_TYPE_;
constructor(
address cloneFactory,
address erc20Template,
address mintableErc20Template,
address moonErc20Template,
address moonProxyTemplate
) public {
_CLONE_FACTORY_ = cloneFactory;
_ERC20_TEMPLATE_ = erc20Template;
_MINTABLE_ERC20_TEMPLATE_ = mintableErc20Template;
_MOON_ERC20_TEMPLATE_ = moonErc20Template;
_MOON_PROXY_TEMPLATE_ = moonProxyTemplate;
youSwapRouter = IYouSwapRouter(0xf80Ddd58E040dF41C0761566295a8c1b75B30770);
YOU = IERC20(0x1d32916CFA6534D261AD53E2498AB95505bd2510);
USDT = IERC20USDT(0xdAC17F958D2ee523a2206206994597C13D831ec7);
usdtFeeForStd = 40 * 10 ** uint256(USDT.decimals());
//40USDT as default
youFeeForStd = 40 * 10 ** uint256(YOU.decimals());
//40YOU as default
usdtFeeForMintable = 200 * 10 ** uint256(USDT.decimals());
//200USDT as default
youFeeForMintable = 200 * 10 ** uint256(YOU.decimals());
//200YOU as default
usdtFeeForMoon = 500 * 10 ** uint256(USDT.decimals());
//500USDT as default
youFeeForMoon = 500 * 10 ** uint256(YOU.decimals());
//500YOU as default
}
function createStdERC20(
uint256 totalSupply,
string calldata name,
string calldata symbol,
uint8 decimals,
uint8 feeTokenType //YOU:1 USDT:2
) external returns (address newERC20) {
takeFeeForStd(feeTokenType);
newERC20 = ICloneFactory(_CLONE_FACTORY_).clone(_ERC20_TEMPLATE_);
ERC20Template(newERC20).init(msg.sender, totalSupply, name, symbol, decimals);
_USER_REGISTRY_[msg.sender].push(newERC20);
_USER_REGISTRY_TYPE_[msg.sender].push(1);
emit NewERC20(newERC20, msg.sender, false, 1);
}
function createMintableERC20(
uint256 initSupply,
string calldata name,
string calldata symbol,
uint8 decimals,
uint8 feeTokenType //YOU:1 USDT:2
) external returns (address newMintableERC20) {
takeFeeForMintable(feeTokenType);
newMintableERC20 = ICloneFactory(_CLONE_FACTORY_).clone(_MINTABLE_ERC20_TEMPLATE_);
MintableERC20Template(newMintableERC20).init(
msg.sender,
initSupply,
name,
symbol,
decimals
);
_USER_REGISTRY_[msg.sender].push(newMintableERC20);
_USER_REGISTRY_TYPE_[msg.sender].push(2);
emit NewERC20(newMintableERC20, msg.sender, true, 2);
}
function createMoonERC20(
uint256 initSupply,
string calldata name,
string calldata symbol,
uint8 decimals,
uint8 taxFee,
uint8 liquidityFee,
uint8 feeTokenType //YOU:1 USDT:2
) external returns (address newMoonERC20) {
takeFeeForMoon(feeTokenType);
newMoonERC20 = ICloneFactory(_CLONE_FACTORY_).clone(_MOON_ERC20_TEMPLATE_);
MoonERC20Template(newMoonERC20).init(
msg.sender,
address(YOU),
address(youSwapRouter),
initSupply,
name,
symbol,
decimals,
taxFee,
liquidityFee,
_CLONE_FACTORY_,
_MOON_PROXY_TEMPLATE_
);
_USER_REGISTRY_[msg.sender].push(newMoonERC20);
_USER_REGISTRY_TYPE_[msg.sender].push(3);
emit NewERC20(newMoonERC20, msg.sender, false, 3);
}
function getTokenByUser(address user) external view returns (address[] memory tokens, uint8[] memory tokenTypes){
return (_USER_REGISTRY_[user], _USER_REGISTRY_TYPE_[user]);
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function takeFeeForStd(uint8 feeTokenType) private {
if (_isExcludedFromFee[msg.sender]) return;
if (feeTokenType == 1) {//YOU
YOU.transferFrom(msg.sender, address(this), youFeeForStd);
}
else {//USDT
takeUsdtFee(usdtFeeForStd);
}
}
function takeFeeForMintable(uint8 feeTokenType) private {
if (_isExcludedFromFee[msg.sender]) return;
if (feeTokenType == 1) {//YOU
YOU.transferFrom(msg.sender, address(this), youFeeForMintable);
}
else {//USDT
takeUsdtFee(usdtFeeForMintable);
}
}
function takeFeeForMoon(uint8 feeTokenType) private {
if (_isExcludedFromFee[msg.sender]) return;
if (feeTokenType == 1) {//YOU
YOU.transferFrom(msg.sender, address(this), youFeeForMoon);
}
else {//USDT
takeUsdtFee(usdtFeeForMoon);
}
}
function takeUsdtFee(uint256 feeAmount) private {
USDT.transferFrom(msg.sender, address(this), feeAmount);
uint256 balanceOfU = USDT.balanceOf(address(this));
if (balanceOfU >= feeAmount) {
swapUSDTForYOU(balanceOfU);
}
}
function swapUSDTForYOU(uint256 usdtAmount) private {
// generate the youswap pair path of USDT -> YOU
address[] memory path = new address[](2);
path[0] = address(USDT);
path[1] = address(YOU);
USDT.approve(address(youSwapRouter), usdtAmount);
youSwapRouter.swapExactTokensForTokens(
usdtAmount,
0, // accept any amount of YOU
path,
address(this),
block.timestamp
);
}
function setUsdtFeeForStd(uint256 newFee) external onlyOwner {
usdtFeeForStd = newFee;
}
function setYouFeeForStd(uint256 newFee) external onlyOwner {
youFeeForStd = newFee;
}
function setUsdtFeeForMintable(uint256 newFee) external onlyOwner {
usdtFeeForMintable = newFee;
}
function setYouFeeForMintable(uint256 newFee) external onlyOwner {
youFeeForMintable = newFee;
}
function setUsdtFeeForMoon(uint256 newFee) external onlyOwner {
usdtFeeForMoon = newFee;
}
function setYouFeeForMoon(uint256 newFee) external onlyOwner {
youFeeForMoon = newFee;
}
function withdraw(address token, address recipient, uint256 amount) onlyOwner external {
IERC20(token).transfer(recipient, amount);
}
} | this method is responsible for taking all fee, if takeFee is true | function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private {
if (!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
_transferToExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
_transferBothExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
}
if (!takeFee)
restoreAllFee();
}
| 184,166 |
./full_match/5/0x18C68B3adacE08C934408c343BC50a7EDe3F4aD7/sources/project_/contracts/EchoooERC721.sol | Required interface of an ERC721 compliant contract./ | interface IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId, string txType);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function balanceOf(address owner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data, string calldata txType) external;
function safeTransferFrom(address from, address to, uint256 tokenId,string calldata txType) external;
function transferFrom(address from, address to, uint256 tokenId, string calldata txType) external;
function approve(address to, uint256 tokenId) external;
function setApprovalForAll(address operator, bool approved) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
| 1,859,613 |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol";
import "@openzeppelin/contracts/utils/Address.sol";
/* This contract is a variation on ERC1155 with the additions of _setData, getData and _canTransfer and ownerOf. _setData and getData allows the use of the other 96 bits next to the address of the owner for extra data. We use this to store 'fuses' that control permissions that can be burnt. */
error OperationProhibited(bytes32 node);
abstract contract ERC1155Fuse is ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
mapping(uint256 => uint256) public _tokens;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**************************************************************************
* ERC721 methods
*************************************************************************/
function ownerOf(uint256 id) public view returns (address) {
(address owner, ) = getData(id);
return owner;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id)
public
view
virtual
override
returns (uint256)
{
require(
account != address(0),
"ERC1155: balance query for the zero address"
);
(address owner, ) = getData(id);
if (owner == account) {
return 1;
}
return 0;
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(
accounts.length == ids.length,
"ERC1155: accounts and ids length mismatch"
);
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
virtual
override
{
require(
msg.sender != operator,
"ERC1155: setting approval status for self"
);
_operatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[account][operator];
}
/**
* @dev Returns the Name's owner address and fuses
*/
function getData(uint256 tokenId)
public
view
returns (address owner, uint96 fuses)
{
uint256 t = _tokens[tokenId];
owner = address(uint160(t));
fuses = uint96(t >> 160);
}
/**
* @dev Sets the Name's owner address and fuses
*/
function _setData(
uint256 tokenId,
address owner,
uint96 fuses
) internal virtual {
_tokens[tokenId] = uint256(uint160(owner)) | (uint256(fuses) << 160);
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == msg.sender || isApprovedForAll(from, msg.sender),
"ERC1155: caller is not owner nor approved"
);
(address oldOwner, uint96 fuses) = getData(id);
if (!_canTransfer(fuses)) {
revert OperationProhibited(bytes32(id));
}
require(
amount == 1 && oldOwner == from,
"ERC1155: insufficient balance for transfer"
);
_setData(id, to, fuses);
emit TransferSingle(msg.sender, from, to, id, amount);
_doSafeTransferAcceptanceCheck(msg.sender, from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
ids.length == amounts.length,
"ERC1155: ids and amounts length mismatch"
);
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == msg.sender || isApprovedForAll(from, msg.sender),
"ERC1155: transfer caller is not owner nor approved"
);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
(address oldOwner, uint96 fuses) = getData(id);
if (!_canTransfer(fuses)) {
revert OperationProhibited(bytes32(id));
}
require(
amount == 1 && oldOwner == from,
"ERC1155: insufficient balance for transfer"
);
_setData(id, to, fuses);
}
emit TransferBatch(msg.sender, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(
msg.sender,
from,
to,
ids,
amounts,
data
);
}
/**************************************************************************
* Internal/private methods
*************************************************************************/
function _canTransfer(uint96 fuses) internal virtual returns (bool);
function _mint(
bytes32 node,
address newOwner,
uint96 _fuses
) internal virtual {
uint256 tokenId = uint256(node);
address owner = ownerOf(tokenId);
require(owner == address(0), "ERC1155: mint of existing token");
require(newOwner != address(0), "ERC1155: mint to the zero address");
require(
newOwner != address(this),
"ERC1155: newOwner cannot be the NameWrapper contract"
);
_setData(tokenId, newOwner, _fuses);
emit TransferSingle(msg.sender, address(0x0), newOwner, tokenId, 1);
_doSafeTransferAcceptanceCheck(
msg.sender,
address(0),
newOwner,
tokenId,
1,
""
);
}
function _burn(uint256 tokenId) internal virtual {
address owner = ownerOf(tokenId);
// Clear fuses and set owner to 0
_setData(tokenId, address(0x0), 0);
emit TransferSingle(msg.sender, owner, address(0x0), tokenId, 1);
}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try
IERC1155Receiver(to).onERC1155Received(
operator,
from,
id,
amount,
data
)
returns (bytes4 response) {
if (
response != IERC1155Receiver(to).onERC1155Received.selector
) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try
IERC1155Receiver(to).onERC1155BatchReceived(
operator,
from,
ids,
amounts,
data
)
returns (bytes4 response) {
if (
response !=
IERC1155Receiver(to).onERC1155BatchReceived.selector
) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
}
| See {IERC1155-safeTransferFrom}./ | function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == msg.sender || isApprovedForAll(from, msg.sender),
"ERC1155: caller is not owner nor approved"
);
(address oldOwner, uint96 fuses) = getData(id);
if (!_canTransfer(fuses)) {
revert OperationProhibited(bytes32(id));
}
require(
amount == 1 && oldOwner == from,
"ERC1155: insufficient balance for transfer"
);
_setData(id, to, fuses);
emit TransferSingle(msg.sender, from, to, id, amount);
_doSafeTransferAcceptanceCheck(msg.sender, from, to, id, amount, data);
}
| 6,390,016 |
/**
*Submitted for verification at Etherscan.io on 2022-02-02
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
// (c) by Mario, Santa Cruz - España.
interface ERC721
{
/**
* @dev Emits when ownership of any NFT changes by any mechanism. This event emits when NFTs are
* created (`from` == 0) and destroyed (`to` == 0). Exception: during contract creation, any
* number of NFTs may be created and assigned without emitting Transfer. At the time of any
* transfer, the approved address for that NFT (if any) is reset to none.
*/
event Transfer(
address indexed _from,
address indexed _to,
uint256 indexed _tokenId
);
/**
* @dev This emits when the approved address for an NFT is changed or reaffirmed. The zero
* address indicates there is no approved address. When a Transfer event emits, this also
* indicates that the approved address for that NFT (if any) is reset to none.
*/
event Approval(
address indexed _owner,
address indexed _approved,
uint256 indexed _tokenId
);
/**
* @dev This emits when an operator is enabled or disabled for an owner. The operator can manage
* all NFTs of the owner.
*/
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
/**
* @dev Transfers the ownership of an NFT from one address to another address.
* @notice Throws unless `msg.sender` is the current owner, an authorized operator, or the
* approved address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is
* the zero address. Throws if `_tokenId` is not a valid NFT. When transfer is complete, this
* function checks if `_to` is a smart contract (code size > 0). If so, it calls
* `onERC721Received` on `_to` and throws if the return value is not
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
* @param _data Additional data with no specified format, sent in call to `_to`.
*/
/* slim
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes calldata _data
)
external;
*/
/**
* @dev Transfers the ownership of an NFT from one address to another address.
* @notice This works identically to the other function with an extra data parameter, except this
* function just sets data to ""
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
external;
/**
* @dev Throws unless `msg.sender` is the current owner, an authorized operator, or the approved
* address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is the zero
* address. Throws if `_tokenId` is not a valid NFT.
* @notice The caller is responsible to confirm that `_to` is capable of receiving NFTs or else
* they may be permanently lost.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
*/
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external;
/**
* @dev Set or reaffirm the approved address for an NFT.
* @notice The zero address indicates there is no approved address. Throws unless `msg.sender` is
* the current NFT owner, or an authorized operator of the current owner.
* @param _approved The new approved NFT controller.
* @param _tokenId The NFT to approve.
*/
function approve(
address _approved,
uint256 _tokenId
)
external;
/**
* @dev Enables or disables approval for a third party ("operator") to manage all of
* `msg.sender`'s assets. It also emits the ApprovalForAll event.
* @notice The contract MUST allow multiple operators per owner.
* @param _operator Address to add to the set of authorized operators.
* @param _approved True if the operators is approved, false to revoke approval.
*/
function setApprovalForAll(
address _operator,
bool _approved
)
external;
/**
* @dev Returns the number of NFTs owned by `_owner`. NFTs assigned to the zero address are
* considered invalid, and this function throws for queries about the zero address.
* @param _owner Address for whom to query the balance.
* @return Balance of _owner.
*/
/*
function balanceOf(
address _owner
)
external
view
returns (uint256);
*/
/**
* @dev Returns the address of the owner of the NFT. NFTs assigned to the zero address are
* considered invalid, and queries about them do throw.
* @param _tokenId The identifier for an NFT.
* @return Address of _tokenId owner.
*/
function ownerOf(
uint256 _tokenId
)
external
view
returns (address);
/**
* @dev Get the approved address for a single NFT.
* @notice Throws if `_tokenId` is not a valid NFT.
* @param _tokenId The NFT to find the approved address for.
* @return Address that _tokenId is approved for.
*/
function getApproved(
uint256 _tokenId
)
external
view
returns (address);
/**
* @dev Returns true if `_operator` is an approved operator for `_owner`, false otherwise.
* @param _owner The address that owns the NFTs.
* @param _operator The address that acts on behalf of the owner.
* @return True if approved for all, false otherwise.
*/
function isApprovedForAll(
address _owner,
address _operator
)
external
view
returns (bool);
}
interface ERC721TokenReceiver
{
/**
* @dev Handle the receipt of a NFT. The ERC721 smart contract calls this function on the
* recipient after a `transfer`. This function MAY throw to revert and reject the transfer. Return
* of other than the magic value MUST result in the transaction being reverted.
* Returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` unless throwing.
* @notice The contract address is always the message sender. A wallet/broker/auction application
* MUST implement the wallet interface if it will accept safe transfers.
* @param _operator The address which called `safeTransferFrom` function.
* @param _from The address which previously owned the token.
* @param _tokenId The NFT identifier which is being transferred.
* @param _data Additional data with no specified format.
* @return Returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes calldata _data
)
external
returns(bytes4);
}interface ERC165
{
/**
* @dev Checks if the smart contract includes a specific interface.
* This function uses less than 30,000 gas.
* @param _interfaceID The interface identifier, as specified in ERC-165.
* @return True if _interfaceID is supported, false otherwise.
*/
function supportsInterface(
bytes4 _interfaceID
)
external
view
returns (bool);
}
contract SupportsInterface is
ERC165
{
/**
* @dev Mapping of supported intefraces. You must not set element 0xffffffff to true.
*/
mapping(bytes4 => bool) internal supportedInterfaces;
/**
* @dev Contract constructor.
*/
constructor()
{
supportedInterfaces[0x01ffc9a7] = true; // ERC165
}
/**
* @dev Function to check which interfaces are suported by this contract.
* @param _interfaceID Id of the interface.
* @return True if _interfaceID is supported, false otherwise.
*/
function supportsInterface(
bytes4 _interfaceID
)
external
override
view
returns (bool)
{
return supportedInterfaces[_interfaceID];
}
}
library AddressUtils
{
/**
* @dev Returns whether the target address is a contract.
* @param _addr Address to check.
* @return addressCheck True if _addr is a contract, false if not.
*/
function isContract(
address _addr
)
internal
view
returns (bool addressCheck)
{
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// 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;
assembly { codehash := extcodehash(_addr) } // solhint-disable-line
addressCheck = (codehash != 0x0 && codehash != accountHash);
}
}
interface ERC721Metadata
{
/**
* @dev Returns a descriptive name for a collection of NFTs in this contract.
* @return _name Representing name.
*/
function name()
external
view
returns (string memory _name);
/**
* @dev Returns a abbreviated name for a collection of NFTs in this contract.
* @return _symbol Representing symbol.
*/
function symbol()
external
view
returns (string memory _symbol);
/**
* @dev Returns a distinct Uniform Resource Identifier (URI) for a given asset. It Throws if
* `_tokenId` is not a valid NFT. URIs are defined in RFC3986. The URI may point to a JSON file
* that conforms to the "ERC721 Metadata JSON Schema".
* @return URI of _tokenId.
*/
function tokenURI(uint256 _tokenId)
external
view
returns (string memory);
}
contract NFToken is
ERC721,
SupportsInterface
{
using AddressUtils for address;
/**
* @dev List of revert message codes. Implementing dApp should handle showing the correct message.
* Based on 0xcert framework error codes.
*/
string constant ZERO_ADDRESS = "003001";
string constant NOT_VALID_NFT = "003002";
string constant NOT_OWNER_OR_OPERATOR = "003003";
string constant NOT_OWNER_APPROVED_OR_OPERATOR = "003004";
string constant NOT_ABLE_TO_RECEIVE_NFT = "003005";
string constant NFT_ALREADY_EXISTS = "003006";
string constant NOT_OWNER = "003007";
string constant IS_OWNER = "003008";
/**
* @dev Magic value of a smart contract that can receive NFT.
* Equal to: bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")).
*/
bytes4 internal constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02;
/**
* @dev A mapping from NFT ID to the address that owns it.
*/
mapping (uint256 => address) internal idToOwner;
/**
* @dev Mapping from NFT ID to approved address.
*/
mapping (uint256 => address) internal idToApproval;
/**
* @dev Mapping from owner address to count of his tokens.
*/
//mapping (address => uint256) private ownerToNFTokenCount;
/**
* @dev Mapping from owner address to mapping of operator addresses.
*/
mapping (address => mapping (address => bool)) internal ownerToOperators;
/**
* @dev Guarantees that the msg.sender is an owner or operator of the given NFT.
* @param _tokenId ID of the NFT to validate.
*/
modifier canOperate(
uint256 _tokenId
)
{
address tokenOwner = idToOwner[_tokenId];
require(
tokenOwner == msg.sender || ownerToOperators[tokenOwner][msg.sender],
NOT_OWNER_OR_OPERATOR
);
_;
}
/**
* @dev Guarantees that the msg.sender is allowed to transfer NFT.
* @param _tokenId ID of the NFT to transfer.
*/
modifier canTransfer(
uint256 _tokenId
)
{
address tokenOwner = idToOwner[_tokenId];
require(
tokenOwner == msg.sender
|| idToApproval[_tokenId] == msg.sender
|| ownerToOperators[tokenOwner][msg.sender],
NOT_OWNER_APPROVED_OR_OPERATOR
);
_;
}
/**
* @dev Guarantees that _tokenId is a valid Token.
* @param _tokenId ID of the NFT to validate.
*/
modifier validNFToken(
uint256 _tokenId
)
{
require(idToOwner[_tokenId] != address(0), NOT_VALID_NFT);
_;
}
/**
* @dev Contract constructor.
*/
constructor()
{
supportedInterfaces[0x80ac58cd] = true; // ERC721
//owner = msg.sender;
}
/**
* @dev Transfers the ownership of an NFT from one address to another address. This function can
* be changed to payable.
* @notice Throws unless `msg.sender` is the current owner, an authorized operator, or the
* approved address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is
* the zero address. Throws if `_tokenId` is not a valid NFT. When transfer is complete, this
* function checks if `_to` is a smart contract (code size > 0). If so, it calls
* `onERC721Received` on `_to` and throws if the return value is not
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
* @param _data Additional data with no specified format, sent in call to `_to`.
*/
/*
slim
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes calldata _data
)
external
override
{
_safeTransferFrom(_from, _to, _tokenId, _data);
}
*/
/**
* @dev Transfers the ownership of an NFT from one address to another address. This function can
* be changed to payable.
* @notice This works identically to the other function with an extra data parameter, except this
* function just sets data to ""
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
override
{
_safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Throws unless `msg.sender` is the current owner, an authorized operator, or the approved
* address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is the zero
* address. Throws if `_tokenId` is not a valid NFT. This function can be changed to payable.
* @notice The caller is responsible to confirm that `_to` is capable of receiving NFTs or else
* they may be permanently lost.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
*/
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
override
canTransfer(_tokenId)
validNFToken(_tokenId)
{
address tokenOwner = idToOwner[_tokenId];
require(tokenOwner == _from, NOT_OWNER);
require(_to != address(0), ZERO_ADDRESS);
_transfer(_to, _tokenId);
}
/**
* @dev Set or reaffirm the approved address for an NFT. This function can be changed to payable.
* @notice The zero address indicates there is no approved address. Throws unless `msg.sender` is
* the current NFT owner, or an authorized operator of the current owner.
* @param _approved Address to be approved for the given NFT ID.
* @param _tokenId ID of the token to be approved.
*/
function approve(
address _approved,
uint256 _tokenId
)
external
override
canOperate(_tokenId)
validNFToken(_tokenId)
{
address tokenOwner = idToOwner[_tokenId];
require(_approved != tokenOwner, IS_OWNER);
idToApproval[_tokenId] = _approved;
emit Approval(tokenOwner, _approved, _tokenId);
}
/**
* @dev Enables or disables approval for a third party ("operator") to manage all of
* `msg.sender`'s assets. It also emits the ApprovalForAll event.
* @notice This works even if sender doesn't own any tokens at the time.
* @param _operator Address to add to the set of authorized operators.
* @param _approved True if the operators is approved, false to revoke approval.
*/
function setApprovalForAll(
address _operator,
bool _approved
)
external
override
{
ownerToOperators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @dev Returns the number of NFTs owned by `_owner`. NFTs assigned to the zero address are
* considered invalid, and this function throws for queries about the zero address.
* @param _owner Address for whom to query the balance.
* @return Balance of _owner.
*/
/* slim
function balanceOf(
address _owner
)
external
override
view
returns (uint256)
{
require(_owner != address(0), ZERO_ADDRESS);
return _getOwnerNFTCount(_owner);
}
*/
/**
* @dev Returns the address of the owner of the NFT. NFTs assigned to the zero address are
* considered invalid, and queries about them do throw.
* @param _tokenId The identifier for an NFT.
* @return _owner Address of _tokenId owner.
*/
function ownerOf(
uint256 _tokenId
)
external
override
view
returns (address _owner)
{
_owner = idToOwner[_tokenId];
require(_owner != address(0), NOT_VALID_NFT);
}
/**
* @dev Get the approved address for a single NFT.
* @notice Throws if `_tokenId` is not a valid NFT.
* @param _tokenId ID of the NFT to query the approval of.
* @return Address that _tokenId is approved for.
*/
function getApproved(
uint256 _tokenId
)
external
override
view
validNFToken(_tokenId)
returns (address)
{
return idToApproval[_tokenId];
}
/**
* @dev Checks if `_operator` is an approved operator for `_owner`.
* @param _owner The address that owns the NFTs.
* @param _operator The address that acts on behalf of the owner.
* @return True if approved for all, false otherwise.
*/
function isApprovedForAll(
address _owner,
address _operator
)
external
override
view
returns (bool)
{
return ownerToOperators[_owner][_operator];
}
/**
* @dev Actually performs the transfer.
* @notice Does NO checks.
* @param _to Address of a new owner.
* @param _tokenId The NFT that is being transferred.
*/
function _transfer(
address _to,
uint256 _tokenId
)
internal
{
address from = idToOwner[_tokenId];
_clearApproval(_tokenId);
_removeNFToken(from, _tokenId);
_addNFToken(_to, _tokenId);
emit Transfer(from, _to, _tokenId);
}
/**
* @dev Mints a new NFT.
* @notice This is an internal function which should be called from user-implemented external
* mint function. Its purpose is to show and properly initialize data structures when using this
* implementation.
* @param _to The address that will own the minted NFT.
* @param _tokenId of the NFT to be minted by the msg.sender.
*/
function _mint(
address _to,
uint256 _tokenId
)
internal
virtual
{
require(_to != address(0), ZERO_ADDRESS);
require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS);
_addNFToken(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
/**
* @dev Burns a NFT.
* @notice This is an internal function which should be called from user-implemented external burn
* function. Its purpose is to show and properly initialize data structures when using this
* implementation. Also, note that this burn implementation allows the minter to re-mint a burned
* NFT.
* @param _tokenId ID of the NFT to be burned.
*/
/* slim
function _burn(
uint256 _tokenId
)
internal
virtual
validNFToken(_tokenId)
{
address tokenOwner = idToOwner[_tokenId];
_clearApproval(_tokenId);
_removeNFToken(tokenOwner, _tokenId);
emit Transfer(tokenOwner, address(0), _tokenId);
}
*/
/**
* @dev Removes a NFT from owner.
* @notice Use and override this function with caution. Wrong usage can have serious consequences.
* @param _from Address from which we want to remove the NFT.
* @param _tokenId Which NFT we want to remove.
*/
function _removeNFToken(
address _from,
uint256 _tokenId
)
internal
virtual
{
require(idToOwner[_tokenId] == _from, NOT_OWNER);
delete idToOwner[_tokenId];
}
/**
* @dev Assigns a new NFT to owner.
* @notice Use and override this function with caution. Wrong usage can have serious consequences.
* @param _to Address to which we want to add the NFT.
* @param _tokenId Which NFT we want to add.
*/
function _addNFToken(
address _to,
uint256 _tokenId
)
internal
virtual
{
require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS);
idToOwner[_tokenId] = _to;
}
function _safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes memory _data
)
private
canTransfer(_tokenId)
validNFToken(_tokenId)
{
address tokenOwner = idToOwner[_tokenId];
require(tokenOwner == _from, NOT_OWNER);
require(_to != address(0), ZERO_ADDRESS);
_transfer(_to, _tokenId);
if (_to.isContract())
{
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data);
require(retval == MAGIC_ON_ERC721_RECEIVED, NOT_ABLE_TO_RECEIVE_NFT);
}
}
/**
* @dev Clears the current approval of a given NFT ID.
* @param _tokenId ID of the NFT to be transferred.
*/
function _clearApproval(
uint256 _tokenId
)
private
{
if (idToApproval[_tokenId] != address(0))
{
delete idToApproval[_tokenId];
}
}
}
/**
* @dev Optional metadata implementation for ERC-721 non-fungible token standard.
*/
contract NFTokenCollection is
NFToken,
ERC721Metadata
{
string internal nftName;
string internal nftSymbol;
uint256 public nftTokenIdLast = 0;
//mapping (uint256 => string) internal idToUri;
address payable public owner;
string public baseURI;
mapping(address => bool) private whiteList;
uint256 constant public MAX_SUPPLY = 10000;
event newTokenMinted(
uint newNFT
);
/**
* @dev Contract constructor.
* @notice When implementing this contract don't forget to set nftName and nftSymbol.
*/
constructor()
{
supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata
supportedInterfaces[0x780e9d63] = true; // ERC721Enumarable
nftName = "CATS SAGA CLUB";
nftSymbol = "CATS-SAGA-CLUB";
owner = payable(msg.sender);
/* Vealed Ipfs TMP Images */
baseURI = "ipfs://QmUwhHW3XpbCHYkEsxr8RKJihD5qH5WZeYkvTpqFj5akzV/";
whiteList[msg.sender]=true;
}
/**
* @dev Returns a descriptive name for a collection of NFTokens.
* @return _name Representing name.
*/
function name()
external
override
view
returns (string memory _name)
{
_name = nftName;
}
/**
* @dev Returns an abbreviated name for NFTokens.
* @return _symbol Representing symbol.
*/
function symbol()
external
override
view
returns (string memory _symbol)
{
_symbol = nftSymbol;
}
function mint(
address _to,
uint256 _tokenId
//,string memory _uri
)
internal
{
_mint(_to, _tokenId);
}
/**
* @dev A distinct URI (RFC 3986) for a given NFT.
* @param _tokenId Id for which we want uri.
* @return URI of _tokenId.
*/
function tokenURI(
uint256 _tokenId
)
external
override
view
validNFToken(_tokenId)
returns (string memory)
{
return string(abi.encodePacked(baseURI,uintToString(_tokenId)));
}
function uintToString(uint v) internal pure returns (string memory) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = bytes1(uint8(48 + remainder));
}
bytes memory s = new bytes(i); // i + 1 is inefficient
for (uint j = 0; j < i; j++) {
s[j] = reversed[i - j - 1]; // to avoid the off-by-one error
}
string memory str = string(s); // memory isn't implicitly convertible to storage
return str;
}
/* CONTRACT CUSTOM FUNCTIONS*/
function includeToPrivateWhiteList(address[] memory _users) public {
require(msg.sender==owner,"Only approved staff can act here");
for(uint8 i = 0; i < _users.length; i++) {
whiteList[_users[i]] = true;
}
}
function buyTokenNFT (uint256 _numTokens) external payable returns (bool success){
uint256 amount = msg.value;
uint256 tokenPrice;
require((nftTokenIdLast)+(_numTokens) <= MAX_SUPPLY,"Collection is not more available");
require (_numTokens <= 10 ,"Max 10 Mints each transaction");
if(whiteList[msg.sender]){
tokenPrice = 0.02 ether;
}else{
tokenPrice = 0.03 ether;
}
require(amount >= tokenPrice * _numTokens,"Not enought amount to buy this NFT");
owner.transfer(amount);
for(uint i = 0; i < _numTokens; i++){
nftTokenIdLast += 1;
mint(msg.sender,nftTokenIdLast);
}
emit newTokenMinted(nftTokenIdLast);
return true;
}
/*reveal the collection*/
function setBaseURIpfs (string memory _baseUri) external returns (bool success){
require(msg.sender==owner,"Only Admin can act this operation");
baseURI = _baseUri;
return true;
}
/* Mint NFTs for the team*/
function mintTokenAdmin (uint256 _numTokens) external returns (bool success){
require(msg.sender==owner,"Only Admin can act this operation");
require((nftTokenIdLast)+(_numTokens) <= MAX_SUPPLY,"Collection is not more available");
for(uint i = 0; i < _numTokens; i++){
nftTokenIdLast += 1;
mint(msg.sender,nftTokenIdLast);
}
emit newTokenMinted(nftTokenIdLast);
return true;
}
function totalSupply()public view returns (uint256) {
return nftTokenIdLast;
}
} | CONTRACT CUSTOM FUNCTIONS/ | function includeToPrivateWhiteList(address[] memory _users) public {
require(msg.sender==owner,"Only approved staff can act here");
for(uint8 i = 0; i < _users.length; i++) {
whiteList[_users[i]] = true;
}
}
| 6,807,691 |
// SPDX-License-Identifier: MIT
// Amended by LeZig
/* ______ ______ _____ __ ______ ______ ______ __ __ __ __ ______ __ ______ ______ ______ ______
/\___ \ /\ __ \ /\ __-. /\ \ /\ __ \ /\ ___\ /\ ___\ /\ "-.\ \ /\ \ / / /\ ___\ /\ \ /\ __ \ /\ == \ /\ ___\ /\ ___\
\/_/ /__ \ \ \/\ \ \ \ \/\ \ \ \ \ \ \ __ \ \ \ \____ \ \ __\ \ \ \-. \ \ \ \'/ \ \ __\ \ \ \____ \ \ \/\ \ \ \ _-/ \ \ __\ \ \___ \
/\_____\ \ \_____\ \ \____- \ \_\ \ \_\ \_\ \ \_____\ \ \_____\ \ \_\\"\_\ \ \__| \ \_____\ \ \_____\ \ \_____\ \ \_\ \ \_____\ \/\_____\
\/_____/ \/_____/ \/____/ \/_/ \/_/\/_/ \/_____/ \/_____/ \/_/ \/_/ \/_/ \/_____/ \/_____/ \/_____/ \/_/ \/_____/ \/_____/
*/
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/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/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/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/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/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/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/token/ERC721/ERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
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;
}
}
pragma solidity ^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;
}
}
pragma solidity ^0.8.0;
contract ZodiacEnvelopes is
Ownable,
ERC721Enumerable
{
using SafeMath for uint256;
using Strings for uint256;
using Address for address;
using Counters for Counters.Counter;
// economics
Counters.Counter private _supply;
uint256 _max_supply = 8888;
uint256 _max_mint_per_transaction = 1;
uint256 _current_mint_token_id = 1;
// mint conditions
bool public _sale_open = true;
bool private _paused = false;
uint256 public _sale_start_time = 1643770800;
// reserve for the team in giveaways and partnerships
uint256 public _reserved_tokens_red = 50;
uint256 public _reserved_tokens_gold = 10;
uint256 public _minted_tokens_red = 0;
uint256 public _minted_tokens_gold = 0;
uint256 private _gold_modulo = 100;
// mapping tokenId to owner address
mapping(uint256 => address) public _token_id_to_owner;
// metadata uri for both packets
string private _base_URI;
string private _uri_suffix = ".json";
// IERC721 standards
string private _name;
string private _symbol;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(
string memory base_URI_,
string memory name_,
string memory symbol_
) ERC721(name_, symbol_) {
_set_base_uri(base_URI_);
}
function _total_supply() public view returns (uint256) {
return _supply.current();
}
function _is_sale_open() public view returns (bool) {
return block.timestamp >= _sale_start_time;
}
modifier _mint_compliance(uint256 _mint_amount) {
require(_mint_amount > 0 && _mint_amount <= _max_mint_per_transaction, "ZODIACS: Invalid mint amount!");
require(_total_supply() + _mint_amount <= _max_supply, "ZODIACS: Max supply exceeded!");
require(((_is_sale_open() || _sale_open) && !_paused), "ZODIACS: public sale has not started!");
require(msg.sender == tx.origin, "ZODIACS: Only EOA (no smart contract mint)");
_;
}
function _is_gold(uint256 _token_id) public view returns (bool) {
return _token_id > 0 && _token_id % _gold_modulo == 0;
}
function _update_minted_tokens_count(uint256 _token_id_minted) internal {
if (_is_gold(_token_id_minted)){
_minted_tokens_gold = _minted_tokens_gold.add(1);
}
else{
_minted_tokens_red = _minted_tokens_red.add(1);
}
}
function _mint() public _mint_compliance(1) {
// this should only happen when we are near the end of mint, where regular mint encounters dev mints ids that are already minted
while (_token_id_to_owner[_current_mint_token_id] != address(0)){
_current_mint_token_id++;
}
// sanity check for max supply
require(_current_mint_token_id <= _max_supply, "ZODIACS: Max supply exceeded!");
_supply.increment();
_update_minted_tokens_count(_current_mint_token_id);
// assign owner and mint!
_token_id_to_owner[_current_mint_token_id] = msg.sender;
_safeMint(msg.sender, _current_mint_token_id);
}
function _dev_mint(address _to, uint256[] memory _token_ids) internal {
for (uint256 i = 0; i < _token_ids.length; i++) {
uint256 _next_token_id_candidate = _token_ids[i];
// check bounds and augment supply
require(_next_token_id_candidate > 0 && _next_token_id_candidate <= _max_supply, "ZODIACS: Token id out of bounds!");
_supply.increment();
// reset the reserves count and minted counts
_update_minted_tokens_count(_next_token_id_candidate);
if (_is_gold(_next_token_id_candidate)){
_reserved_tokens_gold = _reserved_tokens_gold.sub(1);
}
else{
_reserved_tokens_red = _reserved_tokens_red.sub(1);
}
// assign owner and mint!
_token_id_to_owner[_next_token_id_candidate] = _to;
_safeMint(_to, _next_token_id_candidate);
}
}
function _mint_reserved_tokens(uint256[] memory _token_ids) public onlyOwner {
uint256 _mint_amount = _token_ids.length;
require(_mint_amount > 0 && _mint_amount <= _reserved_tokens_red+_reserved_tokens_gold, "ZODIACS: Not enough reserve left for team");
require(_total_supply() + _mint_amount <= _max_supply, "ZODIACS: Max supply exceeded!");
_dev_mint(msg.sender, _token_ids);
}
function _withdraw() public onlyOwner {
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
require(os);
}
function _set_sale_open(bool sale_open_) public onlyOwner {
_sale_open = sale_open_;
}
function _set_sale_start_time(uint256 sale_start_time_) public onlyOwner {
_sale_start_time = sale_start_time_;
}
function _set_paused(bool paused_) public onlyOwner {
_paused = paused_;
}
function _set_base_uri(string memory _uri) public onlyOwner {
_base_URI = _uri;
}
function _set_current_mint_token_id(uint256 current_mint_token_id_) public onlyOwner {
_current_mint_token_id = current_mint_token_id_;
}
function _get_minted_tokens_red() public view returns (uint256) {
return _minted_tokens_red;
}
function _get_minted_tokens_gold() public view returns (uint256) {
return _minted_tokens_gold;
}
function _get_max_supply() public view returns (uint256) {
return _max_supply;
}
function _get_current_mint_token_id() public onlyOwner view returns (uint256) {
return _current_mint_token_id;
}
function _wallet_of_owner(address _owner)
public
view
returns (uint256[] memory) {
uint256 _owner_token_count = balanceOf(_owner);
uint256[] memory _owned_token_ids = new uint256[](_owner_token_count);
for (uint256 i; i < _owner_token_count; i++) {
_owned_token_ids[i] = tokenOfOwnerByIndex(_owner, i);
}
return _owned_token_ids;
}
function _owner_of(uint256 _token_id) public view returns (address) {
return _token_id_to_owner[_token_id];
}
function _get_red_holders() public view returns (address[] memory) {
uint256 _current_token_id = 1;
uint256 _max_token_id = _total_supply();
uint256 _red_owner_index = 0;
address[] memory _red_holders = new address[](_minted_tokens_red);
while (_current_token_id <= _max_token_id){
if(!_is_gold(_current_token_id)){
_red_holders[_red_owner_index] = _token_id_to_owner[_current_token_id];
_red_owner_index++;
}
_current_token_id++;
}
return _red_holders;
}
function _get_gold_holders() public view returns (address[] memory) {
uint256 _current_token_id = 1;
uint256 _max_token_id = _total_supply();
uint256 _gold_owner_index = 0;
address[] memory _gold_holders = new address[](_minted_tokens_gold);
while (_current_token_id <= _max_token_id){
if(_is_gold(_current_token_id)){
_gold_holders[_gold_owner_index] = _token_id_to_owner[_current_token_id];
_gold_owner_index++;
}
_current_token_id++;
}
return _gold_holders;
}
function tokenURI(uint256 _token_id)
public
view
virtual
override
returns (string memory){
require(
_exists(_token_id),
"ERC721Metadata: URI query for nonexistent token"
);
return bytes(_base_URI).length > 0 ?
string(abi.encodePacked(_base_URI, _token_id.toString(), _uri_suffix))
:
"";
}
} | 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;
}
| 13,457,786 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
contract NFT is ERC721, AccessControl {
bytes32 public constant REDEEMER_ROLE = keccak256("REDEEMER_ROLE");
string private _mediaURI;
string private _tokenURI;
string public musicSheetI;
string public musicSheetLove;
string public musicSheetYou;
address public royaltyReciever;
uint256 public royalty;
bool public redeemed = false;
event Redeemed();
constructor(string memory name_, string memory symbol_, string memory mediaURI_, string memory tokenURI_, address royaltyReciever_, string memory musicSheetI_, string memory musicSheetLove_, string memory musicSheetYou_) ERC721(name_, symbol_) {
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(REDEEMER_ROLE, msg.sender);
royaltyReciever = royaltyReciever_;
_mediaURI = mediaURI_;
_tokenURI = tokenURI_;
musicSheetI = musicSheetI_;
musicSheetLove = musicSheetLove_;
musicSheetYou = musicSheetYou_;
_safeMint(msg.sender, 0);
}
///@notice returns uri for token metadata
function tokenURI(uint256) public view override returns(string memory) {
return _tokenURI;
}
///@notice returns uri for audio file for owner
function mediaURI() public view returns(string memory) {
return _mediaURI;
}
///@notice sets redeem status. Called only by REDEEMER_ROLE
function redeem() public onlyRole(REDEEMER_ROLE) {
redeemed = true;
emit Redeemed();
}
///@notice change the roylaty receiver.
function changeRoyaltiesReceiver(address royaltyReciever_) public onlyRole(DEFAULT_ADMIN_ROLE) {
royaltyReciever = royaltyReciever_;
}
///@notice returns royalty amount and reciever
///@param _tokenId in our case allways 0
///@param _salePrice token price
function royaltyInfo(
uint256 _tokenId,
uint256 _salePrice
) external view returns (
address receiver,
uint256 royaltyAmount
) {
return (royaltyReciever, _salePrice / 10);
}
function supportsInterface(bytes4 _interfaceId)
public
view
override(ERC721, AccessControl)
returns (bool)
{
return super.supportsInterface(_interfaceId) || _interfaceId == 0x2a55205a;
}
} | returns uri for audio file for owner | function mediaURI() public view returns(string memory) {
return _mediaURI;
}
| 5,385,142 |
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
/**
* @title 1Inch(On-chain).
* @dev On-chain and off-chian DEX Aggregator.
*/
import { TokenInterface , MemoryInterface } from "../../common/interfaces.sol";
import { Stores } from "../../common/stores.sol";
import { OneProtoInterface, OneProtoData, OneProtoMultiData } from "./interface.sol";
import { Helpers } from "./helpers.sol";
import { Events } from "./events.sol";
abstract contract OneProtoResolver is Helpers, Events {
/**
* @dev 1proto contract swap handler
* @param oneProtoData - Struct with swap data defined in interfaces.sol
*/
function oneProtoSwap(
OneProtoData memory oneProtoData
) internal returns (uint buyAmt) {
TokenInterface _sellAddr = oneProtoData.sellToken;
TokenInterface _buyAddr = oneProtoData.buyToken;
uint _sellAmt = oneProtoData._sellAmt;
uint _slippageAmt = getSlippageAmt(_buyAddr, _sellAddr, _sellAmt, oneProtoData.unitAmt);
uint ethAmt;
if (address(_sellAddr) == ethAddr) {
ethAmt = _sellAmt;
} else {
approve(_sellAddr, address(oneProto), _sellAmt);
}
uint initalBal = getTokenBal(_buyAddr);
oneProto.swap{value: ethAmt}(
_sellAddr,
_buyAddr,
_sellAmt,
_slippageAmt,
oneProtoData.distribution,
oneProtoData.disableDexes
);
uint finalBal = getTokenBal(_buyAddr);
buyAmt = sub(finalBal, initalBal);
require(_slippageAmt <= buyAmt, "Too much slippage");
}
/**
* @dev 1proto contract multi swap handler
* @param oneProtoData - Struct with multiple swap data defined in interfaces.sol
*/
function oneProtoSwapMulti(OneProtoMultiData memory oneProtoData) internal returns (uint buyAmt) {
TokenInterface _sellAddr = oneProtoData.sellToken;
TokenInterface _buyAddr = oneProtoData.buyToken;
uint _sellAmt = oneProtoData._sellAmt;
uint _slippageAmt = getSlippageAmt(_buyAddr, _sellAddr, _sellAmt, oneProtoData.unitAmt);
uint ethAmt;
if (address(_sellAddr) == ethAddr) {
ethAmt = _sellAmt;
} else {
approve(_sellAddr, address(oneProto), _sellAmt);
}
uint initalBal = getTokenBal(_buyAddr);
oneProto.swapMulti{value: ethAmt}(
convertToTokenInterface(oneProtoData.tokens),
_sellAmt,
_slippageAmt,
oneProtoData.distribution,
oneProtoData.disableDexes
);
uint finalBal = getTokenBal(_buyAddr);
buyAmt = sub(finalBal, initalBal);
require(_slippageAmt <= buyAmt, "Too much slippage");
}
}
abstract contract OneProtoResolverHelpers is OneProtoResolver {
/**
* @dev Gets the swapping data offchian for swaps and calls swap.
* @param oneProtoData - Struct with swap data defined in interfaces.sol
* @param getId Get token amount at this ID from `InstaMemory` Contract.
* @param setId Set token amount at this ID in `InstaMemory` Contract.
*/
function _sell(
OneProtoData memory oneProtoData,
uint getId,
uint setId
) internal returns (OneProtoData memory) {
uint _sellAmt = getUint(getId, oneProtoData._sellAmt);
oneProtoData._sellAmt = _sellAmt == uint(-1) ?
getTokenBal(oneProtoData.sellToken) :
_sellAmt;
oneProtoData._buyAmt = oneProtoSwap(oneProtoData);
setUint(setId, oneProtoData._buyAmt);
return oneProtoData;
}
/**
* @dev Gets the swapping data offchian for swaps and calls swap.
* @param oneProtoData - Struct with multiple swap data defined in interfaces.sol
* @param getId Get token amount at this ID from `InstaMemory` Contract.
* @param setId Set token amount at this ID in `InstaMemory` Contract.
*/
function _sellMulti(
OneProtoMultiData memory oneProtoData,
uint getId,
uint setId
) internal returns (OneProtoMultiData memory) {
uint _sellAmt = getUint(getId, oneProtoData._sellAmt);
oneProtoData._sellAmt = _sellAmt == uint(-1) ?
getTokenBal(oneProtoData.sellToken) :
_sellAmt;
oneProtoData._buyAmt = oneProtoSwapMulti(oneProtoData);
setUint(setId, oneProtoData._buyAmt);
// emitLogSellMulti(oneProtoData, getId, setId);
return oneProtoData;
}
}
abstract contract OneProto is OneProtoResolverHelpers {
/**
* @dev Sell ETH/ERC20_Token using 1Proto using off-chain calculation.
* @notice Swap tokens from exchanges like Uniswap, Kyber etc, with calculation done off-chain.
* @param buyAddr The address of the token to buy.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param sellAddr The address of the token to sell.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param sellAmt The amount of the token to sell.
* @param unitAmt The amount of buyAmt/sellAmt with slippage.
* @param distribution The distribution of swap across different DEXs.
* @param disableDexes Disable a dex. (To disable none: 0)
* @param getId ID to retrieve sellAmt.
* @param setId ID stores the amount of token brought.
*/
function sell(
address buyAddr,
address sellAddr,
uint sellAmt,
uint unitAmt,
uint[] calldata distribution,
uint disableDexes,
uint getId,
uint setId
) external payable returns (string memory _eventName, bytes memory _eventParam) {
OneProtoData memory oneProtoData = OneProtoData({
buyToken: TokenInterface(buyAddr),
sellToken: TokenInterface(sellAddr),
_sellAmt: sellAmt,
unitAmt: unitAmt,
distribution: distribution,
disableDexes: disableDexes,
_buyAmt: 0
});
oneProtoData = _sell(oneProtoData, getId, setId);
_eventName = "LogSell(address,address,uint256,uint256,uint256,uint256)";
_eventParam = abi.encode(buyAddr, sellAddr, oneProtoData._buyAmt, oneProtoData._sellAmt, getId, setId);
}
/**
* @dev Sell Multiple tokens using 1proto using off-chain calculation.
* @notice Swap multiple tokens from exchanges like Uniswap, Kyber etc, with calculation done off-chain.
* @param tokens Array of tokens.
* @param sellAmt The amount of the token to sell.
* @param unitAmt The amount of buyAmt/sellAmt with slippage.
* @param distribution The distribution of swap across different DEXs.
* @param disableDexes Disable a dex. (To disable none: 0)
* @param getId ID to retrieve sellAmt.
* @param setId ID stores the amount of token brought.
*/
function sellMulti(
address[] calldata tokens,
uint sellAmt,
uint unitAmt,
uint[] calldata distribution,
uint[] calldata disableDexes,
uint getId,
uint setId
) external payable returns (string memory _eventName, bytes memory _eventParam) {
uint _length = tokens.length;
OneProtoMultiData memory oneProtoData = OneProtoMultiData({
tokens: tokens,
buyToken: TokenInterface(address(tokens[_length - 1])),
sellToken: TokenInterface(address(tokens[0])),
unitAmt: unitAmt,
distribution: distribution,
disableDexes: disableDexes,
_sellAmt: sellAmt,
_buyAmt: 0
});
oneProtoData = _sellMulti(oneProtoData, getId, setId);
_eventName = "LogSellMulti(address[],address,address,uint256,uint256,uint256,uint256)";
_eventParam = abi.encode(
tokens,
address(oneProtoData.buyToken),
address(oneProtoData.sellToken),
oneProtoData._buyAmt,
oneProtoData._sellAmt,
getId,
setId
);
}
}
contract ConnectV2OneProto is OneProto {
string public name = "1Proto-v1.1";
}
pragma solidity ^0.7.0;
interface TokenInterface {
function approve(address, uint256) external;
function transfer(address, uint) external;
function transferFrom(address, address, uint) external;
function deposit() external payable;
function withdraw(uint) external;
function balanceOf(address) external view returns (uint);
function decimals() external view returns (uint);
}
interface MemoryInterface {
function getUint(uint id) external returns (uint num);
function setUint(uint id, uint val) external;
}
interface InstaMapping {
function cTokenMapping(address) external view returns (address);
function gemJoinMapping(bytes32) external view returns (address);
}
interface AccountInterface {
function enable(address) external;
function disable(address) external;
function isAuth(address) external view returns (bool);
}
pragma solidity ^0.7.0;
import { MemoryInterface, InstaMapping } from "./interfaces.sol";
abstract contract Stores {
/**
* @dev Return ethereum address
*/
address constant internal ethAddr = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/**
* @dev Return Wrapped ETH address
*/
address constant internal wethAddr = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
/**
* @dev Return memory variable address
*/
MemoryInterface constant internal instaMemory = MemoryInterface(0x8a5419CfC711B2343c17a6ABf4B2bAFaBb06957F);
/**
* @dev Return InstaDApp Mapping Addresses
*/
InstaMapping constant internal instaMapping = InstaMapping(0xe81F70Cc7C0D46e12d70efc60607F16bbD617E88);
/**
* @dev Get Uint value from InstaMemory Contract.
*/
function getUint(uint getId, uint val) internal returns (uint returnVal) {
returnVal = getId == 0 ? val : instaMemory.getUint(getId);
}
/**
* @dev Set Uint value in InstaMemory Contract.
*/
function setUint(uint setId, uint val) virtual internal {
if (setId != 0) instaMemory.setUint(setId, val);
}
}
pragma solidity ^0.7.0;
import { TokenInterface } from "../../common/interfaces.sol";
interface OneProtoInterface {
function swap(
TokenInterface fromToken,
TokenInterface destToken,
uint256 amount,
uint256 minReturn,
uint256[] calldata distribution,
uint256 flags // See contants in IOneSplit.sol
) external payable returns(uint256);
function swapMulti(
TokenInterface[] calldata tokens,
uint256 amount,
uint256 minReturn,
uint256[] calldata distribution,
uint256[] calldata flags
) external payable returns(uint256 returnAmount);
function getExpectedReturn(
TokenInterface fromToken,
TokenInterface destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
)
external
view
returns(
uint256 returnAmount,
uint256[] memory distribution
);
}
interface OneProtoMappingInterface {
function oneProtoAddress() external view returns(address);
}
struct OneProtoData {
TokenInterface sellToken;
TokenInterface buyToken;
uint _sellAmt;
uint _buyAmt;
uint unitAmt;
uint[] distribution;
uint disableDexes;
}
struct OneProtoMultiData {
address[] tokens;
TokenInterface sellToken;
TokenInterface buyToken;
uint _sellAmt;
uint _buyAmt;
uint unitAmt;
uint[] distribution;
uint[] disableDexes;
}
pragma solidity ^0.7.0;
import { TokenInterface } from "../../common/interfaces.sol";
import { DSMath } from "../../common/math.sol";
import { Basic } from "../../common/basic.sol";
import { TokenInterface, OneProtoInterface } from "./interface.sol";
abstract contract Helpers is DSMath, Basic {
/**
* @dev 1proto Address
*/
OneProtoInterface constant internal oneProto = OneProtoInterface(0x50FDA034C0Ce7a8f7EFDAebDA7Aa7cA21CC1267e);
function getSlippageAmt(
TokenInterface _buyAddr,
TokenInterface _sellAddr,
uint _sellAmt,
uint unitAmt
) internal view returns(uint _slippageAmt) {
(uint _buyDec, uint _sellDec) = getTokensDec(_buyAddr, _sellAddr);
uint _sellAmt18 = convertTo18(_sellDec, _sellAmt);
_slippageAmt = convert18ToDec(_buyDec, wmul(unitAmt, _sellAmt18));
}
function convertToTokenInterface(address[] memory tokens) internal pure returns(TokenInterface[] memory) {
TokenInterface[] memory _tokens = new TokenInterface[](tokens.length);
for (uint i = 0; i < tokens.length; i++) {
_tokens[i] = TokenInterface(tokens[i]);
}
return _tokens;
}
}
pragma solidity ^0.7.0;
contract Events {
event LogSell(
address indexed buyToken,
address indexed sellToken,
uint256 buyAmt,
uint256 sellAmt,
uint256 getId,
uint256 setId
);
event LogSellMulti(
address[] tokens,
address indexed buyToken,
address indexed sellToken,
uint256 buyAmt,
uint256 sellAmt,
uint256 getId,
uint256 setId
);
}
pragma solidity ^0.7.0;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
contract DSMath {
uint constant WAD = 10 ** 18;
uint constant RAY = 10 ** 27;
function add(uint x, uint y) internal pure returns (uint z) {
z = SafeMath.add(x, y);
}
function sub(uint x, uint y) internal virtual pure returns (uint z) {
z = SafeMath.sub(x, y);
}
function mul(uint x, uint y) internal pure returns (uint z) {
z = SafeMath.mul(x, y);
}
function div(uint x, uint y) internal pure returns (uint z) {
z = SafeMath.div(x, y);
}
function wmul(uint x, uint y) internal pure returns (uint z) {
z = SafeMath.add(SafeMath.mul(x, y), WAD / 2) / WAD;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = SafeMath.add(SafeMath.mul(x, WAD), y / 2) / y;
}
function rdiv(uint x, uint y) internal pure returns (uint z) {
z = SafeMath.add(SafeMath.mul(x, RAY), y / 2) / y;
}
function rmul(uint x, uint y) internal pure returns (uint z) {
z = SafeMath.add(SafeMath.mul(x, y), RAY / 2) / RAY;
}
function toInt(uint x) internal pure returns (int y) {
y = int(x);
require(y >= 0, "int-overflow");
}
function toRad(uint wad) internal pure returns (uint rad) {
rad = mul(wad, 10 ** 27);
}
}
pragma solidity ^0.7.0;
import { TokenInterface } from "./interfaces.sol";
import { Stores } from "./stores.sol";
import { DSMath } from "./math.sol";
abstract contract Basic is DSMath, Stores {
function convert18ToDec(uint _dec, uint256 _amt) internal pure returns (uint256 amt) {
amt = (_amt / 10 ** (18 - _dec));
}
function convertTo18(uint _dec, uint256 _amt) internal pure returns (uint256 amt) {
amt = mul(_amt, 10 ** (18 - _dec));
}
function getTokenBal(TokenInterface token) internal view returns(uint _amt) {
_amt = address(token) == ethAddr ? address(this).balance : token.balanceOf(address(this));
}
function getTokensDec(TokenInterface buyAddr, TokenInterface sellAddr) internal view returns(uint buyDec, uint sellDec) {
buyDec = address(buyAddr) == ethAddr ? 18 : buyAddr.decimals();
sellDec = address(sellAddr) == ethAddr ? 18 : sellAddr.decimals();
}
function encodeEvent(string memory eventName, bytes memory eventParam) internal pure returns (bytes memory) {
return abi.encode(eventName, eventParam);
}
function approve(TokenInterface token, address spender, uint256 amount) internal {
try token.approve(spender, amount) {
} catch {
token.approve(spender, 0);
token.approve(spender, amount);
}
}
function changeEthAddress(address buy, address sell) internal pure returns(TokenInterface _buy, TokenInterface _sell){
_buy = buy == ethAddr ? TokenInterface(wethAddr) : TokenInterface(buy);
_sell = sell == ethAddr ? TokenInterface(wethAddr) : TokenInterface(sell);
}
function convertEthToWeth(bool isEth, TokenInterface token, uint amount) internal {
if(isEth) token.deposit{value: amount}();
}
function convertWethToEth(bool isEth, TokenInterface token, uint amount) internal {
if(isEth) {
approve(token, address(token), amount);
token.withdraw(amount);
}
}
}
// 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;
}
}
| 1proto contract multi swap handler oneProtoData - Struct with multiple swap data defined in interfaces.sol/ | function oneProtoSwapMulti(OneProtoMultiData memory oneProtoData) internal returns (uint buyAmt) {
TokenInterface _sellAddr = oneProtoData.sellToken;
TokenInterface _buyAddr = oneProtoData.buyToken;
uint _sellAmt = oneProtoData._sellAmt;
uint _slippageAmt = getSlippageAmt(_buyAddr, _sellAddr, _sellAmt, oneProtoData.unitAmt);
uint ethAmt;
if (address(_sellAddr) == ethAddr) {
ethAmt = _sellAmt;
approve(_sellAddr, address(oneProto), _sellAmt);
}
uint initalBal = getTokenBal(_buyAddr);
convertToTokenInterface(oneProtoData.tokens),
_sellAmt,
_slippageAmt,
oneProtoData.distribution,
oneProtoData.disableDexes
);
uint finalBal = getTokenBal(_buyAddr);
buyAmt = sub(finalBal, initalBal);
require(_slippageAmt <= buyAmt, "Too much slippage");
}
| 104,292 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import { Ownable } from "./lib/Ownable.sol";
import { SafeTransferLib } from "solmate/utils/SafeTransferLib.sol";
import { ReentrancyGuard } from "solmate/utils/ReentrancyGuard.sol";
import { ERC20 } from "solmate/tokens/ERC20.sol";
import { ERC721, ERC721TokenReceiver } from "solmate/tokens/ERC721.sol";
/// @title Auction
/// @notice Smart contract that allows a user to start a first price sealed bid auction(aka blind auction)
/// for a single ERC721 asset. Inspired by the ENS RegistrarController.
/// The contract maintains custody of the Asset until the auction is Finalized, or Cancelled.
contract Auction is ERC721TokenReceiver, ReentrancyGuard, Ownable {
enum AuctionPhase {
INACTIVE,
COMMIT,
REVEAL,
FINALIZED,
RESERVE_NOT_MET,
CANCELED
}
/// Events
event NewHighestBid(address highestBidder, uint256 highestBid, address oldHighestBidder, uint256 oldHighestBid);
event Finalized(address indexed caller, address indexed winner, uint256 indexed winningBid);
event Cancelled(address indexed caller);
/// @dev ERC20 token address used to bid on this auction
ERC20 public immutable bidToken;
/// @dev ERC721 token address that is being auctioned
address public immutable auctionAsset;
/// @dev ERC721 token ID that is being auctioned
uint256 public immutable auctionAssetID;
/// @dev The duration of the commit phase
uint256 public immutable commitPhaseDuration;
/// @dev The duration of the reveal phase
uint256 public immutable revealPhaseDuration;
/// @dev The minimum price that the auctionAsset can be sold for.
/// Can be set to 0.
uint256 public immutable reservePrice;
address public highestBidder = address(0);
uint256 public highestBid = 0;
uint256 public commitPhaseEnd;
uint256 public revealPhaseEnd;
/// @dev starting auction phase is always INACTIVE
AuctionPhase public currentPhase = AuctionPhase.INACTIVE;
/// @dev Mapping of received commitments
mapping(bytes32 => bool) public commitments;
constructor(
address admin,
address bidToken_,
address asset_,
uint256 assetID_,
uint256 commitPhaseDuration_,
uint256 revealPhaseDuration_,
uint256 reservePrice_
) ERC721TokenReceiver() Ownable() {
bidToken = ERC20(bidToken_);
auctionAsset = asset_;
auctionAssetID = assetID_;
commitPhaseDuration = commitPhaseDuration_;
revealPhaseDuration = revealPhaseDuration_;
reservePrice = reservePrice_;
transferOwnership(admin);
}
/// @notice Starts an auction
/// @notice Moves the auction to the COMMIT phase
/// @notice Only the Auction owner can start the auction
function startAuction() public onlyOwner {
require(currentPhase == AuctionPhase.INACTIVE, "Auction::auction already in progress");
commitPhaseEnd = block.timestamp + commitPhaseDuration;
currentPhase = AuctionPhase.COMMIT;
}
/// @notice Starts the reveal phase of the auction
function startRevealPhase() public {
require(currentPhase == AuctionPhase.COMMIT, "Auction::must be in commit phase");
require(block.timestamp > commitPhaseEnd, "Auction::commit phase has not ended");
revealPhaseEnd = block.timestamp + revealPhaseDuration;
currentPhase = AuctionPhase.REVEAL;
}
/// @notice Creates a commitment to bid at a certain price
/// @param commitment - A hash of the bidder, bidAmount and a secret
function commit(bytes32 commitment) public {
require(currentPhase == AuctionPhase.COMMIT, "Auction::must be in commit phase");
require(block.timestamp <= commitPhaseEnd, "Auction::commit phase has ended");
commitments[commitment] = true;
}
/// @notice Reveals a previously placed bid
/// @param bid - The Bid amount
/// @param secret - The Secret
function reveal(uint256 bid, bytes32 secret) public nonReentrant {
require(currentPhase == AuctionPhase.REVEAL, "Auction::must be in reveal phase");
require(block.timestamp <= revealPhaseEnd, "Auction::reveal phase has ended");
bytes32 commitment = createCommitment(msg.sender, bid, secret);
require(commitments[commitment], "Auction::nonexistent commitment");
require(bid >= reservePrice, "Auction::unmet reserve price");
// First bid
if(highestBidder == address(0)) {
// Update highest bidder and highest bid
highestBidder = msg.sender;
highestBid = bid;
// Transfer bid token from the bidder to the auction contract
SafeTransferLib.safeTransferFrom(bidToken, msg.sender, address(this), bid);
// Clear the commitment
delete commitments[commitment];
emit NewHighestBid(msg.sender, bid, address(0), 0);
return;
}
// If current bid strictly > highest bid
if (bid > highestBid) {
address oldHighestBidder = highestBidder;
uint256 oldHighestBid = highestBid;
// Refund previous highest bidder
SafeTransferLib.safeTransfer(bidToken, highestBidder, highestBid);
// Transfer bid token to the auction contract
SafeTransferLib.safeTransferFrom(bidToken, msg.sender, address(this), bid);
// Update highest bidder and highest bid
highestBidder = msg.sender;
highestBid = bid;
// Clear the commitment
delete commitments[commitment];
emit NewHighestBid(msg.sender, bid, oldHighestBidder, oldHighestBid);
return;
}
}
/// @notice Creates a commitment hash
/// @param bidder - The address placing the bid
/// @param bid - The bid to be placed
/// @param secret - The secret
function createCommitment(address bidder, uint256 bid, bytes32 secret) public pure returns (bytes32 commitment) {
commitment= keccak256(abi.encodePacked(bidder, bid, secret));
}
/// @notice Ends the auction and transfers the asset to the winner of the auction
/// @notice If the reserve price isn't met, the auction is set to RESERVE_NOT_MET
function finalizeAuction() public nonReentrant {
require(currentPhase == AuctionPhase.REVEAL, "Auction::must be in reveal phase");
require(block.timestamp > revealPhaseEnd, "Auction::reveal phase has not ended");
if(highestBid >= reservePrice) {
currentPhase = AuctionPhase.FINALIZED;
// Transfer auctionAsset to the highest bidder
ERC721(auctionAsset).safeTransferFrom(address(this), highestBidder, auctionAssetID);
// transfer the auction proceeds to the Auction owner
SafeTransferLib.safeTransfer(bidToken, owner(), highestBid);
emit Finalized(msg.sender, highestBidder, highestBid);
} else {
// Reserve price not met
currentPhase = AuctionPhase.RESERVE_NOT_MET;
}
}
/// @notice Cancels the auction and returns the asset to the auction owner
/// @notice Can only be called if an auction is in the INACTIVE or RESERVE_NOT_MET phases
function cancelAuction() public onlyOwner {
require(
currentPhase == AuctionPhase.INACTIVE
||
currentPhase == AuctionPhase.RESERVE_NOT_MET,
"Auction::auction cannot be cancelled"
);
emit Cancelled(msg.sender);
currentPhase = AuctionPhase.CANCELED;
// transfer auctionAsset to owner
ERC721(auctionAsset).safeTransferFrom(address(this), owner(), auctionAssetID);
}
function onERC721Received(
address,
address,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
} | Cancels the auction and returns the asset to the auction owner Can only be called if an auction is in the INACTIVE or RESERVE_NOT_MET phases transfer auctionAsset to owner | function cancelAuction() public onlyOwner {
require(
currentPhase == AuctionPhase.INACTIVE
||
currentPhase == AuctionPhase.RESERVE_NOT_MET,
"Auction::auction cannot be cancelled"
);
emit Cancelled(msg.sender);
currentPhase = AuctionPhase.CANCELED;
ERC721(auctionAsset).safeTransferFrom(address(this), owner(), auctionAssetID);
}
| 12,595,646 |
pragma solidity ^0.4.18;
import "./lib/Ownable.sol";
import "./lib/Convert.sol";
import "./CardTypes.sol";
import "./Cards.sol";
contract Challenges is Ownable {
enum challengeResultEnum {INITIATOR_WIN, CHALLENGER_WIN, DRAFT, UNKNOWN}
struct Challenge {
address initiator;
address challenger;
challengeResultEnum challengeResult;
bytes32 initiatorCardsHash;
uint challengerHero;
uint[5] challengerCards;
}
uint constant cardAmount = 5;
Cards cards;
CardTypes cardTypes;
Challenge[] public challenges;
mapping(uint => address) challengeToInitiator;
constructor(address cardsAddress, address cardTypesAddress) public {
cards = Cards(cardsAddress);
cardTypes = CardTypes(cardTypesAddress);
}
function challenge(bytes32 cardsHash) public {
uint[5] memory emptyArray;
uint id = challenges.push(Challenge(msg.sender, address(0), challengeResultEnum.UNKNOWN,
cardsHash, 0, emptyArray)) - 1;
challengeToInitiator[id] = msg.sender;
}
function accept(uint id, uint hero, uint[cardAmount] _cards) public {
Challenge storage _challenge = challenges[id];
//require(_challenge.initiator != msg.sender);
require(_challenge.challenger == address(0));
_challenge.challenger = msg.sender;
_challenge.challengerHero = hero;
_challenge.challengerCards = _cards;
}
function battle(uint id, uint initiatorHero, uint[cardAmount] initiatorCards, string salt) public {
Challenge storage _challenge = challenges[id];
require(_challenge.initiator == msg.sender);
checkHash(_challenge.initiatorCardsHash, initiatorHero, initiatorCards, salt);
uint initiatorHeroHealth = getHero(initiatorHero);
uint challengerHeroHealth = getHero(_challenge.challengerHero);
uint8 elementAmount = cardTypes.elementAmount();
uint initiatorElement;
uint challengerElement;
uint initiatorDamage;
uint challengerDamage;
for (uint i = 0; i != elementAmount; i++) {
(challengerElement, challengerDamage) = getCard(_challenge.challengerCards[0]);
(initiatorElement, initiatorDamage) = getCard(initiatorCards[0]);
uint result = (elementAmount + initiatorElement - challengerElement) % elementAmount;
if(result != 0) {
if (result % 2 == 1) {
initiatorDamage *= 2;
} else if (result % 2 == 0) {
challengerDamage *= 2;
}
}
initiatorHeroHealth -= challengerDamage;
challengerHeroHealth -= initiatorDamage;
if (initiatorHeroHealth <= 0 || challengerHeroHealth <= 0) {
break;
}
}
if (initiatorHeroHealth > challengerHeroHealth) {
_challenge.challengeResult = challengeResultEnum.INITIATOR_WIN;
} else if (challengerHeroHealth > initiatorHeroHealth) {
_challenge.challengeResult = challengeResultEnum.CHALLENGER_WIN;
} else {
_challenge.challengeResult = challengeResultEnum.DRAFT;
}
}
function getHero(uint id) private view returns (uint) {
uint cardTypeId;
(cardTypeId, ,) = cards.cards(id);
uint heroHealth;
(heroHealth) = cardTypes.getHero(cardTypeId);
return heroHealth;
}
function getCard(uint id) public view returns (uint, uint) {
uint actionId;
(actionId, ,) = cards.cards(id);
return cardTypes.getAction(actionId);
}
function getResult(uint id) public view returns (challengeResultEnum) {
return challenges[id].challengeResult;
}
function checkHash(bytes32 initiatorCardsHash, uint initiatorHero, uint[cardAmount] initiatorCards, string salt) private pure {
string memory cardIds = Convert.uintConcat(initiatorCards[0], initiatorCards[1], initiatorCards[2],
initiatorCards[3],initiatorCards[4]);
bytes32 cardsHash = keccak256(Convert.uint2str(initiatorHero), cardIds, salt);
require(initiatorCardsHash == cardsHash);
}
}
| require(_challenge.initiator != msg.sender); | function accept(uint id, uint hero, uint[cardAmount] _cards) public {
Challenge storage _challenge = challenges[id];
require(_challenge.challenger == address(0));
_challenge.challenger = msg.sender;
_challenge.challengerHero = hero;
_challenge.challengerCards = _cards;
}
| 12,734,730 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.6.8;
import "./ProtoBufRuntime.sol";
import "./GoogleProtobufAny.sol";
import "./Types.sol";
import "./Validator.sol";
import "./Proofs.sol";
import "./Commitment.sol";
library ClientState {
//struct definition
struct Data {
string chain_id;
Fraction.Data trust_level;
int64 trusting_period;
int64 unbonding_period;
int64 max_clock_drift;
Height.Data latest_height;
ProofSpec.Data[] proof_specs;
MerklePrefix.Data merkle_prefix;
uint64 time_delay;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[10] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_chain_id(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_trust_level(pointer, bs, r, counters);
}
else if (fieldId == 3) {
pointer += _read_trusting_period(pointer, bs, r, counters);
}
else if (fieldId == 4) {
pointer += _read_unbonding_period(pointer, bs, r, counters);
}
else if (fieldId == 5) {
pointer += _read_max_clock_drift(pointer, bs, r, counters);
}
else if (fieldId == 6) {
pointer += _read_latest_height(pointer, bs, r, counters);
}
else if (fieldId == 7) {
pointer += _read_proof_specs(pointer, bs, nil(), counters);
}
else if (fieldId == 8) {
pointer += _read_merkle_prefix(pointer, bs, r, counters);
}
else if (fieldId == 9) {
pointer += _read_time_delay(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
pointer = offset;
r.proof_specs = new ProofSpec.Data[](counters[7]);
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_chain_id(pointer, bs, nil(), counters);
}
else if (fieldId == 2) {
pointer += _read_trust_level(pointer, bs, nil(), counters);
}
else if (fieldId == 3) {
pointer += _read_trusting_period(pointer, bs, nil(), counters);
}
else if (fieldId == 4) {
pointer += _read_unbonding_period(pointer, bs, nil(), counters);
}
else if (fieldId == 5) {
pointer += _read_max_clock_drift(pointer, bs, nil(), counters);
}
else if (fieldId == 6) {
pointer += _read_latest_height(pointer, bs, nil(), counters);
}
else if (fieldId == 7) {
pointer += _read_proof_specs(pointer, bs, r, counters);
}
else if (fieldId == 8) {
pointer += _read_merkle_prefix(pointer, bs, nil(), counters);
}
else if (fieldId == 9) {
pointer += _read_time_delay(pointer, bs, nil(), counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_chain_id(
uint256 p,
bytes memory bs,
Data memory r,
uint[10] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(string memory x, uint256 sz) = ProtoBufRuntime._decode_string(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.chain_id = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_trust_level(
uint256 p,
bytes memory bs,
Data memory r,
uint[10] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(Fraction.Data memory x, uint256 sz) = _decode_Fraction(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.trust_level = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_trusting_period(
uint256 p,
bytes memory bs,
Data memory r,
uint[10] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs);
if (isNil(r)) {
counters[3] += 1;
} else {
r.trusting_period = x;
if (counters[3] > 0) counters[3] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_unbonding_period(
uint256 p,
bytes memory bs,
Data memory r,
uint[10] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs);
if (isNil(r)) {
counters[4] += 1;
} else {
r.unbonding_period = x;
if (counters[4] > 0) counters[4] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_max_clock_drift(
uint256 p,
bytes memory bs,
Data memory r,
uint[10] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs);
if (isNil(r)) {
counters[5] += 1;
} else {
r.max_clock_drift = x;
if (counters[5] > 0) counters[5] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_latest_height(
uint256 p,
bytes memory bs,
Data memory r,
uint[10] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(Height.Data memory x, uint256 sz) = _decode_Height(p, bs);
if (isNil(r)) {
counters[6] += 1;
} else {
r.latest_height = x;
if (counters[6] > 0) counters[6] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_proof_specs(
uint256 p,
bytes memory bs,
Data memory r,
uint[10] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(ProofSpec.Data memory x, uint256 sz) = _decode_ProofSpec(p, bs);
if (isNil(r)) {
counters[7] += 1;
} else {
r.proof_specs[r.proof_specs.length - counters[7]] = x;
if (counters[7] > 0) counters[7] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_merkle_prefix(
uint256 p,
bytes memory bs,
Data memory r,
uint[10] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(MerklePrefix.Data memory x, uint256 sz) = _decode_MerklePrefix(p, bs);
if (isNil(r)) {
counters[8] += 1;
} else {
r.merkle_prefix = x;
if (counters[8] > 0) counters[8] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_time_delay(
uint256 p,
bytes memory bs,
Data memory r,
uint[10] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs);
if (isNil(r)) {
counters[9] += 1;
} else {
r.time_delay = x;
if (counters[9] > 0) counters[9] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_Fraction(uint256 p, bytes memory bs)
internal
pure
returns (Fraction.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(Fraction.Data memory r, ) = Fraction._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_Height(uint256 p, bytes memory bs)
internal
pure
returns (Height.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(Height.Data memory r, ) = Height._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_ProofSpec(uint256 p, bytes memory bs)
internal
pure
returns (ProofSpec.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(ProofSpec.Data memory r, ) = ProofSpec._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_MerklePrefix(uint256 p, bytes memory bs)
internal
pure
returns (MerklePrefix.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(MerklePrefix.Data memory r, ) = MerklePrefix._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
uint256 i;
if (bytes(r.chain_id).length != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_string(r.chain_id, pointer, bs);
}
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += Fraction._encode_nested(r.trust_level, pointer, bs);
if (r.trusting_period != 0) {
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_int64(r.trusting_period, pointer, bs);
}
if (r.unbonding_period != 0) {
pointer += ProtoBufRuntime._encode_key(
4,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_int64(r.unbonding_period, pointer, bs);
}
if (r.max_clock_drift != 0) {
pointer += ProtoBufRuntime._encode_key(
5,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_int64(r.max_clock_drift, pointer, bs);
}
pointer += ProtoBufRuntime._encode_key(
6,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += Height._encode_nested(r.latest_height, pointer, bs);
if (r.proof_specs.length != 0) {
for(i = 0; i < r.proof_specs.length; i++) {
pointer += ProtoBufRuntime._encode_key(
7,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs)
;
pointer += ProofSpec._encode_nested(r.proof_specs[i], pointer, bs);
}
}
pointer += ProtoBufRuntime._encode_key(
8,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += MerklePrefix._encode_nested(r.merkle_prefix, pointer, bs);
if (r.time_delay != 0) {
pointer += ProtoBufRuntime._encode_key(
9,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_uint64(r.time_delay, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;uint256 i;
e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.chain_id).length);
e += 1 + ProtoBufRuntime._sz_lendelim(Fraction._estimate(r.trust_level));
e += 1 + ProtoBufRuntime._sz_int64(r.trusting_period);
e += 1 + ProtoBufRuntime._sz_int64(r.unbonding_period);
e += 1 + ProtoBufRuntime._sz_int64(r.max_clock_drift);
e += 1 + ProtoBufRuntime._sz_lendelim(Height._estimate(r.latest_height));
for(i = 0; i < r.proof_specs.length; i++) {
e += 1 + ProtoBufRuntime._sz_lendelim(ProofSpec._estimate(r.proof_specs[i]));
}
e += 1 + ProtoBufRuntime._sz_lendelim(MerklePrefix._estimate(r.merkle_prefix));
e += 1 + ProtoBufRuntime._sz_uint64(r.time_delay);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (bytes(r.chain_id).length != 0) {
return false;
}
if (r.trusting_period != 0) {
return false;
}
if (r.unbonding_period != 0) {
return false;
}
if (r.max_clock_drift != 0) {
return false;
}
if (r.proof_specs.length != 0) {
return false;
}
if (r.time_delay != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.chain_id = input.chain_id;
Fraction.store(input.trust_level, output.trust_level);
output.trusting_period = input.trusting_period;
output.unbonding_period = input.unbonding_period;
output.max_clock_drift = input.max_clock_drift;
Height.store(input.latest_height, output.latest_height);
for(uint256 i7 = 0; i7 < input.proof_specs.length; i7++) {
output.proof_specs.push(input.proof_specs[i7]);
}
MerklePrefix.store(input.merkle_prefix, output.merkle_prefix);
output.time_delay = input.time_delay;
}
//array helpers for ProofSpecs
/**
* @dev Add value to an array
* @param self The in-memory struct
* @param value The value to add
*/
function addProofSpecs(Data memory self, ProofSpec.Data memory value) internal pure {
/**
* First resize the array. Then add the new element to the end.
*/
ProofSpec.Data[] memory tmp = new ProofSpec.Data[](self.proof_specs.length + 1);
for (uint256 i = 0; i < self.proof_specs.length; i++) {
tmp[i] = self.proof_specs[i];
}
tmp[self.proof_specs.length] = value;
self.proof_specs = tmp;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library ClientState
library ConsensusState {
//struct definition
struct Data {
Timestamp.Data timestamp;
bytes root;
bytes next_validators_hash;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[4] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_timestamp(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_root(pointer, bs, r, counters);
}
else if (fieldId == 3) {
pointer += _read_next_validators_hash(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_timestamp(
uint256 p,
bytes memory bs,
Data memory r,
uint[4] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(Timestamp.Data memory x, uint256 sz) = _decode_Timestamp(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.timestamp = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_root(
uint256 p,
bytes memory bs,
Data memory r,
uint[4] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.root = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_next_validators_hash(
uint256 p,
bytes memory bs,
Data memory r,
uint[4] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs);
if (isNil(r)) {
counters[3] += 1;
} else {
r.next_validators_hash = x;
if (counters[3] > 0) counters[3] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_Timestamp(uint256 p, bytes memory bs)
internal
pure
returns (Timestamp.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(Timestamp.Data memory r, ) = Timestamp._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += Timestamp._encode_nested(r.timestamp, pointer, bs);
if (r.root.length != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.root, pointer, bs);
}
if (r.next_validators_hash.length != 0) {
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bytes(r.next_validators_hash, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_lendelim(Timestamp._estimate(r.timestamp));
e += 1 + ProtoBufRuntime._sz_lendelim(r.root.length);
e += 1 + ProtoBufRuntime._sz_lendelim(r.next_validators_hash.length);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.root.length != 0) {
return false;
}
if (r.next_validators_hash.length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
Timestamp.store(input.timestamp, output.timestamp);
output.root = input.root;
output.next_validators_hash = input.next_validators_hash;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library ConsensusState
library Header {
//struct definition
struct Data {
SignedHeader.Data signed_header;
ValidatorSet.Data validator_set;
Height.Data trusted_height;
ValidatorSet.Data trusted_validators;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[5] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_signed_header(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_validator_set(pointer, bs, r, counters);
}
else if (fieldId == 3) {
pointer += _read_trusted_height(pointer, bs, r, counters);
}
else if (fieldId == 4) {
pointer += _read_trusted_validators(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_signed_header(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(SignedHeader.Data memory x, uint256 sz) = _decode_SignedHeader(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.signed_header = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_validator_set(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(ValidatorSet.Data memory x, uint256 sz) = _decode_ValidatorSet(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.validator_set = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_trusted_height(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(Height.Data memory x, uint256 sz) = _decode_Height(p, bs);
if (isNil(r)) {
counters[3] += 1;
} else {
r.trusted_height = x;
if (counters[3] > 0) counters[3] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_trusted_validators(
uint256 p,
bytes memory bs,
Data memory r,
uint[5] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(ValidatorSet.Data memory x, uint256 sz) = _decode_ValidatorSet(p, bs);
if (isNil(r)) {
counters[4] += 1;
} else {
r.trusted_validators = x;
if (counters[4] > 0) counters[4] -= 1;
}
return sz;
}
// struct decoder
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_SignedHeader(uint256 p, bytes memory bs)
internal
pure
returns (SignedHeader.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(SignedHeader.Data memory r, ) = SignedHeader._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_ValidatorSet(uint256 p, bytes memory bs)
internal
pure
returns (ValidatorSet.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(ValidatorSet.Data memory r, ) = ValidatorSet._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
/**
* @dev The decoder for reading a inner struct field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The decoded inner-struct
* @return The number of bytes used to decode
*/
function _decode_Height(uint256 p, bytes memory bs)
internal
pure
returns (Height.Data memory, uint)
{
uint256 pointer = p;
(uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += bytesRead;
(Height.Data memory r, ) = Height._decode(pointer, bs, sz);
return (r, sz + bytesRead);
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += SignedHeader._encode_nested(r.signed_header, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ValidatorSet._encode_nested(r.validator_set, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += Height._encode_nested(r.trusted_height, pointer, bs);
pointer += ProtoBufRuntime._encode_key(
4,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ValidatorSet._encode_nested(r.trusted_validators, pointer, bs);
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_lendelim(SignedHeader._estimate(r.signed_header));
e += 1 + ProtoBufRuntime._sz_lendelim(ValidatorSet._estimate(r.validator_set));
e += 1 + ProtoBufRuntime._sz_lendelim(Height._estimate(r.trusted_height));
e += 1 + ProtoBufRuntime._sz_lendelim(ValidatorSet._estimate(r.trusted_validators));
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
SignedHeader.store(input.signed_header, output.signed_header);
ValidatorSet.store(input.validator_set, output.validator_set);
Height.store(input.trusted_height, output.trusted_height);
ValidatorSet.store(input.trusted_validators, output.trusted_validators);
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library Header
library Fraction {
//struct definition
struct Data {
uint64 numerator;
uint64 denominator;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[3] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_numerator(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_denominator(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_numerator(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.numerator = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_denominator(
uint256 p,
bytes memory bs,
Data memory r,
uint[3] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.denominator = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
if (r.numerator != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_uint64(r.numerator, pointer, bs);
}
if (r.denominator != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_uint64(r.denominator, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_uint64(r.numerator);
e += 1 + ProtoBufRuntime._sz_uint64(r.denominator);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (r.numerator != 0) {
return false;
}
if (r.denominator != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.numerator = input.numerator;
output.denominator = input.denominator;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library Fraction | The decoder for reading a field p The offset of bytes array to start decode bs The bytes array to be decoded r The in-memory struct counters The counters for repeated fields return The number of bytes decoded/ if `r` is NULL, then only counting the number of fields./ | function _read_time_delay(
uint256 p,
bytes memory bs,
Data memory r,
uint[10] memory counters
) internal pure returns (uint) {
(uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs);
if (isNil(r)) {
counters[9] += 1;
r.time_delay = x;
if (counters[9] > 0) counters[9] -= 1;
}
return sz;
}
| 5,547,561 |
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.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);
}
/**
* @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 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;
}
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
* @dev Handles the receipt of a single ERC1155 token type. This function is
* called at the end of a `safeTransferFrom` after the balance has been updated.
*
* NOTE: To accept the transfer, this must return
* `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* (i.e. 0xf23a6e61, or its own function selector).
*
* @param operator The address which initiated the transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param id The ID of the token being transferred
* @param value The amount of tokens being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
* @dev Handles the receipt of a multiple ERC1155 token types. This function
* is called at the end of a `safeBatchTransferFrom` after the balances have
* been updated.
*
* NOTE: To accept the transfer(s), this must return
* `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* (i.e. 0xbc197c81, or its own function selector).
*
* @param operator The address which initiated the batch transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param ids An array containing ids of each token being transferred (order and length must match values array)
* @param values An array containing amounts of each token being transferred (order and length must match ids array)
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @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 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 Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI, Ownable {
using Address for address;
using Strings for uint256;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
contract NafstarsAvatarsNFT is ERC1155("https://nafstars.nft4all.com/metadata/avatars/presale/{id}.json") {
uint256 public mintPrice = 0.15 ether;
uint256 public supplyCount = 0;
uint256 public supplyMax = 500;
address public withdrawAddress;
string public name = "Nafstars Avatars NFT";
string public symbol = "NAVATARS";
function setURI(string memory newURI) public virtual onlyOwner {
_setURI(newURI);
}
function setMintPrice(uint256 mintPrice_) public onlyOwner {
mintPrice = mintPrice_;
}
function setWithdrawAddress(address withdrawAddress_) public onlyOwner {
withdrawAddress = withdrawAddress_;
}
function mint(address to) public payable {
require(supplyCount + 1 <= supplyMax, "Supply reached.");
if (_msgSender() != owner()) {
require(msg.value >= mintPrice, "Insufficient funds.");
}
supplyCount = supplyCount + 1;
_mint(to, 1, 1, "");
}
function batchMint(address to, uint256 amount) public payable {
require(amount > 0, "Invalid amount.");
require(supplyCount + amount <= supplyMax, "Supply reached.");
if (_msgSender() != owner()) {
require(msg.value >= mintPrice * amount, "Insufficient funds.");
}
supplyCount = supplyCount + amount;
_mint(to, 1, amount, "");
}
function withdraw() external payable {
require(_msgSender() == owner() || _msgSender() == withdrawAddress, "Ownable: caller not authorized");
(bool payment, ) = payable(withdrawAddress).call{value: address(this).balance}("");
require(payment);
}
} | xref:ROOT:erc1155.adocbatch-operations[Batched] version of {_safeTransferFrom}. Emits a {TransferBatch} event. Requirements: - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the acceptance magic value./ | function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
| 5,879,056 |
pragma solidity 0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
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 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) {
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.
*/
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 Based on the 'final' ERC20 token standard as specified at:
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
*/
contract ERC20Interface {
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function name() public view returns (string);
function symbol() public view returns (string);
function decimals() public view returns (uint8);
function totalSupply() public view returns (uint256);
function balanceOf(address _owner) public view returns (uint256);
function allowance(address _owner, address _spender) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
}
/**
* @title TestToken
* @dev The TestToken contract provides the token functionality of the IPT Global token
* and allows the admin to distribute frozen tokens which requires defrosting to become transferable.
*/
contract TestToken is ERC20Interface, Ownable {
using SafeMath for uint256;
//Name of the token.
string internal constant NAME = "Test Token";
//Symbol of the token.
string internal constant SYMBOL = "TEST";
//Granularity of the token.
uint8 internal constant DECIMALS = 8;
//Factor for numerical calculations.
uint256 internal constant DECIMALFACTOR = 10 ** uint(DECIMALS);
//Total supply of IPT Global tokens.
uint256 internal constant TOTAL_SUPPLY = 300000000 * uint256(DECIMALFACTOR);
//Base defrosting value used to calculate fractional percentage of 0.2 %
uint8 internal constant standardDefrostingValue = 2;
//Base defrosting numerator used to calculate fractional percentage of 0.2 %
uint8 internal constant standardDefrostingNumerator = 10;
//Stores all frozen TEST Global token holders.
mapping(address => bool) public frostbite;
//Stores received frozen IPT Global tokens in an accumulated fashion.
mapping(address => uint256) public frozenTokensReceived;
//Stores and tracks frozen IPT Global token balances.
mapping(address => uint256) public frozenBalance;
//Stores custom frozen IPT Global token defrosting % rates.
mapping(address => uint8) public customDefrostingRate;
//Stores the balance of IPT Global holders (complies with ERC-Standard).
mapping(address => uint256) internal balances;
//Stores any allowances given to other IPT Global holders.
mapping(address => mapping(address => uint256)) internal allowed;
//Event which allows for logging of frostbite granting activities.
event FrostbiteGranted(
address recipient,
uint256 frozenAmount,
uint256 defrostingRate);
//Event which allows for logging of frostbite terminating activities.
event FrostBiteTerminated(
address recipient,
uint256 frozenBalance);
//Event which allows for logging of frozen token transfer activities.
event FrozenTokensTransferred(
address owner,
address recipient,
uint256 frozenAmount,
uint256 defrostingRate);
//Event which allows for logging of custom frozen token defrosting activities.
event CustomTokenDefrosting(
address owner,
uint256 percentage,
uint256 defrostedAmount);
//Event which allows for logging of calculated frozen token defrosting activities.
event CalculatedTokenDefrosting(
address owner,
uint256 defrostedAmount);
//Event which allows for logging of complete recipient recovery activities.
event RecipientRecovered(
address recipient,
uint256 customDefrostingRate,
uint256 frozenBalance,
bool frostbite);
//Event which allows for logging of recipient balance recovery activities.
event FrozenBalanceDefrosted(
address recipient,
uint256 frozenBalance,
bool frostbite);
//Event which allows for logging of defrostingrate-adjusting activities.
event DefrostingRateChanged(
address recipient,
uint256 defrostingRate);
//Event which allows for logging of frozenBalance-adjusting activities.
event FrozenBalanceChanged(
address recipient,
uint256 defrostedAmount);
/**
* @dev constructor sets initialises and configurates the smart contract.
* More specifically, it grants the smart contract owner the total supply
* of IPT Global tokens.
*/
constructor() public {
balances[msg.sender] = TOTAL_SUPPLY;
}
/**
* @dev frozenTokenTransfer function allows the owner of the smart contract to Transfer
* frozen tokens (untransferable till melted) to a particular recipient.
* @param _recipient the address which will receive the frozen tokens.
* @param _frozenAmount the value which will be sent to the _recipient.
* @param _customDefrostingRate the rate at which the tokens will be melted.
* @return a boolean representing whether the function was executed succesfully.
*/
function frozenTokenTransfer(address _recipient, uint256 _frozenAmount, uint8 _customDefrostingRate) external onlyOwner returns (bool) {
require(_recipient != address(0));
require(_frozenAmount <= balances[msg.sender]);
frozenTokensReceived[_recipient] = _frozenAmount;
frozenBalance[_recipient] = _frozenAmount;
customDefrostingRate[_recipient] = _customDefrostingRate;
frostbite[_recipient] = true;
balances[msg.sender] = balances[msg.sender].sub(_frozenAmount);
balances[_recipient] = balances[_recipient].add(_frozenAmount);
emit FrozenTokensTransferred(msg.sender, _recipient, _frozenAmount, customDefrostingRate[_recipient]);
return true;
}
/**
* @dev changeCustomDefrostingRate function allows the owner of the smart contract to change individual custom defrosting rates.
* @param _recipient the address whose defrostingRate will be adjusted.
* @param _newCustomDefrostingRate the new defrosting rate which will be placed on the recipient.
* @return a boolean representing whether the function was executed succesfully.
*/
function changeCustomDefrostingRate(address _recipient, uint8 _newCustomDefrostingRate) external onlyOwner returns (bool) {
require(_recipient != address(0));
require(frostbite[_recipient]);
customDefrostingRate[_recipient] = _newCustomDefrostingRate;
emit DefrostingRateChanged(_recipient, _newCustomDefrostingRate);
return true;
}
/**
* @dev changeFrozenBalance function allows the owner of the smart contract to change individual particular frozen balances.
* @param _recipient the address whose defrostingRate will be adjusted.
* @param _defrostedAmount the defrosted/subtracted amount of an existing particular frozen balance..
* @return a boolean representing whether the function was executed succesfully.
*/
function changeFrozenBalance(address _recipient, uint256 _defrostedAmount) external onlyOwner returns (bool) {
require(_recipient != address(0));
require(_defrostedAmount <= frozenBalance[_recipient]);
require(frostbite[_recipient]);
frozenBalance[_recipient] = frozenBalance[_recipient].sub(_defrostedAmount);
emit FrozenBalanceChanged(_recipient, _defrostedAmount);
return true;
}
/**
* @dev removeFrozenTokenConfigurations function allows the owner of the smart contract to remove all
* frostbites, frozenbalances and defrosting rates of an array of recipient addresses < 50.
* @param _recipients the address(es) which will be recovered.
* @return a boolean representing whether the function was executed succesfully.
*/
function removeFrozenTokenConfigurations(address[] _recipients) external onlyOwner returns (bool) {
for (uint256 i = 0; i < _recipients.length; i++) {
if (frostbite[_recipients[i]]) {
customDefrostingRate[_recipients[i]] = 0;
frozenBalance[_recipients[i]] = 0;
frostbite[_recipients[i]] = false;
emit RecipientRecovered(_recipients[i], customDefrostingRate[_recipients[i]], frozenBalance[_recipients[i]], false);
}
}
return true;
}
/**
* @dev standardTokenDefrosting function allows the owner of the smart contract to defrost
* frozen tokens based on a base defrosting Rate of 0.2 % (from multiple recipients at once if desired) of particular recipient addresses < 50.
* @param _recipients the address(es) which will receive defrosting of frozen tokens.
* @return a boolean representing whether the function was executed succesfully.
*/
function standardTokenDefrosting(address[] _recipients) external onlyOwner returns (bool) {
for (uint256 i = 0; i < _recipients.length; i++) {
if (frostbite[_recipients[i]]) {
uint256 defrostedAmount = (frozenTokensReceived[_recipients[i]].mul(standardDefrostingValue).div(standardDefrostingNumerator)).div(100);
frozenBalance[_recipients[i]] = frozenBalance[_recipients[i]].sub(defrostedAmount);
emit CalculatedTokenDefrosting(msg.sender, defrostedAmount);
}
if (frozenBalance[_recipients[i]] == 0) {
frostbite[_recipients[i]] = false;
emit FrozenBalanceDefrosted(_recipients[i], frozenBalance[_recipients[i]], false);
}
}
return true;
}
/**
* @dev customTokenDefrosting function allows the owner of the smart contract to defrost
* frozen tokens based on custom defrosting Rates (from multiple recipients at once if desired) of particular recipient addresses < 50.
* @param _recipients the address(es) which will receive defrosting of frozen tokens.
* @return a boolean representing whether the function was executed succesfully.
*/
function customTokenDefrosting(address[] _recipients) external onlyOwner returns (bool) {
for (uint256 i = 0; i < _recipients.length; i++) {
if (frostbite[_recipients[i]]) {
uint256 defrostedAmount = (frozenTokensReceived[_recipients[i]].mul(customDefrostingRate[_recipients[i]])).div(100);
frozenBalance[_recipients[i]] = frozenBalance[_recipients[i]].sub(defrostedAmount);
emit CustomTokenDefrosting(msg.sender, customDefrostingRate[_recipients[i]], defrostedAmount);
}
if (frozenBalance[_recipients[i]] == 0) {
frostbite[_recipients[i]] = false;
emit FrozenBalanceDefrosted(_recipients[i], frozenBalance[_recipients[i]], false);
}
}
return true;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
* @return a boolean representing whether the function was executed succesfully.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
if (frostbite[msg.sender]) {
require(_value <= balances[msg.sender].sub(frozenBalance[msg.sender]));
}
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev 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
* @return a boolean representing whether the function was executed succesfully.
*/
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]);
if (frostbite[_from]) {
require(_value <= balances[_from].sub(frozenBalance[_from]));
require(_value <= allowed[_from][msg.sender]);
}
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
* @return a boolean representing whether the function was executed succesfully.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev balanceOf function gets the balance of the specified address.
* @param _owner The address to query the balance of.
* @return An uint256 representing the token balance of the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
/**
* @dev allowance function checks the amount of tokens allowed by an owner for a spender to spend.
* @param _owner address is the address which owns the spendable funds.
* @param _spender address is the address which will spend the owned funds.
* @return A uint256 specifying the amount of tokens which are still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev totalSupply function returns the total supply of tokens.
*/
function totalSupply() public view returns (uint256) {
return TOTAL_SUPPLY;
}
/**
* @dev decimals function returns the decimal units of the token.
*/
function decimals() public view returns (uint8) {
return DECIMALS;
}
/**
* @dev symbol function returns the symbol ticker of the token.
*/
function symbol() public view returns (string) {
return SYMBOL;
}
/**
* @dev name function returns the name of the token.
*/
function name() public view returns (string) {
return NAME;
}
} | totalSupply function returns the total supply of tokens./ | function totalSupply() public view returns (uint256) {
return TOTAL_SUPPLY;
}
| 8,052,369 |
./full_match/4/0x19D59Ea6A136Cc5Fd55e09b2Bacc745B2a0B4eE8/sources/contracts/interfaces/IProject.sol | MODIFIERS initialize this contract with required parameters. This is initialized by HomeFi contract modifier initializer _currency currency address for this project _sender address of the creator / builder for this project _homeFiAddress address of the HomeFi contract/ Contractor with fee schedule can be added to project nonReentrant _data bytes encoded from- - address _contractor: address of project contractor - uint256[] _phaseCosts: array where each element represent phase cost, length of this array is number of phase to be added - address _projectAddress this project address, for signature security/ update project ipfs hash with adequate signatures. If contractor is approved then both builder and contractor signature needed. Else only builder's. _data bytes encoded from- - bytes _hash bytes encoded ipfs hash. - uint256 _nonce current hashChangeNonce _signature bytes representing signature on _data by required members./ change order to add phases in project. signature of both builder and contractor required. modifier contractorAccepted. _data bytes encoded from- - uint256[] _phaseCosts array where each element represent phase cost, length of this array is number of phase to be added - uint256 _phaseCount current phase count, for signature security - address _projectAddress this project address, for signature security _signature bytes representing signature on _data by builder and contractor./ change order to change cost of existing phases. signature of both builder and contractor required. modifier contractorAccepted. _data bytes encoded from- - uint256[] _phaseList array of phase indexes that needs to be updated - uint256[] _phaseCosts cost that needs to be updated for each phase index in _phaseList - address _projectAddress this project address, for signature security _signature bytes representing signature on _data by builder and contractor./ release phase payment of a contractor modifier contractorAccepted _phaseID the phase index for which the payment needs to be released/ allows investing in the project, also funds 50 phase and tasks. If the project currency is ERC20 token, then before calling this function the sender must approve the tokens to this contract. If the project's currency is native, then user can also pay in the native currency by passing msg.value, it will be converted in to wrapped tokens internally can only be called by builder or community contract(via investor). _cost the cost that is needed to be invested/ Task-Specific adds tasks in a particular phase. Needs both builder and contractor signature. contractor must be approved. _data bytes encoded from- - uint256 _phaseID phase number in which tasks are added - bytes[] _hash bytes ipfs hash of task details - uint256[] _cost an array of cost for each task index - address[] _sc an array subcontractor address for each task index - uint256 _taskCount current task count before adding these tasks. Can be fetched by taskCount. For signature security. - address _projectAddress the address of this contract. For signature security. _signature bytes representing signature on _data by builder and contractor./ If subcontractor is approved then builder, contractor and subcontractor signature needed. Else only builder and contractor. update ipfs hash for a particular task _data bytes encoded from- - bytes[] _hash bytes ipfs hash of task details - uint256 _nonce current hashChangeNonce - uint256 _taskID task index _signature bytes representing signature on _data by required members./ invite subcontractors for existing tasks. This can be called by builder or contractor. this function internally calls _inviteSC. _taskList must not have a task which already has approved subcontractor. _taskList array the task index for which subcontractors needs to be assigned. _scList array of addresses of subcontractor for the respective task index./ invite subcontractors for a single task. This can be called by builder or contractor. invite subcontractors for a single task. This can be called by builder or contractor. _taskList must not have a task which already has approved subcontractor. _task uint256 task index _sc address addresses of subcontractor for the respective task _emitEvent whether to emit event for each sc added or not/ accept invite as subcontractor for a particular task. Only subcontractor invited can call this. subcontractor must be unapproved. _taskList the task list of indexes for which sender wants to accept invite./ mark a task a complete and release subcontractor payment. Needs builder,contractor and subcontractor signature. task must be in active state. _data bytes encoded from- - uint256 _taskID the index of task - address _projectAddress the address of this contract. For signature security. _signature bytes representing signature on _data by builder,contractor and subcontractor./ checks trustedForwarder on HomeFi contract _forwarder address of contract forwarding meta tx/ | function initialize(
address _currency,
address _sender,
address _homeFiAddress
) external virtual;
function inviteContractor(bytes calldata _data, bytes calldata _signature)
external
virtual;
function updateProjectHash(bytes calldata _data, bytes calldata _signature)
external
virtual;
function addPhasesGC(bytes calldata _data, bytes calldata _signature)
external
virtual;
function changeCostGC(bytes calldata _data, bytes calldata _signature)
external
virtual;
function releaseFeeContractor(uint256 _phaseID) external virtual;
function investInProject(uint256 _cost) external payable virtual;
function addTasks(bytes calldata _data, bytes calldata _signature)
external
virtual;
function updateTaskHash(bytes calldata _data, bytes calldata _signature)
external
virtual;
function inviteSC(uint256[] calldata _taskList, address[] calldata _scList)
external
virtual;
function _inviteSC(
uint256 _task,
address _sc,
bool _emitEvent
) internal virtual;
function acceptInviteSC(uint256[] calldata _taskList) external virtual;
function setComplete(bytes calldata _data, bytes calldata _signature)
external
virtual;
function isTrustedForwarder(address _forwarder)
public
view
override
returns (bool)
{
return homeFi.isTrustedForwarder(_forwarder);
}
| 671,252 |
pragma solidity ^0.4.15;
import "./AuctionInterface.sol";
/** @title GoodAuction */
contract GoodAuction is AuctionInterface {
/* New data structure, keeps track of refunds owed to ex-highest bidders */
mapping(address => uint) refunds;
/* Bid function, shifts to push paradigm
* Must return true on successful send and/or bid, bidder
* reassignment
* Must return false on failure and allow people to
* retrieve their funds
*/
function bid() payable external returns(bool) {
if (msg.value <= highestBid){
refunds[msg.sender] = msg.value;
return false;
}
if (highestBidder != 0){
refunds[highestBidder] = highestBid;
}
highestBidder = msg.sender;
highestBid = msg.value;
return true;
}
/* New withdraw function, shifts to push paradigm */
function withdrawRefund() external returns(bool) {
uint refund = refunds[msg.sender];
refunds[msg.sender] = 0;
if (!msg.sender.send(refund)){
refunds[msg.sender] = refund;
return false;
}
return true;
}
/* Allow users to check the amount they can withdraw */
function getMyBalance() constant external returns(uint) {
return refunds[msg.sender];
}
/* Give people their funds back */
function () payable {
revert();
}
} | New data structure, keeps track of refunds owed to ex-highest bidders / Bid function, shifts to push paradigm Must return true on successful send and/or bid, bidder reassignment Must return false on failure and allow people to retrieve their funds/ | function bid() payable external returns(bool) {
if (msg.value <= highestBid){
refunds[msg.sender] = msg.value;
return false;
}
if (highestBidder != 0){
refunds[highestBidder] = highestBid;
}
highestBidder = msg.sender;
highestBid = msg.value;
return true;
}
| 1,789,979 |
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/security/ReentrancyGuard.sol
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/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: contracts/0xCryptoPunks.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. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* Does not support burning tokens to address(0).
*
* Assumes that an owner cannot have more than the 2**128 - 1 (max value of uint128) of supply
*/
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 internal currentIndex = 9999;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) internal _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
function totalSupply() public view returns (uint256) {
return currentIndex;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), 'ERC721A: balance query for the zero address');
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(owner != address(0), 'ERC721A: number minted query for the zero address');
return uint256(_addressData[owner].numberMinted);
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/
function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
require(_exists(tokenId), 'ERC721A: owner query for nonexistent token');
unchecked {
for (uint256 curr = tokenId; curr >= 0; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
revert('ERC721A: unable to determine the owner of token');
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), 'ERC721Metadata: URI query for nonexistent token');
string memory baseURI = _baseURI();
return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : '';
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return '';
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, 'ERC721A: approval to current owner');
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
'ERC721A: approve caller is not owner nor approved for all'
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), 'ERC721A: approved query for nonexistent token');
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
require(operator != _msgSender(), 'ERC721A: approve to caller');
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, '');
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
'ERC721A: transfer to non ERC721Receiver implementer'
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return (tokenId <= currentIndex && tokenId > 9999) ;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, '');
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), 'ERC721A: mint to the zero address');
require(quantity != 0, 'ERC721A: quantity must be greater than 0');
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1
// updatedIndex overflows if currentIndex + quantity > 1.56e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint128(quantity);
_addressData[to].numberMinted += uint128(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
for (uint256 i; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
if (safe) {
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
'ERC721A: transfer to non ERC721Receiver implementer'
);
}
updatedIndex++;
}
currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(isApprovedOrOwner, 'ERC721A: transfer caller is not owner nor approved');
require(prevOwnership.addr == from, 'ERC721A: transfer from incorrect owner');
require(to != address(0), 'ERC721A: transfer to the zero address');
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert('ERC721A: transfer to non ERC721Receiver implementer');
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
pragma solidity ^0.8.4;
contract xCryptoPunks is ERC721A, Ownable, ReentrancyGuard {
using Strings for uint256;
uint256 public PRICE = 10000000000000000;
uint256 public MAX_SUPPLY = 19999;
uint256 public FREE_MINT_LIMIT_PER_WALLET = 5;
uint256 public MAX_MINT_AMOUNT_PER_TX = 5;
uint256 public FREE_MINT_IS_ALLOWED_UNTIL = 10002; // Free mint is allowed until x mint
bool public IS_SALE_ACTIVE = true;
bool public REVEALED = false;
bool public IS_ALLOW_LIST_ACTIVE = true;
string public URIPREFIX = "";
string public URISUFFIX = ".json";
string public HIDDENMETADATAURI = "";
mapping(address => uint8) private NUMBER_MINTS_FOR_WHITELIST;
mapping(address => uint256) private freeMintCountMap;
constructor()
ERC721A("0xCryptoPunks", "0xCP") {
setHiddenMetadataUri("ipfs://QmY3jckW4JoHJwj2CHXrEcPTAtQVtWGTbsYzf8Cm4t31TX/hidden.json");
}
/** White List **/
function setIsAllowListActive(bool _isAllowListActive) external onlyOwner {
IS_ALLOW_LIST_ACTIVE = _isAllowListActive;
}
function setAllowList(address[] calldata _addresses, uint8 _numAllowedToMint) external onlyOwner {
for (uint256 i = 0; i < _addresses.length; i++) {
NUMBER_MINTS_FOR_WHITELIST[_addresses[i]] = _numAllowedToMint;
}
}
function numAvailableToMint(address _address) external view returns (uint8) {
return NUMBER_MINTS_FOR_WHITELIST[_address];
}
function mintWhiteList(uint8 _mintAmount) external payable mintCompliance(_mintAmount) {
require(IS_ALLOW_LIST_ACTIVE, "Whitelist sale is not active!");
require(_mintAmount <= NUMBER_MINTS_FOR_WHITELIST[msg.sender], "Not are not able to mint or exceeded max available to purchase");
uint256 price = PRICE * _mintAmount;
if (currentIndex < FREE_MINT_IS_ALLOWED_UNTIL) {
uint256 remainingFreeMint = FREE_MINT_LIMIT_PER_WALLET - freeMintCountMap[msg.sender];
if (remainingFreeMint > 0) {
if (_mintAmount >= remainingFreeMint) {
price -= remainingFreeMint * PRICE;
updateFreeMintCount(msg.sender, remainingFreeMint);
} else {
price -= _mintAmount * PRICE;
updateFreeMintCount(msg.sender, _mintAmount);
}
}
}
NUMBER_MINTS_FOR_WHITELIST[msg.sender] -= _mintAmount;
require(msg.value >= price, "Insufficient funds!");
_safeMint(msg.sender, _mintAmount);
}
/** FREE MINT **/
function updateFreeMintCount(address minter, uint256 count) private {
freeMintCountMap[minter] += count;
}
/** GETTERS **/
function _baseURI() internal view virtual override returns (string memory) {
return URIPREFIX;
}
function tokenURI(uint256 _tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(_tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if (REVEALED == false) {
return HIDDENMETADATAURI;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), URISUFFIX))
: "";
}
/** SETTERS **/
function setPrice(uint256 customPrice) external onlyOwner {
PRICE = customPrice;
}
function setLowerMaxSupply(uint256 newMaxSupply) external onlyOwner {
require(newMaxSupply < MAX_SUPPLY, "Invalid new max supply");
require(newMaxSupply >= currentIndex, "Invalid new max supply");
MAX_SUPPLY = newMaxSupply;
}
function setFreeMintPerWallet(uint256 _setFreeMintPerWallet) external onlyOwner {
FREE_MINT_LIMIT_PER_WALLET = _setFreeMintPerWallet;
}
function setMaxMintPerTx(uint256 maxMintPerTx) external onlyOwner {
MAX_MINT_AMOUNT_PER_TX = maxMintPerTx;
}
function setSaleActive(bool saleIsActive) external onlyOwner {
IS_SALE_ACTIVE = saleIsActive;
}
function setFreeMintAllowedUntil(uint256 freeMintIsAllowedUntil) external onlyOwner {
FREE_MINT_IS_ALLOWED_UNTIL = freeMintIsAllowedUntil;
}
function setHiddenMetadataUri(string memory _hiddenMetadataUri) internal onlyOwner {
HIDDENMETADATAURI = _hiddenMetadataUri;
}
function setRevealed(bool _state) external onlyOwner {
string memory currentBaseURI = _baseURI();
require(bytes(currentBaseURI).length != 0, "Set the URIprefix before revealing the NFTs!");
REVEALED = _state;
}
function setUriPrefix(string memory _uriPrefix) external onlyOwner {
URIPREFIX = _uriPrefix;
}
function setUriSuffix(string memory _uriSuffix) external onlyOwner {
URISUFFIX = _uriSuffix;
}
/** MINT **/
modifier mintCompliance(uint256 _mintAmount) {
require(_mintAmount > 0 && _mintAmount <= MAX_MINT_AMOUNT_PER_TX, "Invalid mint amount!");
require(currentIndex + _mintAmount <= MAX_SUPPLY, "Max supply exceeded!");
_;
}
function mint(uint256 _mintAmount) external payable mintCompliance(_mintAmount) {
require(IS_SALE_ACTIVE, "Sale is not active!");
uint256 price = PRICE * _mintAmount;
if (currentIndex < FREE_MINT_IS_ALLOWED_UNTIL) {
uint256 remainingFreeMint = FREE_MINT_LIMIT_PER_WALLET - freeMintCountMap[msg.sender];
if (remainingFreeMint > 0) {
if (_mintAmount >= remainingFreeMint) {
price -= remainingFreeMint * PRICE;
updateFreeMintCount(msg.sender, remainingFreeMint);
} else {
price -= _mintAmount * PRICE;
updateFreeMintCount(msg.sender, _mintAmount);
}
}
}
require(msg.value >= price, "Insufficient funds!");
_safeMint(msg.sender, _mintAmount);
}
function mintOwner(address _to, uint256 _mintAmount) external mintCompliance(_mintAmount) onlyOwner {
_safeMint(_to, _mintAmount);
}
function withdraw() external onlyOwner nonReentrant {
// Transfer balance to the owner.
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
require(os, "Transfer failed.");
}
} | See {IERC721-balanceOf}./ | function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), 'ERC721A: balance query for the zero address');
return uint256(_addressData[owner].balance);
}
| 14,565,524 |
pragma solidity ^0.5.12;
library SafeMath {
function MUL98(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a == 0)
return 0;
uint256 c = a * b;
require(c / a == b);
return c;
}
function DIV107(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0);
uint256 c = a / b;
return c;
}
function SUB705(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a);
uint256 c = a - b;
return c;
}
function ADD235(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a);
return c;
}
function MOD157(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0);
return a % b;
}
}
contract ERC20 {
using SafeMath for uint256;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) internal _allowed;
event TRANSFER731(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL787(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
uint256 internal _totalSupply;
function TOTALSUPPLY882() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF767(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[owner];
}
function ALLOWANCE10(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowed[owner][spender];
}
function TRANSFER204(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER522(msg.sender, to, value);
return true;
}
function APPROVE277(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_allowed[msg.sender][spender] = value;
emit APPROVAL787(msg.sender, spender, value);
return true;
}
function TRANSFERFROM832(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER522(from, to, value);
_allowed[msg.sender][to] = _allowed[msg.sender][to].SUB705(value);
return true;
}
function _TRANSFER522(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
require(to != address(0));
_balances[from] = _balances[from].SUB705(value);
_balances[to] = _balances[to].ADD235(value);
emit TRANSFER731(from, to, value);
}
}
contract ERC20Mintable is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
function _MINT321(address to, uint256 amount) internal { //inject NONSTANDARD NAMING
_balances[to] = _balances[to].ADD235(amount);
_totalSupply = _totalSupply.ADD235(amount);
emit TRANSFER731(address(0), to, amount);
}
function _BURN441(address from, uint256 amount) internal { //inject NONSTANDARD NAMING
_balances[from] = _balances[from].SUB705(amount);
_totalSupply = _totalSupply.SUB705(amount);
emit TRANSFER731(from, address(0), amount);
}
}
// ----------- Aave ----------------
contract ILendingPoolAddressesProvider {
function GETLENDINGPOOL38() public view returns (address); //inject NONSTANDARD NAMING
function SETLENDINGPOOLIMPL881(address _pool) public; //inject NONSTANDARD NAMING
function GETLENDINGPOOLCORE21() public view returns (address payable); //inject NONSTANDARD NAMING
function SETLENDINGPOOLCOREIMPL156(address _lendingPoolCore) public; //inject NONSTANDARD NAMING
function GETLENDINGPOOLCONFIGURATOR254() public view returns (address); //inject NONSTANDARD NAMING
function SETLENDINGPOOLCONFIGURATORIMPL555(address _configurator) public; //inject NONSTANDARD NAMING
function GETLENDINGPOOLDATAPROVIDER61() public view returns (address); //inject NONSTANDARD NAMING
function SETLENDINGPOOLDATAPROVIDERIMPL193(address _provider) public; //inject NONSTANDARD NAMING
function GETLENDINGPOOLPARAMETERSPROVIDER362() public view returns (address); //inject NONSTANDARD NAMING
function SETLENDINGPOOLPARAMETERSPROVIDERIMPL978(address _parametersProvider) public; //inject NONSTANDARD NAMING
function GETTOKENDISTRIBUTOR827() public view returns (address); //inject NONSTANDARD NAMING
function SETTOKENDISTRIBUTOR348(address _tokenDistributor) public; //inject NONSTANDARD NAMING
function GETFEEPROVIDER168() public view returns (address); //inject NONSTANDARD NAMING
function SETFEEPROVIDERIMPL718(address _feeProvider) public; //inject NONSTANDARD NAMING
function GETLENDINGPOOLLIQUIDATIONMANAGER82() public view returns (address); //inject NONSTANDARD NAMING
function SETLENDINGPOOLLIQUIDATIONMANAGER708(address _manager) public; //inject NONSTANDARD NAMING
function GETLENDINGPOOLMANAGER762() public view returns (address); //inject NONSTANDARD NAMING
function SETLENDINGPOOLMANAGER882(address _lendingPoolManager) public; //inject NONSTANDARD NAMING
function GETPRICEORACLE485() public view returns (address); //inject NONSTANDARD NAMING
function SETPRICEORACLE428(address _priceOracle) public; //inject NONSTANDARD NAMING
function GETLENDINGRATEORACLE592() public view returns (address); //inject NONSTANDARD NAMING
function SETLENDINGRATEORACLE655(address _lendingRateOracle) public; //inject NONSTANDARD NAMING
}
interface ILendingPool {
function ADDRESSESPROVIDER344() external view returns(address); //inject NONSTANDARD NAMING
function DEPOSIT818(address _reserve, uint256 _amount, uint16 _referralCode) external payable; //inject NONSTANDARD NAMING
function REDEEMUNDERLYING805(address _reserve, address _user, uint256 _amount) external; //inject NONSTANDARD NAMING
function BORROW264(address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode) external; //inject NONSTANDARD NAMING
function REPAY662(address _reserve, uint256 _amount, address _onBehalfOf) external payable; //inject NONSTANDARD NAMING
function SWAPBORROWRATEMODE766(address _reserve) external; //inject NONSTANDARD NAMING
function REBALANCEFIXEDBORROWRATE627(address _reserve, address _user) external; //inject NONSTANDARD NAMING
function SETUSERUSERESERVEASCOLLATERAL986(address _reserve, bool _useAsCollateral) external; //inject NONSTANDARD NAMING
function LIQUIDATIONCALL807(address _collateral, address _reserve, address _user, uint256 _purchaseAmount, bool _receiveAToken) external payable; //inject NONSTANDARD NAMING
function FLASHLOAN206(address _receiver, address _reserve, uint256 _amount, bytes calldata _params) external; //inject NONSTANDARD NAMING
function GETRESERVECONFIGURATIONDATA59(address _reserve) external view returns(uint256 ltv, uint256 liquidationThreshold, uint256 liquidationDiscount, address interestRateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool fixedBorrowRateEnabled, bool isActive); //inject NONSTANDARD NAMING
function GETRESERVEDATA692(address _reserve) external view returns(uint256 totalLiquidity, uint256 availableLiquidity, uint256 totalBorrowsFixed, uint256 totalBorrowsVariable, uint256 liquidityRate, uint256 variableBorrowRate, uint256 fixedBorrowRate, uint256 averageFixedBorrowRate, uint256 utilizationRate, uint256 liquidityIndex, uint256 variableBorrowIndex, address aTokenAddress, uint40 lastUpdateTimestamp); //inject NONSTANDARD NAMING
function GETUSERACCOUNTDATA811(address _user) external view returns(uint256 totalLiquidityETH, uint256 totalCollateralETH, uint256 totalBorrowsETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor); //inject NONSTANDARD NAMING
function GETUSERRESERVEDATA732(address _reserve, address _user) external view returns(uint256 currentATokenBalance, uint256 currentBorrowBalance, uint256 principalBorrowBalance, uint256 borrowRateMode, uint256 borrowRate, uint256 liquidityRate, uint256 originationFee, uint256 variableBorrowIndex, uint256 lastUpdateTimestamp, bool usageAsCollateralEnabled); //inject NONSTANDARD NAMING
function GETRESERVES689() external view; //inject NONSTANDARD NAMING
}
interface ILendingPoolCore {
function GETRESERVEATOKENADDRESS314(address _reserve) external view returns (address); //inject NONSTANDARD NAMING
function GETRESERVECURRENTVARIABLEBORROWRATE762(address _token) external view returns (uint256); //inject NONSTANDARD NAMING
function GETRESERVECURRENTLIQUIDITYRATE636(address _token) external view returns (uint256); //inject NONSTANDARD NAMING
}
interface IAavePriceOracleGetter {
function GETASSETPRICE734(address _asset) external view returns (uint256); //inject NONSTANDARD NAMING
function GETASSETSPRICES996(address[] calldata _assets) external view returns(uint256[] memory); //inject NONSTANDARD NAMING
function GETSOURCEOFASSET324(address _asset) external view returns(address); //inject NONSTANDARD NAMING
function GETFALLBACKORACLE535() external view returns(address); //inject NONSTANDARD NAMING
}
interface IAToken {
function REDIRECTINTERESTSTREAM242(address _to) external; //inject NONSTANDARD NAMING
function REDIRECTINTERESTSTREAMOF292(address _from, address _to) external; //inject NONSTANDARD NAMING
function ALLOWINTERESTREDIRECTIONTO292(address _to) external; //inject NONSTANDARD NAMING
function REDEEM632(uint256 _amount) external; //inject NONSTANDARD NAMING
function PRINCIPALBALANCEOF100(address _user) external view returns(uint256); //inject NONSTANDARD NAMING
function ISTRANSFERALLOWED396(address _user, uint256 _amount) external view returns (bool); //inject NONSTANDARD NAMING
function GETUSERINDEX768(address _user) external view returns(uint256); //inject NONSTANDARD NAMING
function GETINTERESTREDIRECTIONADDRESS228(address _user) external view returns(address); //inject NONSTANDARD NAMING
function GETREDIRECTEDBALANCE288(address _user) external view returns(uint256); //inject NONSTANDARD NAMING
function TOTALSUPPLY882() external view returns (uint256 supply); //inject NONSTANDARD NAMING
function BALANCEOF767(address _owner) external view returns (uint256 balance); //inject NONSTANDARD NAMING
function TRANSFER204(address _to, uint256 _value) external returns (bool success); //inject NONSTANDARD NAMING
function TRANSFERFROM832(address _from, address _to, uint256 _value) external returns (bool success); //inject NONSTANDARD NAMING
function APPROVE277(address _spender, uint256 _value) external returns (bool success); //inject NONSTANDARD NAMING
function ALLOWANCE10(address _owner, address _spender) external view returns (uint256 remaining); //inject NONSTANDARD NAMING
function NAME858() external view returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL894() external view returns (string memory); //inject NONSTANDARD NAMING
function DECIMALS454() external view returns (uint8); //inject NONSTANDARD NAMING
}
interface PriceOracle {
function GETUNDERLYINGPRICE929(address) external view returns (uint256); //inject NONSTANDARD NAMING
}
// ---------- Compound ----------
interface CErc20 {
function BORROW264(uint256) external returns (uint256); //inject NONSTANDARD NAMING
function BORROWRATEPERBLOCK388() external view returns (uint256); //inject NONSTANDARD NAMING
function BORROWBALANCECURRENT444(address) external returns (uint256); //inject NONSTANDARD NAMING
function REPAYBORROW515(uint256) external returns (uint256); //inject NONSTANDARD NAMING
}
interface CEth {
function MINT397() external payable; //inject NONSTANDARD NAMING
function REDEEMUNDERLYING805(uint redeemAmount) external returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOFUNDERLYING788(address owner) external returns (uint256); //inject NONSTANDARD NAMING
function SUPPLYRATEPERBLOCK15() external view returns (uint256); //inject NONSTANDARD NAMING
}
interface Comptroller {
function MARKETS249(address) external returns (bool, uint256); //inject NONSTANDARD NAMING
function ENTERMARKETS82(address[] calldata) //inject NONSTANDARD NAMING
external
returns (uint256[] memory);
function GETACCOUNTLIQUIDITY384(address) //inject NONSTANDARD NAMING
external
view
returns (uint256, uint256, uint256);
function ORACLE168() external view returns(address); //inject NONSTANDARD NAMING
}
// ---------- kyber ----------
interface Exchange {
function TRADE301( //inject NONSTANDARD NAMING
address src,
uint srcAmount,
address dest,
address destAddress,
uint maxDestAmount,
uint minConversionRate,
address walletId )external payable returns(uint);
}
// -----tCDP-----
contract tCDPConstants {
uint256 constant dust264 = 1e6; // minimum mint amount //inject NONSTANDARD NAMING
ERC20 constant dai445 = ERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); // DAI(debt) token address //inject NONSTANDARD NAMING
//Compound
Comptroller constant comptroller75 = Comptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); //inject NONSTANDARD NAMING
CEth constant ceth501 = CEth(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5); //inject NONSTANDARD NAMING
CErc20 constant cdai61 = CErc20(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643); //inject NONSTANDARD NAMING
//AAVE
ILendingPoolAddressesProvider constant addressesprovider654 = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); //inject NONSTANDARD NAMING
uint16 constant referral215 = 47; // TODO: apply new referral code //inject NONSTANDARD NAMING
//Kyber
Exchange constant kybernetwork927 = Exchange(0x818E6FECD516Ecc3849DAf6845e3EC868087B755); //inject NONSTANDARD NAMING
address constant etheraddr36 = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; //inject NONSTANDARD NAMING
address constant ref472 = 0xD0533664013a82c31584B7FFDB215139f38Ad77A; //inject NONSTANDARD NAMING
//rebalance target/boundary/size
uint256 constant targetratio559 = 0.4e18; //40% //inject NONSTANDARD NAMING
uint256 constant upperbound23 = 444444444444444444; // 1/225% //inject NONSTANDARD NAMING
uint256 constant lowerbound414 = 363636363636363636; // 1/275% //inject NONSTANDARD NAMING
uint256 constant bite558 = 0.025 * 1e18; //2.5% //inject NONSTANDARD NAMING
}
contract tCDP is ERC20Mintable, tCDPConstants{
using SafeMath for *;
bool public isCompound;
event MIGRATION431(uint8); // 0x01 = to Compound, 0x02 = to Aave //inject NONSTANDARD NAMING
constructor() public {
symbol = "tETH-DAI";
name = "tokenized CDP ETH-DAI v1";
decimals = 18;
address lendingPoolCoreAddress = addressesprovider654.GETLENDINGPOOLCORE21();
dai445.APPROVE277(lendingPoolCoreAddress, uint256(-1));
dai445.APPROVE277(address(cdai61), uint256(-1));
address[] memory cTokens = new address[](1);
cTokens[0] = address(ceth501);
uint256[] memory errors = comptroller75.ENTERMARKETS82(cTokens);
require(errors[0] == 0, "Comptroller.enterMarkets failed.");
dai445.APPROVE277(address(kybernetwork927), uint256(-1));
isCompound = FINDBESTRATE616();
}
function INITIATE270(uint256 amount) external payable { //inject NONSTANDARD NAMING
require(_totalSupply < dust264, "initiated");
require(msg.value > dust264, "value too small");
if(isCompound) {
ceth501.MINT397.value(msg.value)();
_MINT321(msg.sender, msg.value);
require(cdai61.BORROW264(amount) == 0, "borrow failed");
dai445.TRANSFER204(msg.sender, amount);
}
else {
ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38());
lendingPool.DEPOSIT818.value(msg.value)(etheraddr36, msg.value, referral215);
_MINT321(msg.sender, msg.value);
lendingPool.BORROW264(address(dai445), amount, 2, referral215);
dai445.TRANSFER204(msg.sender, amount);
}
}
function COLLATERAL797() public returns(uint256) { //inject NONSTANDARD NAMING
if(isCompound) {
return ceth501.BALANCEOFUNDERLYING788(address(this));
}
else {
address lendingPoolCore = addressesprovider654.GETLENDINGPOOLCORE21();
address aETH = ILendingPoolCore(lendingPoolCore).GETRESERVEATOKENADDRESS314(etheraddr36);
return IAToken(aETH).BALANCEOF767(address(this));
}
}
function DEBT567() public returns(uint256) { //inject NONSTANDARD NAMING
if(isCompound) {
return cdai61.BORROWBALANCECURRENT444(address(this));
}
else {
ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38());
(, uint256 borrowBalance,,,,,,,,) = lendingPool.GETUSERRESERVEDATA732(address(dai445), address(this));
return borrowBalance;
}
}
function MINT397() external payable returns(uint256) { //inject NONSTANDARD NAMING
require(_totalSupply >= dust264, "not initiated");
uint256 amount = msg.value;
uint256 tokenToMint = _totalSupply.MUL98(amount).DIV107(COLLATERAL797());
uint256 tokenToBorrow = DEBT567().MUL98(amount).DIV107(COLLATERAL797());
_MINT321(msg.sender, tokenToMint);
if(isCompound) {
ceth501.MINT397.value(amount)();
require(cdai61.BORROW264(tokenToBorrow) == 0, "borrow failed");
dai445.TRANSFER204(msg.sender, tokenToBorrow);
}
else{
// deposit
ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38());
lendingPool.DEPOSIT818.value(amount)(etheraddr36, amount, referral215);
// borrow
lendingPool.BORROW264(address(dai445), tokenToBorrow, 2, referral215);
// transfer
dai445.TRANSFER204(msg.sender, tokenToBorrow);
}
return tokenToMint;
}
function BURN250(uint256 amount) external { //inject NONSTANDARD NAMING
uint256 tokenToRepay = amount.MUL98(DEBT567()).DIV107(_totalSupply);
uint256 tokenToDraw = amount.MUL98(COLLATERAL797()).DIV107(_totalSupply);
_BURN441(msg.sender, amount);
dai445.TRANSFERFROM832(msg.sender, address(this), tokenToRepay);
if(isCompound) {
require(cdai61.REPAYBORROW515(tokenToRepay) == 0, "repay failed");
require(ceth501.REDEEMUNDERLYING805(tokenToDraw) == 0, "redeem failed");
}
else {
// repay
ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38());
address lendingPoolCoreAddress = addressesprovider654.GETLENDINGPOOLCORE21();
// Dai.approve(lendingPoolCoreAddress, tokenToRepay);
lendingPool.REPAY662(address(dai445), tokenToRepay, address(this));
// redeem
IAToken aETH = IAToken(ILendingPoolCore(lendingPoolCoreAddress).GETRESERVEATOKENADDRESS314(etheraddr36));
aETH.REDEEM632(tokenToDraw);
}
(bool success, ) = msg.sender.call.value(tokenToDraw)("");
require(success, "Failed to transfer ether to msg.sender");
}
function() external payable{}
//true if (cEth APR - cDai APR) >= (aEth APR - aDai APR), otherwise, false
function FINDBESTRATE616() public view returns (bool) { //inject NONSTANDARD NAMING
return AAVEDAIAPR797().MUL98(targetratio559).DIV107(1e18).ADD235(COMPOUNDETHAPR912()) > COMPOUNDDAIAPR961().MUL98(targetratio559).DIV107(1e18).ADD235(AAVEETHAPR160());
}
function COMPOUNDDAIAPR961() public view returns (uint256) { //inject NONSTANDARD NAMING
return cdai61.BORROWRATEPERBLOCK388().MUL98(2102400);
}
function COMPOUNDETHAPR912() public view returns (uint256) { //inject NONSTANDARD NAMING
return ceth501.SUPPLYRATEPERBLOCK15().MUL98(2102400);
}
function AAVEDAIAPR797() public view returns (uint256) { //inject NONSTANDARD NAMING
ILendingPoolCore core = ILendingPoolCore(addressesprovider654.GETLENDINGPOOLCORE21());
return core.GETRESERVECURRENTVARIABLEBORROWRATE762(address(dai445)).DIV107(1e9);
}
function AAVEETHAPR160() public view returns (uint256) { //inject NONSTANDARD NAMING
ILendingPoolCore core = ILendingPoolCore(addressesprovider654.GETLENDINGPOOLCORE21());
return core.GETRESERVECURRENTLIQUIDITYRATE636(etheraddr36).DIV107(1e9);
}
function GETUNDERLYINGPRICE929() public view returns(uint256) { //inject NONSTANDARD NAMING
uint256 price;
if(isCompound) {
address oracle = comptroller75.ORACLE168();
PriceOracle priceOracle = PriceOracle(oracle);
price = priceOracle.GETUNDERLYINGPRICE929(address(cdai61));
}
else {
address oracleAddress = addressesprovider654.GETPRICEORACLE485();
IAavePriceOracleGetter priceOracle = IAavePriceOracleGetter(oracleAddress);
price = priceOracle.GETASSETPRICE734(address(dai445));
}
return price;
}
function DEBTRATIO670() public returns (uint256) { //inject NONSTANDARD NAMING
uint256 price = GETUNDERLYINGPRICE929();
uint256 ratio = DEBT567().MUL98(price).DIV107(COLLATERAL797());
return ratio;
}
function DELEVERAGE904() external { //inject NONSTANDARD NAMING
require(_totalSupply >= dust264, "not initiated");
require(DEBTRATIO670() > upperbound23, "debt ratio is good");
uint256 amount = COLLATERAL797().MUL98(bite558).DIV107(1e18);
if(isCompound) {
require(ceth501.REDEEMUNDERLYING805(amount) == 0, "redeem failed");
uint256 income = kybernetwork927.TRADE301.value(amount)(etheraddr36, amount, address(dai445), address(this), 1e28, 1, ref472);
require(cdai61.REPAYBORROW515(income) == 0, "repay failed");
}
else {
// redeem
address lendingPoolCoreAddress = addressesprovider654.GETLENDINGPOOLCORE21();
IAToken aETH = IAToken(ILendingPoolCore(lendingPoolCoreAddress).GETRESERVEATOKENADDRESS314(etheraddr36));
aETH.REDEEM632(amount);
uint256 income = kybernetwork927.TRADE301.value(amount)(etheraddr36, amount, address(dai445), address(this), 1e28, 1, ref472);
// repay
ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38());
// Dai.approve(lendingPoolCoreAddress, income);
lendingPool.REPAY662(address(dai445), income, address(this));
}
}
function LEVERAGE920() external { //inject NONSTANDARD NAMING
require(_totalSupply >= dust264, "not initiated");
require(DEBTRATIO670() < lowerbound414, "debt ratio is good");
uint256 amount = DEBT567().MUL98(bite558).DIV107(1e18);
if(isCompound) {
require(cdai61.BORROW264(amount) == 0, "borrow failed");
uint256 income = kybernetwork927.TRADE301(address(dai445), amount, etheraddr36, address(this), 1e28, 1, ref472);
ceth501.MINT397.value(income)();
}
else {
// borrow
ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38());
lendingPool.BORROW264(address(dai445), amount, 2, referral215);
uint256 income = kybernetwork927.TRADE301(address(dai445), amount, etheraddr36, address(this), 1e28, 1, ref472);
// deposit
lendingPool.DEPOSIT818.value(income)(etheraddr36, income, referral215);
}
}
function MIGRATE814() external { //inject NONSTANDARD NAMING
if(FINDBESTRATE616() != isCompound) {
uint256 _debt = DEBT567();
uint256 _collateral = COLLATERAL797();
dai445.TRANSFERFROM832(msg.sender, address(this), _debt);
uint256 newBorrow = _debt.ADD235(2);
if(isCompound) {
require(cdai61.REPAYBORROW515(_debt) == 0, "borrow failed");
require(ceth501.REDEEMUNDERLYING805(_collateral) == 0, "redeem failed");
ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38());
lendingPool.DEPOSIT818.value(_collateral)(etheraddr36, _collateral, referral215);
lendingPool.BORROW264(address(dai445), newBorrow, 2, referral215);
isCompound = false;
emit MIGRATION431(0x02);
}
else {
ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38());
address lendingPoolCoreAddress = addressesprovider654.GETLENDINGPOOLCORE21();
lendingPool.REPAY662(address(dai445), _debt, address(this));
IAToken aETH = IAToken(ILendingPoolCore(lendingPoolCoreAddress).GETRESERVEATOKENADDRESS314(etheraddr36));
aETH.REDEEM632(_collateral);
ceth501.MINT397.value(_collateral)();
require(cdai61.BORROW264(newBorrow) == 0, "borrow failed");
isCompound = true;
emit MIGRATION431(0x01);
}
dai445.TRANSFER204(msg.sender, newBorrow);
}
}
} | inject NONSTANDARD NAMING | function SETPRICEORACLE428(address _priceOracle) public; | 5,544,567 |
/**
authorized to perform the sacred rituals of The Cult.
Every Church Needs A Priest.
**/
// 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 PriestDAO 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("Priest DAO", unicode"PRIEST") {
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 = 9;
uint256 _buyLiquidityFee = 1;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 9;
uint256 _sellLiquidityFee = 1;
uint256 _sellDevFee = 0;
uint256 totalSupply = 1_000_000_000 * 1e18;
maxTransactionAmount = 1_000_000_000 * 1e18;
maxWallet = 1_000_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(0xaA469AA0F05E4A7Ac3B8f76135dAfD99C9Fd191A); // set as marketing wallet
devWallet = address(0xaA469AA0F05E4A7Ac3B8f76135dAfD99C9Fd191A); // 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 PriestStart() 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;
}
} | / exclude from paying fees or having max transaction amount | constructor() ERC20("Priest DAO", unicode"PRIEST") {
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 = 9;
uint256 _buyLiquidityFee = 1;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 9;
uint256 _sellLiquidityFee = 1;
uint256 _sellDevFee = 0;
uint256 totalSupply = 1_000_000_000 * 1e18;
maxTransactionAmount = 1_000_000_000 * 1e18;
maxWallet = 1_000_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;
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);
| 13,799,385 |
./full_match/3/0x777Ad6549e2a1fd15142cF1794e02Baa161be659/sources/home/jonathancole/Documents/GitHub/cryptokitties-clone/contracts/Kittycontract.sol | color mixing algorithm for mouth, belly and tail in colors.js file the color ranges are: red 9-24 orange 25-39 yellow 40-54 green 55-69 blue 70-84 purple 85-98 / this is 'eye shape' and 'markings shape' only numbers less than 80 (for the 'tens' digit, eye shape) AND less than 8 (for the 'ones' digit, markings shape) are eligible. (87 or 78 return false for example). This ensures only numbers 1-7 for both markings shape and eyes shape will ever be eligible to be randomized / rand10 can only be 0-9, so if rand10 is in 5-9 range use the _momDna rand10 can only be 0-9, so if rand10 is 0-4 use _dadDna the bitwise operator "&" compares the random 8bit to "1" at every slot and returns 1 (true) or 0 (false) for all 'index' vals except i = 2 or 4 / the % 100 yields the last two digits of the _momDna number to use at this slot same as above but uses the dadDna if (random & i != 0) returns "false" above except i = 2 or 4 | function _mixDna(uint256 _dadDna, uint256 _momDna) internal returns (uint256) {
uint256[8] memory geneArray;
uint256 mom_Dna = _momDna;
uint256 dad_Dna = _dadDna;
uint256 rand100 = now % 100;
uint256 rand10 = now % 10;
uint256 index = 7;
uint256 mouth = 1e12;
uint256 eyes = 1e10;
if(index == 1) {
geneArray[1] = colorBlender( dad_Dna, mom_Dna, i, mouth, random);
}
else if(index == 2){
geneArray[2] = colorBlender( dad_Dna, mom_Dna, i, eyes, random);
}
else if(index == 4){
if((rand10 < 8 && rand10 > 0) && (rand100 >= 10 && rand100 < 80)){
}
else if(rand10 > 4){
geneArray[4] = uint8(_momDna % 100);
}
else {
geneArray[4] = uint8(_dadDna % 100);
}
}
else if(random & i != 0 && index != 1 && index != 2 && index != 4){
geneArray[index] = uint8(_momDna % 100);
}
else if(index != 1 && index != 2 && index != 4){
geneArray[index] = uint8(_dadDna % 100);
}
_dadDna = _dadDna / 100;
}
| 8,228,717 |
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title 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));
}
}
/**
* @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 Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/// @title Ownable
/// @author Applicature
/// @notice helper mixed to other contracts to link contract on an owner
/// @dev Base class
contract Ownable {
//Variables
address public owner;
address public newOwner;
// Modifiers
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @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));
newOwner = _newOwner;
}
function acceptOwnership() public {
if (msg.sender == newOwner) {
owner = newOwner;
}
}
}
/// @title OpenZeppelinERC20
/// @author Applicature
/// @notice Open Zeppelin implementation of standart ERC20
/// @dev Base class
contract OpenZeppelinERC20 is StandardToken, Ownable {
using SafeMath for uint256;
uint8 public decimals;
string public name;
string public symbol;
string public standard;
constructor(
uint256 _totalSupply,
string _tokenName,
uint8 _decimals,
string _tokenSymbol,
bool _transferAllSupplyToOwner
) public {
standard = 'ERC20 0.1';
totalSupply_ = _totalSupply;
if (_transferAllSupplyToOwner) {
balances[msg.sender] = _totalSupply;
} else {
balances[this] = _totalSupply;
}
name = _tokenName;
// Set the name for display purposes
symbol = _tokenSymbol;
// Set the symbol for display purposes
decimals = _decimals;
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
/// @title MintableToken
/// @author Applicature
/// @notice allow to mint tokens
/// @dev Base class
contract MintableToken is BasicToken, Ownable {
using SafeMath for uint256;
uint256 public maxSupply;
bool public allowedMinting;
mapping(address => bool) public mintingAgents;
mapping(address => bool) public stateChangeAgents;
event Mint(address indexed holder, uint256 tokens);
modifier onlyMintingAgents () {
require(mintingAgents[msg.sender]);
_;
}
modifier onlyStateChangeAgents () {
require(stateChangeAgents[msg.sender]);
_;
}
constructor(uint256 _maxSupply, uint256 _mintedSupply, bool _allowedMinting) public {
maxSupply = _maxSupply;
totalSupply_ = totalSupply_.add(_mintedSupply);
allowedMinting = _allowedMinting;
mintingAgents[msg.sender] = true;
}
/// @notice allow to mint tokens
function mint(address _holder, uint256 _tokens) public onlyMintingAgents() {
require(allowedMinting == true && totalSupply_.add(_tokens) <= maxSupply);
totalSupply_ = totalSupply_.add(_tokens);
balances[_holder] = balanceOf(_holder).add(_tokens);
if (totalSupply_ == maxSupply) {
allowedMinting = false;
}
emit Transfer(address(0), _holder, _tokens);
emit Mint(_holder, _tokens);
}
/// @notice update allowedMinting flat
function disableMinting() public onlyStateChangeAgents() {
allowedMinting = false;
}
/// @notice update minting agent
function updateMintingAgent(address _agent, bool _status) public onlyOwner {
mintingAgents[_agent] = _status;
}
/// @notice update state change agent
function updateStateChangeAgent(address _agent, bool _status) public onlyOwner {
stateChangeAgents[_agent] = _status;
}
/// @return available tokens
function availableTokens() public view returns (uint256 tokens) {
return maxSupply.sub(totalSupply_);
}
}
/// @title MintableBurnableToken
/// @author Applicature
/// @notice helper mixed to other contracts to burn tokens
/// @dev implementation
contract MintableBurnableToken is MintableToken, BurnableToken {
mapping (address => bool) public burnAgents;
modifier onlyBurnAgents () {
require(burnAgents[msg.sender]);
_;
}
event Burn(address indexed burner, uint256 value);
constructor(
uint256 _maxSupply,
uint256 _mintedSupply,
bool _allowedMinting
) public MintableToken(
_maxSupply,
_mintedSupply,
_allowedMinting
) {
}
/// @notice update minting agent
function updateBurnAgent(address _agent, bool _status) public onlyOwner {
burnAgents[_agent] = _status;
}
function burnByAgent(address _holder, uint256 _tokensToBurn) public onlyBurnAgents() returns (uint256) {
if (_tokensToBurn == 0) {
_tokensToBurn = balanceOf(_holder);
}
_burn(_holder, _tokensToBurn);
return _tokensToBurn;
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
maxSupply = maxSupply.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
/// @title TimeLocked
/// @author Applicature
/// @notice helper mixed to other contracts to lock contract on a timestamp
/// @dev Base class
contract TimeLocked {
uint256 public time;
mapping(address => bool) public excludedAddresses;
modifier isTimeLocked(address _holder, bool _timeLocked) {
bool locked = (block.timestamp < time);
require(excludedAddresses[_holder] == true || locked == _timeLocked);
_;
}
constructor(uint256 _time) public {
time = _time;
}
function updateExcludedAddress(address _address, bool _status) public;
}
/// @title TimeLockedToken
/// @author Applicature
/// @notice helper mixed to other contracts to lock contract on a timestamp
/// @dev Base class
contract TimeLockedToken is TimeLocked, StandardToken {
constructor(uint256 _time) public TimeLocked(_time) {}
function transfer(address _to, uint256 _tokens) public isTimeLocked(msg.sender, false) returns (bool) {
return super.transfer(_to, _tokens);
}
function transferFrom(
address _holder,
address _to,
uint256 _tokens
) public isTimeLocked(_holder, false) returns (bool) {
return super.transferFrom(_holder, _to, _tokens);
}
}
contract CHLToken is OpenZeppelinERC20, MintableBurnableToken, TimeLockedToken {
CHLCrowdsale public crowdsale;
bool public isSoftCapAchieved;
//_unlockTokensTime - Lockup 3 months after end of the ICO
constructor(uint256 _unlockTokensTime) public
OpenZeppelinERC20(0, 'ChelleCoin', 18, 'CHL', false)
MintableBurnableToken(59500000e18, 0, true)
TimeLockedToken(_unlockTokensTime) {
}
function updateMaxSupply(uint256 _newMaxSupply) public onlyOwner {
require(_newMaxSupply > 0);
maxSupply = _newMaxSupply;
}
function updateExcludedAddress(address _address, bool _status) public onlyOwner {
excludedAddresses[_address] = _status;
}
function setCrowdSale(address _crowdsale) public onlyOwner {
require(_crowdsale != address(0));
crowdsale = CHLCrowdsale(_crowdsale);
}
function setUnlockTime(uint256 _unlockTokensTime) public onlyStateChangeAgents {
time = _unlockTokensTime;
}
function setIsSoftCapAchieved() public onlyStateChangeAgents {
isSoftCapAchieved = true;
}
function transfer(address _to, uint256 _tokens) public returns (bool) {
require(true == isTransferAllowed(msg.sender, _tokens));
return super.transfer(_to, _tokens);
}
function transferFrom(address _holder, address _to, uint256 _tokens) public returns (bool) {
require(true == isTransferAllowed(_holder, _tokens));
return super.transferFrom(_holder, _to, _tokens);
}
function isTransferAllowed(address _address, uint256 _value) public view returns (bool) {
if (excludedAddresses[_address] == true) {
return true;
}
if (!isSoftCapAchieved && (address(crowdsale) == address(0) || false == crowdsale.isSoftCapAchieved(0))) {
return false;
}
return true;
}
function burnUnsoldTokens(uint256 _tokensToBurn) public onlyBurnAgents() returns (uint256) {
require(totalSupply_.add(_tokensToBurn) <= maxSupply);
maxSupply = maxSupply.sub(_tokensToBurn);
emit Burn(address(0), _tokensToBurn);
return _tokensToBurn;
}
}
/// @title Agent
/// @author Applicature
/// @notice Contract which takes actions on state change and contribution
/// @dev Base class
contract Agent {
using SafeMath for uint256;
function isInitialized() public constant returns (bool) {
return false;
}
}
/// @title CrowdsaleAgent
/// @author Applicature
/// @notice Contract which takes actions on state change and contribution
/// @dev Base class
contract CrowdsaleAgent is Agent {
Crowdsale public crowdsale;
bool public _isInitialized;
modifier onlyCrowdsale() {
require(msg.sender == address(crowdsale));
_;
}
constructor(Crowdsale _crowdsale) public {
crowdsale = _crowdsale;
if (address(0) != address(_crowdsale)) {
_isInitialized = true;
} else {
_isInitialized = false;
}
}
function isInitialized() public constant returns (bool) {
return _isInitialized;
}
function onContribution(address _contributor, uint256 _weiAmount, uint256 _tokens, uint256 _bonus)
public onlyCrowdsale();
function onStateChange(Crowdsale.State _state) public onlyCrowdsale();
function onRefund(address _contributor, uint256 _tokens) public onlyCrowdsale() returns (uint256 burned);
}
/// @title MintableCrowdsaleOnSuccessAgent
/// @author Applicature
/// @notice Contract which takes actions on state change and contribution
/// un-pause tokens and disable minting on Crowdsale success
/// @dev implementation
contract MintableCrowdsaleOnSuccessAgent is CrowdsaleAgent {
Crowdsale public crowdsale;
MintableToken public token;
bool public _isInitialized;
constructor(Crowdsale _crowdsale, MintableToken _token) public CrowdsaleAgent(_crowdsale) {
crowdsale = _crowdsale;
token = _token;
if (address(0) != address(_token) &&
address(0) != address(_crowdsale)) {
_isInitialized = true;
} else {
_isInitialized = false;
}
}
/// @notice Check whether contract is initialised
/// @return true if initialized
function isInitialized() public constant returns (bool) {
return _isInitialized;
}
/// @notice Takes actions on contribution
function onContribution(address _contributor, uint256 _weiAmount, uint256 _tokens, uint256 _bonus)
public onlyCrowdsale() {
_contributor = _contributor;
_weiAmount = _weiAmount;
_tokens = _tokens;
_bonus = _bonus;
// TODO: add impl
}
/// @notice Takes actions on state change,
/// un-pause tokens and disable minting on Crowdsale success
/// @param _state Crowdsale.State
function onStateChange(Crowdsale.State _state) public onlyCrowdsale() {
if (_state == Crowdsale.State.Success) {
token.disableMinting();
}
}
function onRefund(address _contributor, uint256 _tokens) public onlyCrowdsale() returns (uint256 burned) {
_contributor = _contributor;
_tokens = _tokens;
}
}
contract CHLAgent is MintableCrowdsaleOnSuccessAgent, Ownable {
CHLPricingStrategy public strategy;
CHLCrowdsale public crowdsale;
CHLAllocation public allocation;
bool public isEndProcessed;
constructor(
CHLCrowdsale _crowdsale,
CHLToken _token,
CHLPricingStrategy _strategy,
CHLAllocation _allocation
) public MintableCrowdsaleOnSuccessAgent(_crowdsale, _token) {
strategy = _strategy;
crowdsale = _crowdsale;
allocation = _allocation;
}
/// @notice update pricing strategy
function setPricingStrategy(CHLPricingStrategy _strategy) public onlyOwner {
strategy = _strategy;
}
/// @notice update allocation
function setAllocation(CHLAllocation _allocation) public onlyOwner {
allocation = _allocation;
}
function burnUnsoldTokens(uint256 _tierId) public onlyOwner {
uint256 tierUnsoldTokensAmount = strategy.getTierUnsoldTokens(_tierId);
require(tierUnsoldTokensAmount > 0);
CHLToken(token).burnUnsoldTokens(tierUnsoldTokensAmount);
}
/// @notice Takes actions on contribution
function onContribution(
address,
uint256 _tierId,
uint256 _tokens,
uint256 _bonus
) public onlyCrowdsale() {
strategy.updateTierTokens(_tierId, _tokens, _bonus);
}
function onStateChange(Crowdsale.State _state) public onlyCrowdsale() {
CHLToken chlToken = CHLToken(token);
if (
chlToken.isSoftCapAchieved() == false
&& (_state == Crowdsale.State.Success || _state == Crowdsale.State.Finalized)
&& crowdsale.isSoftCapAchieved(0)
) {
chlToken.setIsSoftCapAchieved();
}
if (_state > Crowdsale.State.InCrowdsale && isEndProcessed == false) {
allocation.allocateFoundersTokens(strategy.getSaleEndDate());
}
}
function onRefund(address _contributor, uint256 _tokens) public onlyCrowdsale() returns (uint256 burned) {
burned = CHLToken(token).burnByAgent(_contributor, _tokens);
}
function updateStateWithPrivateSale(
uint256 _tierId,
uint256 _tokensAmount,
uint256 _usdAmount
) public {
require(msg.sender == address(allocation));
strategy.updateMaxTokensCollected(_tierId, _tokensAmount);
crowdsale.updateStatsVars(_usdAmount, _tokensAmount);
}
function updateLockPeriod(uint256 _time) public {
require(msg.sender == address(strategy));
CHLToken(token).setUnlockTime(_time.add(12 weeks));
}
}
/// @title TokenAllocator
/// @author Applicature
/// @notice Contract responsible for defining distribution logic of tokens.
/// @dev Base class
contract TokenAllocator is Ownable {
mapping(address => bool) public crowdsales;
modifier onlyCrowdsale() {
require(crowdsales[msg.sender]);
_;
}
function addCrowdsales(address _address) public onlyOwner {
crowdsales[_address] = true;
}
function removeCrowdsales(address _address) public onlyOwner {
crowdsales[_address] = false;
}
function isInitialized() public constant returns (bool) {
return false;
}
function allocate(address _holder, uint256 _tokens) public onlyCrowdsale() {
internalAllocate(_holder, _tokens);
}
function tokensAvailable() public constant returns (uint256);
function internalAllocate(address _holder, uint256 _tokens) internal onlyCrowdsale();
}
/// @title MintableTokenAllocator
/// @author Applicature
/// @notice Contract responsible for defining distribution logic of tokens.
/// @dev implementation
contract MintableTokenAllocator is TokenAllocator {
using SafeMath for uint256;
MintableToken public token;
constructor(MintableToken _token) public {
require(address(0) != address(_token));
token = _token;
}
/// @return available tokens
function tokensAvailable() public constant returns (uint256) {
return token.availableTokens();
}
/// @notice transfer tokens on holder account
function allocate(address _holder, uint256 _tokens) public onlyCrowdsale() {
internalAllocate(_holder, _tokens);
}
/// @notice Check whether contract is initialised
/// @return true if initialized
function isInitialized() public constant returns (bool) {
return token.mintingAgents(this);
}
/// @notice update instance of MintableToken
function setToken(MintableToken _token) public onlyOwner {
token = _token;
}
function internalAllocate(address _holder, uint256 _tokens) internal {
token.mint(_holder, _tokens);
}
}
/// @title ContributionForwarder
/// @author Applicature
/// @notice Contract is responsible for distributing collected ethers, that are received from CrowdSale.
/// @dev Base class
contract ContributionForwarder {
using SafeMath for uint256;
uint256 public weiCollected;
uint256 public weiForwarded;
event ContributionForwarded(address receiver, uint256 weiAmount);
function isInitialized() public constant returns (bool) {
return false;
}
/// @notice transfer wei to receiver
function forward() public payable {
require(msg.value > 0);
weiCollected += msg.value;
internalForward();
}
function internalForward() internal;
}
/// @title DistributedDirectContributionForwarder
/// @author Applicature
/// @notice Contract is responsible for distributing collected ethers, that are received from CrowdSale.
/// @dev implementation
contract DistributedDirectContributionForwarder is ContributionForwarder {
Receiver[] public receivers;
uint256 public proportionAbsMax;
bool public isInitialized_;
struct Receiver {
address receiver;
uint256 proportion; // abslolute value in range of 0 - proportionAbsMax
uint256 forwardedWei;
}
// @TODO: should we use uint256 [] for receivers & proportions?
constructor(uint256 _proportionAbsMax, address[] _receivers, uint256[] _proportions) public {
proportionAbsMax = _proportionAbsMax;
require(_receivers.length == _proportions.length);
require(_receivers.length > 0);
uint256 totalProportion;
for (uint256 i = 0; i < _receivers.length; i++) {
uint256 proportion = _proportions[i];
totalProportion = totalProportion.add(proportion);
receivers.push(Receiver(_receivers[i], proportion, 0));
}
require(totalProportion == proportionAbsMax);
isInitialized_ = true;
}
/// @notice Check whether contract is initialised
/// @return true if initialized
function isInitialized() public constant returns (bool) {
return isInitialized_;
}
function internalForward() internal {
uint256 transferred;
for (uint256 i = 0; i < receivers.length; i++) {
Receiver storage receiver = receivers[i];
uint256 value = msg.value.mul(receiver.proportion).div(proportionAbsMax);
if (i == receivers.length - 1) {
value = msg.value.sub(transferred);
}
transferred = transferred.add(value);
receiver.receiver.transfer(value);
emit ContributionForwarded(receiver.receiver, value);
}
weiForwarded = weiForwarded.add(transferred);
}
}
contract Crowdsale {
uint256 public tokensSold;
enum State {Unknown, Initializing, BeforeCrowdsale, InCrowdsale, Success, Finalized, Refunding}
function externalContribution(address _contributor, uint256 _wei) public payable;
function contribute(uint8 _v, bytes32 _r, bytes32 _s) public payable;
function updateState() public;
function internalContribution(address _contributor, uint256 _wei) internal;
function getState() public view returns (State);
}
/// @title Crowdsale
/// @author Applicature
/// @notice Contract is responsible for collecting, refunding, allocating tokens during different stages of Crowdsale.
contract CrowdsaleImpl is Crowdsale, Ownable {
using SafeMath for uint256;
State public currentState;
TokenAllocator public allocator;
ContributionForwarder public contributionForwarder;
PricingStrategy public pricingStrategy;
CrowdsaleAgent public crowdsaleAgent;
bool public finalized;
uint256 public startDate;
uint256 public endDate;
bool public allowWhitelisted;
bool public allowSigned;
bool public allowAnonymous;
mapping(address => bool) public whitelisted;
mapping(address => bool) public signers;
mapping(address => bool) public externalContributionAgents;
event Contribution(address _contributor, uint256 _wei, uint256 _tokensExcludingBonus, uint256 _bonus);
constructor(
TokenAllocator _allocator,
ContributionForwarder _contributionForwarder,
PricingStrategy _pricingStrategy,
uint256 _startDate,
uint256 _endDate,
bool _allowWhitelisted,
bool _allowSigned,
bool _allowAnonymous
) public {
allocator = _allocator;
contributionForwarder = _contributionForwarder;
pricingStrategy = _pricingStrategy;
startDate = _startDate;
endDate = _endDate;
allowWhitelisted = _allowWhitelisted;
allowSigned = _allowSigned;
allowAnonymous = _allowAnonymous;
currentState = State.Unknown;
}
/// @notice default payable function
function() public payable {
require(allowWhitelisted || allowAnonymous);
if (!allowAnonymous) {
if (allowWhitelisted) {
require(whitelisted[msg.sender]);
}
}
internalContribution(msg.sender, msg.value);
}
/// @notice update crowdsale agent
function setCrowdsaleAgent(CrowdsaleAgent _crowdsaleAgent) public onlyOwner {
crowdsaleAgent = _crowdsaleAgent;
}
/// @notice allows external user to do contribution
function externalContribution(address _contributor, uint256 _wei) public payable {
require(externalContributionAgents[msg.sender]);
internalContribution(_contributor, _wei);
}
/// @notice update external contributor
function addExternalContributor(address _contributor) public onlyOwner {
externalContributionAgents[_contributor] = true;
}
/// @notice update external contributor
function removeExternalContributor(address _contributor) public onlyOwner {
externalContributionAgents[_contributor] = false;
}
/// @notice update whitelisting address
function updateWhitelist(address _address, bool _status) public onlyOwner {
whitelisted[_address] = _status;
}
/// @notice update signer
function addSigner(address _signer) public onlyOwner {
signers[_signer] = true;
}
/// @notice update signer
function removeSigner(address _signer) public onlyOwner {
signers[_signer] = false;
}
/// @notice allows to do signed contributions
function contribute(uint8 _v, bytes32 _r, bytes32 _s) public payable {
address recoveredAddress = verify(msg.sender, _v, _r, _s);
require(signers[recoveredAddress]);
internalContribution(msg.sender, msg.value);
}
/// @notice Crowdsale state
function updateState() public {
State state = getState();
if (currentState != state) {
if (crowdsaleAgent != address(0)) {
crowdsaleAgent.onStateChange(state);
}
currentState = state;
}
}
function internalContribution(address _contributor, uint256 _wei) internal {
require(getState() == State.InCrowdsale);
uint256 tokensAvailable = allocator.tokensAvailable();
uint256 collectedWei = contributionForwarder.weiCollected();
uint256 tokens;
uint256 tokensExcludingBonus;
uint256 bonus;
(tokens, tokensExcludingBonus, bonus) = pricingStrategy.getTokens(
_contributor, tokensAvailable, tokensSold, _wei, collectedWei);
require(tokens > 0 && tokens <= tokensAvailable);
tokensSold = tokensSold.add(tokens);
allocator.allocate(_contributor, tokens);
if (msg.value > 0) {
contributionForwarder.forward.value(msg.value)();
}
emit Contribution(_contributor, _wei, tokensExcludingBonus, bonus);
}
/// @notice check sign
function verify(address _sender, uint8 _v, bytes32 _r, bytes32 _s) public view returns (address) {
bytes32 hash = keccak256(abi.encodePacked(this, _sender));
bytes memory prefix = '\x19Ethereum Signed Message:\n32';
return ecrecover(keccak256(abi.encodePacked(prefix, hash)), _v, _r, _s);
}
/// @return Crowdsale state
function getState() public view returns (State) {
if (finalized) {
return State.Finalized;
} else if (allocator.isInitialized() == false) {
return State.Initializing;
} else if (contributionForwarder.isInitialized() == false) {
return State.Initializing;
} else if (pricingStrategy.isInitialized() == false) {
return State.Initializing;
} else if (block.timestamp < startDate) {
return State.BeforeCrowdsale;
} else if (block.timestamp >= startDate && block.timestamp <= endDate) {
return State.InCrowdsale;
} else if (block.timestamp > endDate) {
return State.Success;
}
return State.Unknown;
}
}
/// @title HardCappedCrowdsale
/// @author Applicature
/// @notice Contract is responsible for collecting, refunding, allocating tokens during different stages of Crowdsale.
/// with hard limit
contract HardCappedCrowdsale is CrowdsaleImpl {
using SafeMath for uint256;
uint256 public hardCap;
constructor(
TokenAllocator _allocator,
ContributionForwarder _contributionForwarder,
PricingStrategy _pricingStrategy,
uint256 _startDate,
uint256 _endDate,
bool _allowWhitelisted,
bool _allowSigned,
bool _allowAnonymous,
uint256 _hardCap
) public CrowdsaleImpl(
_allocator,
_contributionForwarder,
_pricingStrategy,
_startDate,
_endDate,
_allowWhitelisted,
_allowSigned,
_allowAnonymous
) {
hardCap = _hardCap;
}
/// @return Crowdsale state
function getState() public view returns (State) {
State state = super.getState();
if (state == State.InCrowdsale) {
if (isHardCapAchieved(0)) {
return State.Success;
}
}
return state;
}
function isHardCapAchieved(uint256 _value) public view returns (bool) {
if (hardCap <= tokensSold.add(_value)) {
return true;
}
return false;
}
function internalContribution(address _contributor, uint256 _wei) internal {
require(getState() == State.InCrowdsale);
uint256 tokensAvailable = allocator.tokensAvailable();
uint256 collectedWei = contributionForwarder.weiCollected();
uint256 tokens;
uint256 tokensExcludingBonus;
uint256 bonus;
(tokens, tokensExcludingBonus, bonus) = pricingStrategy.getTokens(
_contributor, tokensAvailable, tokensSold, _wei, collectedWei);
require(tokens <= tokensAvailable && tokens > 0 && false == isHardCapAchieved(tokens.sub(1)));
tokensSold = tokensSold.add(tokens);
allocator.allocate(_contributor, tokens);
if (msg.value > 0) {
contributionForwarder.forward.value(msg.value)();
}
crowdsaleAgent.onContribution(_contributor, _wei, tokensExcludingBonus, bonus);
emit Contribution(_contributor, _wei, tokensExcludingBonus, bonus);
}
}
/// @title RefundableCrowdsale
/// @author Applicature
/// @notice Contract is responsible for collecting, refunding, allocating tokens during different stages of Crowdsale.
/// with hard and soft limits
contract RefundableCrowdsale is HardCappedCrowdsale {
using SafeMath for uint256;
uint256 public softCap;
mapping(address => uint256) public contributorsWei;
address[] public contributors;
event Refund(address _holder, uint256 _wei, uint256 _tokens);
constructor(
TokenAllocator _allocator,
ContributionForwarder _contributionForwarder,
PricingStrategy _pricingStrategy,
uint256 _startDate,
uint256 _endDate,
bool _allowWhitelisted,
bool _allowSigned,
bool _allowAnonymous,
uint256 _softCap,
uint256 _hardCap
) public HardCappedCrowdsale(
_allocator, _contributionForwarder, _pricingStrategy,
_startDate, _endDate,
_allowWhitelisted, _allowSigned, _allowAnonymous, _hardCap
) {
softCap = _softCap;
}
/// @notice refund ethers to contributor
function refund() public {
internalRefund(msg.sender);
}
/// @notice refund ethers to delegate
function delegatedRefund(address _address) public {
internalRefund(_address);
}
function internalContribution(address _contributor, uint256 _wei) internal {
require(block.timestamp >= startDate && block.timestamp <= endDate);
uint256 tokensAvailable = allocator.tokensAvailable();
uint256 collectedWei = contributionForwarder.weiCollected();
uint256 tokens;
uint256 tokensExcludingBonus;
uint256 bonus;
(tokens, tokensExcludingBonus, bonus) = pricingStrategy.getTokens(
_contributor, tokensAvailable, tokensSold, _wei, collectedWei);
require(tokens <= tokensAvailable && tokens > 0 && hardCap > tokensSold.add(tokens));
tokensSold = tokensSold.add(tokens);
allocator.allocate(_contributor, tokens);
// transfer only if softcap is reached
if (isSoftCapAchieved(0)) {
if (msg.value > 0) {
contributionForwarder.forward.value(address(this).balance)();
}
} else {
// store contributor if it is not stored before
if (contributorsWei[_contributor] == 0) {
contributors.push(_contributor);
}
contributorsWei[_contributor] = contributorsWei[_contributor].add(msg.value);
}
crowdsaleAgent.onContribution(_contributor, _wei, tokensExcludingBonus, bonus);
emit Contribution(_contributor, _wei, tokensExcludingBonus, bonus);
}
function internalRefund(address _holder) internal {
updateState();
require(block.timestamp > endDate);
require(!isSoftCapAchieved(0));
require(crowdsaleAgent != address(0));
uint256 value = contributorsWei[_holder];
require(value > 0);
contributorsWei[_holder] = 0;
uint256 burnedTokens = crowdsaleAgent.onRefund(_holder, 0);
_holder.transfer(value);
emit Refund(_holder, value, burnedTokens);
}
/// @return Crowdsale state
function getState() public view returns (State) {
State state = super.getState();
if (state == State.Success) {
if (!isSoftCapAchieved(0)) {
return State.Refunding;
}
}
return state;
}
function isSoftCapAchieved(uint256 _value) public view returns (bool) {
if (softCap <= tokensSold.add(_value)) {
return true;
}
return false;
}
}
contract CHLCrowdsale is RefundableCrowdsale {
uint256 public maxSaleSupply = 38972500e18;
uint256 public usdCollected;
address public processingFeeAddress;
uint256 public percentageAbsMax = 1000;
uint256 public processingFeePercentage = 25;
event ProcessingFeeAllocation(address _contributor, uint256 _feeAmount);
event Contribution(address _contributor, uint256 _usdAmount, uint256 _tokensExcludingBonus, uint256 _bonus);
constructor(
MintableTokenAllocator _allocator,
DistributedDirectContributionForwarder _contributionForwarder,
CHLPricingStrategy _pricingStrategy,
uint256 _startTime,
uint256 _endTime,
address _processingFeeAddress
) public RefundableCrowdsale(
_allocator,
_contributionForwarder,
_pricingStrategy,
_startTime,
_endTime,
true,
true,
false,
10000000e5,//softCap
102860625e5//hardCap
) {
require(_processingFeeAddress != address(0));
processingFeeAddress = _processingFeeAddress;
}
function() public payable {
require(allowWhitelisted || allowAnonymous);
if (!allowAnonymous) {
if (allowWhitelisted) {
require(whitelisted[msg.sender]);
}
}
internalContribution(
msg.sender,
CHLPricingStrategy(pricingStrategy).getUSDAmountByWeis(msg.value)
);
}
/// @notice allows to do signed contributions
function contribute(uint8 _v, bytes32 _r, bytes32 _s) public payable {
address recoveredAddress = verify(msg.sender, _v, _r, _s);
require(signers[recoveredAddress]);
internalContribution(
msg.sender,
CHLPricingStrategy(pricingStrategy).getUSDAmountByWeis(msg.value)
);
}
/// @notice allows external user to do contribution
function externalContribution(address _contributor, uint256 _usdAmount) public payable {
require(externalContributionAgents[msg.sender]);
internalContribution(_contributor, _usdAmount);
}
function updateState() public {
(startDate, endDate) = CHLPricingStrategy(pricingStrategy).getActualDates();
super.updateState();
}
function isHardCapAchieved(uint256 _value) public view returns (bool) {
if (hardCap <= usdCollected.add(_value)) {
return true;
}
return false;
}
function isSoftCapAchieved(uint256 _value) public view returns (bool) {
if (softCap <= usdCollected.add(_value)) {
return true;
}
return false;
}
function getUnsoldTokensAmount() public view returns (uint256) {
return maxSaleSupply.sub(tokensSold);
}
function updateStatsVars(uint256 _usdAmount, uint256 _tokensAmount) public {
require(msg.sender == address(crowdsaleAgent) && _tokensAmount > 0);
tokensSold = tokensSold.add(_tokensAmount);
usdCollected = usdCollected.add(_usdAmount);
}
function internalContribution(address _contributor, uint256 _usdAmount) internal {
updateState();
require(currentState == State.InCrowdsale);
CHLPricingStrategy pricing = CHLPricingStrategy(pricingStrategy);
require(!isHardCapAchieved(_usdAmount.sub(1)));
uint256 tokensAvailable = allocator.tokensAvailable();
uint256 collectedWei = contributionForwarder.weiCollected();
uint256 tierIndex = pricing.getTierIndex();
uint256 tokens;
uint256 tokensExcludingBonus;
uint256 bonus;
(tokens, tokensExcludingBonus, bonus) = pricing.getTokens(
_contributor, tokensAvailable, tokensSold, _usdAmount, collectedWei);
require(tokens > 0);
tokensSold = tokensSold.add(tokens);
allocator.allocate(_contributor, tokens);
//allocate Processing fee
uint256 processingFeeAmount = tokens.mul(processingFeePercentage).div(percentageAbsMax);
allocator.allocate(processingFeeAddress, processingFeeAmount);
if (isSoftCapAchieved(_usdAmount)) {
if (msg.value > 0) {
contributionForwarder.forward.value(address(this).balance)();
}
} else {
// store contributor if it is not stored before
if (contributorsWei[_contributor] == 0) {
contributors.push(_contributor);
}
if (msg.value > 0) {
contributorsWei[_contributor] = contributorsWei[_contributor].add(msg.value);
}
}
usdCollected = usdCollected.add(_usdAmount);
crowdsaleAgent.onContribution(_contributor, tierIndex, tokensExcludingBonus, bonus);
emit Contribution(_contributor, _usdAmount, tokensExcludingBonus, bonus);
emit ProcessingFeeAllocation(_contributor, processingFeeAmount);
}
}
contract USDExchange is Ownable {
using SafeMath for uint256;
uint256 public etherPriceInUSD;
uint256 public priceUpdateAt;
mapping(address => bool) public trustedAddresses;
event NewPriceTicker(string _price);
modifier onlyTursted() {
require(trustedAddresses[msg.sender] == true);
_;
}
constructor(uint256 _etherPriceInUSD) public {
etherPriceInUSD = _etherPriceInUSD;
priceUpdateAt = block.timestamp;
trustedAddresses[msg.sender] = true;
}
function setTrustedAddress(address _address, bool _status) public onlyOwner {
trustedAddresses[_address] = _status;
}
// set ether price in USD with 5 digits after the decimal point
//ex. 308.75000
//for updating the price through multivest
function setEtherInUSD(string _price) public onlyTursted {
bytes memory bytePrice = bytes(_price);
uint256 dot = bytePrice.length.sub(uint256(6));
// check if dot is in 6 position from the last
require(0x2e == uint(bytePrice[dot]));
uint256 newPrice = uint256(10 ** 23).div(parseInt(_price, 5));
require(newPrice > 0);
etherPriceInUSD = parseInt(_price, 5);
priceUpdateAt = block.timestamp;
emit NewPriceTicker(_price);
}
function parseInt(string _a, uint _b) internal pure returns (uint) {
bytes memory bresult = bytes(_a);
uint res = 0;
bool decimals = false;
for (uint i = 0; i < bresult.length; i++) {
if ((bresult[i] >= 48) && (bresult[i] <= 57)) {
if (decimals) {
if (_b == 0) break;
else _b--;
}
res *= 10;
res += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) res *= 10 ** _b;
return res;
}
}
/// @title PricingStrategy
/// @author Applicature
/// @notice Contract is responsible for calculating tokens amount depending on different criterias
/// @dev Base class
contract PricingStrategy {
function isInitialized() public view returns (bool);
function getTokens(
address _contributor,
uint256 _tokensAvailable,
uint256 _tokensSold,
uint256 _weiAmount,
uint256 _collectedWei
)
public
view
returns (uint256 tokens, uint256 tokensExcludingBonus, uint256 bonus);
function getWeis(
uint256 _collectedWei,
uint256 _tokensSold,
uint256 _tokens
)
public
view
returns (uint256 weiAmount, uint256 tokensBonus);
}
/// @title USDDateTiersPricingStrategy
/// @author Applicature
/// @notice Contract is responsible for calculating tokens amount depending on price in USD
/// @dev implementation
contract USDDateTiersPricingStrategy is PricingStrategy, USDExchange {
using SafeMath for uint256;
//tokenInUSD token price in usd * 10 ^ 5
//maxTokensCollected max tokens amount that can be distributed
//bonusCap tokens amount cap; while sold tokens < bonus cap - contributors will receive bonus % tokens
//soldTierTokens tokens that already been sold
//bonusTierTokens bonus tokens that already been allocated
//bonusPercents bonus percentage
//minInvestInUSD min investment in usd * 10 * 5
//startDate tier start time
//endDate tier end time
struct Tier {
uint256 tokenInUSD;
uint256 maxTokensCollected;
uint256 bonusCap;
uint256 soldTierTokens;
uint256 bonusTierTokens;
uint256 bonusPercents;
uint256 minInvestInUSD;
uint256 startDate;
uint256 endDate;
}
Tier[] public tiers;
uint256 public decimals;
constructor(uint256[] _tiers, uint256 _decimals, uint256 _etherPriceInUSD) public USDExchange(_etherPriceInUSD) {
decimals = _decimals;
trustedAddresses[msg.sender] = true;
require(_tiers.length % 9 == 0);
uint256 length = _tiers.length / 9;
for (uint256 i = 0; i < length; i++) {
tiers.push(
Tier(
_tiers[i * 9],
_tiers[i * 9 + 1],
_tiers[i * 9 + 2],
_tiers[i * 9 + 3],
_tiers[i * 9 + 4],
_tiers[i * 9 + 5],
_tiers[i * 9 + 6],
_tiers[i * 9 + 7],
_tiers[i * 9 + 8]
)
);
}
}
/// @return tier index
function getTierIndex() public view returns (uint256) {
for (uint256 i = 0; i < tiers.length; i++) {
if (
block.timestamp >= tiers[i].startDate &&
block.timestamp < tiers[i].endDate &&
tiers[i].maxTokensCollected > tiers[i].soldTierTokens
) {
return i;
}
}
return tiers.length;
}
function getActualTierIndex() public view returns (uint256) {
for (uint256 i = 0; i < tiers.length; i++) {
if (
block.timestamp >= tiers[i].startDate
&& block.timestamp < tiers[i].endDate
&& tiers[i].maxTokensCollected > tiers[i].soldTierTokens
|| block.timestamp < tiers[i].startDate
) {
return i;
}
}
return tiers.length.sub(1);
}
/// @return actual dates
function getActualDates() public view returns (uint256 startDate, uint256 endDate) {
uint256 tierIndex = getActualTierIndex();
startDate = tiers[tierIndex].startDate;
endDate = tiers[tierIndex].endDate;
}
/// @return tokens based on sold tokens and wei amount
function getTokens(
address,
uint256 _tokensAvailable,
uint256,
uint256 _usdAmount,
uint256
) public view returns (uint256 tokens, uint256 tokensExcludingBonus, uint256 bonus) {
if (_usdAmount == 0) {
return (0, 0, 0);
}
uint256 tierIndex = getTierIndex();
if (tierIndex < tiers.length && _usdAmount < tiers[tierIndex].minInvestInUSD) {
return (0, 0, 0);
}
if (tierIndex == tiers.length) {
return (0, 0, 0);
}
tokensExcludingBonus = _usdAmount.mul(1e18).div(getTokensInUSD(tierIndex));
if (tiers[tierIndex].maxTokensCollected < tiers[tierIndex].soldTierTokens.add(tokensExcludingBonus)) {
return (0, 0, 0);
}
bonus = calculateBonusAmount(tierIndex, tokensExcludingBonus);
tokens = tokensExcludingBonus.add(bonus);
if (tokens > _tokensAvailable) {
return (0, 0, 0);
}
}
/// @return usd amount based on required tokens
function getUSDAmountByTokens(
uint256 _tokens
) public view returns (uint256 totalUSDAmount, uint256 tokensBonus) {
if (_tokens == 0) {
return (0, 0);
}
uint256 tierIndex = getTierIndex();
if (tierIndex == tiers.length) {
return (0, 0);
}
if (tiers[tierIndex].maxTokensCollected < tiers[tierIndex].soldTierTokens.add(_tokens)) {
return (0, 0);
}
totalUSDAmount = _tokens.mul(getTokensInUSD(tierIndex)).div(1e18);
if (totalUSDAmount < tiers[tierIndex].minInvestInUSD) {
return (0, 0);
}
tokensBonus = calculateBonusAmount(tierIndex, _tokens);
}
/// @return weis based on sold and required tokens
function getWeis(
uint256,
uint256,
uint256 _tokens
) public view returns (uint256 totalWeiAmount, uint256 tokensBonus) {
uint256 usdAmount;
(usdAmount, tokensBonus) = getUSDAmountByTokens(_tokens);
if (usdAmount == 0) {
return (0, 0);
}
totalWeiAmount = usdAmount.mul(1e18).div(etherPriceInUSD);
}
/// calculates bonus tokens amount by bonusPercents in case if bonusCap is not reached;
/// if reached returns 0
/// @return bonus tokens amount
function calculateBonusAmount(uint256 _tierIndex, uint256 _tokens) public view returns (uint256 bonus) {
if (tiers[_tierIndex].soldTierTokens < tiers[_tierIndex].bonusCap) {
if (tiers[_tierIndex].soldTierTokens.add(_tokens) <= tiers[_tierIndex].bonusCap) {
bonus = _tokens.mul(tiers[_tierIndex].bonusPercents).div(100);
} else {
bonus = (tiers[_tierIndex].bonusCap.sub(tiers[_tierIndex].soldTierTokens))
.mul(tiers[_tierIndex].bonusPercents).div(100);
}
}
}
function getTokensInUSD(uint256 _tierIndex) public view returns (uint256) {
if (_tierIndex < uint256(tiers.length)) {
return tiers[_tierIndex].tokenInUSD;
}
}
function getMinEtherInvest(uint256 _tierIndex) public view returns (uint256) {
if (_tierIndex < uint256(tiers.length)) {
return tiers[_tierIndex].minInvestInUSD.mul(1 ether).div(etherPriceInUSD);
}
}
function getUSDAmountByWeis(uint256 _weiAmount) public view returns (uint256) {
return _weiAmount.mul(etherPriceInUSD).div(1 ether);
}
/// @notice Check whether contract is initialised
/// @return true if initialized
function isInitialized() public view returns (bool) {
return true;
}
/// @notice updates tier start/end dates by id
function updateDates(uint8 _tierId, uint256 _start, uint256 _end) public onlyOwner() {
if (_start != 0 && _start < _end && _tierId < tiers.length) {
Tier storage tier = tiers[_tierId];
tier.startDate = _start;
tier.endDate = _end;
}
}
}
contract CHLPricingStrategy is USDDateTiersPricingStrategy {
CHLAgent public agent;
modifier onlyAgent() {
require(msg.sender == address(agent));
_;
}
event MaxTokensCollectedDecreased(uint256 tierId, uint256 oldValue, uint256 amount);
constructor(
uint256[] _emptyArray,
uint256[4] _periods,
uint256 _etherPriceInUSD
) public USDDateTiersPricingStrategy(_emptyArray, 18, _etherPriceInUSD) {
//pre-ico
tiers.push(Tier(0.75e5, 6247500e18, 0, 0, 0, 0, 100e5, _periods[0], _periods[1]));
//public ico
tiers.push(Tier(3e5, 32725000e18, 0, 0, 0, 0, 100e5, _periods[2], _periods[3]));
}
function getArrayOfTiers() public view returns (uint256[12] tiersData) {
uint256 j = 0;
for (uint256 i = 0; i < tiers.length; i++) {
tiersData[j++] = uint256(tiers[i].tokenInUSD);
tiersData[j++] = uint256(tiers[i].maxTokensCollected);
tiersData[j++] = uint256(tiers[i].soldTierTokens);
tiersData[j++] = uint256(tiers[i].minInvestInUSD);
tiersData[j++] = uint256(tiers[i].startDate);
tiersData[j++] = uint256(tiers[i].endDate);
}
}
function updateTier(
uint256 _tierId,
uint256 _start,
uint256 _end,
uint256 _minInvest,
uint256 _price,
uint256 _bonusCap,
uint256 _bonus,
bool _updateLockNeeded
) public onlyOwner() {
require(
_start != 0 &&
_price != 0 &&
_start < _end &&
_tierId < tiers.length
);
if (_updateLockNeeded) {
agent.updateLockPeriod(_end);
}
Tier storage tier = tiers[_tierId];
tier.tokenInUSD = _price;
tier.minInvestInUSD = _minInvest;
tier.startDate = _start;
tier.endDate = _end;
tier.bonusCap = _bonusCap;
tier.bonusPercents = _bonus;
}
function setCrowdsaleAgent(CHLAgent _crowdsaleAgent) public onlyOwner {
agent = _crowdsaleAgent;
}
function updateTierTokens(uint256 _tierId, uint256 _soldTokens, uint256 _bonusTokens) public onlyAgent {
require(_tierId < tiers.length && _soldTokens > 0);
Tier storage tier = tiers[_tierId];
tier.soldTierTokens = tier.soldTierTokens.add(_soldTokens);
tier.bonusTierTokens = tier.bonusTierTokens.add(_bonusTokens);
}
function updateMaxTokensCollected(uint256 _tierId, uint256 _amount) public onlyAgent {
require(_tierId < tiers.length && _amount > 0);
Tier storage tier = tiers[_tierId];
require(tier.maxTokensCollected.sub(_amount) >= tier.soldTierTokens.add(tier.bonusTierTokens));
emit MaxTokensCollectedDecreased(_tierId, tier.maxTokensCollected, _amount);
tier.maxTokensCollected = tier.maxTokensCollected.sub(_amount);
}
function getTokensWithoutRestrictions(uint256 _usdAmount) public view returns (
uint256 tokens,
uint256 tokensExcludingBonus,
uint256 bonus
) {
if (_usdAmount == 0) {
return (0, 0, 0);
}
uint256 tierIndex = getActualTierIndex();
tokensExcludingBonus = _usdAmount.mul(1e18).div(getTokensInUSD(tierIndex));
bonus = calculateBonusAmount(tierIndex, tokensExcludingBonus);
tokens = tokensExcludingBonus.add(bonus);
}
function getTierUnsoldTokens(uint256 _tierId) public view returns (uint256) {
if (_tierId >= tiers.length) {
return 0;
}
return tiers[_tierId].maxTokensCollected.sub(tiers[_tierId].soldTierTokens);
}
function getSaleEndDate() public view returns (uint256) {
return tiers[tiers.length.sub(1)].endDate;
}
}
contract Referral is Ownable {
using SafeMath for uint256;
MintableTokenAllocator public allocator;
CrowdsaleImpl public crowdsale;
uint256 public constant DECIMALS = 18;
uint256 public totalSupply;
bool public unLimited;
bool public sentOnce;
mapping(address => bool) public claimed;
mapping(address => uint256) public claimedBalances;
constructor(
uint256 _totalSupply,
address _allocator,
address _crowdsale,
bool _sentOnce
) public {
require(_allocator != address(0) && _crowdsale != address(0));
totalSupply = _totalSupply;
if (totalSupply == 0) {
unLimited = true;
}
allocator = MintableTokenAllocator(_allocator);
crowdsale = CrowdsaleImpl(_crowdsale);
sentOnce = _sentOnce;
}
function setAllocator(address _allocator) public onlyOwner {
if (_allocator != address(0)) {
allocator = MintableTokenAllocator(_allocator);
}
}
function setCrowdsale(address _crowdsale) public onlyOwner {
require(_crowdsale != address(0));
crowdsale = CrowdsaleImpl(_crowdsale);
}
function multivestMint(
address _address,
uint256 _amount,
uint8 _v,
bytes32 _r,
bytes32 _s
) public {
require(true == crowdsale.signers(verify(msg.sender, _amount, _v, _r, _s)));
if (true == sentOnce) {
require(claimed[_address] == false);
claimed[_address] = true;
}
require(
_address == msg.sender &&
_amount > 0 &&
(true == unLimited || _amount <= totalSupply)
);
claimedBalances[_address] = claimedBalances[_address].add(_amount);
if (false == unLimited) {
totalSupply = totalSupply.sub(_amount);
}
allocator.allocate(_address, _amount);
}
/// @notice check sign
function verify(address _sender, uint256 _amount, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) {
bytes32 hash = keccak256(abi.encodePacked(_sender, _amount));
bytes memory prefix = '\x19Ethereum Signed Message:\n32';
return ecrecover(keccak256(abi.encodePacked(prefix, hash)), _v, _r, _s);
}
}
contract CHLReferral is Referral {
CHLPricingStrategy public pricingStrategy;
constructor(
address _allocator,
address _crowdsale,
CHLPricingStrategy _strategy
) public Referral(1190000e18, _allocator, _crowdsale, true) {
require(_strategy != address(0));
pricingStrategy = _strategy;
}
function multivestMint(
address _address,
uint256 _amount,
uint8 _v,
bytes32 _r,
bytes32 _s
) public {
require(pricingStrategy.getSaleEndDate() <= block.timestamp);
super.multivestMint(_address, _amount, _v, _r, _s);
}
}
contract CHLAllocation is Ownable {
using SafeMath for uint256;
MintableTokenAllocator public allocator;
CHLAgent public agent;
//manualMintingSupply = Advisors 2975000 + Bounty 1785000 + LWL (Non Profit Initiative) 1190000
uint256 public manualMintingSupply = 5950000e18;
uint256 public foundersVestingAmountPeriodOne = 7140000e18;
uint256 public foundersVestingAmountPeriodTwo = 2975000e18;
uint256 public foundersVestingAmountPeriodThree = 1785000e18;
address[] public vestings;
address public foundersAddress;
bool public isFoundersTokensSent;
event VestingCreated(
address _vesting,
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
uint256 _periods,
bool _revocable
);
event VestingRevoked(address _vesting);
constructor(MintableTokenAllocator _allocator, address _foundersAddress) public {
require(_foundersAddress != address(0));
foundersAddress = _foundersAddress;
allocator = _allocator;
}
function setAllocator(MintableTokenAllocator _allocator) public onlyOwner {
require(_allocator != address(0));
allocator = _allocator;
}
function setAgent(CHLAgent _agent) public onlyOwner {
require(_agent != address(0));
agent = _agent;
}
function allocateManualMintingTokens(address[] _addresses, uint256[] _tokens) public onlyOwner {
require(_addresses.length == _tokens.length);
for (uint256 i = 0; i < _addresses.length; i++) {
require(_addresses[i] != address(0) && _tokens[i] > 0 && _tokens[i] <= manualMintingSupply);
manualMintingSupply -= _tokens[i];
allocator.allocate(_addresses[i], _tokens[i]);
}
}
function allocatePrivateSaleTokens(
uint256 _tierId,
uint256 _totalTokensSupply,
uint256 _tokenPriceInUsd,
address[] _addresses,
uint256[] _tokens
) public onlyOwner {
require(
_addresses.length == _tokens.length &&
_totalTokensSupply > 0
);
agent.updateStateWithPrivateSale(_tierId, _totalTokensSupply, _totalTokensSupply.mul(_tokenPriceInUsd).div(1e18));
for (uint256 i = 0; i < _addresses.length; i++) {
require(_addresses[i] != address(0) && _tokens[i] > 0 && _tokens[i] <= _totalTokensSupply);
_totalTokensSupply = _totalTokensSupply.sub(_tokens[i]);
allocator.allocate(_addresses[i], _tokens[i]);
}
require(_totalTokensSupply == 0);
}
function allocateFoundersTokens(uint256 _start) public {
require(!isFoundersTokensSent && msg.sender == address(agent));
isFoundersTokensSent = true;
allocator.allocate(foundersAddress, foundersVestingAmountPeriodOne);
createVestingInternal(
foundersAddress,
_start,
0,
365 days,
1,
true,
owner,
foundersVestingAmountPeriodTwo
);
createVestingInternal(
foundersAddress,
_start,
0,
730 days,
1,
true,
owner,
foundersVestingAmountPeriodThree
);
}
function createVesting(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
uint256 _periods,
bool _revocable,
address _unreleasedHolder,
uint256 _amount
) public onlyOwner returns (PeriodicTokenVesting vesting) {
vesting = createVestingInternal(
_beneficiary,
_start,
_cliff,
_duration,
_periods,
_revocable,
_unreleasedHolder,
_amount
);
}
function revokeVesting(PeriodicTokenVesting _vesting, ERC20Basic token) public onlyOwner() {
_vesting.revoke(token);
emit VestingRevoked(_vesting);
}
function createVestingInternal(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
uint256 _periods,
bool _revocable,
address _unreleasedHolder,
uint256 _amount
) internal returns (PeriodicTokenVesting) {
PeriodicTokenVesting vesting = new PeriodicTokenVesting(
_beneficiary, _start, _cliff, _duration, _periods, _revocable, _unreleasedHolder
);
vestings.push(vesting);
emit VestingCreated(vesting, _beneficiary, _start, _cliff, _duration, _periods, _revocable);
allocator.allocate(address(vesting), _amount);
return vesting;
}
}
/**
* @title TokenVesting
* @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 TokenVesting 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 cliff;
uint256 public start;
uint256 public duration;
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, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
constructor(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable
)
public
{
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
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(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(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
}
contract PeriodicTokenVesting is TokenVesting {
address public unreleasedHolder;
uint256 public periods;
constructor(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _periodDuration,
uint256 _periods,
bool _revocable,
address _unreleasedHolder
) public TokenVesting(_beneficiary, _start, _cliff, _periodDuration, _revocable) {
require(_revocable == false || _unreleasedHolder != address(0));
periods = _periods;
unreleasedHolder = _unreleasedHolder;
}
/**
* @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(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (now < cliff) {
return 0;
} else if (now >= start.add(duration * periods) || revoked[token]) {
return totalBalance;
} else {
uint256 periodTokens = totalBalance.div(periods);
uint256 periodsOver = now.sub(start).div(duration);
if (periodsOver >= periods) {
return totalBalance;
}
return periodTokens.mul(periodsOver);
}
}
/**
* @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(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.safeTransfer(unreleasedHolder, refund);
emit Revoked();
}
}
contract Stats {
using SafeMath for uint256;
MintableToken public token;
MintableTokenAllocator public allocator;
CHLCrowdsale public crowdsale;
CHLPricingStrategy public pricing;
constructor(
MintableToken _token,
MintableTokenAllocator _allocator,
CHLCrowdsale _crowdsale,
CHLPricingStrategy _pricing
) public {
token = _token;
allocator = _allocator;
crowdsale = _crowdsale;
pricing = _pricing;
}
function getTokens(
uint256 _type,
uint256 _usdAmount
) public view returns (uint256 tokens, uint256 tokensExcludingBonus, uint256 bonus) {
_type = _type;
return pricing.getTokensWithoutRestrictions(_usdAmount);
}
function getWeis(
uint256 _type,
uint256 _tokenAmount
) public view returns (uint256 totalWeiAmount, uint256 tokensBonus) {
_type = _type;
return pricing.getWeis(0, 0, _tokenAmount);
}
function getUSDAmount(
uint256 _type,
uint256 _tokenAmount
) public view returns (uint256 totalUSDAmount, uint256 tokensBonus) {
_type = _type;
return pricing.getUSDAmountByTokens(_tokenAmount);
}
function getStats(uint256 _userType, uint256[7] _ethPerCurrency) public view returns (
uint256[8] stats,
uint256[26] tiersData,
uint256[21] currencyContr //tokensPerEachCurrency,
) {
stats = getStatsData(_userType);
tiersData = getTiersData(_userType);
currencyContr = getCurrencyContrData(_userType, _ethPerCurrency);
}
function getTiersData(uint256 _type) public view returns (
uint256[26] tiersData
) {
_type = _type;
uint256[12] memory tiers = pricing.getArrayOfTiers();
uint256 length = tiers.length / 6;
uint256 j = 0;
for (uint256 i = 0; i < length; i++) {
tiersData[j++] = uint256(1e23).div(tiers[i.mul(6)]);// tokenInUSD;
tiersData[j++] = 0;// tokenInWei;
tiersData[j++] = uint256(tiers[i.mul(6).add(1)]);// maxTokensCollected;
tiersData[j++] = uint256(tiers[i.mul(6).add(2)]);// soldTierTokens;
tiersData[j++] = 0;// discountPercents;
tiersData[j++] = 0;// bonusPercents;
tiersData[j++] = uint256(tiers[i.mul(6).add(3)]);// minInvestInUSD;
tiersData[j++] = 0;// minInvestInWei;
tiersData[j++] = 0;// maxInvestInUSD;
tiersData[j++] = 0;// maxInvestInWei;
tiersData[j++] = uint256(tiers[i.mul(6).add(4)]); // startDate;
tiersData[j++] = uint256(tiers[i.mul(6).add(5)]); // endDate;
tiersData[j++] = 1;
}
tiersData[25] = 2;
}
function getStatsData(uint256 _type) public view returns (
uint256[8] stats
) {
_type = _type;
stats[0] = token.maxSupply();
stats[1] = token.totalSupply();
stats[2] = crowdsale.maxSaleSupply();
stats[3] = crowdsale.tokensSold();
stats[4] = uint256(crowdsale.currentState());
stats[5] = pricing.getActualTierIndex();
stats[6] = pricing.getTierUnsoldTokens(stats[5]);
stats[7] = pricing.getMinEtherInvest(stats[5]);
}
function getCurrencyContrData(uint256 _type, uint256[7] _usdPerCurrency) public view returns (
uint256[21] currencyContr
) {
_type = _type;
uint256 j = 0;
for (uint256 i = 0; i < _usdPerCurrency.length; i++) {
(currencyContr[j++], currencyContr[j++], currencyContr[j++]) = pricing.getTokensWithoutRestrictions(
_usdPerCurrency[i]
);
}
}
} | Check whether contract is initialised return true if initialized | function isInitialized() public constant returns (bool) {
return isInitialized_;
}
| 5,374,371 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "./utils/Context.sol";
import "./interfaces/IERC721.sol";
import "./interfaces/IERC721Metadata.sol";
import "./interfaces/IERC721Enumerable.sol";
import "./interfaces/IERC721Receiver.sol";
import "./utils/ERC165.sol";
import "./utils/SafeMath.sol";
import "./utils/Address.sol";
import "./utils/EnumerableSet.sol";
import "./utils/EnumerableMap.sol";
import "./utils/Strings.sol";
import "./utils/Pausable.sol";
import "./utils/Ownable.sol";
/**
* @title Anoncats ERC721 Implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract Anoncats is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Pausable, Ownable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Token counter, starts from 1 and ends at 100, 1 <= x <= 100
uint256 public tokenCount = 1;
uint256 public tokenCountMax = 100;
// Mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Mapping for delegates
mapping (address => address) public delegates;
// Checkpoint marking number of votes from a given block
struct Checkpoint {
uint64 fromBlock;
uint96 votes;
}
// Record of checkpoints for each account by index
mapping (address => mapping (uint64 => Checkpoint)) public checkpoints;
// Number of checkpoints for each account
mapping (address => uint64) public numCheckpoints;
// An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
// An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
// A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
// The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
// The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (
string memory name_,
string memory symbol_,
address owner_
)
Ownable(owner_)
{
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "Anoncats: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _tokenOwners.get(tokenId, "Anoncats: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "Anoncats: URI query for nonexistent token");
return _tokenURIs[tokenId];
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = Anoncats.ownerOf(tokenId);
require(to != owner, "Anoncats: approval to current owner");
require(_msgSender() == owner || Anoncats.isApprovedForAll(owner, _msgSender()),
"Anoncats: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "Anoncats: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
require(operator != _msgSender(), "Anoncats: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "Anoncats: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "Anoncats: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Pauses the contract in case of any serious unknown issue.
* This will prevent all token transfers.
*
* Requirements:
*
* - onlyOwner
*/
function pause() onlyOwner external {
_pause();
}
/**
* @dev Unpauses the contract and allows token transfers
*
* Requirements:
*
* - onlyOwner
*/
function unpause() onlyOwner external {
_unpause();
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
* This allows the contract owner to edit URI when token is in possession.
* This is to prevent any potential rugpulls by deleting all token URIs.
*
* Requirements:
* - token can only be editable by the owner
* - token must be in possession of owner of contract
* - `tokenId` must exist.
*/
function setTokenURI(uint256 tokenId, string memory _tokenURI) external {
require(_exists(tokenId), "Anoncats: URI set of nonexistent token");
require(_msgSender() == owner(), "Anoncats: not the contract owner");
require(Anoncats.ownerOf(tokenId) == owner(), "Anoncats: not in contract owner possession");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Mints token with tokenURI
*
* Requirements:
* - tokens can only be minted by owner of contract
* - max number of tokens is 100
*/
function mint(string memory _tokenURI) external onlyOwner {
require(tokenCount <= tokenCountMax, "Anoncats: max number of token minted");
_safeMint(_msgSender(), tokenCount);
_tokenURIs[tokenCount] = _tokenURI;
tokenCount = tokenCount.add(1);
}
/**
* @dev Get current votes for account
*/
function getCurrentVotes(address account) public view returns (uint96) {
uint64 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @dev Get prior votes for an account as of a given blocknumber
*/
function getPriorVotes(address account, uint blockNumber) public view returns(uint96) {
require(blockNumber < block.number, "Anoncats: not yet determined");
uint64 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint64 lower = 0;
uint64 upper = nCheckpoints - 1;
while (upper > lower) {
uint64 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
/**
* @dev Delegate votes from `_msgSender()` to `delegatee`
*/
function delegate(address delegatee) public {
require(delegatee != address(0), "Anoncats: cannot delegate to 0 address");
return _delegate(_msgSender(), delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(_name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Anoncats: invalid signature");
require(nonce == nonces[signatory]++, "Anoncats: invalid nonce");
require(block.timestamp <= expiry, "Anoncats: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @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 {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "Anoncats: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "Anoncats: operator query for nonexistent token");
address owner = Anoncats.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || Anoncats.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal {
_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 {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "Anoncats: 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 {
require(to != address(0), "Anoncats: mint to the zero address");
require(!_exists(tokenId), "Anoncats: token already minted");
_beforeTokenTransfer();
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
_moveDelegates(address(0), delegates[to], 1);
}
/**
* @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 {
require(Anoncats.ownerOf(tokenId) == from, "Anoncats: transfer of token that is not own"); // internal owner
require(to != address(0), "Anoncats: transfer to the zero address");
require(from != address(0), "Anoncats: transfer from the zero address");
_beforeTokenTransfer();
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
_moveDelegates(delegates[from], delegates[to], 1);
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = toUint96(Anoncats.balanceOf(delegator));
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint64 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "Anoncats: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint64 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "Anoncats: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint64 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint64 blockNumber = toUint64(block.number);
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "Anoncats: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal {
_tokenApprovals[tokenId] = to;
emit Approval(Anoncats.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer.
*/
function _beforeTokenTransfer() internal view {
require(!paused(), "Anoncats: token transfer prohibited when paused");
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function toUint96(uint256 value) internal pure returns (uint96) {
require(value < 2**96, "SafeCast: value doesn\'t fit in 96 bits");
return uint96(value);
}
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
function getChainId() public pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
// 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.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;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <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.6.2 <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.6.0 <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.6.0 <0.8.0;
import "../interfaces/IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor (address owner_) {
_owner = owner_;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @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);
}
| See {IERC721-safeTransferFrom}./ | function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "Anoncats: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
| 10,180,118 |
pragma solidity 0.5.15;
contract IAugur {
function createChildUniverse(bytes32 _parentPayoutDistributionHash, uint256[] memory _parentPayoutNumerators) public returns (IUniverse);
function isKnownUniverse(IUniverse _universe) public view returns (bool);
function trustedCashTransfer(address _from, address _to, uint256 _amount) public returns (bool);
function isTrustedSender(address _address) public returns (bool);
function onCategoricalMarketCreated(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, bytes32[] memory _outcomes) public returns (bool);
function onYesNoMarketCreated(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash) public returns (bool);
function onScalarMarketCreated(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, int256[] memory _prices, uint256 _numTicks) public returns (bool);
function logInitialReportSubmitted(IUniverse _universe, address _reporter, address _market, address _initialReporter, uint256 _amountStaked, bool _isDesignatedReporter, uint256[] memory _payoutNumerators, string memory _description, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime) public returns (bool);
function disputeCrowdsourcerCreated(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _size, uint256 _disputeRound) public returns (bool);
function logDisputeCrowdsourcerContribution(IUniverse _universe, address _reporter, address _market, address _disputeCrowdsourcer, uint256 _amountStaked, string memory description, uint256[] memory _payoutNumerators, uint256 _currentStake, uint256 _stakeRemaining, uint256 _disputeRound) public returns (bool);
function logDisputeCrowdsourcerCompleted(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime, bool _pacingOn, uint256 _totalRepStakedInPayout, uint256 _totalRepStakedInMarket, uint256 _disputeRound) public returns (bool);
function logInitialReporterRedeemed(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool);
function logDisputeCrowdsourcerRedeemed(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool);
function logMarketFinalized(IUniverse _universe, uint256[] memory _winningPayoutNumerators) public returns (bool);
function logMarketMigrated(IMarket _market, IUniverse _originalUniverse) public returns (bool);
function logReportingParticipantDisavowed(IUniverse _universe, IMarket _market) public returns (bool);
function logMarketParticipantsDisavowed(IUniverse _universe) public returns (bool);
function logCompleteSetsPurchased(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets) public returns (bool);
function logCompleteSetsSold(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets, uint256 _fees) public returns (bool);
function logMarketOIChanged(IUniverse _universe, IMarket _market) public returns (bool);
function logTradingProceedsClaimed(IUniverse _universe, address _sender, address _market, uint256 _outcome, uint256 _numShares, uint256 _numPayoutTokens, uint256 _fees) public returns (bool);
function logUniverseForked(IMarket _forkingMarket) public returns (bool);
function logReputationTokensTransferred(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool);
function logReputationTokensBurned(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool);
function logReputationTokensMinted(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool);
function logShareTokensBalanceChanged(address _account, IMarket _market, uint256 _outcome, uint256 _balance) public returns (bool);
function logDisputeCrowdsourcerTokensTransferred(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool);
function logDisputeCrowdsourcerTokensBurned(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool);
function logDisputeCrowdsourcerTokensMinted(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool);
function logDisputeWindowCreated(IDisputeWindow _disputeWindow, uint256 _id, bool _initial) public returns (bool);
function logParticipationTokensRedeemed(IUniverse universe, address _sender, uint256 _attoParticipationTokens, uint256 _feePayoutShare) public returns (bool);
function logTimestampSet(uint256 _newTimestamp) public returns (bool);
function logInitialReporterTransferred(IUniverse _universe, IMarket _market, address _from, address _to) public returns (bool);
function logMarketTransferred(IUniverse _universe, address _from, address _to) public returns (bool);
function logParticipationTokensTransferred(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool);
function logParticipationTokensBurned(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool);
function logParticipationTokensMinted(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool);
function logMarketRepBondTransferred(address _universe, address _from, address _to) public returns (bool);
function logWarpSyncDataUpdated(address _universe, uint256 _warpSyncHash, uint256 _marketEndTime) public returns (bool);
function isKnownFeeSender(address _feeSender) public view returns (bool);
function lookup(bytes32 _key) public view returns (address);
function getTimestamp() public view returns (uint256);
function getMaximumMarketEndDate() public returns (uint256);
function isKnownMarket(IMarket _market) public view returns (bool);
function derivePayoutDistributionHash(uint256[] memory _payoutNumerators, uint256 _numTicks, uint256 numOutcomes) public view returns (bytes32);
function logValidityBondChanged(uint256 _validityBond) public returns (bool);
function logDesignatedReportStakeChanged(uint256 _designatedReportStake) public returns (bool);
function logNoShowBondChanged(uint256 _noShowBond) public returns (bool);
function logReportingFeeChanged(uint256 _reportingFee) public returns (bool);
function getUniverseForkIndex(IUniverse _universe) public view returns (uint256);
}
interface IAugurWallet {
function initialize(address _owner, address _referralAddress, bytes32 _fingerprint, address _augur, address _registry, address _registryV2, IERC20 _cash, IAffiliates _affiliates, IERC1155 _shareToken, address _createOrder, address _fillOrder, address _zeroXTrade) external;
function transferCash(address _to, uint256 _amount) external;
function executeTransaction(address _to, bytes calldata _data, uint256 _value) external returns (bool);
}
interface IAugurWalletRegistry {
function ethExchange() external returns (IUniswapV2Pair);
function WETH() external returns (IWETH);
function token0IsCash() external returns (bool);
}
contract IAugurWalletFactory {
function getCreate2WalletAddress(address _owner) external view returns (address);
function createAugurWallet(address _owner, address _referralAddress, bytes32 _fingerprint) public returns (IAugurWallet);
}
contract Context {
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;
}
}
interface IRelayHub {
// Relay management
/**
* @dev Adds stake to a relay and sets its `unstakeDelay`. If the relay does not exist, it is created, and the caller
* of this function becomes its owner. If the relay already exists, only the owner can call this function. A relay
* cannot be its own owner.
*
* All Ether in this function call will be added to the relay's stake.
* Its unstake delay will be assigned to `unstakeDelay`, but the new value must be greater or equal to the current one.
*
* Emits a {Staked} event.
*/
function stake(address relayaddr, uint256 unstakeDelay) external payable;
/**
* @dev Emitted when a relay's stake or unstakeDelay are increased
*/
event Staked(address indexed relay, uint256 stake, uint256 unstakeDelay);
/**
* @dev Registers the caller as a relay.
* The relay must be staked for, and not be a contract (i.e. this function must be called directly from an EOA).
*
* This function can be called multiple times, emitting new {RelayAdded} events. Note that the received
* `transactionFee` is not enforced by {relayCall}.
*
* Emits a {RelayAdded} event.
*/
function registerRelay(uint256 transactionFee, string calldata url) external;
/**
* @dev Emitted when a relay is registered or re-registerd. Looking at these events (and filtering out
* {RelayRemoved} events) lets a client discover the list of available relays.
*/
event RelayAdded(address indexed relay, address indexed owner, uint256 transactionFee, uint256 stake, uint256 unstakeDelay, string url);
/**
* @dev Removes (deregisters) a relay. Unregistered (but staked for) relays can also be removed.
*
* Can only be called by the owner of the relay. After the relay's `unstakeDelay` has elapsed, {unstake} will be
* callable.
*
* Emits a {RelayRemoved} event.
*/
function removeRelayByOwner(address relay) external;
/**
* @dev Emitted when a relay is removed (deregistered). `unstakeTime` is the time when unstake will be callable.
*/
event RelayRemoved(address indexed relay, uint256 unstakeTime);
/** Deletes the relay from the system, and gives back its stake to the owner.
*
* Can only be called by the relay owner, after `unstakeDelay` has elapsed since {removeRelayByOwner} was called.
*
* Emits an {Unstaked} event.
*/
function unstake(address relay) external;
/**
* @dev Emitted when a relay is unstaked for, including the returned stake.
*/
event Unstaked(address indexed relay, uint256 stake);
// States a relay can be in
enum RelayState {
Unknown, // The relay is unknown to the system: it has never been staked for
Staked, // The relay has been staked for, but it is not yet active
Registered, // The relay has registered itself, and is active (can relay calls)
Removed // The relay has been removed by its owner and can no longer relay calls. It must wait for its unstakeDelay to elapse before it can unstake
}
/**
* @dev Returns a relay's status. Note that relays can be deleted when unstaked or penalized, causing this function
* to return an empty entry.
*/
function getRelay(address relay) external view returns (uint256 totalStake, uint256 unstakeDelay, uint256 unstakeTime, address payable owner, RelayState state);
// Balance management
/**
* @dev Deposits Ether for a contract, so that it can receive (and pay for) relayed transactions.
*
* Unused balance can only be withdrawn by the contract itself, by calling {withdraw}.
*
* Emits a {Deposited} event.
*/
function depositFor(address target) external payable;
/**
* @dev Emitted when {depositFor} is called, including the amount and account that was funded.
*/
event Deposited(address indexed recipient, address indexed from, uint256 amount);
/**
* @dev Returns an account's deposits. These can be either a contracts's funds, or a relay owner's revenue.
*/
function balanceOf(address target) external view returns (uint256);
/**
* Withdraws from an account's balance, sending it back to it. Relay owners call this to retrieve their revenue, and
* contracts can use it to reduce their funding.
*
* Emits a {Withdrawn} event.
*/
function withdraw(uint256 amount, address payable dest) external;
/**
* @dev Emitted when an account withdraws funds from `RelayHub`.
*/
event Withdrawn(address indexed account, address indexed dest, uint256 amount);
// Relaying
/**
* @dev Checks if the `RelayHub` will accept a relayed operation.
* Multiple things must be true for this to happen:
* - all arguments must be signed for by the sender (`from`)
* - the sender's nonce must be the current one
* - the recipient must accept this transaction (via {acceptRelayedCall})
*
* Returns a `PreconditionCheck` value (`OK` when the transaction can be relayed), or a recipient-specific error
* code if it returns one in {acceptRelayedCall}.
*/
function canRelay(
address relay,
address from,
address to,
bytes calldata encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes calldata signature,
bytes calldata approvalData
) external view returns (uint256 status, bytes memory recipientContext);
// Preconditions for relaying, checked by canRelay and returned as the corresponding numeric values.
enum PreconditionCheck {
OK, // All checks passed, the call can be relayed
WrongSignature, // The transaction to relay is not signed by requested sender
WrongNonce, // The provided nonce has already been used by the sender
AcceptRelayedCallReverted, // The recipient rejected this call via acceptRelayedCall
InvalidRecipientStatusCode // The recipient returned an invalid (reserved) status code
}
/**
* @dev Relays a transaction.
*
* For this to succeed, multiple conditions must be met:
* - {canRelay} must `return PreconditionCheck.OK`
* - the sender must be a registered relay
* - the transaction's gas price must be larger or equal to the one that was requested by the sender
* - the transaction must have enough gas to not run out of gas if all internal transactions (calls to the
* recipient) use all gas available to them
* - the recipient must have enough balance to pay the relay for the worst-case scenario (i.e. when all gas is
* spent)
*
* If all conditions are met, the call will be relayed and the recipient charged. {preRelayedCall}, the encoded
* function and {postRelayedCall} will be called in that order.
*
* Parameters:
* - `from`: the client originating the request
* - `to`: the target {IRelayRecipient} contract
* - `encodedFunction`: the function call to relay, including data
* - `transactionFee`: fee (%) the relay takes over actual gas cost
* - `gasPrice`: gas price the client is willing to pay
* - `gasLimit`: gas to forward when calling the encoded function
* - `nonce`: client's nonce
* - `signature`: client's signature over all previous params, plus the relay and RelayHub addresses
* - `approvalData`: dapp-specific data forwared to {acceptRelayedCall}. This value is *not* verified by the
* `RelayHub`, but it still can be used for e.g. a signature.
*
* Emits a {TransactionRelayed} event.
*/
function relayCall(
address from,
address to,
bytes calldata encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes calldata signature,
bytes calldata approvalData
) external;
/**
* @dev Emitted when an attempt to relay a call failed.
*
* This can happen due to incorrect {relayCall} arguments, or the recipient not accepting the relayed call. The
* actual relayed call was not executed, and the recipient not charged.
*
* The `reason` parameter contains an error code: values 1-10 correspond to `PreconditionCheck` entries, and values
* over 10 are custom recipient error codes returned from {acceptRelayedCall}.
*/
event CanRelayFailed(address indexed relay, address indexed from, address indexed to, bytes4 selector, uint256 reason);
/**
* @dev Emitted when a transaction is relayed.
* Useful when monitoring a relay's operation and relayed calls to a contract
*
* Note that the actual encoded function might be reverted: this is indicated in the `status` parameter.
*
* `charge` is the Ether value deducted from the recipient's balance, paid to the relay's owner.
*/
event TransactionRelayed(address indexed relay, address indexed from, address indexed to, bytes4 selector, RelayCallStatus status, uint256 charge);
// Reason error codes for the TransactionRelayed event
enum RelayCallStatus {
OK, // The transaction was successfully relayed and execution successful - never included in the event
RelayedCallFailed, // The transaction was relayed, but the relayed call failed
PreRelayedFailed, // The transaction was not relayed due to preRelatedCall reverting
PostRelayedFailed, // The transaction was relayed and reverted due to postRelatedCall reverting
RecipientBalanceChanged // The transaction was relayed and reverted due to the recipient's balance changing
}
/**
* @dev Returns how much gas should be forwarded to a call to {relayCall}, in order to relay a transaction that will
* spend up to `relayedCallStipend` gas.
*/
function requiredGas(uint256 relayedCallStipend) external view returns (uint256);
/**
* @dev Returns the maximum recipient charge, given the amount of gas forwarded, gas price and relay fee.
*/
function maxPossibleCharge(uint256 relayedCallStipend, uint256 gasPrice, uint256 transactionFee) external view returns (uint256);
// Relay penalization.
// Any account can penalize relays, removing them from the system immediately, and rewarding the
// reporter with half of the relay's stake. The other half is burned so that, even if the relay penalizes itself, it
// still loses half of its stake.
/**
* @dev Penalize a relay that signed two transactions using the same nonce (making only the first one valid) and
* different data (gas price, gas limit, etc. may be different).
*
* The (unsigned) transaction data and signature for both transactions must be provided.
*/
function penalizeRepeatedNonce(bytes calldata unsignedTx1, bytes calldata signature1, bytes calldata unsignedTx2, bytes calldata signature2) external;
/**
* @dev Penalize a relay that sent a transaction that didn't target `RelayHub`'s {registerRelay} or {relayCall}.
*/
function penalizeIllegalTransaction(bytes calldata unsignedTx, bytes calldata signature) external;
/**
* @dev Emitted when a relay is penalized.
*/
event Penalized(address indexed relay, address sender, uint256 amount);
/**
* @dev Returns an account's nonce in `RelayHub`.
*/
function getNonce(address from) external view returns (uint256);
}
interface IRelayRecipient {
/**
* @dev Returns the address of the {IRelayHub} instance this recipient interacts with.
*/
function getHubAddr() external view returns (address);
/**
* @dev Called by {IRelayHub} to validate if this recipient accepts being charged for a relayed call. Note that the
* recipient will be charged regardless of the execution result of the relayed call (i.e. if it reverts or not).
*
* The relay request was originated by `from` and will be served by `relay`. `encodedFunction` is the relayed call
* calldata, so its first four bytes are the function selector. The relayed call will be forwarded `gasLimit` gas,
* and the transaction executed with a gas price of at least `gasPrice`. `relay`'s fee is `transactionFee`, and the
* recipient will be charged at most `maxPossibleCharge` (in wei). `nonce` is the sender's (`from`) nonce for
* replay attack protection in {IRelayHub}, and `approvalData` is a optional parameter that can be used to hold a signature
* over all or some of the previous values.
*
* Returns a tuple, where the first value is used to indicate approval (0) or rejection (custom non-zero error code,
* values 1 to 10 are reserved) and the second one is data to be passed to the other {IRelayRecipient} functions.
*
* {acceptRelayedCall} is called with 50k gas: if it runs out during execution, the request will be considered
* rejected. A regular revert will also trigger a rejection.
*/
function acceptRelayedCall(
address relay,
address from,
bytes calldata encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes calldata approvalData,
uint256 maxPossibleCharge
)
external
view
returns (uint256, bytes memory);
/**
* @dev Called by {IRelayHub} on approved relay call requests, before the relayed call is executed. This allows to e.g.
* pre-charge the sender of the transaction.
*
* `context` is the second value returned in the tuple by {acceptRelayedCall}.
*
* Returns a value to be passed to {postRelayedCall}.
*
* {preRelayedCall} is called with 100k gas: if it runs out during exection or otherwise reverts, the relayed call
* will not be executed, but the recipient will still be charged for the transaction's cost.
*/
function preRelayedCall(bytes calldata context) external returns (bytes32);
/**
* @dev Called by {IRelayHub} on approved relay call requests, after the relayed call is executed. This allows to e.g.
* charge the user for the relayed call costs, return any overcharges from {preRelayedCall}, or perform
* contract-specific bookkeeping.
*
* `context` is the second value returned in the tuple by {acceptRelayedCall}. `success` is the execution status of
* the relayed call. `actualCharge` is an estimate of how much the recipient will be charged for the transaction,
* not including any gas used by {postRelayedCall} itself. `preRetVal` is {preRelayedCall}'s return value.
*
*
* {postRelayedCall} is called with 100k gas: if it runs out during execution or otherwise reverts, the relayed call
* and the call to {preRelayedCall} will be reverted retroactively, but the recipient will still be charged for the
* transaction's cost.
*/
function postRelayedCall(bytes calldata context, bool success, uint256 actualCharge, bytes32 preRetVal) external;
}
contract GSNRecipient is IRelayRecipient, Context {
// Default RelayHub address, deployed on mainnet and all testnets at the same address
address private _relayHub = 0xD216153c06E857cD7f72665E0aF1d7D82172F494;
uint256 constant private RELAYED_CALL_ACCEPTED = 0;
uint256 constant private RELAYED_CALL_REJECTED = 11;
// How much gas is forwarded to postRelayedCall
uint256 constant internal POST_RELAYED_CALL_MAX_GAS = 100000;
/**
* @dev Emitted when a contract changes its {IRelayHub} contract to a new one.
*/
event RelayHubChanged(address indexed oldRelayHub, address indexed newRelayHub);
/**
* @dev Returns the address of the {IRelayHub} contract for this recipient.
*/
function getHubAddr() public view returns (address) {
return _relayHub;
}
/**
* @dev Switches to a new {IRelayHub} instance. This method is added for future-proofing: there's no reason to not
* use the default instance.
*
* IMPORTANT: After upgrading, the {GSNRecipient} will no longer be able to receive relayed calls from the old
* {IRelayHub} instance. Additionally, all funds should be previously withdrawn via {_withdrawDeposits}.
*/
function _upgradeRelayHub(address newRelayHub) internal {
address currentRelayHub = _relayHub;
require(newRelayHub != address(0), "GSNRecipient: new RelayHub is the zero address");
require(newRelayHub != currentRelayHub, "GSNRecipient: new RelayHub is the current one");
emit RelayHubChanged(currentRelayHub, newRelayHub);
_relayHub = newRelayHub;
}
/**
* @dev Returns the version string of the {IRelayHub} for which this recipient implementation was built. If
* {_upgradeRelayHub} is used, the new {IRelayHub} instance should be compatible with this version.
*/
// This function is view for future-proofing, it may require reading from
// storage in the future.
function relayHubVersion() public view returns (string memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return "1.0.0";
}
/**
* @dev Withdraws the recipient's deposits in `RelayHub`.
*
* Derived contracts should expose this in an external interface with proper access control.
*/
function _withdrawDeposits(uint256 amount, address payable payee) internal {
IRelayHub(_relayHub).withdraw(amount, payee);
}
// Overrides for Context's functions: when called from RelayHub, sender and
// data require some pre-processing: the actual sender is stored at the end
// of the call data, which in turns means it needs to be removed from it
// when handling said data.
/**
* @dev Replacement for msg.sender. Returns the actual sender of a transaction: msg.sender for regular transactions,
* and the end-user for GSN relayed calls (where msg.sender is actually `RelayHub`).
*
* IMPORTANT: Contracts derived from {GSNRecipient} should never use `msg.sender`, and use {_msgSender} instead.
*/
function _msgSender() internal view returns (address payable) {
if (block.coinbase != _relayHub) { //injected CONTRACT AFFECTED BY MINERS
return msg.sender;
} else {
return _getRelayedCallSender();
}
}
/**
* @dev Replacement for msg.data. Returns the actual calldata of a transaction: msg.data for regular transactions,
* and a reduced version for GSN relayed calls (where msg.data contains additional information).
*
* IMPORTANT: Contracts derived from {GSNRecipient} should never use `msg.data`, and use {_msgData} instead.
*/
function _msgData() internal view returns (bytes memory) {
if (block.coinbase != _relayHub) { //injected CONTRACT AFFECTED BY MINERS
return msg.data;
} else {
return _getRelayedCallData();
}
}
// Base implementations for pre and post relayedCall: only RelayHub can invoke them, and data is forwarded to the
// internal hook.
/**
* @dev See `IRelayRecipient.preRelayedCall`.
*
* This function should not be overriden directly, use `_preRelayedCall` instead.
*
* * Requirements:
*
* - the caller must be the `RelayHub` contract.
*/
function preRelayedCall(bytes calldata context) external returns (bytes32) {
require(msg.sender == getHubAddr(), "GSNRecipient: caller is not RelayHub");
return _preRelayedCall(context);
}
/**
* @dev See `IRelayRecipient.preRelayedCall`.
*
* Called by `GSNRecipient.preRelayedCall`, which asserts the caller is the `RelayHub` contract. Derived contracts
* must implement this function with any relayed-call preprocessing they may wish to do.
*
*/
function _preRelayedCall(bytes memory context) internal returns (bytes32);
/**
* @dev See `IRelayRecipient.postRelayedCall`.
*
* This function should not be overriden directly, use `_postRelayedCall` instead.
*
* * Requirements:
*
* - the caller must be the `RelayHub` contract.
*/
function postRelayedCall(bytes calldata context, bool success, uint256 actualCharge, bytes32 preRetVal) external {
require(msg.sender == getHubAddr(), "GSNRecipient: caller is not RelayHub");
_postRelayedCall(context, success, actualCharge, preRetVal);
}
/**
* @dev See `IRelayRecipient.postRelayedCall`.
*
* Called by `GSNRecipient.postRelayedCall`, which asserts the caller is the `RelayHub` contract. Derived contracts
* must implement this function with any relayed-call postprocessing they may wish to do.
*
*/
function _postRelayedCall(bytes memory context, bool success, uint256 actualCharge, bytes32 preRetVal) internal;
/**
* @dev Return this in acceptRelayedCall to proceed with the execution of a relayed call. Note that this contract
* will be charged a fee by RelayHub
*/
function _approveRelayedCall() internal pure returns (uint256, bytes memory) {
return _approveRelayedCall("");
}
/**
* @dev See `GSNRecipient._approveRelayedCall`.
*
* This overload forwards `context` to _preRelayedCall and _postRelayedCall.
*/
function _approveRelayedCall(bytes memory context) internal pure returns (uint256, bytes memory) {
return (RELAYED_CALL_ACCEPTED, context);
}
/**
* @dev Return this in acceptRelayedCall to impede execution of a relayed call. No fees will be charged.
*/
function _rejectRelayedCall(uint256 errorCode) internal pure returns (uint256, bytes memory) {
return (RELAYED_CALL_REJECTED + errorCode, "");
}
/*
* @dev Calculates how much RelayHub will charge a recipient for using `gas` at a `gasPrice`, given a relayer's
* `serviceFee`.
*/
function _computeCharge(uint256 gas, uint256 gasPrice, uint256 serviceFee) internal pure returns (uint256) {
// The fee is expressed as a percentage. E.g. a value of 40 stands for a 40% fee, so the recipient will be
// charged for 1.4 times the spent amount.
return (gas * gasPrice * (100 + serviceFee)) / 100;
}
function _getRelayedCallSender() private pure returns (address payable result) {
// We need to read 20 bytes (an address) located at array index msg.data.length - 20. In memory, the array
// is prefixed with a 32-byte length value, so we first add 32 to get the memory read index. However, doing
// so would leave the address in the upper 20 bytes of the 32-byte word, which is inconvenient and would
// require bit shifting. We therefore subtract 12 from the read index so the address lands on the lower 20
// bytes. This can always be done due to the 32-byte prefix.
// The final memory read index is msg.data.length - 20 + 32 - 12 = msg.data.length. Using inline assembly is the
// easiest/most-efficient way to perform this operation.
// These fields are not accessible from assembly
bytes memory array = msg.data;
uint256 index = msg.data.length;
// solhint-disable-next-line no-inline-assembly
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
result := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
return result;
}
function _getRelayedCallData() private pure returns (bytes memory) {
// RelayHub appends the sender address at the end of the calldata, so in order to retrieve the actual msg.data,
// we must strip the last 20 bytes (length of an address type) from it.
uint256 actualDataLength = msg.data.length - 20;
bytes memory actualData = new bytes(actualDataLength);
for (uint256 i = 0; i < actualDataLength; ++i) {
actualData[i] = msg.data[i];
}
return actualData;
}
}
library RLPReader {
uint8 constant STRING_SHORT_START = 0x80;
uint8 constant STRING_LONG_START = 0xb8;
uint8 constant LIST_SHORT_START = 0xc0;
uint8 constant LIST_LONG_START = 0xf8;
uint8 constant WORD_SIZE = 32;
struct RLPItem {
uint len;
uint memPtr;
}
using RLPReader for bytes;
using RLPReader for uint;
using RLPReader for RLPReader.RLPItem;
// helper function to decode rlp encoded ethereum transaction
/*
* @param rawTransaction RLP encoded ethereum transaction
* @return tuple (nonce,gasPrice,gasLimit,to,value,data)
*/
function decodeTransaction(bytes memory rawTransaction) internal pure returns (uint, uint, uint, address, uint, bytes memory){
RLPReader.RLPItem[] memory values = rawTransaction.toRlpItem().toList(); // must convert to an rlpItem first!
return (values[0].toUint(), values[1].toUint(), values[2].toUint(), values[3].toAddress(), values[4].toUint(), values[5].toBytes());
}
/*
* @param item RLP encoded bytes
*/
function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) {
if (item.length == 0)
return RLPItem(0, 0);
uint memPtr;
assembly {
memPtr := add(item, 0x20)
}
return RLPItem(item.length, memPtr);
}
/*
* @param item RLP encoded list in bytes
*/
function toList(RLPItem memory item) internal pure returns (RLPItem[] memory result) {
require(isList(item), "isList failed");
uint items = numItems(item);
result = new RLPItem[](items);
uint memPtr = item.memPtr + _payloadOffset(item.memPtr);
uint dataLen;
for (uint i = 0; i < items; i++) {
dataLen = _itemLength(memPtr);
result[i] = RLPItem(dataLen, memPtr);
memPtr = memPtr + dataLen;
}
}
/*
* Helpers
*/
// @return indicator whether encoded payload is a list. negate this function call for isData.
function isList(RLPItem memory item) internal pure returns (bool) {
uint8 byte0;
uint memPtr = item.memPtr;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < LIST_SHORT_START)
return false;
return true;
}
// @return number of payload items inside an encoded list.
function numItems(RLPItem memory item) internal pure returns (uint) {
uint count = 0;
uint currPtr = item.memPtr + _payloadOffset(item.memPtr);
uint endPtr = item.memPtr + item.len;
while (currPtr < endPtr) {
currPtr = currPtr + _itemLength(currPtr);
// skip over an item
count++;
}
return count;
}
// @return entire rlp item byte length
function _itemLength(uint memPtr) internal pure returns (uint len) {
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
return 1;
else if (byte0 < STRING_LONG_START)
return byte0 - STRING_SHORT_START + 1;
else if (byte0 < LIST_SHORT_START) {
assembly {
let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is
memPtr := add(memPtr, 1) // skip over the first byte
/* 32 byte word size */
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len
len := add(dataLen, add(byteLen, 1))
}
}
else if (byte0 < LIST_LONG_START) {
return byte0 - LIST_SHORT_START + 1;
}
else {
assembly {
let byteLen := sub(byte0, 0xf7)
memPtr := add(memPtr, 1)
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length
len := add(dataLen, add(byteLen, 1))
}
}
}
// @return number of bytes until the data
function _payloadOffset(uint memPtr) internal pure returns (uint) {
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
return 0;
else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START))
return 1;
else if (byte0 < LIST_SHORT_START) // being explicit
return byte0 - (STRING_LONG_START - 1) + 1;
else
return byte0 - (LIST_LONG_START - 1) + 1;
}
/** RLPItem conversions into data types **/
// @returns raw rlp encoding in bytes
function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) {
bytes memory result = new bytes(item.len);
uint ptr;
assembly {
ptr := add(0x20, result)
}
copy(item.memPtr, ptr, item.len);
return result;
}
function toBoolean(RLPItem memory item) internal pure returns (bool) {
require(item.len == 1, "Invalid RLPItem. Booleans are encoded in 1 byte");
uint result;
uint memPtr = item.memPtr;
assembly {
result := byte(0, mload(memPtr))
}
return result == 0 ? false : true;
}
function toAddress(RLPItem memory item) internal pure returns (address) {
// 1 byte for the length prefix according to RLP spec
require(item.len <= 21, "Invalid RLPItem. Addresses are encoded in 20 bytes or less");
return address(toUint(item));
}
function toUint(RLPItem memory item) internal pure returns (uint) {
uint offset = _payloadOffset(item.memPtr);
uint len = item.len - offset;
uint memPtr = item.memPtr + offset;
uint result;
assembly {
result := div(mload(memPtr), exp(256, sub(32, len))) // shift to the correct location
}
return result;
}
function toBytes(RLPItem memory item) internal pure returns (bytes memory) {
uint offset = _payloadOffset(item.memPtr);
uint len = item.len - offset;
// data length
bytes memory result = new bytes(len);
uint destPtr;
assembly {
destPtr := add(0x20, result)
}
copy(item.memPtr + offset, destPtr, len);
return result;
}
/*
* @param src Pointer to source
* @param dest Pointer to destination
* @param len Amount of memory to copy from the source
*/
function copy(uint src, uint dest, uint len) internal pure {
// copy as many word sizes as possible
for (; len >= WORD_SIZE; len -= WORD_SIZE) {
assembly {
mstore(dest, mload(src))
}
src += WORD_SIZE;
dest += WORD_SIZE;
}
// left over bytes. Mask is used to remove unwanted bytes from the word
uint mask = 256 ** (WORD_SIZE - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask)) // zero out src
let destpart := and(mload(dest), mask) // retrieve the bytes
mstore(dest, or(destpart, srcpart))
}
}
}
library ContractExists {
function exists(address _address) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(_address) }
return size > 0;
}
}
contract IOwnable {
function getOwner() public view returns (address);
function transferOwnership(address _newOwner) public returns (bool);
}
contract ITyped {
function getTypeName() public view returns (bytes32);
}
contract Initializable {
bool private initialized = false;
modifier beforeInitialized {
require(!initialized);
_;
}
function endInitialization() internal beforeInitialized {
initialized = true;
}
function getInitialized() public view returns (bool) {
return initialized;
}
}
contract AugurWallet is Initializable, IAugurWallet {
using SafeMathUint256 for uint256;
IAugurWalletRegistry public registry;
mapping(address => bool) public authorizedProxies;
uint256 private constant MAX_APPROVAL_AMOUNT = 2 ** 256 - 1;
//keccak256("EIP712Domain(address verifyingContract)");
bytes32 public constant DOMAIN_SEPARATOR_TYPEHASH = 0x035aff83d86937d35b32e04f0ddc6ff469290eef2f1b692d8a815c89404d4749;
//keccak256("AugurWalletMessage(bytes message)");
bytes32 public constant MSG_TYPEHASH = 0xe0e790a7bae5fba0106cf286392dd87dfd6ec8631e5631988133e4470b9e7b0d;
// bytes4(keccak256("isValidSignature(bytes,bytes)")
bytes4 constant internal EIP1271_MAGIC_VALUE = 0x20c13b0b;
address owner;
bytes32 public domainSeparator;
IERC20 public cash;
function initialize(address _owner, address _referralAddress, bytes32 _fingerprint, address _augur, address _registry, address _registryV2, IERC20 _cash, IAffiliates _affiliates, IERC1155 _shareToken, address _createOrder, address _fillOrder, address _zeroXTrade) external beforeInitialized {
endInitialization();
domainSeparator = keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, this));
owner = _owner;
registry = IAugurWalletRegistry(_registryV2);
authorizedProxies[_registry] = true;
authorizedProxies[_registryV2] = true;
cash = _cash;
_cash.approve(_augur, MAX_APPROVAL_AMOUNT);
_cash.approve(_createOrder, MAX_APPROVAL_AMOUNT);
_shareToken.setApprovalForAll(_createOrder, true);
_cash.approve(_fillOrder, MAX_APPROVAL_AMOUNT);
_shareToken.setApprovalForAll(_fillOrder, true);
_cash.approve(_zeroXTrade, MAX_APPROVAL_AMOUNT);
_affiliates.setFingerprint(_fingerprint);
if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS
_affiliates.setReferrer(_referralAddress);
}
}
function transferCash(address _to, uint256 _amount) external {
require(authorizedProxies[msg.sender]);
cash.transfer(_to, _amount);
}
function executeTransaction(address _to, bytes calldata _data, uint256 _value) external returns (bool) {
require(authorizedProxies[msg.sender]);
(bool _didSucceed, bytes memory _resultData) = address(_to).call.value(_value)(_data);
return _didSucceed;
}
function addAuthorizedProxy(address _authorizedProxy) external returns (bool) {
require(msg.sender == owner || authorizedProxies[msg.sender] || msg.sender == address(this));
authorizedProxies[_authorizedProxy] = true;
return true;
}
function removeAuthorizedProxy(address _authorizedProxy) external returns (bool) {
require(msg.sender == owner || authorizedProxies[msg.sender] || msg.sender == address(this));
authorizedProxies[_authorizedProxy] = false;
return true;
}
function withdrawAllFundsAsDai(address _destination, uint256 _minExchangeRateInDai) external payable returns (bool) {
require(msg.sender == owner);
IUniswapV2Pair _ethExchange = registry.ethExchange();
IWETH _weth = registry.WETH();
bool _token0IsCash = registry.token0IsCash();
uint256 _ethAmount = address(this).balance;
(uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) = _ethExchange.getReserves();
uint256 _cashAmount = getAmountOut(_ethAmount, _token0IsCash ? _reserve1 : _reserve0, _token0IsCash ? _reserve0 : _reserve1);
uint256 _exchangeRate = _cashAmount.mul(10**18).div(_ethAmount);
require(_minExchangeRateInDai <= _exchangeRate, "Exchange rate too low");
_weth.deposit.value(_ethAmount)();
_weth.transfer(address(_ethExchange), _ethAmount);
_ethExchange.swap(_token0IsCash ? _cashAmount : 0, _token0IsCash ? 0 : _cashAmount, address(this), "");
cash.transfer(_destination, cash.balanceOf(address(this)));
return true;
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) public pure returns (uint amountOut) {
require(amountIn > 0);
require(reserveIn > 0 && reserveOut > 0);
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
function isValidSignature(bytes calldata _data, bytes calldata _signature) external view returns (bytes4) {
bytes32 _messageHash = getMessageHash(_data);
require(_signature.length >= 65, "Signature data length incorrect");
bytes32 _r;
bytes32 _s;
uint8 _v;
bytes memory _sig = _signature;
assembly {
_r := mload(add(_sig, 32))
_s := mload(add(_sig, 64))
_v := and(mload(add(_sig, 65)), 255)
}
require(owner == ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _messageHash)), _v, _r, _s), "Invalid Signature");
return EIP1271_MAGIC_VALUE;
}
/// @dev Returns hash of a message that can be signed by the owner.
/// @param _message Message that should be hashed
/// @return Message hash.
function getMessageHash(bytes memory _message) public view returns (bytes32) {
bytes32 safeMessageHash = keccak256(abi.encode(MSG_TYPEHASH, keccak256(_message)));
return keccak256(abi.encodePacked(byte(0x19), byte(0x01), domainSeparator, safeMessageHash));
}
function () external payable {}
}
library LibBytes {
using LibBytes for bytes;
/// @dev Tests equality of two byte arrays.
/// @param lhs First byte array to compare.
/// @param rhs Second byte array to compare.
/// @return True if arrays are the same. False otherwise.
function equals(
bytes memory lhs,
bytes memory rhs
)
internal
pure
returns (bool equal)
{
// Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare.
// We early exit on unequal lengths, but keccak would also correctly
// handle this.
return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs);
}
/// @dev Gets the memory address for the contents of a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of the contents of the byte array.
function contentAddress(bytes memory input)
internal
pure
returns (uint256 memoryAddress)
{
assembly {
memoryAddress := add(input, 32)
}
return memoryAddress;
}
/// @dev Copies `length` bytes from memory location `source` to `dest`.
/// @param dest memory address to copy bytes to.
/// @param source memory address to copy bytes from.
/// @param length number of bytes to copy.
function memCopy(
uint256 dest,
uint256 source,
uint256 length
)
internal
pure
{
if (length < 32) {
// Handle a partial word by reading destination and masking
// off the bits we are interested in.
// This correctly handles overlap, zero lengths and source == dest
assembly {
let mask := sub(exp(256, sub(32, length)), 1)
let s := and(mload(source), not(mask))
let d := and(mload(dest), mask)
mstore(dest, or(s, d))
}
} else {
// Skip the O(length) loop when source == dest.
if (source == dest) {
return;
}
// For large copies we copy whole words at a time. The final
// word is aligned to the end of the range (instead of after the
// previous) to handle partial words. So a copy will look like this:
//
// ####
// ####
// ####
// ####
//
// We handle overlap in the source and destination range by
// changing the copying direction. This prevents us from
// overwriting parts of source that we still need to copy.
//
// This correctly handles source == dest
//
if (source > dest) {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because it
// is easier to compare with in the loop, and these
// are also the addresses we need for copying the
// last bytes.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the last 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the last bytes in
// source already due to overlap.
let last := mload(sEnd)
// Copy whole words front to back
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} lt(source, sEnd) {} {
mstore(dest, mload(source))
source := add(source, 32)
dest := add(dest, 32)
}
// Write the last 32 bytes
mstore(dEnd, last)
}
} else {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because those
// are the starting points when copying a word at the end.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the first 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the first bytes in
// source already due to overlap.
let first := mload(source)
// Copy whole words back to front
// We use a signed comparisson here to allow dEnd to become
// negative (happens when source and dest < 32). Valid
// addresses in local memory will never be larger than
// 2**255, so they can be safely re-interpreted as signed.
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} slt(dest, dEnd) {} {
mstore(dEnd, mload(sEnd))
sEnd := sub(sEnd, 32)
dEnd := sub(dEnd, 32)
}
// Write the first 32 bytes
mstore(dest, first)
}
}
}
}
/// @dev Returns a slices from a byte array.
/// @param b The byte array to take a slice from.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
function slice(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
// Ensure that the from and to positions are valid positions for a slice within
// the byte array that is being used.
if (from > to) {
revert();
}
if (to > b.length) {
revert();
}
// Create a new bytes structure and copy contents
result = new bytes(to - from);
memCopy(
result.contentAddress(),
b.contentAddress() + from,
result.length
);
return result;
}
/// @dev Returns a slice from a byte array without preserving the input.
/// @param b The byte array to take a slice from. Will be destroyed in the process.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
/// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted.
function sliceDestructive(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
// Ensure that the from and to positions are valid positions for a slice within
// the byte array that is being used.
if (from > to) {
revert();
}
if (to > b.length) {
revert();
}
// Create a new bytes structure around [from, to) in-place.
assembly {
result := add(b, from)
mstore(result, sub(to, from))
}
return result;
}
/// @dev Pops the last byte off of a byte array by modifying its length.
/// @param b Byte array that will be modified.
/// @return The byte that was popped off.
function popLastByte(bytes memory b)
internal
pure
returns (bytes1 result)
{
if (b.length == 0) {
revert();
}
// Store last byte.
result = b[b.length - 1];
assembly {
// Decrement length of byte array.
let newLen := sub(mload(b), 1)
mstore(b, newLen)
}
return result;
}
}
library SafeMathUint256 {
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;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
if (a <= b) {
return a;
} else {
return b;
}
}
function max(uint256 a, uint256 b) internal pure returns (uint256) {
if (a >= b) {
return a;
} else {
return b;
}
}
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
uint256 x = (y + 1) / 2;
z = y;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
function getUint256Min() internal pure returns (uint256) {
return 0;
}
function getUint256Max() internal pure returns (uint256) {
// 2 ** 256 - 1
return 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
}
function isMultipleOf(uint256 a, uint256 b) internal pure returns (bool) {
return a % b == 0;
}
// Float [fixed point] Operations
function fxpMul(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) {
return div(mul(a, b), base);
}
function fxpDiv(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) {
return div(mul(a, base), b);
}
}
interface IERC1155 {
/// @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred,
/// including zero value transfers as well as minting or burning.
/// Operator will always be msg.sender.
/// Either event from address `0x0` signifies a minting operation.
/// An event to address `0x0` signifies a burning or melting operation.
/// The total value transferred from address 0x0 minus the total value transferred to 0x0 may
/// be used by clients and exchanges to be added to the "circulating supply" for a given token ID.
/// To define a token ID with no initial balance, the contract SHOULD emit the TransferSingle event
/// from `0x0` to `0x0`, with the token creator as `_operator`.
event TransferSingle(
address indexed operator,
address indexed from,
address indexed to,
uint256 id,
uint256 value
);
/// @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred,
/// including zero value transfers as well as minting or burning.
///Operator will always be msg.sender.
/// Either event from address `0x0` signifies a minting operation.
/// An event to address `0x0` signifies a burning or melting operation.
/// The total value transferred from address 0x0 minus the total value transferred to 0x0 may
/// be used by clients and exchanges to be added to the "circulating supply" for a given token ID.
/// To define multiple token IDs with no initial balance, this SHOULD emit the TransferBatch event
/// from `0x0` to `0x0`, with the token creator as `_operator`.
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/// @dev MUST emit when an approval is updated.
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
/// @dev MUST emit when the URI is updated for a token ID.
/// URIs are defined in RFC 3986.
/// The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata JSON Schema".
event URI(
string value,
uint256 indexed id
);
/// @notice Transfers value amount of an _id from the _from address to the _to address specified.
/// @dev MUST emit TransferSingle event on success.
/// Caller must be approved to manage the _from account's tokens (see isApprovedForAll).
/// MUST throw if `_to` is the zero address.
/// MUST throw if balance of sender for token `_id` is lower than the `_value` sent.
/// MUST throw on any other error.
/// When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0).
/// If so, it MUST call `onERC1155Received` on `_to` and revert if the return value
/// is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`.
/// @param from Source address
/// @param to Target address
/// @param id ID of the token type
/// @param value Transfer amount
/// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 value,
bytes calldata data
)
external;
/// @notice Send multiple types of Tokens from a 3rd party in one transfer (with safety call).
/// @dev MUST emit TransferBatch event on success.
/// Caller must be approved to manage the _from account's tokens (see isApprovedForAll).
/// MUST throw if `_to` is the zero address.
/// MUST throw if length of `_ids` is not the same as length of `_values`.
/// MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_values` sent.
/// MUST throw on any other error.
/// When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0).
/// If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return value
/// is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`.
/// @param from Source addresses
/// @param to Target addresses
/// @param ids IDs of each token type
/// @param values Transfer amounts per token type
/// @param data Additional data with no specified format, sent in call to `_to`
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external;
/// @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens.
/// @dev MUST emit the ApprovalForAll event on success.
/// @param operator Address to add to the set of authorized operators
/// @param approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address operator, bool approved) external;
/// @notice Queries the approval status of an operator for a given owner.
/// @param owner The owner of the Tokens
/// @param operator Address of authorized operator
/// @return True if the operator is approved, false if not
function isApprovedForAll(address owner, address operator) external view returns (bool);
/// @notice Get the balance of an account's Tokens.
/// @param owner The address of the token holder
/// @param id ID of the Token
/// @return The _owner's balance of the Token type requested
function balanceOf(address owner, uint256 id) external view returns (uint256);
/// @notice Get the total supply of a Token.
/// @param id ID of the Token
/// @return The total supply of the Token type requested
function totalSupply(uint256 id) external view returns (uint256);
/// @notice Get the balance of multiple account/token pairs
/// @param owners The addresses of the token holders
/// @param ids ID of the Tokens
/// @return The _owner's balance of the Token types requested
function balanceOfBatch(
address[] calldata owners,
uint256[] calldata ids
)
external
view
returns (uint256[] memory balances_);
}
contract IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address owner) public view returns (uint256);
function transfer(address to, uint256 amount) public returns (bool);
function transferFrom(address from, address to, uint256 amount) public returns (bool);
function approve(address spender, uint256 amount) public returns (bool);
function allowance(address owner, address spender) public view returns (uint256);
// solhint-disable-next-line no-simple-event-func-name
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract ICash is IERC20 {
}
contract IAffiliateValidator {
function validateReference(address _account, address _referrer) external view returns (bool);
}
contract IAffiliates {
function setFingerprint(bytes32 _fingerprint) external;
function setReferrer(address _referrer) external;
function getAccountFingerprint(address _account) external returns (bytes32);
function getReferrer(address _account) external returns (address);
function getAndValidateReferrer(address _account, IAffiliateValidator affiliateValidator) external returns (address);
function affiliateValidators(address _affiliateValidator) external returns (bool);
}
contract IDisputeWindow is ITyped, IERC20 {
function invalidMarketsTotal() external view returns (uint256);
function validityBondTotal() external view returns (uint256);
function incorrectDesignatedReportTotal() external view returns (uint256);
function initialReportBondTotal() external view returns (uint256);
function designatedReportNoShowsTotal() external view returns (uint256);
function designatedReporterNoShowBondTotal() external view returns (uint256);
function initialize(IAugur _augur, IUniverse _universe, uint256 _disputeWindowId, bool _participationTokensEnabled, uint256 _duration, uint256 _startTime) public;
function trustedBuy(address _buyer, uint256 _attotokens) public returns (bool);
function getUniverse() public view returns (IUniverse);
function getReputationToken() public view returns (IReputationToken);
function getStartTime() public view returns (uint256);
function getEndTime() public view returns (uint256);
function getWindowId() public view returns (uint256);
function isActive() public view returns (bool);
function isOver() public view returns (bool);
function onMarketFinalized() public;
function redeem(address _account) public returns (bool);
}
contract IMarket is IOwnable {
enum MarketType {
YES_NO,
CATEGORICAL,
SCALAR
}
function initialize(IAugur _augur, IUniverse _universe, uint256 _endTime, uint256 _feePerCashInAttoCash, IAffiliateValidator _affiliateValidator, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, address _creator, uint256 _numOutcomes, uint256 _numTicks) public;
function derivePayoutDistributionHash(uint256[] memory _payoutNumerators) public view returns (bytes32);
function doInitialReport(uint256[] memory _payoutNumerators, string memory _description, uint256 _additionalStake) public returns (bool);
function getUniverse() public view returns (IUniverse);
function getDisputeWindow() public view returns (IDisputeWindow);
function getNumberOfOutcomes() public view returns (uint256);
function getNumTicks() public view returns (uint256);
function getMarketCreatorSettlementFeeDivisor() public view returns (uint256);
function getForkingMarket() public view returns (IMarket _market);
function getEndTime() public view returns (uint256);
function getWinningPayoutDistributionHash() public view returns (bytes32);
function getWinningPayoutNumerator(uint256 _outcome) public view returns (uint256);
function getWinningReportingParticipant() public view returns (IReportingParticipant);
function getReputationToken() public view returns (IV2ReputationToken);
function getFinalizationTime() public view returns (uint256);
function getInitialReporter() public view returns (IInitialReporter);
function getDesignatedReportingEndTime() public view returns (uint256);
function getValidityBondAttoCash() public view returns (uint256);
function affiliateFeeDivisor() external view returns (uint256);
function getNumParticipants() public view returns (uint256);
function getDisputePacingOn() public view returns (bool);
function deriveMarketCreatorFeeAmount(uint256 _amount) public view returns (uint256);
function recordMarketCreatorFees(uint256 _marketCreatorFees, address _sourceAccount, bytes32 _fingerprint) public returns (bool);
function isContainerForReportingParticipant(IReportingParticipant _reportingParticipant) public view returns (bool);
function isFinalizedAsInvalid() public view returns (bool);
function finalize() public returns (bool);
function isFinalized() public view returns (bool);
function getOpenInterest() public view returns (uint256);
}
contract IReportingParticipant {
function getStake() public view returns (uint256);
function getPayoutDistributionHash() public view returns (bytes32);
function liquidateLosing() public;
function redeem(address _redeemer) public returns (bool);
function isDisavowed() public view returns (bool);
function getPayoutNumerator(uint256 _outcome) public view returns (uint256);
function getPayoutNumerators() public view returns (uint256[] memory);
function getMarket() public view returns (IMarket);
function getSize() public view returns (uint256);
}
contract IInitialReporter is IReportingParticipant, IOwnable {
function initialize(IAugur _augur, IMarket _market, address _designatedReporter) public;
function report(address _reporter, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, uint256 _initialReportStake) public;
function designatedReporterShowed() public view returns (bool);
function initialReporterWasCorrect() public view returns (bool);
function getDesignatedReporter() public view returns (address);
function getReportTimestamp() public view returns (uint256);
function migrateToNewUniverse(address _designatedReporter) public;
function returnRepFromDisavow() public;
}
contract IReputationToken is IERC20 {
function migrateOutByPayout(uint256[] memory _payoutNumerators, uint256 _attotokens) public returns (bool);
function migrateIn(address _reporter, uint256 _attotokens) public returns (bool);
function trustedReportingParticipantTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool);
function trustedMarketTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool);
function trustedUniverseTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool);
function trustedDisputeWindowTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool);
function getUniverse() public view returns (IUniverse);
function getTotalMigrated() public view returns (uint256);
function getTotalTheoreticalSupply() public view returns (uint256);
function mintForReportingParticipant(uint256 _amountMigrated) public returns (bool);
}
contract IShareToken is ITyped, IERC1155 {
function initialize(IAugur _augur) external;
function initializeMarket(IMarket _market, uint256 _numOutcomes, uint256 _numTicks) public;
function unsafeTransferFrom(address _from, address _to, uint256 _id, uint256 _value) public;
function unsafeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _values) public;
function claimTradingProceeds(IMarket _market, address _shareHolder, bytes32 _fingerprint) external returns (uint256[] memory _outcomeFees);
function getMarket(uint256 _tokenId) external view returns (IMarket);
function getOutcome(uint256 _tokenId) external view returns (uint256);
function getTokenId(IMarket _market, uint256 _outcome) public pure returns (uint256 _tokenId);
function getTokenIds(IMarket _market, uint256[] memory _outcomes) public pure returns (uint256[] memory _tokenIds);
function buyCompleteSets(IMarket _market, address _account, uint256 _amount) external returns (bool);
function buyCompleteSetsForTrade(IMarket _market, uint256 _amount, uint256 _longOutcome, address _longRecipient, address _shortRecipient) external returns (bool);
function sellCompleteSets(IMarket _market, address _holder, address _recipient, uint256 _amount, bytes32 _fingerprint) external returns (uint256 _creatorFee, uint256 _reportingFee);
function sellCompleteSetsForTrade(IMarket _market, uint256 _outcome, uint256 _amount, address _shortParticipant, address _longParticipant, address _shortRecipient, address _longRecipient, uint256 _price, address _sourceAccount, bytes32 _fingerprint) external returns (uint256 _creatorFee, uint256 _reportingFee);
function totalSupplyForMarketOutcome(IMarket _market, uint256 _outcome) public view returns (uint256);
function balanceOfMarketOutcome(IMarket _market, uint256 _outcome, address _account) public view returns (uint256);
function lowestBalanceOfMarketOutcomes(IMarket _market, uint256[] memory _outcomes, address _account) public view returns (uint256);
}
contract IUniverse {
function creationTime() external view returns (uint256);
function marketBalance(address) external view returns (uint256);
function fork() public returns (bool);
function updateForkValues() public returns (bool);
function getParentUniverse() public view returns (IUniverse);
function createChildUniverse(uint256[] memory _parentPayoutNumerators) public returns (IUniverse);
function getChildUniverse(bytes32 _parentPayoutDistributionHash) public view returns (IUniverse);
function getReputationToken() public view returns (IV2ReputationToken);
function getForkingMarket() public view returns (IMarket);
function getForkEndTime() public view returns (uint256);
function getForkReputationGoal() public view returns (uint256);
function getParentPayoutDistributionHash() public view returns (bytes32);
function getDisputeRoundDurationInSeconds(bool _initial) public view returns (uint256);
function getOrCreateDisputeWindowByTimestamp(uint256 _timestamp, bool _initial) public returns (IDisputeWindow);
function getOrCreateCurrentDisputeWindow(bool _initial) public returns (IDisputeWindow);
function getOrCreateNextDisputeWindow(bool _initial) public returns (IDisputeWindow);
function getOrCreatePreviousDisputeWindow(bool _initial) public returns (IDisputeWindow);
function getOpenInterestInAttoCash() public view returns (uint256);
function getTargetRepMarketCapInAttoCash() public view returns (uint256);
function getOrCacheValidityBond() public returns (uint256);
function getOrCacheDesignatedReportStake() public returns (uint256);
function getOrCacheDesignatedReportNoShowBond() public returns (uint256);
function getOrCacheMarketRepBond() public returns (uint256);
function getOrCacheReportingFeeDivisor() public returns (uint256);
function getDisputeThresholdForFork() public view returns (uint256);
function getDisputeThresholdForDisputePacing() public view returns (uint256);
function getInitialReportMinValue() public view returns (uint256);
function getPayoutNumerators() public view returns (uint256[] memory);
function getReportingFeeDivisor() public view returns (uint256);
function getPayoutNumerator(uint256 _outcome) public view returns (uint256);
function getWinningChildPayoutNumerator(uint256 _outcome) public view returns (uint256);
function isOpenInterestCash(address) public view returns (bool);
function isForkingMarket() public view returns (bool);
function getCurrentDisputeWindow(bool _initial) public view returns (IDisputeWindow);
function getDisputeWindowStartTimeAndDuration(uint256 _timestamp, bool _initial) public view returns (uint256, uint256);
function isParentOf(IUniverse _shadyChild) public view returns (bool);
function updateTentativeWinningChildUniverse(bytes32 _parentPayoutDistributionHash) public returns (bool);
function isContainerForDisputeWindow(IDisputeWindow _shadyTarget) public view returns (bool);
function isContainerForMarket(IMarket _shadyTarget) public view returns (bool);
function isContainerForReportingParticipant(IReportingParticipant _reportingParticipant) public view returns (bool);
function migrateMarketOut(IUniverse _destinationUniverse) public returns (bool);
function migrateMarketIn(IMarket _market, uint256 _cashBalance, uint256 _marketOI) public returns (bool);
function decrementOpenInterest(uint256 _amount) public returns (bool);
function decrementOpenInterestFromMarket(IMarket _market) public returns (bool);
function incrementOpenInterest(uint256 _amount) public returns (bool);
function getWinningChildUniverse() public view returns (IUniverse);
function isForking() public view returns (bool);
function deposit(address _sender, uint256 _amount, address _market) public returns (bool);
function withdraw(address _recipient, uint256 _amount, address _market) public returns (bool);
function createScalarMarket(uint256 _endTime, uint256 _feePerCashInAttoCash, IAffiliateValidator _affiliateValidator, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, int256[] memory _prices, uint256 _numTicks, string memory _extraInfo) public returns (IMarket _newMarket);
}
contract IV2ReputationToken is IReputationToken {
function parentUniverse() external returns (IUniverse);
function burnForMarket(uint256 _amountToBurn) public returns (bool);
function mintForWarpSync(uint256 _amountToMint, address _target) public returns (bool);
}
contract IAugurTrading {
function lookup(bytes32 _key) public view returns (address);
function logProfitLossChanged(IMarket _market, address _account, uint256 _outcome, int256 _netPosition, uint256 _avgPrice, int256 _realizedProfit, int256 _frozenFunds, int256 _realizedCost) public returns (bool);
function logOrderCreated(IUniverse _universe, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool);
function logOrderCanceled(IUniverse _universe, IMarket _market, address _creator, uint256 _tokenRefund, uint256 _sharesRefund, bytes32 _orderId) public returns (bool);
function logOrderFilled(IUniverse _universe, address _creator, address _filler, uint256 _price, uint256 _fees, uint256 _amountFilled, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool);
function logMarketVolumeChanged(IUniverse _universe, address _market, uint256 _volume, uint256[] memory _outcomeVolumes, uint256 _totalTrades) public returns (bool);
function logZeroXOrderFilled(IUniverse _universe, IMarket _market, bytes32 _orderHash, bytes32 _tradeGroupId, uint8 _orderType, address[] memory _addressData, uint256[] memory _uint256Data) public returns (bool);
function logZeroXOrderCanceled(address _universe, address _market, address _account, uint256 _outcome, uint256 _price, uint256 _amount, uint8 _type, bytes32 _orderHash) public;
}
contract IOrders {
function saveOrder(uint256[] calldata _uints, bytes32[] calldata _bytes32s, Order.Types _type, IMarket _market, address _sender) external returns (bytes32 _orderId);
function removeOrder(bytes32 _orderId) external returns (bool);
function getMarket(bytes32 _orderId) public view returns (IMarket);
function getOrderType(bytes32 _orderId) public view returns (Order.Types);
function getOutcome(bytes32 _orderId) public view returns (uint256);
function getAmount(bytes32 _orderId) public view returns (uint256);
function getPrice(bytes32 _orderId) public view returns (uint256);
function getOrderCreator(bytes32 _orderId) public view returns (address);
function getOrderSharesEscrowed(bytes32 _orderId) public view returns (uint256);
function getOrderMoneyEscrowed(bytes32 _orderId) public view returns (uint256);
function getOrderDataForCancel(bytes32 _orderId) public view returns (uint256, uint256, Order.Types, IMarket, uint256, address);
function getOrderDataForLogs(bytes32 _orderId) public view returns (Order.Types, address[] memory _addressData, uint256[] memory _uint256Data);
function getBetterOrderId(bytes32 _orderId) public view returns (bytes32);
function getWorseOrderId(bytes32 _orderId) public view returns (bytes32);
function getBestOrderId(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32);
function getWorstOrderId(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32);
function getLastOutcomePrice(IMarket _market, uint256 _outcome) public view returns (uint256);
function getOrderId(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed) public pure returns (bytes32);
function getTotalEscrowed(IMarket _market) public view returns (uint256);
function isBetterPrice(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool);
function isWorsePrice(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool);
function assertIsNotBetterPrice(Order.Types _type, uint256 _price, bytes32 _betterOrderId) public view returns (bool);
function assertIsNotWorsePrice(Order.Types _type, uint256 _price, bytes32 _worseOrderId) public returns (bool);
function recordFillOrder(bytes32 _orderId, uint256 _sharesFilled, uint256 _tokensFilled, uint256 _fill) external returns (bool);
function setPrice(IMarket _market, uint256 _outcome, uint256 _price) external returns (bool);
}
library Order {
using SafeMathUint256 for uint256;
enum Types {
Bid, Ask
}
enum TradeDirections {
Long, Short
}
struct Data {
// Contracts
IMarket market;
IAugur augur;
IAugurTrading augurTrading;
IShareToken shareToken;
ICash cash;
// Order
bytes32 id;
address creator;
uint256 outcome;
Order.Types orderType;
uint256 amount;
uint256 price;
uint256 sharesEscrowed;
uint256 moneyEscrowed;
bytes32 betterOrderId;
bytes32 worseOrderId;
}
function create(IAugur _augur, IAugurTrading _augurTrading, address _creator, uint256 _outcome, Order.Types _type, uint256 _attoshares, uint256 _price, IMarket _market, bytes32 _betterOrderId, bytes32 _worseOrderId) internal view returns (Data memory) {
require(_outcome < _market.getNumberOfOutcomes(), "Order.create: Outcome is not within market range");
require(_price != 0, "Order.create: Price may not be 0");
require(_price < _market.getNumTicks(), "Order.create: Price is outside of market range");
require(_attoshares > 0, "Order.create: Cannot use amount of 0");
require(_creator != address(0), "Order.create: Creator is 0x0");
IShareToken _shareToken = IShareToken(_augur.lookup("ShareToken"));
return Data({
market: _market,
augur: _augur,
augurTrading: _augurTrading,
shareToken: _shareToken,
cash: ICash(_augur.lookup("Cash")),
id: 0,
creator: _creator,
outcome: _outcome,
orderType: _type,
amount: _attoshares,
price: _price,
sharesEscrowed: 0,
moneyEscrowed: 0,
betterOrderId: _betterOrderId,
worseOrderId: _worseOrderId
});
}
//
// "public" functions
//
function getOrderId(Order.Data memory _orderData, IOrders _orders) internal view returns (bytes32) {
if (blockhash(block.number) == bytes32(0)) { //injected CONTRACT AFFECTED BY MINERS
bytes32 _orderId = calculateOrderId(_orderData.orderType, _orderData.market, _orderData.amount, _orderData.price, _orderData.creator, block.number, _orderData.outcome, _orderData.moneyEscrowed, _orderData.sharesEscrowed);
require(_orders.getAmount(_orderId) == 0, "Order.getOrderId: New order had amount. This should not be possible");
_orderData.id = _orderId;
}
return _orderData.id;
}
function calculateOrderId(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed) internal pure returns (bytes32) {
return sha256(abi.encodePacked(_type, _market, _amount, _price, _sender, _blockNumber, _outcome, _moneyEscrowed, _sharesEscrowed));
}
function getOrderTradingTypeFromMakerDirection(Order.TradeDirections _creatorDirection) internal pure returns (Order.Types) {
return (_creatorDirection == Order.TradeDirections.Long) ? Order.Types.Bid : Order.Types.Ask;
}
function getOrderTradingTypeFromFillerDirection(Order.TradeDirections _fillerDirection) internal pure returns (Order.Types) {
return (_fillerDirection == Order.TradeDirections.Long) ? Order.Types.Ask : Order.Types.Bid;
}
function saveOrder(Order.Data memory _orderData, bytes32 _tradeGroupId, IOrders _orders) internal returns (bytes32) {
getOrderId(_orderData, _orders);
uint256[] memory _uints = new uint256[](5);
_uints[0] = _orderData.amount;
_uints[1] = _orderData.price;
_uints[2] = _orderData.outcome;
_uints[3] = _orderData.moneyEscrowed;
_uints[4] = _orderData.sharesEscrowed;
bytes32[] memory _bytes32s = new bytes32[](4);
_bytes32s[0] = _orderData.betterOrderId;
_bytes32s[1] = _orderData.worseOrderId;
_bytes32s[2] = _tradeGroupId;
_bytes32s[3] = _orderData.id;
return _orders.saveOrder(_uints, _bytes32s, _orderData.orderType, _orderData.market, _orderData.creator);
}
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IWETH {
function deposit() external payable;
function balanceOf(address owner) external view returns (uint);
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
contract AugurWalletRegistry is Initializable, GSNRecipient {
using LibBytes for bytes;
using ContractExists for address;
using SafeMathUint256 for uint256;
enum GSNRecipientERC20FeeErrorCodes {
OK,
TX_COST_TOO_HIGH,
INSUFFICIENT_BALANCE
}
event ExecuteTransactionStatus(bool success, bool fundingSuccess);
IAugur public augur;
IAugurTrading public augurTrading;
IERC20 public cash;
IUniswapV2Pair public ethExchange;
IWETH public WETH;
bool public token0IsCash;
IAugurWalletFactory public augurWalletFactory;
uint256 private constant MAX_APPROVAL_AMOUNT = 2 ** 256 - 1;
uint256 private constant MAX_TX_FEE_IN_ETH = 10**17;
function initialize(IAugur _augur, IAugurTrading _augurTrading) public payable beforeInitialized returns (bool) {
require(msg.value >= MAX_TX_FEE_IN_ETH, "Must provide initial Max TX Fee Deposit");
endInitialization();
augur = _augur;
cash = IERC20(_augur.lookup("Cash"));
augurTrading = _augurTrading;
WETH = IWETH(_augurTrading.lookup("WETH9"));
augurWalletFactory = IAugurWalletFactory(_augurTrading.lookup("AugurWalletFactory"));
IUniswapV2Factory _uniswapFactory = IUniswapV2Factory(_augur.lookup("UniswapV2Factory"));
address _ethExchangeAddress = _uniswapFactory.getPair(address(WETH), address(cash));
if (block.coinbase == address(0)) { //injected CONTRACT AFFECTED BY MINERS
_ethExchangeAddress = _uniswapFactory.createPair(address(WETH), address(cash));
}
ethExchange = IUniswapV2Pair(_ethExchangeAddress);
token0IsCash = ethExchange.token0() == address(cash);
IRelayHub(getHubAddr()).depositFor.value(address(this).balance)(address(this));
return true;
}
function acceptRelayedCall(
address,
address _from,
bytes calldata _encodedFunction,
uint256,
uint256,
uint256,
uint256,
bytes calldata,
uint256 _maxPossibleCharge
)
external
view
returns (uint256 _reason, bytes memory _context)
{
// executeWalletTransaction is the only encodedFunction that can succesfully be called through the relayHub
uint256 _payment = getPaymentFromEncodedFunction(_encodedFunction);
GSNRecipientERC20FeeErrorCodes _code = getAcceptRelayCallStatus(_from, _payment, _maxPossibleCharge);
if (_code != GSNRecipientERC20FeeErrorCodes.OK) {
return _rejectRelayedCall(uint256(_code));
}
uint256 _initialEth = address(this).balance;
return _approveRelayedCall(abi.encode(_from, _initialEth));
}
function getPaymentFromEncodedFunction(bytes memory _encodedFunction) private pure returns (uint256) {
bytes memory _encodedFunctionParams = _encodedFunction.sliceDestructive(4, _encodedFunction.length);
(address _to, bytes memory _data, uint256 _value, uint256 _payment, address _affilate, bytes32 _fingerprint) = abi.decode(_encodedFunctionParams, (address, bytes, uint256, uint256, address, bytes32));
return _payment;
}
function getAcceptRelayCallStatus(address _from, uint256 _payment, uint256 _maxPossibleCharge) private view returns (GSNRecipientERC20FeeErrorCodes _code) {
(uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) = ethExchange.getReserves();
uint256 _maxDaiNeeded = getAmountIn(_maxPossibleCharge, token0IsCash ? _reserve0 : _reserve1, token0IsCash ? _reserve1 : _reserve0);
if (block.number > _payment) { //injected CONTRACT AFFECTED BY MINERS
return GSNRecipientERC20FeeErrorCodes.TX_COST_TOO_HIGH;
}
if (block.number < _payment) { //injected CONTRACT AFFECTED BY MINERS
return GSNRecipientERC20FeeErrorCodes.INSUFFICIENT_BALANCE;
}
return GSNRecipientERC20FeeErrorCodes.OK;
}
function _preRelayedCall(bytes memory _context) internal returns (bytes32) { }
function _postRelayedCall(bytes memory _context, bool, uint256 _actualCharge, bytes32) internal {
(address _from, uint256 _initialEth) = abi.decode(_context, (address, uint256));
// Refund any excess ETH paid back to the wallet
uint256 _ethPaid = address(this).balance.sub(_initialEth);
uint256 _ethRefund = _ethPaid.sub(_actualCharge);
(bool _success,) = address(_from).call.value(_ethRefund)("");
require(_success);
// Top off Relay Hub balance with whatever ETH we have
uint256 _depositAmount = address(this).balance;
_depositAmount = _depositAmount.min(2 ether); // This is the maximum single RelayHub deposit
IRelayHub(getHubAddr()).depositFor.value(_depositAmount)(address(this));
}
function getEthFromWallet(IAugurWallet _wallet, uint256 _cashAmount) private {
(uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) = ethExchange.getReserves();
uint256 _ethAmount = getAmountOut(_cashAmount, token0IsCash ? _reserve0 : _reserve1, token0IsCash ? _reserve1 : _reserve0);
_wallet.transferCash(address(ethExchange), _cashAmount);
ethExchange.swap(token0IsCash ? 0 : _ethAmount, token0IsCash ? _ethAmount : 0, address(this), "");
WETH.withdraw(_ethAmount);
}
// Returns whether the signer eth balance was funded as desired
function fundMsgSender(uint256 _desiredSignerBalance, uint256 _maxExchangeRateInDai) private returns (bool) {
address _msgSender = address(_msgSender());
IAugurWallet _wallet = getWallet(_msgSender);
uint256 _msgSenderBalance = _msgSender.balance;
if (block.gaslimit >= _desiredSignerBalance) { //injected CONTRACT AFFECTED BY MINERS
return true;
}
uint256 _ethDelta = _desiredSignerBalance - _msgSenderBalance;
(uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) = ethExchange.getReserves();
uint256 _cashAmount = getAmountIn(_ethDelta, token0IsCash ? _reserve0 : _reserve1, token0IsCash ? _reserve1 : _reserve0);
uint256 _exchangeRate = _cashAmount.mul(10**18).div(_ethDelta);
if (block.number < _exchangeRate) { //injected CONTRACT AFFECTED BY MINERS
return false;
}
_wallet.transferCash(address(ethExchange), _cashAmount);
ethExchange.swap(token0IsCash ? 0 : _ethDelta, token0IsCash ? _ethDelta : 0, address(this), "");
WETH.withdraw(_ethDelta);
(bool _success,) = _msgSender.call.value(_ethDelta)("");
return _success;
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) public pure returns (uint amountOut) {
require(amountIn > 0);
require(reserveIn > 0 && reserveOut > 0);
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) public pure returns (uint amountIn) {
require(amountOut > 0);
require(reserveIn > 0 && reserveOut > 0);
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
function createAugurWallet(address _referralAddress, bytes32 _fingerprint) private returns (IAugurWallet) {
return augurWalletFactory.createAugurWallet(_msgSender(), _referralAddress, _fingerprint);
}
function getCreate2WalletAddress(address _owner) public view returns (address) {
return augurWalletFactory.getCreate2WalletAddress(_owner);
}
/**
* @notice Get the Wallet for the given account
* @param _account The account to look up
* @return IAugurWallet for the account or 0x if none exists
*/
function getWallet(address _account) public view returns (IAugurWallet) {
address _walletAddress = getCreate2WalletAddress(_account);
if (!_walletAddress.exists()) {
return IAugurWallet(0);
}
return IAugurWallet(_walletAddress);
}
// 1. Create a user's wallet if it does not exist
// 2. Get funds from the wallet to compensate this contract for paying the relayer
// 3. Execute the transaction and return success status, or revert if appropriate
// 4. Fund the signer with ETH as specified
function executeWalletTransaction(address _to, bytes calldata _data, uint256 _value, uint256 _payment, address _referralAddress, bytes32 _fingerprint, uint256 _desiredSignerBalance, uint256 _maxExchangeRateInDai, bool _revertOnFailure) external {
address _user = _msgSender();
IAugurWallet _wallet = getWallet(_user);
if (_wallet == IAugurWallet(0)) {
_wallet = createAugurWallet(_referralAddress, _fingerprint);
}
// If the user is having this sent via relay we need to reimburse this contract for paying the relayer. We do the payment here to avoid hard coded gas stipend problems in GSN V1
if (block.coinbase != msg.sender) { //injected CONTRACT AFFECTED BY MINERS
getEthFromWallet(_wallet, _payment);
}
bool _success = _wallet.executeTransaction(_to, _data, _value);
// We need to be able to fail in order to get accurate gas estimates. We only allow this however when not using the relayhub since otherwise funds could be drained this way
if (_user == msg.sender && _revertOnFailure) {
require(_success, "Transaction Execution Failed");
}
// We keep the signing account's ETH balance funded up to an offchain provided value so it can send txs itself without the use of a relay
bool _fundingSuccess = fundMsgSender(_desiredSignerBalance, _maxExchangeRateInDai);
emit ExecuteTransactionStatus(_success, _fundingSuccess);
}
function getRelayMessageHash(
address relay,
address from,
address to,
bytes memory encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce) public view returns (bytes32) {
bytes memory packed = abi.encodePacked("rlx:", from, to, encodedFunction, transactionFee, gasPrice, gasLimit, nonce, getHubAddr());
return keccak256(abi.encodePacked(packed, relay));
}
function () external payable {}
} | 1. Create a user's wallet if it does not exist 2. Get funds from the wallet to compensate this contract for paying the relayer 3. Execute the transaction and return success status, or revert if appropriate 4. Fund the signer with ETH as specified | function executeWalletTransaction(address _to, bytes calldata _data, uint256 _value, uint256 _payment, address _referralAddress, bytes32 _fingerprint, uint256 _desiredSignerBalance, uint256 _maxExchangeRateInDai, bool _revertOnFailure) external {
address _user = _msgSender();
IAugurWallet _wallet = getWallet(_user);
if (_wallet == IAugurWallet(0)) {
_wallet = createAugurWallet(_referralAddress, _fingerprint);
}
getEthFromWallet(_wallet, _payment);
}
| 12,948,708 |
./full_match/42/0xe66C93545aee977584bA8Bb9c4079C765761F6c0/sources/PaymentSystem.sol | amountInMax must be retrieved from an oracle of some kind | function swapExactOut(address _fromToken, address _toToken, uint256 _amountOut, uint256 _msgValue)
internal
returns(uint256, uint256)
{
address[] memory path = new address[](2);
path[0] = _fromToken;
path[1] = _toToken;
uint[] memory amounts;
if(_fromToken == SwapRouter.WETH()){
require(_msgValue >= amountInMax, "[Amount sent less than amount requested]");
return(amounts[amounts.length - 1], _msgValue.sub(amounts[0]));
}
else if(_toToken == SwapRouter.WETH()){
require(token[_fromToken].allowance(msg.sender, address(this)) >= amountInMax, "[Insufficient allowance for user payment token]");
require(token[_fromToken].transferFrom(msg.sender, address(this), amountInMax), "[Value not received from customer]");
require(token[_fromToken].approve(address(SwapRouter), amountInMax), "[Approve failed]");
amounts = SwapRouter.swapTokensForExactETH(_amountOut, amountInMax, path, address(this), block.timestamp);
return(amounts[amounts.length - 1], amountInMax.sub(amounts[0]));
}
else {
require(token[_fromToken].allowance(msg.sender, address(this)) >= amountInMax, "[Insufficient allowance for user payment token]");
require(token[_fromToken].transferFrom(msg.sender, address(this), amountInMax), "[Value not received from customer]");
require(token[_fromToken].approve(address(SwapRouter), amountInMax), "[Approve failed]");
amounts = SwapRouter.swapTokensForExactTokens(_amountOut, amountInMax, path, address(this), block.timestamp);
return(amounts[amounts.length - 1], amountInMax.sub(amounts[0]));
}
}
| 9,595,123 |
./full_match/7701/0x03BCE3eDEaD608171FBcDaB63961dbba3e811e45/sources/src/VotingEscrow.sol | See IVotingEscrow for documentation A lock is active until both lock.amount==0 and lock.end<=block.timestamp Validate inputs Update lock Undelegated lock Delegated lock, update sender's lock first Then, update delegatee's lock and voting power (checkpoint) | function increaseAmount(uint256 _value) external payable nonReentrant {
LockedBalance memory locked_ = locked[msg.sender];
require(_value > 0, "Only non zero amount");
require(msg.value == _value, "Invalid value");
require(locked_.amount > 0, "No lock");
require(locked_.end > block.timestamp, "Lock expired");
address delegatee = locked_.delegatee;
uint256 unlockTime = locked_.end;
LockAction action = LockAction.INCREASE_AMOUNT;
LockedBalance memory newLocked = _copyLock(locked_);
newLocked.amount += int128(int256(_value));
newLocked.end = _floorToWeek(block.timestamp + LOCKTIME);
if (delegatee == msg.sender) {
action = LockAction.INCREASE_AMOUNT_AND_DELEGATION;
newLocked.delegated += int128(int256(_value));
locked[msg.sender] = newLocked;
_checkpoint(msg.sender, locked_, newLocked);
locked[msg.sender] = newLocked;
_checkpoint(msg.sender, locked_, newLocked);
locked_ = locked[delegatee];
require(locked_.amount > 0, "Delegatee has no lock");
require(locked_.end > block.timestamp, "Delegatee lock expired");
newLocked = _copyLock(locked_);
newLocked.delegated += int128(int256(_value));
locked[delegatee] = newLocked;
_checkpoint(delegatee, locked_, newLocked);
emit Deposit(delegatee, _value, newLocked.end, LockAction.DELEGATE, block.timestamp);
}
emit Deposit(msg.sender, _value, unlockTime, action, block.timestamp);
}
| 13,216,408 |
pragma solidity ^0.5.6;
import "./openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol";
import "./openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import "./openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol";
import "./openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol";
import "./openzeppelin-solidity/contracts/access/roles/MinterRole.sol";
import "./openzeppelin-solidity/contracts/lifecycle/Pausable.sol";
import "./openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "./openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./InvictusWhitelist.sol";
/**
* Contract for CRYPTO10 Hedged (C10) fund.
*
*/
contract C10Token is ERC20, ERC20Detailed, ERC20Burnable, Ownable, Pausable, MinterRole {
using SafeERC20 for ERC20;
using SafeMath for uint256;
// Maps participant addresses to the eth balance pending token issuance
mapping(address => uint256) public pendingBuys;
// The participant accounts waiting for token issuance
address[] public participantAddresses;
// Maps participant addresses to the withdrawal request
mapping (address => uint256) public pendingWithdrawals;
address payable[] public withdrawals;
uint256 private minimumWei = 50 finney;
uint256 private fees = 5; // 0.5% , or 5/1000
uint256 private minTokenRedemption = 1 ether;
uint256 private maxAllocationsPerTx = 50;
uint256 private maxWithdrawalsPerTx = 50;
Price public price;
address public whitelistContract;
struct Price {
uint256 numerator;
uint256 denominator;
}
event PriceUpdate(uint256 numerator, uint256 denominator);
event AddLiquidity(uint256 value);
event RemoveLiquidity(uint256 value);
event DepositReceived(address indexed participant, uint256 value);
event TokensIssued(address indexed participant, uint256 amountTokens, uint256 etherAmount);
event WithdrawRequest(address indexed participant, uint256 amountTokens);
event Withdraw(address indexed participant, uint256 amountTokens, uint256 etherAmount);
event TokensClaimed(address indexed token, uint256 balance);
constructor (uint256 priceNumeratorInput, address whitelistContractInput)
ERC20Detailed("Crypto10 Hedged", "C10", 18)
ERC20Burnable()
Pausable() public {
price = Price(priceNumeratorInput, 1000);
require(priceNumeratorInput > 0, "Invalid price numerator");
require(whitelistContractInput != address(0), "Invalid whitelist address");
whitelistContract = whitelistContractInput;
}
/**
* @dev fallback function that buys tokens if the sender is whitelisted.
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev Explicitly buy via contract.
*/
function buy() external payable {
buyTokens(msg.sender);
}
/**
* Sets the maximum number of allocations in a single transaction.
* @dev Allows us to configure batch sizes and avoid running out of gas.
*/
function setMaxAllocationsPerTx(uint256 newMaxAllocationsPerTx) external onlyOwner {
require(newMaxAllocationsPerTx > 0, "Must be greater than 0");
maxAllocationsPerTx = newMaxAllocationsPerTx;
}
/**
* Sets the maximum number of withdrawals in a single transaction.
* @dev Allows us to configure batch sizes and avoid running out of gas.
*/
function setMaxWithdrawalsPerTx(uint256 newMaxWithdrawalsPerTx) external onlyOwner {
require(newMaxWithdrawalsPerTx > 0, "Must be greater than 0");
maxWithdrawalsPerTx = newMaxWithdrawalsPerTx;
}
/// Sets the minimum wei when buying tokens.
function setMinimumBuyValue(uint256 newMinimumWei) external onlyOwner {
require(newMinimumWei > 0, "Minimum must be greater than 0");
minimumWei = newMinimumWei;
}
/// Sets the minimum number of tokens to redeem.
function setMinimumTokenRedemption(uint256 newMinTokenRedemption) external onlyOwner {
require(newMinTokenRedemption > 0, "Minimum must be greater than 0");
minTokenRedemption = newMinTokenRedemption;
}
/// Updates the price numerator.
function updatePrice(uint256 newNumerator) external onlyMinter {
require(newNumerator > 0, "Must be positive value");
price.numerator = newNumerator;
allocateTokens();
processWithdrawals();
emit PriceUpdate(price.numerator, price.denominator);
}
/// Updates the price denominator.
function updatePriceDenominator(uint256 newDenominator) external onlyMinter {
require(newDenominator > 0, "Must be positive value");
price.denominator = newDenominator;
}
/**
* Whitelisted token holders can request token redemption, and withdraw ETH.
* @param amountTokensToWithdraw The number of tokens to withdraw.
* @dev withdrawn tokens are burnt.
*/
function requestWithdrawal(uint256 amountTokensToWithdraw) external whenNotPaused
onlyWhitelisted {
address payable participant = msg.sender;
require(balanceOf(participant) >= amountTokensToWithdraw,
"Cannot withdraw more than balance held");
require(amountTokensToWithdraw >= minTokenRedemption, "Too few tokens");
burn(amountTokensToWithdraw);
uint256 pendingAmount = pendingWithdrawals[participant];
if (pendingAmount == 0) {
withdrawals.push(participant);
}
pendingWithdrawals[participant] = pendingAmount.add(amountTokensToWithdraw);
emit WithdrawRequest(participant, amountTokensToWithdraw);
}
/// Allows owner to claim any ERC20 tokens.
function claimTokens(ERC20 token) external payable onlyOwner {
require(address(token) != address(0), "Invalid address");
uint256 balance = token.balanceOf(address(this));
token.transfer(owner(), token.balanceOf(address(this)));
emit TokensClaimed(address(token), balance);
}
/**
* @dev Allows the owner to burn a specific amount of tokens on a participant's behalf.
* @param value The amount of tokens to be burned.
*/
function burnForParticipant(address account, uint256 value) public onlyOwner {
_burn(account, value);
}
/**
* @dev Function to mint tokens when not paused.
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address to, uint256 value) public onlyMinter whenNotPaused returns (bool) {
_mint(to, value);
return true;
}
/// Adds liquidity to the contract, allowing anyone to deposit ETH
function addLiquidity() public payable {
require(msg.value > 0, "Must be positive value");
emit AddLiquidity(msg.value);
}
/// Removes liquidity, allowing managing wallets to transfer eth to the fund wallet.
function removeLiquidity(uint256 amount) public onlyOwner {
require(amount <= address(this).balance, "Insufficient balance");
msg.sender.transfer(amount);
emit RemoveLiquidity(amount);
}
/// Allow the owner to remove a minter
function removeMinter(address account) public onlyOwner {
require(account != msg.sender, "Use renounceMinter");
_removeMinter(account);
}
/// Allow the owner to remove a pauser
function removePauser(address account) public onlyOwner {
require(account != msg.sender, "Use renouncePauser");
_removePauser(account);
}
/// returns the number of withdrawals pending.
function numberWithdrawalsPending() public view returns (uint256) {
return withdrawals.length;
}
/// returns the number of pending buys, waiting for token issuance.
function numberBuysPending() public view returns (uint256) {
return participantAddresses.length;
}
/**
* First phase of the 2-part buy, the participant deposits eth and waits
* for a price to be set so the tokens can be minted.
* @param participant whitelisted buyer.
*/
function buyTokens(address participant) internal whenNotPaused onlyWhitelisted {
assert(participant != address(0));
// Ensure minimum investment is met
require(msg.value >= minimumWei, "Minimum wei not met");
uint256 pendingAmount = pendingBuys[participant];
if (pendingAmount == 0) {
participantAddresses.push(participant);
}
// Increase the pending balance and wait for the price update
pendingBuys[participant] = pendingAmount.add(msg.value);
emit DepositReceived(participant, msg.value);
}
/// Internal function to allocate token.
function allocateTokens() internal {
uint256 numberOfAllocations = participantAddresses.length <= maxAllocationsPerTx ?
participantAddresses.length : maxAllocationsPerTx;
address payable ownerAddress = address(uint160(owner()));
for (uint256 i = numberOfAllocations; i > 0; i--) {
address participant = participantAddresses[i - 1];
uint256 deposit = pendingBuys[participant];
uint256 feeAmount = deposit.mul(fees) / 1000;
uint256 balance = deposit.sub(feeAmount);
uint256 newTokens = balance.mul(price.numerator) / price.denominator;
pendingBuys[participant] = 0;
participantAddresses.pop();
ownerAddress.transfer(feeAmount);
mint(participant, newTokens);
emit TokensIssued(participant, newTokens, balance);
}
}
/// Internal function to process withdrawals.
function processWithdrawals() internal {
uint256 numberOfWithdrawals = withdrawals.length <= maxWithdrawalsPerTx ?
withdrawals.length : maxWithdrawalsPerTx;
address payable ownerAddress = address(uint160(owner()));
for (uint256 i = numberOfWithdrawals; i > 0; i--) {
address payable participant = withdrawals[i - 1];
uint256 tokens = pendingWithdrawals[participant];
assert(tokens > 0); // participant must have requested a withdrawal
uint256 withdrawValue = tokens.mul(price.denominator) / price.numerator;
pendingWithdrawals[participant] = 0;
withdrawals.pop();
if (address(this).balance >= withdrawValue) {
uint256 feeAmount = withdrawValue.mul(fees) / 1000;
uint256 balance = withdrawValue.sub(feeAmount);
participant.transfer(balance);
ownerAddress.transfer(feeAmount);
emit Withdraw(participant, tokens, balance);
}
else {
mint(participant, tokens);
emit Withdraw(participant, tokens, 0); // indicate a failed withdrawal
}
}
}
modifier onlyWhitelisted() {
require(InvictusWhitelist(whitelistContract).isWhitelisted(msg.sender), "Must be whitelisted");
_;
}
}
| Allows owner to claim any ERC20 tokens. | function claimTokens(ERC20 token) external payable onlyOwner {
require(address(token) != address(0), "Invalid address");
uint256 balance = token.balanceOf(address(this));
token.transfer(owner(), token.balanceOf(address(this)));
emit TokensClaimed(address(token), balance);
}
| 910,286 |
./full_match/1/0x556d9E146CC7Fe7DF93fBdd90347Af8930acb104/sources/browser/Contract_Code_Min.sol | ERC20Basic Simpler version of ERC20 interface/ | interface ERC20Basic {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
event Transfer(
address indexed _from,
address indexed _to,
uint256 _value
);
}
| 3,090,232 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "@openzeppelin/contracts/GSN/Context.sol";
import "@openzeppelin/contracts/token/ERC777/IERC777.sol";
import "@openzeppelin/contracts/token/ERC777/IERC777Recipient.sol";
import "@openzeppelin/contracts/token/ERC777/IERC777Sender.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/introspection/IERC1820Registry.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
/**
* @dev Implementation of the {IERC777} 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}.
*
* Support for ERC20 is included in this contract, as specified by the EIP: both
* the ERC777 and ERC20 interfaces can be safely used when interacting with it.
* Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token
* movements.
*
* Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there
* are no special restrictions in the amount of tokens that created, moved, or
* destroyed. This makes integration with ERC20 applications seamless.
*/
contract CustomERC777 is Context, IERC777, IERC20, Pausable {
using SafeMath for uint256;
using Address for address;
IERC1820Registry internal constant _ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
mapping(address => uint256) private _balances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
// We inline the result of the following hashes because Solidity doesn't resolve them at compile time.
// See https://github.com/ethereum/solidity/issues/4024.
// keccak256("ERC777TokensSender")
bytes32 private constant _TOKENS_SENDER_INTERFACE_HASH =
0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895;
// keccak256("ERC777TokensRecipient")
bytes32 private constant _TOKENS_RECIPIENT_INTERFACE_HASH =
0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
// This isn't ever read from - it's only used to respond to the defaultOperators query.
address[] private _defaultOperatorsArray;
// Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators).
mapping(address => bool) private _defaultOperators;
// For each account, a mapping of its operators and revoked default operators.
mapping(address => mapping(address => bool)) private _operators;
mapping(address => mapping(address => bool)) private _revokedDefaultOperators;
// ERC20-allowances
mapping(address => mapping(address => uint256)) private _allowances;
/**
* @dev `defaultOperators` may be an empty array.
*/
constructor(
string memory name_,
string memory symbol_,
address[] memory defaultOperators_
) public {
_name = name_;
_symbol = symbol_;
_defaultOperatorsArray = defaultOperators_;
for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) {
_defaultOperators[_defaultOperatorsArray[i]] = true;
}
// register interfaces
_ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this));
_ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this));
}
/**
* @dev See {IERC777-name}.
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev See {IERC777-symbol}.
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev See {ERC20-decimals}.
*
* Always returns 18, as per the
* [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility).
*/
function decimals() public pure returns (uint8) {
return 18;
}
/**
* @dev See {IERC777-granularity}.
*
* This implementation always returns `1`.
*/
function granularity() public view override returns (uint256) {
return 1;
}
/**
* @dev See {IERC777-totalSupply}.
*/
function totalSupply() public view override(IERC20, IERC777) returns (uint256) {
return _totalSupply;
}
/**
* @dev Returns the amount of tokens owned by an account (`tokenHolder`).
*/
function balanceOf(address tokenHolder) public view override(IERC20, IERC777) returns (uint256) {
return _balances[tokenHolder];
}
/**
* @dev See {IERC777-send}.
*
* Also emits a {IERC20-Transfer} event for ERC20 compatibility.
*/
function send(
address recipient,
uint256 amount,
bytes memory data
) public override {
_send(_msgSender(), recipient, amount, data, "", true);
}
/**
* @dev See {IERC20-transfer}.
*
* Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient}
* interface if it is a contract.
*
* Also emits a {Sent} event.
*/
function transfer(address recipient, uint256 amount) public override whenNotPaused() returns (bool) {
require(recipient != address(0), "ERC777: transfer to the zero address");
address from = _msgSender();
_callTokensToSend(from, from, recipient, amount, "", "");
_move(from, from, recipient, amount, "", "");
_callTokensReceived(from, from, recipient, amount, "", "", false);
return true;
}
/**
* @dev See {IERC777-burn}.
*
* Also emits a {IERC20-Transfer} event for ERC20 compatibility.
*/
function burn(uint256 amount, bytes memory data) public override whenNotPaused() {
_burn(_msgSender(), amount, data, "");
}
/**
* @dev See {IERC777-isOperatorFor}.
*/
function isOperatorFor(address operator, address tokenHolder) public view override returns (bool) {
return
operator == tokenHolder ||
(_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) ||
_operators[tokenHolder][operator];
}
function _addDefaultOperator(address operator) internal {
_defaultOperatorsArray.push(operator);
_defaultOperators[operator] = true;
emit AuthorizedOperator(operator, address(this));
}
function _removeDefaultOperator(address operator) internal {
_defaultOperators[operator] = false;
for (uint256 x = 0; x <= _defaultOperatorsArray.length - 1; x++) {
if (_defaultOperatorsArray[x] == operator) {
_defaultOperatorsArray[x] = _defaultOperatorsArray[_defaultOperatorsArray.length - 1];
_defaultOperatorsArray.pop();
break;
}
}
emit RevokedOperator(operator, address(this));
}
/**
* @dev See {IERC777-authorizeOperator}.
*/
function authorizeOperator(address operator) public override {
require(_msgSender() != operator, "ERC777: authorizing self as operator");
if (_defaultOperators[operator]) {
delete _revokedDefaultOperators[_msgSender()][operator];
} else {
_operators[_msgSender()][operator] = true;
}
emit AuthorizedOperator(operator, _msgSender());
}
/**
* @dev See {IERC777-revokeOperator}.
*/
function revokeOperator(address operator) public override {
require(operator != _msgSender(), "ERC777: revoking self as operator");
if (_defaultOperators[operator]) {
_revokedDefaultOperators[_msgSender()][operator] = true;
} else {
delete _operators[_msgSender()][operator];
}
emit RevokedOperator(operator, _msgSender());
}
/**
* @dev See {IERC777-defaultOperators}.
*/
function defaultOperators() public view override returns (address[] memory) {
return _defaultOperatorsArray;
}
/**
* @dev See {IERC777-operatorSend}.
*
* Emits {Sent} and {IERC20-Transfer} events.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes memory data,
bytes memory operatorData
) public override {
require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder");
_send(sender, recipient, amount, data, operatorData, true);
}
/**
* @dev See {IERC777-operatorBurn}.
*
* Emits {Burned} and {IERC20-Transfer} events.
*/
function operatorBurn(
address account,
uint256 amount,
bytes memory data,
bytes memory operatorData
) public override {
require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder");
_burn(account, amount, data, operatorData);
}
/**
* @dev See {IERC20-allowance}.
*
* Note that operator and allowance concepts are orthogonal: operators may
* not have allowance, and accounts with allowance may not be operators
* themselves.
*/
function allowance(address holder, address spender) public view override returns (uint256) {
return _allowances[holder][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Note that accounts cannot have allowance issued by their operators.
*/
function approve(address spender, uint256 value) public override whenNotPaused() returns (bool) {
address holder = _msgSender();
_approve(holder, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Note that operator and allowance concepts are orthogonal: operators cannot
* call `transferFrom` (unless they have allowance), and accounts with
* allowance cannot call `operatorSend` (unless they are operators).
*
* Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events.
*/
function transferFrom(
address holder,
address recipient,
uint256 amount
) public override whenNotPaused() returns (bool) {
require(recipient != address(0), "ERC777: transfer to the zero address");
require(holder != address(0), "ERC777: transfer from the zero address");
address spender = _msgSender();
_callTokensToSend(spender, holder, recipient, amount, "", "");
_move(spender, holder, recipient, amount, "", "");
_approve(
holder,
spender,
_allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance")
);
_callTokensReceived(spender, holder, recipient, amount, "", "", false);
return true;
}
/**
* @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `operator`, `data` and `operatorData`.
*
* See {IERC777Sender} and {IERC777Recipient}.
*
* Emits {Minted} and {IERC20-Transfer} events.
*
* Requirements
*
* - `account` cannot be the zero address.
* - if `account` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function _mint(
address account,
uint256 amount,
bytes memory userData,
bytes memory operatorData
) internal virtual {
require(account != address(0), "ERC777: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, amount);
// Update state variables
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
_callTokensReceived(operator, address(0), account, amount, userData, operatorData, true);
emit Minted(operator, account, amount, userData, operatorData);
emit Transfer(address(0), account, amount);
}
/**
* @dev Send tokens
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
* @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient
*/
function _send(
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
) internal {
require(from != address(0), "ERC777: send from the zero address");
require(to != address(0), "ERC777: send to the zero address");
address operator = _msgSender();
_callTokensToSend(operator, from, to, amount, userData, operatorData);
_move(operator, from, to, amount, userData, operatorData);
_callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck);
}
/**
* @dev Burn tokens
* @param from address token holder address
* @param amount uint256 amount of tokens to burn
* @param data bytes extra information provided by the token holder
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _burn(
address from,
uint256 amount,
bytes memory data,
bytes memory operatorData
) internal virtual {
require(from != address(0), "ERC777: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), amount);
_callTokensToSend(operator, from, address(0), amount, data, operatorData);
// Update state variables
_balances[from] = _balances[from].sub(amount, "ERC777: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Burned(operator, from, amount, data, operatorData);
emit Transfer(from, address(0), amount);
}
function _move(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
) private {
_beforeTokenTransfer(operator, from, to, amount);
_balances[from] = _balances[from].sub(amount, "ERC777: transfer amount exceeds balance");
_balances[to] = _balances[to].add(amount);
emit Sent(operator, from, to, amount, userData, operatorData);
emit Transfer(from, to, amount);
}
/**
* @dev See {ERC20-_approve}.
*
* Note that accounts cannot have allowance issued by their operators.
*/
function _approve(
address holder,
address spender,
uint256 value
) internal {
require(holder != address(0), "ERC777: approve from the zero address");
require(spender != address(0), "ERC777: approve to the zero address");
_allowances[holder][spender] = value;
emit Approval(holder, spender, value);
}
/**
* @dev Call from.tokensToSend() if the interface is registered
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _callTokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
) private {
address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(from, _TOKENS_SENDER_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData);
}
}
/**
* @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but
* tokensReceived() was not registered for the recipient
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
* @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient
*/
function _callTokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
) private {
address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(to, _TOKENS_RECIPIENT_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData);
} else if (requireReceptionAck) {
require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient");
}
}
/**
* @dev Hook that is called before any token transfer. This includes
* calls to {send}, {transfer}, {operatorSend}, 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 operator,
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/GSN/Context.sol";
import "./CustomERC777.sol";
import "./KingOfTheHill.sol";
import "./KOTHPresale.sol";
contract KOTH is Context, CustomERC777, AccessControl {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant GAME_MASTER_ROLE = keccak256("GAME_MASTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
constructor(address owner, address presaleContract) CustomERC777("KOTH", "KOTH", new address[](0)) {
_onCreate(owner, presaleContract);
}
function _onCreate(address owner, address presaleContract) private {
_pause();
_setupRole(DEFAULT_ADMIN_ROLE, owner);
_setupRole(GAME_MASTER_ROLE, owner);
_setupRole(MINTER_ROLE, owner);
_setupRole(MINTER_ROLE, presaleContract);
_setupRole(PAUSER_ROLE, owner);
_setupRole(PAUSER_ROLE, presaleContract);
_register(presaleContract);
}
function _register(address presaleContract) private {
KOTHPresale presale = KOTHPresale(payable(presaleContract));
presale.setKOTH();
}
modifier onlyMinter() {
require(hasRole(MINTER_ROLE, _msgSender()), "KOTH: sender must be a minter for minting");
_;
}
modifier onlyGameMaster() {
require(hasRole(GAME_MASTER_ROLE, _msgSender()), "KOTH: sender must be a game master");
_;
}
modifier onlyPauser() {
require(hasRole(PAUSER_ROLE, _msgSender()), "KOTH: sender must be a pauser");
_;
}
function pause() public onlyPauser() {
_pause();
}
function unpause() public onlyPauser() {
_unpause();
}
function mint(address account, uint256 amount) public onlyMinter() {
_mint(account, amount, "", "");
}
// Set game contract as default operator
function addGameContract(address game) public onlyGameMaster() {
require(game != address(0), "KOTH: game is zero address");
require(defaultOperators().length == 0, "KOTH: game contract is already set");
_addDefaultOperator(game);
}
// Unset game contract as default operator
function removeGameContract(address game) public onlyGameMaster() {
_removeDefaultOperator(game);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "@openzeppelin/contracts/GSN/Context.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "./KOTH.sol";
contract KOTHPresale is Context, Ownable, Pausable, ReentrancyGuard {
using SafeMath for uint256;
struct Referrer {
bool isActive;
address parent;
}
uint256 private _price;
uint256 private _weiRaised;
uint256 private _kothBonusPercentage;
uint256 private _originalReferrerPercentage;
uint256 private _childReferrerPercentage;
KOTH private _koth;
address payable private _wallet;
mapping(address => Referrer) private _referrer;
event KOTHPurchased(
address indexed purchaser,
address indexed parentReferrer,
address indexed childReferrer,
uint256 value,
uint256 amount
);
constructor(
address owner,
address payable wallet_,
uint256 price
) {
_pause();
_wallet = wallet_;
_price = price;
_kothBonusPercentage = 10;
_originalReferrerPercentage = 10;
_childReferrerPercentage = 7;
transferOwnership(owner);
}
modifier onlyKOTHRegistered() {
require(address(_koth) != address(0), "KOTHPresale: KOTH token is not registered");
_;
}
// calculate percentage of amount in wei
function percentageToAmount(uint256 amount, uint256 percentage) public pure returns (uint256) {
return amount.mul(percentage).div(100);
}
function wallet() public view returns (address payable) {
return _wallet;
}
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
function getKOTHPrice() public view returns (uint256) {
return _price;
}
function setKOTHPrice(uint256 price) public onlyOwner() {
_price = price;
}
// This function will be called by the KOTH contract at deployment only 1 time
function setKOTH() external {
require(address(_koth) == address(0), "KOTHPresale: KOTH address is already set");
_koth = KOTH(_msgSender());
}
function getKOTH() public view returns (address) {
return address(_koth);
}
function getKOTHBonusPercentage() public view returns (uint256) {
return _kothBonusPercentage;
}
function setKOTHBonusPercentage(uint256 percentage) public onlyOwner() {
require(percentage <= 100, "KOTHPresale: KOTH bonus percentage greater than 100");
_kothBonusPercentage = percentage;
}
function getOriginalReferrerPercentage() public view returns (uint256) {
return _originalReferrerPercentage;
}
function setOriginalReferrerPercentage(uint256 percentage) public onlyOwner() {
require(percentage <= 100, "KOTHPresale: Original referrer percentage greater than 100");
_originalReferrerPercentage = percentage;
}
function getChildReferrerPercentage() public view returns (uint256) {
return _childReferrerPercentage;
}
function setChildReferrerPercentage(uint256 percentage) public onlyOwner() {
require(
_originalReferrerPercentage >= percentage,
"KOTHPresale: Original referrer percentage less than child percentage"
);
_childReferrerPercentage = percentage;
}
function getParentReferrerPercentage() public view returns (uint256) {
return _originalReferrerPercentage.sub(_childReferrerPercentage);
}
function grantReferrer(address account) public onlyOwner() {
require(account != address(0), "KOTHPresale: zero address can not be a referrer");
_referrer[account] = Referrer(true, address(0));
}
function mintReferrer(address account) public {
require(_referrer[account].isActive == true, "KOTHPresale: account is not a referrer");
require(_referrer[account].parent == address(0), "KOTHPresale: account is not an original referrer");
_referrer[_msgSender()] = Referrer(true, account);
}
function isReferrer(address account) public view returns (bool) {
return _referrer[account].isActive;
}
function isOriginalReferrer(address account) public view returns (bool) {
return _referrer[account].parent == address(0) && isReferrer(account);
}
function isChildReferrer(address account) public view returns (bool) {
return isReferrer(account) && !isOriginalReferrer(account);
}
function parentReferrerOf(address account) public view returns (address) {
return _referrer[account].parent;
}
// @dev price of 1 KOTH has to be lesser than 1 ETHER else rate will be 0 !!!
function rate() public view onlyKOTHRegistered() returns (uint256) {
return ((10**uint256(_koth.decimals()))).div(_price);
}
function getKOTHAmount(uint256 weiAmount) public view onlyKOTHRegistered() returns (uint256) {
return weiAmount.mul(rate());
}
function getPurchasePrice(uint256 tokenAmount) public view onlyKOTHRegistered() returns (uint256) {
uint256 purchasePrice = tokenAmount.div(rate());
require(purchasePrice > 0, "KOTHPresale: not enough tokens");
return purchasePrice;
}
function pause() public onlyOwner() onlyKOTHRegistered() {
_pause();
_koth.unpause();
}
function unpause() public onlyOwner() {
_unpause();
}
receive() external payable {
buyKOTH();
}
// buy without referrer
function buyKOTH() public payable whenNotPaused() nonReentrant() onlyKOTHRegistered() {
require(msg.value > 0, "KOTHPresale: purchase price can not be 0");
uint256 nbKOTH = getKOTHAmount(msg.value);
_processPurchase(nbKOTH);
emit KOTHPurchased(_msgSender(), address(0), address(0), msg.value, nbKOTH);
_forwardFunds(address(0));
}
// buy with a referrer
function buyKOTHWithReferrer(address referrer) public payable whenNotPaused() nonReentrant() onlyKOTHRegistered() {
require(_referrer[referrer].isActive == true, "KOTHPresale: account is not a referrer");
if (isChildReferrer(referrer)) {
require(_msgSender() != referrer, "KOTHPresale: child referrer can not buy for himself");
}
require(msg.value > 0, "KOTHPresale: purchase price can not be 0");
uint256 nbKOTH = getKOTHAmount(msg.value);
uint256 nbKOTHWithBonus = nbKOTH.add(percentageToAmount(nbKOTH, _kothBonusPercentage));
_processPurchase(nbKOTHWithBonus);
address parent;
address child;
if (isOriginalReferrer(referrer)) {
parent = referrer;
child = address(0);
} else {
parent = _referrer[referrer].parent;
child = referrer;
}
emit KOTHPurchased(msg.sender, parent, child, msg.value, nbKOTHWithBonus);
_forwardFunds(referrer);
}
function _processPurchase(uint256 kothAmount) private {
_koth.mint(_msgSender(), kothAmount);
}
function _forwardFunds(address referrer) private {
uint256 parentReward;
uint256 childReward;
uint256 remainingWeiAmount;
if (isOriginalReferrer(referrer)) {
parentReward = percentageToAmount(msg.value, _originalReferrerPercentage);
payable(referrer).transfer(parentReward);
} else if (isChildReferrer(referrer)) {
childReward = percentageToAmount(msg.value, _childReferrerPercentage);
parentReward = percentageToAmount(msg.value, _originalReferrerPercentage.sub(_childReferrerPercentage));
payable(referrer).transfer(childReward);
payable(_referrer[referrer].parent).transfer(parentReward);
}
remainingWeiAmount = msg.value.sub(parentReward).sub(childReward);
_weiRaised = _weiRaised.add(remainingWeiAmount);
_wallet.transfer(remainingWeiAmount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./KOTH.sol";
contract KingOfTheHill is Ownable, Pausable {
using SafeMath for uint256;
KOTH private _koth; // Token address of the KOTH ERC20 token
address public _wallet;
address public _potOwner; // Current owner (king of the hill)
uint256 public _bpOfPotToBuy; // % of the current pot required in ETH to own it
uint256 public _percentagePotToSeed; // % of the current pot that will be used to seed the next roung
bool public _isStrengthPowerUp; // Is Strength enabled?
bool public _isDefensePowerUp; // Is Defense enabled?
bool public _isAgilityPowerUp; // Is Agility Enabled?
uint256 public _strengthBonus; // % Extra of the Pot you win
uint256 public _defenseBonus; // Multiplier of how expensive the pot becomes for the next person
uint256 public _agilityBonus; // a number
uint256 public _agilityBuyNbBlockMin;
uint256 private _nbAgility; // a number
uint256 public _nbBlocksWinning;
uint256 private _nbBlockBought; // Block number the current round bought at
uint256 public _pot; // Amount of wei in the pot
uint256 public _seed; // Amount of wei to seed the next pot
address public _weth = address(0x0); // ERC20 address of WETH to calculate WETH / KOTH price
address public _kothUniPool; // KOTH uniswap pool to calculate WETH / KOTH price
uint256 public _defensePerc = 10;
uint256 public KOTH_PER_BLOCK_PRECISION = 10 ** 6;
uint256 public _kothPerBlock = 10 * KOTH_PER_BLOCK_PRECISION; // Amount of KOTH per block for the agility bonus. Precision up to 10^6 (0.000001 KOTH)
uint256 private _rake = 20;
uint256 public _strengthPerc = 30;
constructor(
address owner,
address wallet_
) {
_pause();
_koth = KOTH(0x0);
// _weth = weth_;
_wallet = wallet_;
_bpOfPotToBuy = 100; // Percentage of the pot in ether it
_percentagePotToSeed = 90; // Amount of the pot that is kept as the seed
_nbBlocksWinning = 100; // number
_strengthBonus = 100; // percentage
_defenseBonus = 2; // number
_agilityBonus = 1; // number
_kothUniPool = msg.sender; // WARNING Change this to the KOTH uni pool once created
transferOwnership(owner);
}
modifier onlyPotOwner() {
require(
_msgSender() == _potOwner,
"KingOfTheHill: Only pot owner can buy bonus"
);
_;
}
modifier onlyNotPotOwner() {
require(
_msgSender() != _potOwner,
"KingOfTheHill: sender mut not be the pot owner"
);
_;
}
modifier onlyRationalPercentage(uint256 percentage) {
require(
percentage >= 0 && percentage <= 100,
"KingOfTheHill: percentage value is irrational"
);
_;
}
function setKothUniPool(address p) public onlyOwner {
_kothUniPool = p;
}
function setRake(uint r) public onlyOwner {
_rake = r;
}
function setDefencePerc(uint d) public onlyOwner {
_defensePerc = d;
}
function setStrengthPerc(uint s) public onlyOwner {
_strengthPerc = s;
}
function setKothPerBlock(uint k) public onlyOwner {
_kothPerBlock = k;
}
function setKoth(address k) public onlyOwner {
_koth = KOTH(k);
}
function setWeth(address w) public onlyOwner {
_weth = w;
}
// Used for percentages 1% - 100%
function percentageToAmount(uint256 amount, uint256 percentage) public pure returns (uint256) {
return amount.mul(percentage).div(100);
}
// Used for basis points 0.0001% -> 100.0000%
function basisPointToAmount(uint256 amount, uint256 percentage) public pure returns (uint256) {
return amount.mul(percentage).div(10000);
}
function koth() public view returns (address) {
return address(_koth);
}
function wallet() public view returns (address) {
return _wallet;
}
function nbBlocksWinning() public view returns (uint256) {
return _nbBlocksWinning;
}
function setNbBlocksWinning(uint256 nbBlocks) public onlyOwner() {
require(nbBlocks > 0, "KingOfTheHill: nbBlocks must be greater than 0");
_nbBlocksWinning = nbBlocks;
}
function remainingBlocks() public view returns (uint256) {
uint256 blockPassed =
(block.number).sub(_nbBlockBought).add(
_nbAgility.mul(_agilityBonus)
);
if (_potOwner == address(0)) {
return _nbBlocksWinning;
} else if (blockPassed > _nbBlocksWinning) {
return 0;
} else {
return _nbBlocksWinning.sub(blockPassed);
}
}
function hasWinner() public view returns (bool) {
if (_potOwner != address(0) && remainingBlocks() == 0) {
return true;
} else {
return false;
}
}
function percentagePotToBuy() public view returns (uint256) {
return _bpOfPotToBuy;
}
function setPercentagePotToBuy(uint256 percentage) public onlyOwner() onlyRationalPercentage(percentage) {
_bpOfPotToBuy = percentage;
}
function percentagePotToSeed() public view returns (uint256) {
return _percentagePotToSeed;
}
function setPercentagePotToSeed(uint256 percentage) public onlyOwner() onlyRationalPercentage(percentage) {
_percentagePotToSeed = percentage;
}
function setStrengthBonus(uint256 percentage) public onlyOwner() {
//require("KingOfTheHill: Irration percentage")
_strengthBonus = percentage;
}
function strengthBonus() public view returns (uint256) {
return _strengthBonus;
}
function defenseBonus() public view returns (uint256) {
return _defenseBonus;
}
function setDefenseBonus(uint256 percentage) public onlyOwner() {
_defenseBonus = percentage;
}
function agilityBonus() public view returns (uint256) {
return _agilityBonus;
}
function setAgilityBonus(uint256 nbBlock) public onlyOwner() {
_agilityBonus = nbBlock;
}
function agilityBuyNbBlockMin() public view returns (uint256) {
return _agilityBuyNbBlockMin;
}
function setAgilityBuyNbBlockMin(uint256 nbBlocks) public onlyOwner() {
_agilityBuyNbBlockMin = nbBlocks;
}
function isStrengthPowerUp() public view returns (bool) {
return _isStrengthPowerUp;
}
function isDefensePowerUp() public view returns (bool) {
return _isDefensePowerUp;
}
function isAgilityPowerUp() public view returns (bool) {
return _isAgilityPowerUp;
}
// Visible pot value is the contract balance minus the seed amount for next round
function pot() public view returns (uint256) {
return _pot;
}
function seed() public view returns (uint256) {
return _seed;
}
/*
* POT PRICES
*/
function defensivePotCost() public view returns (uint256) {
uint256 price = basisPointToAmount(
_pot,
_bpOfPotToBuy.mul(_defenseBonus)
);
return price;
}
function regularPotCost() public view returns (uint256) {
return basisPointToAmount(
_pot,
_bpOfPotToBuy.mul(1)
);
}
function priceOfPot() public view returns (uint256) {
if (hasWinner()) return basisPointToAmount(_seed, _bpOfPotToBuy);
if (_isDefensePowerUp) return defensivePotCost();
return regularPotCost();
}
function prize() public view returns (uint256) {
uint256 strBonus = 0;
if (_isStrengthPowerUp) {
strBonus = _strengthBonus;
}
return _pot.add(percentageToAmount(_pot, strBonus));
}
function contractBalance() public view returns (uint256) {
return address(this).balance;
}
function potOwner() public view returns (address) {
return _potOwner;
}
/*
* This function returns the price of KOTH in ETH
*/
function getKOTHPrice() public view returns (uint256) {
if (_weth == address(0x0)) return 2 * 10 ** 18;
uint256 ethAmount = IERC20(_weth).balanceOf(_kothUniPool);
uint256 kothAmount = IERC20(_koth).balanceOf(_kothUniPool).mul(10**18);
return kothAmount.div(ethAmount);
}
function issueWinner() internal {
emit Winner(_potOwner, prize());
payable(_potOwner).transfer(prize());
_pot = _seed;
_seed = 0;
}
function buyPot() public payable onlyNotPotOwner() whenNotPaused() {
require(msg.value >= priceOfPot(), "KingOfTheHill: Not enough ether for buying pot");
// Pay winner and reset contract
if (hasWinner()) {
issueWinner();
}
// Recalculate seed
uint256 rake = percentageToAmount(msg.value, _rake); // 20% rake
uint256 keep = msg.value.sub(rake);
uint256 toSeed = percentageToAmount(keep, _percentagePotToSeed);
uint256 toPot = msg.value.sub(toSeed);
_pot = _pot.add(toPot);
_seed = _seed.add(toSeed);
payable(_wallet).transfer(rake);
// Reset block bought
_nbBlockBought = block.number;
// Reset powerups
_isStrengthPowerUp = false;
_isDefensePowerUp = false;
_isAgilityPowerUp = false;
_nbAgility = 0;
_potOwner = _msgSender();
emit Bought(_msgSender());
}
/*
* STRENGTH POWER UP
*/
function strengthPowerUpCost() public view returns (uint256) {
uint256 amount = 0;
amount = percentageToAmount(
percentageToAmount(priceOfPot(), _strengthBonus),
_strengthPerc
);
amount = amount.mul(getKOTHPrice()).div(10 ** 18);
return amount;
}
function buyStrength() public onlyPotOwner() whenNotPaused() {
require(_isStrengthPowerUp == false, "KingOfTheHill: Already bought a strength power up");
_koth.operatorBurn(_msgSender(), strengthPowerUpCost(), "", "");
_isStrengthPowerUp = true;
emit StrengthActivated(strengthPowerUpCost());
}
/*
* DEFENSIVE POWER UP
*/
function defensePowerUpCost() public view returns (uint256) {
uint256 amount = percentageToAmount(defensivePotCost().sub(regularPotCost()), _defensePerc);
amount = amount.mul(getKOTHPrice()).div(10 ** 18);
return amount;
}
function buyDefense() public onlyPotOwner() whenNotPaused() {
require(_isDefensePowerUp == false, "KingOfTheHill: Already bought a defense power up");
_koth.operatorBurn(_msgSender(), defensePowerUpCost(), "", "");
_isDefensePowerUp = true;
}
function buyAgility(uint256 nbAgility)
public
onlyPotOwner()
whenNotPaused()
{
require(
_isAgilityPowerUp == false,
"KingOfTheHill: Already bought an agility power up"
);
require(nbAgility > 0, "KingOfTheHill: can not buy 0 agility");
require(
remainingBlocks() > (_agilityBonus.mul(nbAgility)).add(3),
"KingOfTheHill: too many agility power-up"
);
uint256 cost = _kothPerBlock.mul(10 ** uint256(_koth.decimals())).div(KOTH_PER_BLOCK_PRECISION);
_koth.operatorBurn(
_msgSender(),
_agilityBonus.mul(nbAgility).mul(cost),
"",
""
);
_nbAgility = nbAgility;
_isAgilityPowerUp = true;
}
function pause() public onlyOwner() {
_pause();
}
function unpause() public onlyOwner() {
_unpause();
}
function withdraw(uint256 amount) public onlyOwner() {
payable(owner()).transfer(amount);
}
receive() external payable {
uint256 toSeed = percentageToAmount(msg.value, _percentagePotToSeed);
uint256 toPot = msg.value.sub(toSeed);
_pot = _pot.add(toPot);
_seed = _seed.add(toSeed);
}
event Winner(address indexed winner, uint256 amount);
event Bought(address indexed buyer);
event StrengthActivated(uint256 cost);
event DefenseActivated(uint256 cost);
event AgilityActivated(uint256 cost);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../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, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../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.
*/
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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the global ERC1820 Registry, as defined in the
* https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register
* implementers for interfaces in this registry, as well as query support.
*
* Implementers may be shared by multiple accounts, and can also implement more
* than a single interface for each account. Contracts can implement interfaces
* for themselves, but externally-owned accounts (EOA) must delegate this to a
* contract.
*
* {IERC165} interfaces can also be queried via the registry.
*
* For an in-depth explanation and source code analysis, see the EIP text.
*/
interface IERC1820Registry {
/**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/
function setManager(address account, address newManager) external;
/**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/
function getManager(address account) external view returns (address);
/**
* @dev Sets the `implementer` contract as ``account``'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
* - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function setInterfaceImplementer(address account, bytes32 _interfaceHash, address implementer) external;
/**
* @dev Returns the implementer of `interfaceHash` for `account`. If no such
* implementer is registered, returns the zero address.
*
* If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/
function getInterfaceImplementer(address account, bytes32 _interfaceHash) external view returns (address);
/**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
/**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/
function updateERC165Cache(address account, bytes4 interfaceId) external;
/**
* @notice Checks whether a contract implements an ERC165 interface or not.
* If the result is not cached a direct lookup on the contract address is performed.
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
* {updateERC165Cache} with the contract address.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
/**
* @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
event ManagerChanged(address indexed account, address indexed newManager);
}
// 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 ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC777Token standard as defined in the EIP.
*
* This contract uses the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let
* token holders and recipients react to token movements by using setting implementers
* for the associated interfaces in said registry. See {IERC1820Registry} and
* {ERC1820Implementer}.
*/
interface IERC777 {
/**
* @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 smallest part of the token that is not divisible. This
* means all token operations (creation, movement and destruction) must have
* amounts that are a multiple of this number.
*
* For most token contracts, this value will equal 1.
*/
function granularity() external view returns (uint256);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by an account (`owner`).
*/
function balanceOf(address owner) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* If send or receive hooks are registered for the caller and `recipient`,
* the corresponding functions will be called with `data` and empty
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function send(address recipient, uint256 amount, bytes calldata data) external;
/**
* @dev Destroys `amount` tokens from the caller's account, reducing the
* total supply.
*
* If a send hook is registered for the caller, the corresponding function
* will be called with `data` and empty `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
*/
function burn(uint256 amount, bytes calldata data) external;
/**
* @dev Returns true if an account is an operator of `tokenHolder`.
* Operators can send and burn tokens on behalf of their owners. All
* accounts are their own operator.
*
* See {operatorSend} and {operatorBurn}.
*/
function isOperatorFor(address operator, address tokenHolder) external view returns (bool);
/**
* @dev Make an account an operator of the caller.
*
* See {isOperatorFor}.
*
* Emits an {AuthorizedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function authorizeOperator(address operator) external;
/**
* @dev Revoke an account's operator status for the caller.
*
* See {isOperatorFor} and {defaultOperators}.
*
* Emits a {RevokedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function revokeOperator(address operator) external;
/**
* @dev Returns the list of default operators. These accounts are operators
* for all token holders, even if {authorizeOperator} was never called on
* them.
*
* This list is immutable, but individual holders may revoke these via
* {revokeOperator}, in which case {isOperatorFor} will return false.
*/
function defaultOperators() external view returns (address[] memory);
/**
* @dev Moves `amount` tokens from `sender` to `recipient`. The caller must
* be an operator of `sender`.
*
* If send or receive hooks are registered for `sender` and `recipient`,
* the corresponding functions will be called with `data` and
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - `sender` cannot be the zero address.
* - `sender` must have at least `amount` tokens.
* - the caller must be an operator for `sender`.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
/**
* @dev Destroys `amount` tokens from `account`, reducing the total supply.
* The caller must be an operator of `account`.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `data` and `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
* - the caller must be an operator for `account`.
*/
function operatorBurn(
address account,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
event Sent(
address indexed operator,
address indexed from,
address indexed to,
uint256 amount,
bytes data,
bytes operatorData
);
event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData);
event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC777TokensRecipient standard as defined in the EIP.
*
* Accounts can be notified of {IERC777} tokens being sent to them by having a
* contract implement this interface (contract holders can be their own
* implementer) and registering it on the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
*
* See {IERC1820Registry} and {ERC1820Implementer}.
*/
interface IERC777Recipient {
/**
* @dev Called by an {IERC777} token contract whenever tokens are being
* moved or created into a registered account (`to`). The type of operation
* is conveyed by `from` being the zero address or not.
*
* This call occurs _after_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the post-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC777TokensSender standard as defined in the EIP.
*
* {IERC777} Token holders can be notified of operations performed on their
* tokens by having a contract implement this interface (contract holders can be
* their own implementer) and registering it on the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
*
* See {IERC1820Registry} and {ERC1820Implementer}.
*/
interface IERC777Sender {
/**
* @dev Called by an {IERC777} token contract whenever a registered holder's
* (`from`) tokens are about to be moved or destroyed. The type of operation
* is conveyed by `to` being the zero address or not.
*
* This call occurs _before_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the pre-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
// 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 Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(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));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.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.
*/
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());
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
} | Unset game contract as default operator | function removeGameContract(address game) public onlyGameMaster() {
_removeDefaultOperator(game);
}
| 1,228,446 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "./IVoteD21.sol";
/**
* @title D21 voting system contract
* @author smrza
* @notice More about D21 voting system: https://www.ih21.org/en/d21-janecekmethod
*/
contract D21 is IVoteD21 {
address immutable public owner; // Chairperson or someone important
uint private timeout; // Time of creation + 1 week, used for 1 week timeout
mapping(address => Subject) private subjects; // Each created subject
mapping(address => Voter) private voters; // Each eligible voter
mapping(address => bool) private subjectCreated; // Map whoever created a subject
address[] private subjectsAddr; // Save addresses of subjects
constructor() {
owner = msg.sender;
timeout = block.timestamp + 1 weeks;
}
// Ensures the elections are still active
modifier electionsActive {
require(timeout > block.timestamp, "Elections have ended.");
_;
}
// Ensures voter has the right to vote
modifier voterActive {
require(voters[msg.sender].canVote, "You cannot vote.");
_;
}
// Ensures subject exists
modifier subjectActive(address addr) {
require(subjectCreated[addr], "This subject does not exist.");
_;
}
/**
* @notice Adds a subject to the polls
* @dev Elections must be active
* @param name Name of the subject
*/
function addSubject(string memory name) external electionsActive {
require(!subjectCreated[msg.sender], "You have already created a subject.");
subjects[msg.sender] = Subject(name, 0);
subjectsAddr.push(msg.sender);
subjectCreated[msg.sender] = true;
}
/**
* @notice Adds an eligible voter to the polls
* @dev Elections must be active
* @param addr Voter's address
*/
function addVoter(address addr) external electionsActive {
require(msg.sender == owner, "Only owner can give right to vote.");
require(!voters[addr].canVote, "This person already has the right to vote.");
voters[addr] = Voter(true, address(0x0), address(0x0), 0);
}
/**
* @notice Gets all subjects' addresses
* @return The addresses of subjects
*/
function getSubjects() external view returns(address[] memory) {
return subjectsAddr;
}
/**
* @notice Gets a single subject by address and its name and vote count
* @param addr Address of the subject
* @return The subject structure with name and vote count
*/
function getSubject(address addr) external view returns(Subject memory) {
return subjects[addr];
}
/**
* @notice A voter votes positive for a subject
* @dev Elections, voter and subject must be active
* @param addr Address of subject to vote for
*/
function votePositive(address addr) external electionsActive voterActive subjectActive(addr) {
Voter storage vot = voters[msg.sender];
require(vot.voteCount < 2, "You have already voted positive twice.");
require(vot.votePositiveAddr != addr, "You have already voted for this subject.");
++vot.voteCount;
++subjects[addr].votes;
if(vot.voteCount == 1)
vot.votePositiveAddr = addr;
else
vot.votePositiveAddr2 = addr;
}
/**
* @notice A voter votes negative for a subject
* @dev Elections, voter and subject must be active
* @param addr Address of subject to vote for
*/
function voteNegative(address addr) external electionsActive voterActive subjectActive(addr) {
Voter storage vot = voters[msg.sender];
require(vot.voteCount > 1, "First, you must vote positive twice.");
require(vot.voteCount < 3, "You have already voted negative.");
require(vot.votePositiveAddr != addr && vot.votePositiveAddr2 != addr, "You already voted positive for this subject");
++vot.voteCount;
--subjects[addr].votes;
}
/**
* @notice Returns how much time is left until the elections are over
* @dev Elections must be active
* @return The remaining time in seconds
*/
function getRemainingTime() external electionsActive view returns(uint) {
return timeout - block.timestamp;
}
} | Gets all subjects' addresses return The addresses of subjects/ | function getSubjects() external view returns(address[] memory) {
return subjectsAddr;
}
| 15,782,244 |
./full_match/43114/0xd288A09f07C5AfBd65AEa7ba9534D5f830f9d1c6/sources/ArkenDexV2.sol | ETH => TOKEN TOKEN => ETH | function _tradeIDfyn(
IERC20 _src,
IERC20 _dest,
uint256 inputAmount,
uint256 minOutputAmount,
address[] memory paths,
address to,
address dexAddr
) private returns (uint256[] memory amounts) {
IUniswapV2Router02 uniRouter = IUniswapV2Router02(dexAddr);
if (_WETH_DFYN_ == address(_src)) {
_unwrapEther(_WETH_, inputAmount);
_wrapEther(_WETH_DFYN_, inputAmount);
}
if (_ETH_ == address(_src)) {
if (paths[0] == address(_ETH_)) {
paths[0] = address(_WETH_DFYN_);
}
minOutputAmount,
paths,
to,
_DEADLINE_
);
if (paths[paths.length - 1] == address(_ETH_)) {
paths[paths.length - 1] = address(_WETH_DFYN_);
}
_increaseAllowance(_src, dexAddr, inputAmount);
amounts = uniRouter.swapExactTokensForETH(
inputAmount,
minOutputAmount,
paths,
to,
_DEADLINE_
);
amounts = uniRouter.swapExactTokensForTokens(
inputAmount,
minOutputAmount,
paths,
to,
_DEADLINE_
);
}
if (_WETH_DFYN_ == address(_dest)) {
_unwrapEther(_WETH_DFYN_, inputAmount);
_unwrapEther(_WETH_, inputAmount);
}
}
| 4,582,035 |
//File: contracts/Owned.sol
pragma solidity ^0.4.19;
/// @title Owned
/// @author Adrià Massanet <[email protected]>
/// @notice The Owned contract has an owner address, and provides basic
/// authorization control functions, this simplifies & the implementation of
/// user permissions; this contract has three work flows for a change in
/// ownership, the first requires the new owner to validate that they have the
/// ability to accept ownership, the second allows the ownership to be
/// directly transfered without requiring acceptance, and the third allows for
/// the ownership to be removed to allow for decentralization
contract Owned {
address public owner;
address public newOwnerCandidate;
event OwnershipRequested(address indexed by, address indexed to);
event OwnershipTransferred(address indexed from, address indexed to);
event OwnershipRemoved();
/// @dev The constructor sets the `msg.sender` as the`owner` of the contract
function Owned() public {
owner = msg.sender;
}
/// @dev `owner` is the only address that can call a function with this
/// modifier
modifier onlyOwner() {
require (msg.sender == owner);
_;
}
/// @dev In this 1st option for ownership transfer `proposeOwnership()` must
/// be called first by the current `owner` then `acceptOwnership()` must be
/// called by the `newOwnerCandidate`
/// @notice `onlyOwner` Proposes to transfer control of the contract to a
/// new owner
/// @param _newOwnerCandidate The address being proposed as the new owner
function proposeOwnership(address _newOwnerCandidate) public onlyOwner {
newOwnerCandidate = _newOwnerCandidate;
OwnershipRequested(msg.sender, newOwnerCandidate);
}
/// @notice Can only be called by the `newOwnerCandidate`, accepts the
/// transfer of ownership
function acceptOwnership() public {
require(msg.sender == newOwnerCandidate);
address oldOwner = owner;
owner = newOwnerCandidate;
newOwnerCandidate = 0x0;
OwnershipTransferred(oldOwner, owner);
}
/// @dev In this 2nd option for ownership transfer `changeOwnership()` can
/// be called and it will immediately assign ownership to the `newOwner`
/// @notice `owner` can step down and assign some other address to this role
/// @param _newOwner The address of the new owner
function changeOwnership(address _newOwner) public onlyOwner {
require(_newOwner != 0x0);
address oldOwner = owner;
owner = _newOwner;
newOwnerCandidate = 0x0;
OwnershipTransferred(oldOwner, owner);
}
/// @dev In this 3rd option for ownership transfer `removeOwnership()` can
/// be called and it will immediately assign ownership to the 0x0 address;
/// it requires a 0xdece be input as a parameter to prevent accidental use
/// @notice Decentralizes the contract, this operation cannot be undone
/// @param _dac `0xdac` has to be entered for this function to work
function removeOwnership(address _dac) public onlyOwner {
require(_dac == 0xdac);
owner = 0x0;
newOwnerCandidate = 0x0;
OwnershipRemoved();
}
}
//File: contracts/ERC20.sol
pragma solidity ^0.4.19;
/**
* @title ERC20
* @dev A standard interface for tokens.
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
*/
contract ERC20 {
/// @dev Returns the total token supply
function totalSupply() public constant returns (uint256 supply);
/// @dev Returns the account balance of the account with address _owner
function balanceOf(address _owner) public constant returns (uint256 balance);
/// @dev Transfers _value number of tokens to address _to
function transfer(address _to, uint256 _value) public returns (bool success);
/// @dev Transfers _value number of tokens from address _from to address _to
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
/// @dev Allows _spender to withdraw from the msg.sender's account up to the _value amount
function approve(address _spender, uint256 _value) public returns (bool success);
/// @dev Returns the amount which _spender is still allowed to withdraw from _owner
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
//File: contracts/Escapable.sol
pragma solidity ^0.4.19;
/*
Copyright 2016, Jordi Baylina
Contributor: Adrià Massanet <[email protected]>
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/>.
*/
/// @dev `Escapable` is a base level contract built off of the `Owned`
/// contract; it creates an escape hatch function that can be called in an
/// emergency that will allow designated addresses to send any ether or tokens
/// held in the contract to an `escapeHatchDestination` as long as they were
/// not blacklisted
contract Escapable is Owned {
address public escapeHatchCaller;
address public escapeHatchDestination;
mapping (address=>bool) private escapeBlacklist; // Token contract addresses
/// @notice The Constructor assigns the `escapeHatchDestination` and the
/// `escapeHatchCaller`
/// @param _escapeHatchCaller The address of a trusted account or contract
/// to call `escapeHatch()` to send the ether in this contract to the
/// `escapeHatchDestination` it would be ideal that `escapeHatchCaller`
/// cannot move funds out of `escapeHatchDestination`
/// @param _escapeHatchDestination The address of a safe location (usu a
/// Multisig) to send the ether held in this contract; if a neutral address
/// is required, the WHG Multisig is an option:
/// 0x8Ff920020c8AD673661c8117f2855C384758C572
function Escapable(address _escapeHatchCaller, address _escapeHatchDestination) public {
escapeHatchCaller = _escapeHatchCaller;
escapeHatchDestination = _escapeHatchDestination;
}
/// @dev The addresses preassigned as `escapeHatchCaller` or `owner`
/// are the only addresses that can call a function with this modifier
modifier onlyEscapeHatchCallerOrOwner {
require ((msg.sender == escapeHatchCaller)||(msg.sender == owner));
_;
}
/// @notice Creates the blacklist of tokens that are not able to be taken
/// out of the contract; can only be done at the deployment, and the logic
/// to add to the blacklist will be in the constructor of a child contract
/// @param _token the token contract address that is to be blacklisted
function blacklistEscapeToken(address _token) internal {
escapeBlacklist[_token] = true;
EscapeHatchBlackistedToken(_token);
}
/// @notice Checks to see if `_token` is in the blacklist of tokens
/// @param _token the token address being queried
/// @return False if `_token` is in the blacklist and can't be taken out of
/// the contract via the `escapeHatch()`
function isTokenEscapable(address _token) view public returns (bool) {
return !escapeBlacklist[_token];
}
/// @notice The `escapeHatch()` should only be called as a last resort if a
/// security issue is uncovered or something unexpected happened
/// @param _token to transfer, use 0x0 for ether
function escapeHatch(address _token) public onlyEscapeHatchCallerOrOwner {
require(escapeBlacklist[_token]==false);
uint256 balance;
/// @dev Logic for ether
if (_token == 0x0) {
balance = this.balance;
escapeHatchDestination.transfer(balance);
EscapeHatchCalled(_token, balance);
return;
}
/// @dev Logic for tokens
ERC20 token = ERC20(_token);
balance = token.balanceOf(this);
require(token.transfer(escapeHatchDestination, balance));
EscapeHatchCalled(_token, balance);
}
/// @notice Changes the address assigned to call `escapeHatch()`
/// @param _newEscapeHatchCaller The address of a trusted account or
/// contract to call `escapeHatch()` to send the value in this contract to
/// the `escapeHatchDestination`; it would be ideal that `escapeHatchCaller`
/// cannot move funds out of `escapeHatchDestination`
function changeHatchEscapeCaller(address _newEscapeHatchCaller) public onlyEscapeHatchCallerOrOwner {
escapeHatchCaller = _newEscapeHatchCaller;
}
event EscapeHatchBlackistedToken(address token);
event EscapeHatchCalled(address token, uint amount);
}
//File: contracts/DAppNodePackageDirectory.sol
pragma solidity ^0.4.19;
/*
Copyright 2018, Eduardo Antuña
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 DAppNodePackageDirectory Contract
/// @author Eduardo Antuña
/// @dev The goal of this smartcontrat is to keep a list of available packages
/// to install in the DAppNode
contract DAppNodePackageDirectory is Owned,Escapable {
enum DAppNodePackageStatus {Preparing, Develop, Active, Deprecated, Deleted}
struct DAppNodePackage {
string name;
address repo;
DAppNodePackageStatus status;
}
DAppNodePackage[] DAppNodePackages;
event PackageAdded(uint indexed idPackage, string name, address repo);
event PackageUpdated(uint indexed idPackage, string name, address repo);
event StatusChanged(uint idPackage, DAppNodePackageStatus newStatus);
/// @notice The Constructor assigns the `escapeHatchDestination` and the
/// `escapeHatchCaller`
/// @param _escapeHatchCaller The address of a trusted account or contract
/// to call `escapeHatch()` to send the ether in this contract to the
/// `escapeHatchDestination` it would be ideal that `escapeHatchCaller`
/// cannot move funds out of `escapeHatchDestination`
/// @param _escapeHatchDestination The address of a safe location (usu a
/// Multisig) to send the ether held in this contract; if a neutral address
/// is required, the WHG Multisig is an option:
/// 0x8Ff920020c8AD673661c8117f2855C384758C572
function DAppNodePackageDirectory(
address _escapeHatchCaller,
address _escapeHatchDestination
)
Escapable(_escapeHatchCaller, _escapeHatchDestination)
public
{
}
/// @notice Add a new DAppNode package
/// @param name the ENS name of the package
/// @param repo the AragonPackageManager address of the repo.
/// @return the idPackage of the new package
function addPackage (
string name,
address repo
) onlyOwner public returns(uint idPackage) {
idPackage = DAppNodePackages.length++;
DAppNodePackage storage c = DAppNodePackages[idPackage];
c.name = name;
c.repo = repo;
// An event to notify that a new package has been added
PackageAdded(idPackage,name,repo);
}
/// @notice Update a DAppNode package
/// @param idPackage the id of the package to be changed
/// @param name the new ENS name of the package
/// @param repo the new AragonPackageManager address of the repo.
function updatePackage (
uint idPackage,
string name,
address repo
) onlyOwner public {
require(idPackage < DAppNodePackages.length);
DAppNodePackage storage c = DAppNodePackages[idPackage];
c.name = name;
c.repo = repo;
// An event to notify that a package has been updated
PackageUpdated(idPackage,name,repo);
}
/// @notice Change the status of a DAppNode package
/// @param idPackage the id of the package to be changed
/// @param newStatus the new status of the package
function changeStatus(
uint idPackage,
DAppNodePackageStatus newStatus
) onlyOwner public {
require(idPackage < DAppNodePackages.length);
DAppNodePackage storage c = DAppNodePackages[idPackage];
c.status = newStatus;
// An event to notify that the status of a packet has been updated
StatusChanged(idPackage, newStatus);
}
/// @notice Returns the information of a DAppNode package
/// @param idPackage the id of the package to be changed
/// @return name the new name of the package
/// @return repo the AragonPackageManager address of the repo.
/// @return status the status of the package
function getPackage(uint idPackage) constant public returns (
string name,
address repo,
DAppNodePackageStatus status
) {
require(idPackage < DAppNodePackages.length);
DAppNodePackage storage c = DAppNodePackages[idPackage];
name = c.name;
repo = c.repo;
status = c.status;
}
/// @notice its goal is to return the total number of DAppNode packages
/// @return the total number of DAppNode packages
function numberOfDAppNodePackages() view public returns (uint) {
return DAppNodePackages.length;
}
} | Update a DAppNode package idPackage the id of the package to be changed name the new ENS name of the package repo the new AragonPackageManager address of the repo. An event to notify that a package has been updated | function updatePackage (
uint idPackage,
string name,
address repo
) onlyOwner public {
require(idPackage < DAppNodePackages.length);
DAppNodePackage storage c = DAppNodePackages[idPackage];
c.name = name;
c.repo = repo;
PackageUpdated(idPackage,name,repo);
}
| 13,943,330 |
pragma solidity ^0.4.25;
/**
* Math operations with safety checks
*/
library Safe {
function safeMul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b > 0);
uint256 c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c>=a && c>=b);
return c;
}
}
contract MyCoin{
uint public totalSupply = 600000000*10**18; //Total amount of distribution
uint8 constant public decimals = 18;
string constant public name = "MACRICH token";
string constant public symbol = "MAR";
address public owner;
mapping (address => uint256) public balanceOf;
mapping (address => uint256) public freezeOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
event Freeze(address indexed from, uint256 value);
event Unfreeze(address indexed from, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
constructor() public{
balanceOf[msg.sender] = totalSupply;
owner = msg.sender;
}
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
function transfer(address _to, uint256 _value) public {
require(_to != 0x0);
require(_value > 0);
require(balanceOf[msg.sender] >= _value);
require(balanceOf[_to] + _value >= balanceOf[_to]);
balanceOf[msg.sender] = Safe.safeSub(balanceOf[msg.sender], _value);
balanceOf[_to] = Safe.safeAdd(balanceOf[_to], _value);
emit Transfer(msg.sender, _to, _value);
}
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Is it successfully approved
function approve(address _spender, uint256 _value) public
returns (bool success) {
require(_value > 0);
allowance[msg.sender][_spender] = _value;
return true;
}
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != 0x0);
require(_value > 0);
require(balanceOf[_from] > _value);
require(balanceOf[_to] + _value >= balanceOf[_to]);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] = Safe.safeSub(balanceOf[_from], _value);
balanceOf[_to] = Safe.safeAdd(balanceOf[_to], _value);
allowance[_from][msg.sender] = Safe.safeSub(allowance[_from][msg.sender], _value);
emit Transfer(_from, _to, _value);
return true;
}
/// @param _value The amount of token to be burned
/// @return Is it successfully burned
function burn(uint256 _value) public returns (bool) {
require(balanceOf[msg.sender] >= _value);
require(_value > 0);
balanceOf[msg.sender] = Safe.safeSub(balanceOf[msg.sender], _value);
totalSupply = Safe.safeSub(totalSupply,_value);
emit Burn(msg.sender, _value);
return true;
}
/// @param _value The amount of token to be freeze
/// @return Is it successfully froze
function freeze(uint256 _value) public returns (bool) {
require(balanceOf[msg.sender] >= _value);
require(_value > 0);
balanceOf[msg.sender] = Safe.safeSub(balanceOf[msg.sender], _value);
freezeOf[msg.sender] = Safe.safeAdd(freezeOf[msg.sender], _value);
emit Freeze(msg.sender, _value);
return true;
}
/// @param _value The amount of token to be unfreeze
/// @return Is it successfully unfroze
function unfreeze(uint256 _value) public returns (bool) {
require(freezeOf[msg.sender] >= _value);
require(_value > 0);
freezeOf[msg.sender] = Safe.safeSub(freezeOf[msg.sender], _value);
balanceOf[msg.sender] = Safe.safeAdd(balanceOf[msg.sender], _value);
emit Unfreeze(msg.sender, _value);
return true;
}
function() payable public {
revert();
}
} | _value The amount of token to be unfreeze return Is it successfully unfroze | function unfreeze(uint256 _value) public returns (bool) {
require(freezeOf[msg.sender] >= _value);
require(_value > 0);
freezeOf[msg.sender] = Safe.safeSub(freezeOf[msg.sender], _value);
balanceOf[msg.sender] = Safe.safeAdd(balanceOf[msg.sender], _value);
emit Unfreeze(msg.sender, _value);
return true;
}
| 6,390,044 |
pragma solidity ^0.4.8;
contract CryptoWaifusMarket {
// You can use this hash to verify the image file containing all the waifus
string public imageHash =
"ac39af4793119ee46bbff351d8cb6b5f23da60222126add4268e261199a2921b";
address owner;
string public standard = "CryptoWaifus";
string public name;
string public symbol;
uint8 public decimals;
uint16 maxWaifus = 100;
uint256 public totalSupply;
uint256 public nextWaifuIndexToAssign = 0;
bool public allWaifusAssigned = false;
uint256 public waifusRemainingToAssign = 0;
//mapping (address => uint) public addressToWaifuIndex;
mapping(uint256 => address) public waifuIndexToAddress;
/* This creates an array with all balances */
mapping(address => uint256) public balanceOf;
struct Offer {
bool isForSale;
uint256 waifuIndex;
address seller;
uint256 minValue; // in ether
address onlySellTo; // specify to sell only to a specific person
}
struct Bid {
bool hasBid;
uint256 waifuIndex;
address bidder;
uint256 value;
}
// A record of waifus that are offered for sale at a specific minimum value, and perhaps to a specific person
mapping(uint256 => Offer) public waifusOfferedForSale;
// A record of the highest waifu bid
mapping(uint256 => Bid) public waifuBids;
mapping(address => uint256) public pendingWithdrawals;
event Assign(address indexed to, uint256 waifuIndex);
event Transfer(address indexed from, address indexed to, uint256 value);
event WaifuTransfer(
address indexed from,
address indexed to,
uint256 waifuIndex
);
event WaifuOffered(
uint256 indexed waifuIndex,
uint256 minValue,
address indexed toAddress
);
event WaifuBidEntered(
uint256 indexed waifuIndex,
uint256 value,
address indexed fromAddress
);
event WaifuBidWithdrawn(
uint256 indexed waifuIndex,
uint256 value,
address indexed fromAddress
);
event WaifuBought(
uint256 indexed waifuIndex,
uint256 value,
address indexed fromAddress,
address indexed toAddress
);
event WaifuNoLongerForSale(uint256 indexed waifuIndex);
/* Initializes contract with initial supply tokens to the creator of the contract */
function CryptoWaifusMarket() payable {
// balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens
owner = msg.sender;
totalSupply = maxWaifus; // Update total supply
waifusRemainingToAssign = totalSupply;
name = "CRYPTOWAIFUS"; // Set the name for display purposes
symbol = "Ͼ"; // Set the symbol for display purposes
decimals = 0; // Amount of decimals for display purposes
}
function setInitialOwner(address to, uint256 waifuIndex) {
if (msg.sender != owner) throw;
if (allWaifusAssigned) throw;
if (waifuIndex >= maxWaifus) throw;
if (waifuIndexToAddress[waifuIndex] != to) {
if (waifuIndexToAddress[waifuIndex] != 0x0) {
balanceOf[waifuIndexToAddress[waifuIndex]]--;
} else {
waifusRemainingToAssign--;
}
waifuIndexToAddress[waifuIndex] = to;
balanceOf[to]++;
Assign(to, waifuIndex);
}
}
function setInitialOwners(address[] addresses, uint256[] indices) {
if (msg.sender != owner) throw;
uint256 n = addresses.length;
for (uint256 i = 0; i < n; i++) {
setInitialOwner(addresses[i], indices[i]);
}
}
function allInitialOwnersAssigned() {
if (msg.sender != owner) throw;
allWaifusAssigned = true;
}
function getWaifu(uint256 waifuIndex) {
if (!allWaifusAssigned) throw;
if (waifusRemainingToAssign == 0) throw;
if (waifuIndexToAddress[waifuIndex] != 0x0) throw;
if (waifuIndex >= maxWaifus) throw;
waifuIndexToAddress[waifuIndex] = msg.sender;
balanceOf[msg.sender]++;
waifusRemainingToAssign--;
Assign(msg.sender, waifuIndex);
}
// Transfer ownership of a waifu to another user without requiring payment
function transferWaifu(address to, uint256 waifuIndex) {
if (!allWaifusAssigned) throw;
if (waifuIndexToAddress[waifuIndex] != msg.sender) throw;
if (waifuIndex >= maxWaifus) throw;
if (waifusOfferedForSale[waifuIndex].isForSale) {
waifuNoLongerForSale(waifuIndex);
}
waifuIndexToAddress[waifuIndex] = to;
balanceOf[msg.sender]--;
balanceOf[to]++;
Transfer(msg.sender, to, 1);
WaifuTransfer(msg.sender, to, waifuIndex);
// Check for the case where there is a bid from the new owner and refund it.
// Any other bid can stay in place.
Bid bid = waifuBids[waifuIndex];
if (bid.bidder == to) {
// Kill bid and refund value
pendingWithdrawals[to] += bid.value;
waifuBids[waifuIndex] = Bid(false, waifuIndex, 0x0, 0);
}
}
function waifuNoLongerForSale(uint256 waifuIndex) {
if (!allWaifusAssigned) throw;
if (waifuIndexToAddress[waifuIndex] != msg.sender) throw;
if (waifuIndex >= maxWaifus) throw;
waifusOfferedForSale[waifuIndex] = Offer(
false,
waifuIndex,
msg.sender,
0,
0x0
);
WaifuNoLongerForSale(waifuIndex);
}
function offerWaifuForSale(uint256 waifuIndex, uint256 minSalePriceInWei) {
if (!allWaifusAssigned) throw;
if (waifuIndexToAddress[waifuIndex] != msg.sender) throw;
if (waifuIndex >= maxWaifus) throw;
waifusOfferedForSale[waifuIndex] = Offer(
true,
waifuIndex,
msg.sender,
minSalePriceInWei,
0x0
);
WaifuOffered(waifuIndex, minSalePriceInWei, 0x0);
}
function offerWaifuForSaleToAddress(
uint256 waifuIndex,
uint256 minSalePriceInWei,
address toAddress
) {
if (!allWaifusAssigned) throw;
if (waifuIndexToAddress[waifuIndex] != msg.sender) throw;
if (waifuIndex >= maxWaifus) throw;
waifusOfferedForSale[waifuIndex] = Offer(
true,
waifuIndex,
msg.sender,
minSalePriceInWei,
toAddress
);
WaifuOffered(waifuIndex, minSalePriceInWei, toAddress);
}
function buyWaifu(uint256 waifuIndex) payable {
if (!allWaifusAssigned) throw;
Offer offer = waifusOfferedForSale[waifuIndex];
if (waifuIndex >= maxWaifus) throw;
if (!offer.isForSale) throw; // waifu not actually for sale
if (offer.onlySellTo != 0x0 && offer.onlySellTo != msg.sender) throw; // waifu not supposed to be sold to this user
if (msg.value < offer.minValue) throw; // Didn't send enough ETH
if (offer.seller != waifuIndexToAddress[waifuIndex]) throw; // Seller no longer owner of waifu
address seller = offer.seller;
waifuIndexToAddress[waifuIndex] = msg.sender;
balanceOf[seller]--;
balanceOf[msg.sender]++;
Transfer(seller, msg.sender, 1);
waifuNoLongerForSale(waifuIndex);
pendingWithdrawals[seller] += msg.value;
WaifuBought(waifuIndex, msg.value, seller, msg.sender);
// Check for the case where there is a bid from the new owner and refund it.
// Any other bid can stay in place.
Bid bid = waifuBids[waifuIndex];
if (bid.bidder == msg.sender) {
// Kill bid and refund value
pendingWithdrawals[msg.sender] += bid.value;
waifuBids[waifuIndex] = Bid(false, waifuIndex, 0x0, 0);
}
}
function withdraw() {
if (!allWaifusAssigned) throw;
uint256 amount = pendingWithdrawals[msg.sender];
// Remember to zero the pending refund before
// sending to prevent re-entrancy attacks
pendingWithdrawals[msg.sender] = 0;
msg.sender.transfer(amount);
}
function enterBidForWaifu(uint256 waifuIndex) payable {
if (waifuIndex >= maxWaifus) throw;
if (!allWaifusAssigned) throw;
if (waifuIndexToAddress[waifuIndex] == 0x0) throw;
if (waifuIndexToAddress[waifuIndex] == msg.sender) throw;
if (msg.value == 0) throw;
Bid existing = waifuBids[waifuIndex];
if (msg.value <= existing.value) throw;
if (existing.value > 0) {
// Refund the failing bid
pendingWithdrawals[existing.bidder] += existing.value;
}
waifuBids[waifuIndex] = Bid(true, waifuIndex, msg.sender, msg.value);
WaifuBidEntered(waifuIndex, msg.value, msg.sender);
}
function acceptBidForWaifu(uint256 waifuIndex, uint256 minPrice) {
if (waifuIndex >= maxWaifus) throw;
if (!allWaifusAssigned) throw;
if (waifuIndexToAddress[waifuIndex] != msg.sender) throw;
address seller = msg.sender;
Bid bid = waifuBids[waifuIndex];
if (bid.value == 0) throw;
if (bid.value < minPrice) throw;
waifuIndexToAddress[waifuIndex] = bid.bidder;
balanceOf[seller]--;
balanceOf[bid.bidder]++;
Transfer(seller, bid.bidder, 1);
waifusOfferedForSale[waifuIndex] = Offer(
false,
waifuIndex,
bid.bidder,
0,
0x0
);
uint256 amount = bid.value;
waifuBids[waifuIndex] = Bid(false, waifuIndex, 0x0, 0);
pendingWithdrawals[seller] += amount;
WaifuBought(waifuIndex, bid.value, seller, bid.bidder);
}
function withdrawBidForWaifu(uint256 waifuIndex) {
if (waifuIndex >= maxWaifus) throw;
if (!allWaifusAssigned) throw;
if (waifuIndexToAddress[waifuIndex] == 0x0) throw;
if (waifuIndexToAddress[waifuIndex] == msg.sender) throw;
Bid bid = waifuBids[waifuIndex];
if (bid.bidder != msg.sender) throw;
WaifuBidWithdrawn(waifuIndex, bid.value, msg.sender);
uint256 amount = bid.value;
waifuBids[waifuIndex] = Bid(false, waifuIndex, 0x0, 0);
// Refund the bid money
msg.sender.transfer(amount);
}
}
| Remember to zero the pending refund before sending to prevent re-entrancy attacks | function withdraw() {
if (!allWaifusAssigned) throw;
uint256 amount = pendingWithdrawals[msg.sender];
pendingWithdrawals[msg.sender] = 0;
msg.sender.transfer(amount);
}
| 912,726 |
// 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 Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.10;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
// Import Compound components
import "./compound/ICErc20.sol";
import "./compound/ICEther.sol";
import "./compound/IComptroller.sol";
import "./compound/IPriceOracle.sol";
// Import Uniswap components
import "./uniswap/UniswapV2Library.sol";
import "./uniswap/IUniswapV2Factory.sol";
import "./uniswap/IUniswapV2Router02.sol";
import "./uniswap/IUniswapV2Callee.sol";
import "./uniswap/IUniswapV2Pair.sol";
import "./uniswap/IWETH.sol";
contract Liquidator is Ownable, IUniswapV2Callee {
using SafeERC20 for IERC20;
address constant public ETHER = address(0);
address immutable public CETH;
address immutable public WETH;
address immutable public ROUTER;
address immutable public FACTORY;
IComptroller public comptroller;
IPriceOracle public priceOracle;
uint private closeFact;
uint private liqIncent;
uint private gasThreshold = 2000000;
event RevenueWithdrawn(address owner, address token, uint256 amount);
constructor(
address _ceth,
address _weth,
address _router,
address _factory,
address _comptrollerAddress
) public {
CETH = _ceth;
WETH = _weth;
ROUTER = _router;
FACTORY = _factory;
setComptroller(_comptrollerAddress);
}
receive() external payable {}
function setComptroller(address _comptrollerAddress) public onlyOwner {
comptroller = IComptroller(_comptrollerAddress);
priceOracle = IPriceOracle(comptroller.oracle());
closeFact = comptroller.closeFactorMantissa();
liqIncent = comptroller.liquidationIncentiveMantissa();
}
function liquidate(address _borrower, address _repayCToken, address _seizeCToken) public {
( , uint liquidity, ) = comptroller.getAccountLiquidity(_borrower);
require(liquidity == 0, "Nothing to liquidate");
// uint(10**18) adjustments ensure that all place values are dedicated
// to repay and seize precision rather than unnecessary closeFact and liqIncent decimals
uint repayMax = ICErc20(_repayCToken).borrowBalanceCurrent(_borrower) * closeFact / uint(10**18);
uint seizeMax = ICErc20(_seizeCToken).balanceOfUnderlying(_borrower) * uint(10**18) / liqIncent;
uint uPriceRepay = priceOracle.getUnderlyingPrice(_repayCToken);
// Gas savings -- instead of making new vars `repayMax_Eth` and `seizeMax_Eth` just reassign
repayMax *= uPriceRepay;
seizeMax *= priceOracle.getUnderlyingPrice(_seizeCToken);
// Gas savings -- instead of creating new var `repay_Eth = repayMax < seizeMax ? ...` and then
// converting to underlying units by dividing by uPriceRepay, we can do it all in one step
_liquidate(_borrower, _repayCToken, _seizeCToken, ((repayMax < seizeMax) ? repayMax : seizeMax) / uPriceRepay);
}
function _liquidate(address _borrower, address _repayCToken, address _seizeCToken, uint _amount) internal {
address pair;
address r;
if (_repayCToken == CETH) {
r = WETH;
pair = IUniswapV2Factory(FACTORY).getPair(WETH, ICErc20Storage(_seizeCToken).underlying());
} else {
r = ICErc20Storage(_repayCToken).underlying();
pair = IUniswapV2Factory(FACTORY).getPair(WETH, r);
}
// Initiate flash swap
bytes memory data = abi.encode(_borrower, _repayCToken, _seizeCToken);
uint amount0 = IUniswapV2Pair(pair).token0() == r ? _amount : 0;
uint amount1 = IUniswapV2Pair(pair).token1() == r ? _amount : 0;
IUniswapV2Pair(pair).swap(amount0, amount1, address(this), data);
}
function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) override external {
// Unpack parameters sent from the `liquidate` function
// NOTE: these are being passed in from some other contract, and cannot necessarily be trusted
(address borrower, address repayCToken, address seizeCToken) = abi.decode(data, (address, address, address));
address token0 = IUniswapV2Pair(msg.sender).token0();
address token1 = IUniswapV2Pair(msg.sender).token1();
require(msg.sender == IUniswapV2Factory(FACTORY).getPair(token0, token1));
if (repayCToken == seizeCToken) {
uint amount = amount0 != 0 ? amount0 : amount1;
address estuary = amount0 != 0 ? token0 : token1;
// Perform the liquidation
IERC20(estuary).safeApprove(repayCToken, amount);
ICErc20(repayCToken).liquidateBorrow(borrower, amount, seizeCToken);
// Redeem cTokens for underlying ERC20
ICErc20(seizeCToken).redeem(IERC20(seizeCToken).balanceOf(address(this)));
// Compute debt and pay back pair
IERC20(estuary).transfer(msg.sender, (amount * 1000 / 997) + 1);
return;
}
if (repayCToken == CETH) {
uint amount = amount0 != 0 ? amount0 : amount1;
address estuary = amount0 != 0 ? token1 : token0;
// Convert WETH to ETH
IWETH(WETH).withdraw(amount);
// Perform the liquidation
ICEther(repayCToken).liquidateBorrow{value: amount}(borrower, seizeCToken);
// Redeem cTokens for underlying ERC20
ICErc20(seizeCToken).redeem(IERC20(seizeCToken).balanceOf(address(this)));
// Compute debt and pay back pair
(uint reserve0, uint reserve1,) = IUniswapV2Pair(msg.sender).getReserves();
(uint reserveIn, uint reserveOut) = token0 == estuary ? (reserve0, reserve1) : (reserve1, reserve0);
IERC20(estuary).transfer(msg.sender, UniswapV2Library.getAmountIn(amount, reserveIn, reserveOut));
return;
}
if (seizeCToken == CETH) {
uint amount = amount0 != 0 ? amount0 : amount1;
address source = amount0 != 0 ? token0 : token1;
// Perform the liquidation
IERC20(source).safeApprove(repayCToken, amount);
ICErc20(repayCToken).liquidateBorrow(borrower, amount, seizeCToken);
// Redeem cTokens for underlying ERC20 or ETH
ICErc20(seizeCToken).redeem(IERC20(seizeCToken).balanceOf(address(this)));
// Convert ETH to WETH
IWETH(WETH).deposit{value: address(this).balance}();
// Compute debt and pay back pair
(uint reserve0, uint reserve1,) = IUniswapV2Pair(msg.sender).getReserves();
(uint reserveIn, uint reserveOut) = token0 == source ? (reserve1, reserve0) : (reserve0, reserve1);
// (uint reserveOut, uint reserveIn) = UniswapV2Library.getReserves(FACTORY, source, WETH);
IERC20(WETH).transfer(msg.sender, UniswapV2Library.getAmountIn(amount, reserveIn, reserveOut));
return;
}
uint amount;
address source;
if (amount0 != 0) {
amount = amount0;
source = token0;
} else {
amount = amount1;
source = token1;
}
// Perform the liquidation
IERC20(source).safeApprove(repayCToken, amount);
ICErc20(repayCToken).liquidateBorrow(borrower, amount, seizeCToken);
// Redeem cTokens for underlying ERC20 or ETH
uint seized_uUnits = ICErc20(seizeCToken).balanceOfUnderlying(address(this));
ICErc20(seizeCToken).redeem(IERC20(seizeCToken).balanceOf(address(this)));
address seizeUToken = ICErc20Storage(seizeCToken).underlying();
// Compute debt
(uint reserve0, uint reserve1,) = IUniswapV2Pair(msg.sender).getReserves();
(uint reserveIn, uint reserveOut) = token0 == source ? (reserve1, reserve0) : (reserve0, reserve1);
// (uint reserveOut, uint reserveIn) = UniswapV2Library.getReserves(FACTORY, source, estuary);
uint debt = UniswapV2Library.getAmountIn(amount, reserveIn, reserveOut);
IERC20(seizeUToken).safeApprove(ROUTER, seized_uUnits);
// Define swapping path
address[] memory path = new address[](2);
path[0] = seizeUToken;
path[1] = WETH;
IUniswapV2Router02(ROUTER).swapTokensForExactTokens(debt, seized_uUnits, path, address(this), now + 1 minutes);
IERC20(seizeUToken).safeApprove(ROUTER, 0);
// Pay back pair
IERC20(WETH).transfer(msg.sender, debt);
}
function withdraw(address _token) external onlyOwner {
require(owner() != address(0), "cannot send to zero address");
uint amount;
if (_token == ETHER) {
address self = address(this); // workaround for a possible solidity bug
amount = self.balance;
(bool success, ) = owner().call{value: amount}("");
require(success, "withdraw failed");
} else {
amount = IERC20(_token).balanceOf(address(this));
IERC20(_token).safeTransfer(owner(), amount);
}
emit RevenueWithdrawn(owner(), _token, amount);
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.6.10;
interface ICErc20 {
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, address collateral) external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function balanceOfUnderlying(address account) external returns (uint);
}
interface ICErc20Storage {
function underlying() external view returns (address);
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.6.10;
interface ICEther {
function mint() external payable;
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow() external payable;
function repayBorrowBehalf(address borrower) external payable;
function liquidateBorrow(address borrower, address cTokenCollateral) external payable;
function balanceOfUnderlying(address account) external returns (uint);
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.6.10;
interface IComptroller {
function enterMarkets(address[] calldata cTokens) external returns (uint[] memory);
function exitMarket(address cToken) external returns (uint);
function getAssetsIn(address account) external view returns (address[] memory);
function markets(address cTokenAddress) external view returns (bool, uint);
function getAccountLiquidity(address account) external returns (uint, uint, uint);
function closeFactorMantissa() external view returns (uint);
function liquidationIncentiveMantissa() external view returns (uint);
function oracle() external view returns (address);
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.6.10;
// For PriceOracle postPrices()
pragma experimental ABIEncoderV2;
interface IPriceOracle {
function getUnderlyingPrice(address cToken) external view returns (uint);
function postPrices(bytes[] calldata messages, bytes[] calldata signatures, string[] calldata symbols) external;
}
// SPDX-License-Identifier: GPL
pragma solidity ^0.6.10;
interface IUniswapV2Callee {
function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
}
// SPDX-License-Identifier: GPL
pragma solidity ^0.6.10;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// SPDX-License-Identifier: GPL
pragma solidity ^0.6.10;
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
pragma solidity ^0.6.10;
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);
}
// SPDX-License-Identifier: GPL
pragma solidity ^0.6.10;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// SPDX-License-Identifier: GPL
pragma solidity ^0.6.10;
interface IWETH {
function balanceOf(address account) external view returns (uint);
function deposit() external payable;
function transfer(address recipient, uint amount) external returns (bool);
function withdraw(uint) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.10;
// Import the ERC20 interface and and SafeMath library
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import './IUniswapV2Pair.sol';
library UniswapV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
function getReservesWithPair(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB, address pair) {
(address token0,) = sortTokens(tokenA, tokenB);
pair = pairFor(factory, tokenA, tokenB);
// check that pair exists
uint32 size;
assembly {
size := extcodesize(pair)
}
if (size == 0) return (0, 0, pair);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pair).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
| Unpack parameters sent from the `liquidate` function NOTE: these are being passed in from some other contract, and cannot necessarily be trusted Perform the liquidation Redeem cTokens for underlying ERC20 Compute debt and pay back pair Convert WETH to ETH Perform the liquidation Redeem cTokens for underlying ERC20 Compute debt and pay back pair Perform the liquidation Redeem cTokens for underlying ERC20 or ETH Convert ETH to WETH Compute debt and pay back pair (uint reserveOut, uint reserveIn) = UniswapV2Library.getReserves(FACTORY, source, WETH); | function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) override external {
(address borrower, address repayCToken, address seizeCToken) = abi.decode(data, (address, address, address));
address token0 = IUniswapV2Pair(msg.sender).token0();
address token1 = IUniswapV2Pair(msg.sender).token1();
require(msg.sender == IUniswapV2Factory(FACTORY).getPair(token0, token1));
if (repayCToken == seizeCToken) {
uint amount = amount0 != 0 ? amount0 : amount1;
address estuary = amount0 != 0 ? token0 : token1;
IERC20(estuary).safeApprove(repayCToken, amount);
ICErc20(repayCToken).liquidateBorrow(borrower, amount, seizeCToken);
ICErc20(seizeCToken).redeem(IERC20(seizeCToken).balanceOf(address(this)));
IERC20(estuary).transfer(msg.sender, (amount * 1000 / 997) + 1);
return;
}
if (repayCToken == CETH) {
uint amount = amount0 != 0 ? amount0 : amount1;
address estuary = amount0 != 0 ? token1 : token0;
IWETH(WETH).withdraw(amount);
ICErc20(seizeCToken).redeem(IERC20(seizeCToken).balanceOf(address(this)));
(uint reserve0, uint reserve1,) = IUniswapV2Pair(msg.sender).getReserves();
(uint reserveIn, uint reserveOut) = token0 == estuary ? (reserve0, reserve1) : (reserve1, reserve0);
IERC20(estuary).transfer(msg.sender, UniswapV2Library.getAmountIn(amount, reserveIn, reserveOut));
return;
}
if (seizeCToken == CETH) {
uint amount = amount0 != 0 ? amount0 : amount1;
address source = amount0 != 0 ? token0 : token1;
IERC20(source).safeApprove(repayCToken, amount);
ICErc20(repayCToken).liquidateBorrow(borrower, amount, seizeCToken);
ICErc20(seizeCToken).redeem(IERC20(seizeCToken).balanceOf(address(this)));
(uint reserve0, uint reserve1,) = IUniswapV2Pair(msg.sender).getReserves();
(uint reserveIn, uint reserveOut) = token0 == source ? (reserve1, reserve0) : (reserve0, reserve1);
IERC20(WETH).transfer(msg.sender, UniswapV2Library.getAmountIn(amount, reserveIn, reserveOut));
return;
}
uint amount;
address source;
if (amount0 != 0) {
amount = amount0;
source = token0;
amount = amount1;
source = token1;
}
ICErc20(repayCToken).liquidateBorrow(borrower, amount, seizeCToken);
ICErc20(seizeCToken).redeem(IERC20(seizeCToken).balanceOf(address(this)));
address seizeUToken = ICErc20Storage(seizeCToken).underlying();
(uint reserveIn, uint reserveOut) = token0 == source ? (reserve1, reserve0) : (reserve0, reserve1);
IERC20(seizeUToken).safeApprove(ROUTER, seized_uUnits);
path[0] = seizeUToken;
path[1] = WETH;
IUniswapV2Router02(ROUTER).swapTokensForExactTokens(debt, seized_uUnits, path, address(this), now + 1 minutes);
IERC20(seizeUToken).safeApprove(ROUTER, 0);
}
| 1,329,758 |
pragma solidity 0.4.25;
library Math {
function min(uint a, uint b) internal pure returns(uint) {
if (a > b) {
return b;
}
return a;
}
}
library Zero {
function requireNotZero(address addr) internal pure {
require(addr != address(0), "require not zero address");
}
function requireNotZero(uint val) internal pure {
require(val != 0, "require not zero value");
}
function notZero(address addr) internal pure returns(bool) {
return !(addr == address(0));
}
function isZero(address addr) internal pure returns(bool) {
return addr == address(0);
}
function isZero(uint a) internal pure returns(bool) {
return a == 0;
}
function notZero(uint a) internal pure returns(bool) {
return a != 0;
}
}
library Percent {
struct percent {
uint num;
uint den;
}
// storage
function mul(percent storage p, uint a) internal view returns (uint) {
if (a == 0) {
return 0;
}
return a*p.num/p.den;
}
function div(percent storage p, uint a) internal view returns (uint) {
return a/p.num*p.den;
}
function sub(percent storage p, uint a) internal view returns (uint) {
uint b = mul(p, a);
if (b >= a) {
return 0;
}
return a - b;
}
function add(percent storage p, uint a) internal view returns (uint) {
return a + mul(p, a);
}
function toMemory(percent storage p) internal view returns (Percent.percent memory) {
return Percent.percent(p.num, p.den);
}
// memory
function mmul(percent memory p, uint a) internal pure returns (uint) {
if (a == 0) {
return 0;
}
return a*p.num/p.den;
}
function mdiv(percent memory p, uint a) internal pure returns (uint) {
return a/p.num*p.den;
}
function msub(percent memory p, uint a) internal pure returns (uint) {
uint b = mmul(p, a);
if (b >= a) {
return 0;
}
return a - b;
}
function madd(percent memory p, uint a) internal pure returns (uint) {
return a + mmul(p, a);
}
}
library Address {
function toAddress(bytes source) internal pure returns(address addr) {
assembly { addr := mload(add(source,0x14)) }
return addr;
}
function isNotContract(address addr) internal view returns(bool) {
uint length;
assembly { length := extcodesize(addr) }
return length == 0;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
// 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;
}
}
contract Accessibility {
address private owner;
modifier onlyOwner() {
require(msg.sender == owner, "Access denied");
_;
}
constructor() public {
owner = msg.sender;
}
function disown() internal {
delete owner;
}
}
contract InvestorsStorage is Accessibility {
using SafeMath for uint;
struct Investor {
uint investment;
uint paymentTime;
uint maxPayout;
bool exit;
}
uint public size;
mapping (address => Investor) private investors;
function isInvestor(address addr) public view returns (bool) {
return investors[addr]. investment > 0;
}
function investorInfo(address addr) public view returns(uint investment, uint paymentTime,uint maxPayout,bool exit) {
investment = investors[addr].investment;
paymentTime = investors[addr].paymentTime;
maxPayout = investors[addr].maxPayout;
exit = investors[addr].exit;
}
function newInvestor(address addr, uint investment, uint paymentTime) public onlyOwner returns (bool) {
// initialize new investor to investment and maxPayout = 2x investment
Investor storage inv = investors[addr];
if (inv.investment != 0 || investment == 0) {
return false;
}
inv.exit = false;
inv.investment = investment;
inv.maxPayout = investment.mul(2);
inv.paymentTime = paymentTime;
size++;
return true;
}
function addInvestment(address addr, uint investment,uint dividends) public onlyOwner returns (bool) {
if (investors[addr].investment == 0) {
return false;
}
investors[addr].investment += investment;
// Update maximum payout exlude dividends
investors[addr].maxPayout += (investment-dividends).mul(2);
return true;
}
function setPaymentTime(address addr, uint paymentTime) public onlyOwner returns (bool) {
if(investors[addr].exit){
return true;
}
if (investors[addr].investment == 0) {
return false;
}
investors[addr].paymentTime = paymentTime;
return true;
}
function investorExit(address addr) public onlyOwner returns (bool){
investors[addr].exit = true;
investors[addr].maxPayout = 0;
investors[addr].investment = 0;
}
function payout(address addr, uint dividend) public onlyOwner returns (uint) {
uint dividendToPay = 0;
if(investors[addr].maxPayout <= dividend){
dividendToPay = investors[addr].maxPayout;
investorExit(addr);
} else{
dividendToPay = dividend;
investors[addr].maxPayout -= dividend;
}
return dividendToPay;
}
}
library RapidGrowthProtection {
using RapidGrowthProtection for rapidGrowthProtection;
struct rapidGrowthProtection {
uint startTimestamp;
uint maxDailyTotalInvestment;
uint8 activityDays;
mapping(uint8 => uint) dailyTotalInvestment;
}
function maxInvestmentAtNow(rapidGrowthProtection storage rgp) internal view returns(uint) {
uint day = rgp.currDay();
if (day == 0 || day > rgp.activityDays) {
return 0;
}
if (rgp.dailyTotalInvestment[uint8(day)] >= rgp.maxDailyTotalInvestment) {
return 0;
}
return rgp.maxDailyTotalInvestment - rgp.dailyTotalInvestment[uint8(day)];
}
function isActive(rapidGrowthProtection storage rgp) internal view returns(bool) {
uint day = rgp.currDay();
return day != 0 && day <= rgp.activityDays;
}
function saveInvestment(rapidGrowthProtection storage rgp, uint investment) internal returns(bool) {
uint day = rgp.currDay();
if (day == 0 || day > rgp.activityDays) {
return false;
}
if (rgp.dailyTotalInvestment[uint8(day)] + investment > rgp.maxDailyTotalInvestment) {
return false;
}
rgp.dailyTotalInvestment[uint8(day)] += investment;
return true;
}
function startAt(rapidGrowthProtection storage rgp, uint timestamp) internal {
rgp.startTimestamp = timestamp;
// restart
for (uint8 i = 1; i <= rgp.activityDays; i++) {
if (rgp.dailyTotalInvestment[i] != 0) {
delete rgp.dailyTotalInvestment[i];
}
}
}
function currDay(rapidGrowthProtection storage rgp) internal view returns(uint day) {
if (rgp.startTimestamp > now) {
return 0;
}
day = (now - rgp.startTimestamp) / 24 hours + 1; // +1 for skipping zero day
}
}
library BonusPool {
using BonusPool for bonusPool;
struct bonusLevel {
uint bonusAmount;
bool triggered;
uint triggeredTimestamp;
bool bonusSet;
}
struct bonusPool {
uint8 nextLevelToTrigger;
mapping(uint8 => bonusLevel) bonusLevels;
}
function setBonus(bonusPool storage self,uint8 level,uint amount) internal {
require(!self.bonusLevels[level].bonusSet,"Bonus already set");
self.bonusLevels[level].bonusAmount = amount;
self.bonusLevels[level].bonusSet = true;
self.bonusLevels[level].triggered = false;
}
function hasMetBonusTriggerLevel(bonusPool storage self) internal returns(bool){
bonusLevel storage nextBonusLevel = self.bonusLevels[self.nextLevelToTrigger];
if(address(this).balance >= nextBonusLevel.bonusAmount){
if(nextBonusLevel.triggered){
self.goToNextLevel();
return false;
}
return true;
}
return false;
}
function prizeToPool(bonusPool storage self) internal returns(uint){
return self.bonusLevels[self.nextLevelToTrigger].bonusAmount;
}
function goToNextLevel(bonusPool storage self) internal {
self.bonusLevels[self.nextLevelToTrigger].triggered = true;
self.nextLevelToTrigger += 1;
}
}
contract Myethsss is Accessibility {
using RapidGrowthProtection for RapidGrowthProtection.rapidGrowthProtection;
using BonusPool for BonusPool.bonusPool;
using Percent for Percent.percent;
using SafeMath for uint;
using Math for uint;
// easy read for investors
using Address for *;
using Zero for *;
RapidGrowthProtection.rapidGrowthProtection private m_rgp;
BonusPool.bonusPool private m_bonusPool;
mapping(address => bool) private m_referrals;
InvestorsStorage private m_investors;
uint totalRealBalance;
// automatically generates getters
uint public constant minInvesment = 0.1 ether; // 0.1 eth
uint public constant maxBalance = 366e5 ether; // 36 600 000 eth
address public advertisingAddress;
address public adminsAddress;
address public riskAddress;
address public bonusAddress;
uint public investmentsNumber;
uint public waveStartup;
// percents
Percent.percent private m_1_percent = Percent.percent(1, 100); // 1/100 *100% = 1%
Percent.percent private m_1_66_percent = Percent.percent(166, 10000); // 166/10000*100% = 1.66%
Percent.percent private m_2_66_percent = Percent.percent(266, 10000); // 266/10000*100% = 2.66%
Percent.percent private m_6_66_percent = Percent.percent(666, 10000); // 666/10000*100% = 6.66% refer bonus
Percent.percent private m_adminsPercent = Percent.percent(5, 100); // 5/100 *100% = 5%
Percent.percent private m_advertisingPercent = Percent.percent(5, 100); // 5/1000 *100% = 5%
Percent.percent private m_riskPercent = Percent.percent(5, 100); // 5/1000 *100% = 5%
Percent.percent private m_bonusPercent = Percent.percent(666, 10000); // 666/10000 *100% = 6.66%
modifier balanceChanged {
_;
}
modifier notFromContract() {
require(msg.sender.isNotContract(), "only externally accounts");
_;
}
constructor() public {
adminsAddress = msg.sender;
advertisingAddress = msg.sender;
riskAddress=msg.sender;
bonusAddress = msg.sender;
nextWave();
}
function() public payable {
if (msg.value.isZero()) {
getMyDividends();
return;
}
doInvest(msg.data.toAddress());
}
function doDisown() public onlyOwner {
disown();
}
// uint timestamp
function init() public onlyOwner {
m_rgp.startTimestamp = now + 1;
m_rgp.maxDailyTotalInvestment = 5000 ether;
m_rgp.activityDays = 21;
// Set bonus pool tier
m_bonusPool.setBonus(0,3000 ether);
m_bonusPool.setBonus(1,6000 ether);
m_bonusPool.setBonus(2,10000 ether);
m_bonusPool.setBonus(3,15000 ether);
m_bonusPool.setBonus(4,20000 ether);
m_bonusPool.setBonus(5,25000 ether);
m_bonusPool.setBonus(6,30000 ether);
m_bonusPool.setBonus(7,35000 ether);
m_bonusPool.setBonus(8,40000 ether);
m_bonusPool.setBonus(9,45000 ether);
m_bonusPool.setBonus(10,50000 ether);
m_bonusPool.setBonus(11,60000 ether);
m_bonusPool.setBonus(12,70000 ether);
m_bonusPool.setBonus(13,80000 ether);
m_bonusPool.setBonus(14,90000 ether);
m_bonusPool.setBonus(15,100000 ether);
m_bonusPool.setBonus(16,150000 ether);
m_bonusPool.setBonus(17,200000 ether);
m_bonusPool.setBonus(18,500000 ether);
m_bonusPool.setBonus(19,1000000 ether);
}
function getBonusAmount(uint8 level) public view returns(uint){
return m_bonusPool.bonusLevels[level].bonusAmount;
}
function doBonusPooling() public onlyOwner {
require(m_bonusPool.hasMetBonusTriggerLevel(),"Has not met next bonus requirement");
bonusAddress.transfer(m_bonusPercent.mul(m_bonusPool.prizeToPool()));
m_bonusPool.goToNextLevel();
}
function setAdvertisingAddress(address addr) public onlyOwner {
addr.requireNotZero();
advertisingAddress = addr;
}
function setAdminsAddress(address addr) public onlyOwner {
addr.requireNotZero();
adminsAddress = addr;
}
function setRiskAddress(address addr) public onlyOwner{
addr.requireNotZero();
riskAddress=addr;
}
function setBonusAddress(address addr) public onlyOwner {
addr.requireNotZero();
bonusAddress = addr;
}
function rapidGrowthProtectionmMaxInvestmentAtNow() public view returns(uint investment) {
investment = m_rgp.maxInvestmentAtNow();
}
function investorsNumber() public view returns(uint) {
return m_investors.size();
}
function balanceETH() public view returns(uint) {
return address(this).balance;
}
function percent1() public view returns(uint numerator, uint denominator) {
(numerator, denominator) = (m_1_percent.num, m_1_percent.den);
}
function percent2() public view returns(uint numerator, uint denominator) {
(numerator, denominator) = (m_1_66_percent.num, m_1_66_percent.den);
}
function percent3_33() public view returns(uint numerator, uint denominator) {
(numerator, denominator) = (m_2_66_percent.num, m_2_66_percent.den);
}
function advertisingPercent() public view returns(uint numerator, uint denominator) {
(numerator, denominator) = (m_advertisingPercent.num, m_advertisingPercent.den);
}
function adminsPercent() public view returns(uint numerator, uint denominator) {
(numerator, denominator) = (m_adminsPercent.num, m_adminsPercent.den);
}
function riskPercent() public view returns(uint numerator, uint denominator) {
(numerator, denominator) = (m_riskPercent.num, m_riskPercent.den);
}
function investorInfo(address investorAddr) public view returns(uint investment, uint paymentTime,uint maxPayout,bool exit, bool isReferral) {
(investment, paymentTime,maxPayout,exit) = m_investors.investorInfo(investorAddr);
isReferral = m_referrals[investorAddr];
}
function investorDividendsAtNow(address investorAddr) public view returns(uint dividends) {
dividends = calcDividends(investorAddr);
}
function dailyPercentAtNow() public view returns(uint numerator, uint denominator) {
Percent.percent memory p = dailyPercent();
(numerator, denominator) = (p.num, p.den);
}
function refBonusPercentAtNow() public view returns(uint numerator, uint denominator) {
Percent.percent memory p = refBonusPercent();
(numerator, denominator) = (p.num, p.den);
}
function getMyDividends() public notFromContract balanceChanged {
// calculate dividends
uint dividends = calcDividends(msg.sender);
require (dividends.notZero(), "cannot pay zero dividends");
// deduct payout from max
dividends = m_investors.payout(msg.sender,dividends);
// update investor payment timestamp
assert(m_investors.setPaymentTime(msg.sender, now));
// check enough eth - goto next wave if needed
if (address(this).balance <= dividends) {
// nextWave();
dividends = address(this).balance;
}
// transfer dividends to investor
msg.sender.transfer(dividends);
}
function doInvest(address referrerAddr) public payable notFromContract balanceChanged {
uint investment = msg.value;
uint receivedEther = msg.value;
require(investment >= minInvesment, "investment must be >= minInvesment");
require(address(this).balance <= maxBalance, "the contract eth balance limit");
if (m_rgp.isActive()) {
// use Rapid Growth Protection if needed
uint rpgMaxInvest = m_rgp.maxInvestmentAtNow();
rpgMaxInvest.requireNotZero();
investment = Math.min(investment, rpgMaxInvest);
assert(m_rgp.saveInvestment(investment));
}
// send excess of ether if needed
if (receivedEther > investment) {
uint excess = receivedEther - investment;
msg.sender.transfer(excess);
receivedEther = investment;
}
// commission
advertisingAddress.transfer(m_advertisingPercent.mul(receivedEther));
adminsAddress.transfer(m_adminsPercent.mul(receivedEther));
riskAddress.transfer(m_riskPercent.mul(receivedEther));
bool senderIsInvestor = m_investors.isInvestor(msg.sender);
// ref system works only once and only on first invest
if (referrerAddr.notZero() && !senderIsInvestor && !m_referrals[msg.sender] &&
referrerAddr != msg.sender && m_investors.isInvestor(referrerAddr)) {
m_referrals[msg.sender] = true;
// add referral bonus to referee's investments and pay investor's refer bonus
uint refBonus = refBonusPercent().mmul(investment);
// Investment increase 2.66%
uint refBonuss = refBonusPercentt().mmul(investment);
// ADD referee bonus to referee investment and maxinvestment
investment += refBonuss;
// PAY referer refer bonus directly
referrerAddr.transfer(refBonus);
// emit LogNewReferral(msg.sender, referrerAddr, now, refBonus);
}
// automatic reinvest - prevent burning dividends
uint dividends = calcDividends(msg.sender);
if (senderIsInvestor && dividends.notZero()) {
investment += dividends;
}
if (senderIsInvestor) {
// update existing investor
assert(m_investors.addInvestment(msg.sender, investment, dividends));
assert(m_investors.setPaymentTime(msg.sender, now));
} else {
// create new investor
assert(m_investors.newInvestor(msg.sender, investment, now));
}
investmentsNumber++;
}
function getMemInvestor(address investorAddr) internal view returns(InvestorsStorage.Investor memory) {
(uint investment, uint paymentTime,uint maxPayout,bool exit) = m_investors.investorInfo(investorAddr);
return InvestorsStorage.Investor(investment, paymentTime,maxPayout,exit);
}
function calcDividends(address investorAddr) internal view returns(uint dividends) {
InvestorsStorage.Investor memory investor = getMemInvestor(investorAddr);
// safe gas if dividends will be 0,
if (investor.investment.isZero()
// || now.sub(investor.paymentTime) < 1 minutes
) {
return 0;
}
// for prevent burning daily dividends if 24h did not pass - calculate it per 10 min interval
// if daily percent is X, then 10min percent = X / (24h / 10 min) = X / 144
// and we must to get numbers of 10 min interval after investor got payment:
// (now - investor.paymentTime) / 10min
// finaly calculate dividends = ((now - investor.paymentTime) / 10min) * (X * investor.investment) / 144)
Percent.percent memory p = dailyPercent();
// dividends = ((now - investor.paymentTime) / 10 minutes) * (p.mmul(investor.investment) / 144);
dividends = ((now - investor.paymentTime) / 10 minutes) * (p.mmul(investor.investment) / 144);
// dividends = p.mmul(investor.investment);
}
function dailyPercent() internal view returns(Percent.percent memory p) {
uint balance = address(this).balance;
// (2) 1.66% if balance < 50 000 ETH
// (1) 1% if >50 000 ETH
if (balance < 50000 ether) {
p = m_1_66_percent.toMemory(); // (2)
} else {
p = m_1_percent.toMemory(); // (1)
}
}
function refBonusPercent() internal view returns(Percent.percent memory p) {
//fix refer bonus payment to 6.66%
p = m_6_66_percent.toMemory();
}
function refBonusPercentt() internal view returns(Percent.percent memory p) {
//fix refer bonus to 2.66%
p = m_2_66_percent.toMemory();
}
function nextWave() private {
m_investors = new InvestorsStorage();
investmentsNumber = 0;
waveStartup = now;
m_rgp.startAt(now);
}
} | 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;
}
| 15,854,893 |
// SPDX-License-Identifier: MIT
// Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier)
pragma solidity >=0.8.0 <0.9.0;
import "../../contracts/crypto/SignatureChecker.sol";
import "../../contracts/crypto/SignerManager.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
/**
@notice Exposes functions allowing testing of SignatureChecker.
*/
contract TestableSignatureChecker is SignerManager {
using EnumerableSet for EnumerableSet.AddressSet;
// SignatureChecker adds additional functionality to an AddressSet, allowing
// for a signature from any set member.
using SignatureChecker for EnumerableSet.AddressSet;
mapping(bytes32 => bool) private usedMessages;
/// @dev Reverts if the signature is invalid or the nonce is already used.
function needsSignature(
bytes memory data,
bytes32 nonce,
bytes calldata signature
) external {
signers.requireValidSignature(
abi.encodePacked(data, nonce),
signature,
usedMessages
);
}
/// @dev Reverts if the signature is invalid.
function needsReusableSignature(bytes memory data, bytes calldata signature)
external
view
returns (bool)
{
signers.requireValidSignature(data, signature);
return true;
}
/// @dev Reverts if the signature is not valid for msg.sender.
function needsSenderSignature(bytes calldata signature)
external
view
returns (bool)
{
signers.requireValidSignature(msg.sender, signature);
return true;
}
}
| Reverts if the signature is invalid or the nonce is already used. | @notice Exposes functions allowing testing of SignatureChecker.
) external {
signers.requireValidSignature(
abi.encodePacked(data, nonce),
signature,
usedMessages
);
}
| 15,841,998 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
/**
* @title DEX Template
* @author stevepham.eth and m00npapi.eth
* @notice Empty DEX.sol that just outlines what features could be part of the challenge (up to you!)
* @dev We want to create an automatic market where our contract will hold reserves of both ETH and 🎈 Balloons. These reserves will provide liquidity that allows anyone to swap between the assets.
* NOTE: functions outlined here are what work with the front end of this branch/repo. Also return variable names that may need to be specified exactly may be referenced (if you are confused, see solutions folder in this repo and/or cross reference with front-end code).
*/
contract DEX {
/* ========== GLOBAL VARIABLES ========== */
using SafeMath for uint256; //outlines use of SafeMath for uint256 variables
IERC20 token; //instantiates the imported contract
/* ========== EVENTS ========== */
/**
* @notice Emitted when ethToToken() swap transacted
*/
event EthToTokenSwap();
/**
* @notice Emitted when tokenToEth() swap transacted
*/
event TokenToEthSwap();
/**
* @notice Emitted when liquidity provided to DEX and mints LPTs.
*/
event LiquidityProvided();
/**
* @notice Emitted when liquidity removed from DEX and decreases LPT count within DEX.
*/
event LiquidityRemoved();
/* ========== CONSTRUCTOR ========== */
constructor(address token_addr) public {
token = IERC20(token_addr); //specifies the token address that will hook into the interface and be used through the variable 'token'
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice initializes amount of tokens that will be transferred to the DEX itself from the erc20 contract mintee (and only them based on how Balloons.sol is written). Loads contract up with both ETH and Balloons.
* @param tokens amount to be transferred to DEX
* @return totalLiquidity is the number of LPTs minting as a result of deposits made to DEX contract
* NOTE: since ratio is 1:1, this is fine to initialize the totalLiquidity (wrt to balloons) as equal to eth balance of contract.
*/
function init(uint256 tokens) public payable returns (uint256) {}
/**
* @notice returns yOutput, or yDelta for xInput (or xDelta)
* @dev Follow along with the [original tutorial](https://medium.com/@austin_48503/%EF%B8%8F-minimum-viable-exchange-d84f30bd0c90) Price section for an understanding of the DEX's pricing model and for a price function to add to your contract. You may need to update the Solidity syntax (e.g. use + instead of .add, * instead of .mul, etc). Deploy when you are done.
*/
function price(
uint256 xInput,
uint256 xReserves,
uint256 yReserves
) public view returns (uint256 yOutput) {}
/**
* @notice returns liquidity for a user. Note this is not needed typically due to the `liquidity()` mapping variable being public and having a getter as a result. This is left though as it is used within the front end code (App.jsx).
*/
function getLiquidity(address lp) public view returns (uint256) {
return liquidity[lp];
}
/**
* @notice sends Ether to DEX in exchange for $BAL
*/
function ethToToken() public payable returns (uint256 tokenOutput) {}
/**
* @notice sends $BAL tokens to DEX in exchange for Ether
*/
function tokenToEth(uint256 tokenInput) public returns (uint256 ethOutput) {}
/**
* @notice allows deposits of $BAL and $ETH to liquidity pool
* NOTE: parameter is the msg.value sent with this function call. That amount is used to determine the amount of $BAL needed as well and taken from the depositor.
* NOTE: user has to make sure to give DEX approval to spend their tokens on their behalf by calling approve function prior to this function call.
* NOTE: Equal parts of both assets will be removed from the user's wallet with respect to the price outlined by the AMM.
*/
function deposit() public payable returns (uint256 tokensDeposited) {}
/**
* @notice allows withdrawal of $BAL and $ETH from liquidity pool
* NOTE: with this current code, the msg caller could end up getting very little back if the liquidity is super low in the pool. I guess they could see that with the UI.
*/
function withdraw(uint256 amount) public returns (uint256 eth_amount, uint256 token_amount) {}
}
| allows deposits of $BAL and $ETH to liquidity pool NOTE: parameter is the msg.value sent with this function call. That amount is used to determine the amount of $BAL needed as well and taken from the depositor. NOTE: user has to make sure to give DEX approval to spend their tokens on their behalf by calling approve function prior to this function call. NOTE: Equal parts of both assets will be removed from the user's wallet with respect to the price outlined by the AMM./ | function deposit() public payable returns (uint256 tokensDeposited) {}
| 12,753,060 |
./partial_match/1/0xE19b31c00c01Ab38ea279E93aC66CA773D314c91/sources/src/interfaces/pool/erc721/IERC721PoolBorrowerActions.sol | ERC721 Pool Borrower Actions/ | interface IERC721PoolBorrowerActions {
function drawDebt(
address borrower_,
uint256 amountToBorrow_,
uint256 limitIndex_,
uint256[] calldata tokenIdsToPledge_
) external;
function repayDebt(
address borrowerAddress_,
uint256 maxQuoteTokenAmountToRepay_,
uint256 noOfNFTsToPull_,
address recipient_,
uint256 limitIndex_
) external;
}
| 3,951,590 |
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.4.14;
import {ERC20 as Token} from "zeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import "./TokenTransferProxy.sol";
import "./base/SafeMath.sol";
/// @title Exchange - Facilitates exchange of ERC20 tokens.
/// @author Amir Bandeali - <[email protected]>, Will Warren - <[email protected]>
contract Exchange is SafeMath {
// Error Codes
enum Errors {
ORDER_EXPIRED, // Order has already expired
ORDER_FULLY_FILLED_OR_CANCELLED, // Order has already been fully filled or cancelled
ROUNDING_ERROR_TOO_LARGE, // Rounding error too large
INSUFFICIENT_BALANCE_OR_ALLOWANCE // Insufficient balance or allowance for token transfer
}
string constant public VERSION = "1.0.0";
uint16 constant public EXTERNAL_QUERY_GAS_LIMIT = 4999; // Changes to state require at least 5000 gas
address public ZRX_TOKEN_CONTRACT;
address public TOKEN_TRANSFER_PROXY_CONTRACT;
// Mappings of orderHash => amounts of takerTokenAmount filled or cancelled.
mapping (bytes32 => uint) public filled;
mapping (bytes32 => uint) public cancelled;
event LogFill(
address indexed maker,
address taker,
address indexed feeRecipient,
address makerToken,
address takerToken,
uint filledMakerTokenAmount,
uint filledTakerTokenAmount,
uint paidMakerFee,
uint paidTakerFee,
bytes32 indexed tokens, // keccak256(makerToken, takerToken), allows subscribing to a token pair
bytes32 orderHash
);
event LogCancel(
address indexed maker,
address indexed feeRecipient,
address makerToken,
address takerToken,
uint cancelledMakerTokenAmount,
uint cancelledTakerTokenAmount,
bytes32 indexed tokens,
bytes32 orderHash
);
event LogError(uint8 indexed errorId, bytes32 indexed orderHash);
struct Order {
address maker;
address taker;
address makerToken;
address takerToken;
address feeRecipient;
uint makerTokenAmount;
uint takerTokenAmount;
uint makerFee;
uint takerFee;
uint expirationTimestampInSec;
bytes32 orderHash;
}
function Exchange(address _zrxToken, address _tokenTransferProxy) {
ZRX_TOKEN_CONTRACT = _zrxToken;
TOKEN_TRANSFER_PROXY_CONTRACT = _tokenTransferProxy;
}
/*
* Core exchange functions
*/
/// @dev Fills the input order.
/// @param orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient.
/// @param orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt.
/// @param fillTakerTokenAmount Desired amount of takerToken to fill.
/// @param shouldThrowOnInsufficientBalanceOrAllowance Test if transfer will fail before attempting.
/// @param v ECDSA signature parameter v.
/// @param r ECDSA signature parameters r.
/// @param s ECDSA signature parameters s.
/// @return Total amount of takerToken filled in trade.
function fillOrder(
address[5] orderAddresses,
uint[6] orderValues,
uint fillTakerTokenAmount,
bool shouldThrowOnInsufficientBalanceOrAllowance,
uint8 v,
bytes32 r,
bytes32 s)
public
returns (uint filledTakerTokenAmount)
{
Order memory order = Order({
maker: orderAddresses[0],
taker: orderAddresses[1],
makerToken: orderAddresses[2],
takerToken: orderAddresses[3],
feeRecipient: orderAddresses[4],
makerTokenAmount: orderValues[0],
takerTokenAmount: orderValues[1],
makerFee: orderValues[2],
takerFee: orderValues[3],
expirationTimestampInSec: orderValues[4],
orderHash: getOrderHash(orderAddresses, orderValues)
});
require(order.taker == address(0) || order.taker == msg.sender);
require(order.makerTokenAmount > 0 && order.takerTokenAmount > 0 && fillTakerTokenAmount > 0);
require(isValidSignature(
order.maker,
order.orderHash,
v,
r,
s
));
if (block.timestamp >= order.expirationTimestampInSec) {
LogError(uint8(Errors.ORDER_EXPIRED), order.orderHash);
return 0;
}
uint remainingTakerTokenAmount = safeSub(order.takerTokenAmount, getUnavailableTakerTokenAmount(order.orderHash));
filledTakerTokenAmount = min256(fillTakerTokenAmount, remainingTakerTokenAmount);
if (filledTakerTokenAmount == 0) {
LogError(uint8(Errors.ORDER_FULLY_FILLED_OR_CANCELLED), order.orderHash);
return 0;
}
if (isRoundingError(filledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount)) {
LogError(uint8(Errors.ROUNDING_ERROR_TOO_LARGE), order.orderHash);
return 0;
}
if (!shouldThrowOnInsufficientBalanceOrAllowance && !isTransferable(order, filledTakerTokenAmount)) {
LogError(uint8(Errors.INSUFFICIENT_BALANCE_OR_ALLOWANCE), order.orderHash);
return 0;
}
uint filledMakerTokenAmount = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount);
uint paidMakerFee;
uint paidTakerFee;
filled[order.orderHash] = safeAdd(filled[order.orderHash], filledTakerTokenAmount);
require(transferViaTokenTransferProxy(
order.makerToken,
order.maker,
msg.sender,
filledMakerTokenAmount
));
require(transferViaTokenTransferProxy(
order.takerToken,
msg.sender,
order.maker,
filledTakerTokenAmount
));
if (order.feeRecipient != address(0)) {
if (order.makerFee > 0) {
paidMakerFee = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.makerFee);
require(transferViaTokenTransferProxy(
ZRX_TOKEN_CONTRACT,
order.maker,
order.feeRecipient,
paidMakerFee
));
}
if (order.takerFee > 0) {
paidTakerFee = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.takerFee);
require(transferViaTokenTransferProxy(
ZRX_TOKEN_CONTRACT,
msg.sender,
order.feeRecipient,
paidTakerFee
));
}
}
LogFill(
order.maker,
msg.sender,
order.feeRecipient,
order.makerToken,
order.takerToken,
filledMakerTokenAmount,
filledTakerTokenAmount,
paidMakerFee,
paidTakerFee,
keccak256(order.makerToken, order.takerToken),
order.orderHash
);
return filledTakerTokenAmount;
}
/// @dev Cancels the input order.
/// @param orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient.
/// @param orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt.
/// @param cancelTakerTokenAmount Desired amount of takerToken to cancel in order.
/// @return Amount of takerToken cancelled.
function cancelOrder(
address[5] orderAddresses,
uint[6] orderValues,
uint cancelTakerTokenAmount)
public
returns (uint)
{
Order memory order = Order({
maker: orderAddresses[0],
taker: orderAddresses[1],
makerToken: orderAddresses[2],
takerToken: orderAddresses[3],
feeRecipient: orderAddresses[4],
makerTokenAmount: orderValues[0],
takerTokenAmount: orderValues[1],
makerFee: orderValues[2],
takerFee: orderValues[3],
expirationTimestampInSec: orderValues[4],
orderHash: getOrderHash(orderAddresses, orderValues)
});
require(order.maker == msg.sender);
require(order.makerTokenAmount > 0 && order.takerTokenAmount > 0 && cancelTakerTokenAmount > 0);
if (block.timestamp >= order.expirationTimestampInSec) {
LogError(uint8(Errors.ORDER_EXPIRED), order.orderHash);
return 0;
}
uint remainingTakerTokenAmount = safeSub(order.takerTokenAmount, getUnavailableTakerTokenAmount(order.orderHash));
uint cancelledTakerTokenAmount = min256(cancelTakerTokenAmount, remainingTakerTokenAmount);
if (cancelledTakerTokenAmount == 0) {
LogError(uint8(Errors.ORDER_FULLY_FILLED_OR_CANCELLED), order.orderHash);
return 0;
}
cancelled[order.orderHash] = safeAdd(cancelled[order.orderHash], cancelledTakerTokenAmount);
LogCancel(
order.maker,
order.feeRecipient,
order.makerToken,
order.takerToken,
getPartialAmount(cancelledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount),
cancelledTakerTokenAmount,
keccak256(order.makerToken, order.takerToken),
order.orderHash
);
return cancelledTakerTokenAmount;
}
/*
* Wrapper functions
*/
/// @dev Fills an order with specified parameters and ECDSA signature, throws if specified amount not filled entirely.
/// @param orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient.
/// @param orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt.
/// @param fillTakerTokenAmount Desired amount of takerToken to fill.
/// @param v ECDSA signature parameter v.
/// @param r ECDSA signature parameters r.
/// @param s ECDSA signature parameters s.
function fillOrKillOrder(
address[5] orderAddresses,
uint[6] orderValues,
uint fillTakerTokenAmount,
uint8 v,
bytes32 r,
bytes32 s)
public
{
require(fillOrder(
orderAddresses,
orderValues,
fillTakerTokenAmount,
false,
v,
r,
s
) == fillTakerTokenAmount);
}
/// @dev Synchronously executes multiple fill orders in a single transaction.
/// @param orderAddresses Array of address arrays containing individual order addresses.
/// @param orderValues Array of uint arrays containing individual order values.
/// @param fillTakerTokenAmounts Array of desired amounts of takerToken to fill in orders.
/// @param shouldThrowOnInsufficientBalanceOrAllowance Test if transfers will fail before attempting.
/// @param v Array ECDSA signature v parameters.
/// @param r Array of ECDSA signature r parameters.
/// @param s Array of ECDSA signature s parameters.
function batchFillOrders(
address[5][] orderAddresses,
uint[6][] orderValues,
uint[] fillTakerTokenAmounts,
bool shouldThrowOnInsufficientBalanceOrAllowance,
uint8[] v,
bytes32[] r,
bytes32[] s)
public
{
for (uint i = 0; i < orderAddresses.length; i++) {
fillOrder(
orderAddresses[i],
orderValues[i],
fillTakerTokenAmounts[i],
shouldThrowOnInsufficientBalanceOrAllowance,
v[i],
r[i],
s[i]
);
}
}
/// @dev Synchronously executes multiple fillOrKill orders in a single transaction.
/// @param orderAddresses Array of address arrays containing individual order addresses.
/// @param orderValues Array of uint arrays containing individual order values.
/// @param fillTakerTokenAmounts Array of desired amounts of takerToken to fill in orders.
/// @param v Array ECDSA signature v parameters.
/// @param r Array of ECDSA signature r parameters.
/// @param s Array of ECDSA signature s parameters.
function batchFillOrKillOrders(
address[5][] orderAddresses,
uint[6][] orderValues,
uint[] fillTakerTokenAmounts,
uint8[] v,
bytes32[] r,
bytes32[] s)
public
{
for (uint i = 0; i < orderAddresses.length; i++) {
fillOrKillOrder(
orderAddresses[i],
orderValues[i],
fillTakerTokenAmounts[i],
v[i],
r[i],
s[i]
);
}
}
/// @dev Synchronously executes multiple fill orders in a single transaction until total fillTakerTokenAmount filled.
/// @param orderAddresses Array of address arrays containing individual order addresses.
/// @param orderValues Array of uint arrays containing individual order values.
/// @param fillTakerTokenAmount Desired total amount of takerToken to fill in orders.
/// @param shouldThrowOnInsufficientBalanceOrAllowance Test if transfers will fail before attempting.
/// @param v Array ECDSA signature v parameters.
/// @param r Array of ECDSA signature r parameters.
/// @param s Array of ECDSA signature s parameters.
/// @return Total amount of fillTakerTokenAmount filled in orders.
function fillOrdersUpTo(
address[5][] orderAddresses,
uint[6][] orderValues,
uint fillTakerTokenAmount,
bool shouldThrowOnInsufficientBalanceOrAllowance,
uint8[] v,
bytes32[] r,
bytes32[] s)
public
returns (uint)
{
uint filledTakerTokenAmount = 0;
for (uint i = 0; i < orderAddresses.length; i++) {
require(orderAddresses[i][3] == orderAddresses[0][3]); // takerToken must be the same for each order
filledTakerTokenAmount = safeAdd(filledTakerTokenAmount, fillOrder(
orderAddresses[i],
orderValues[i],
safeSub(fillTakerTokenAmount, filledTakerTokenAmount),
shouldThrowOnInsufficientBalanceOrAllowance,
v[i],
r[i],
s[i]
));
if (filledTakerTokenAmount == fillTakerTokenAmount) break;
}
return filledTakerTokenAmount;
}
/// @dev Synchronously cancels multiple orders in a single transaction.
/// @param orderAddresses Array of address arrays containing individual order addresses.
/// @param orderValues Array of uint arrays containing individual order values.
/// @param cancelTakerTokenAmounts Array of desired amounts of takerToken to cancel in orders.
function batchCancelOrders(
address[5][] orderAddresses,
uint[6][] orderValues,
uint[] cancelTakerTokenAmounts)
public
{
for (uint i = 0; i < orderAddresses.length; i++) {
cancelOrder(
orderAddresses[i],
orderValues[i],
cancelTakerTokenAmounts[i]
);
}
}
/*
* Constant public functions
*/
/// @dev Calculates Keccak-256 hash of order with specified parameters.
/// @param orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient.
/// @param orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt.
/// @return Keccak-256 hash of order.
function getOrderHash(address[5] orderAddresses, uint[6] orderValues)
public
constant
returns (bytes32)
{
return keccak256(
address(this),
orderAddresses[0], // maker
orderAddresses[1], // taker
orderAddresses[2], // makerToken
orderAddresses[3], // takerToken
orderAddresses[4], // feeRecipient
orderValues[0], // makerTokenAmount
orderValues[1], // takerTokenAmount
orderValues[2], // makerFee
orderValues[3], // takerFee
orderValues[4], // expirationTimestampInSec
orderValues[5] // salt
);
}
/// @dev Verifies that an order signature is valid.
/// @param signer address of signer.
/// @param hash Signed Keccak-256 hash.
/// @param v ECDSA signature parameter v.
/// @param r ECDSA signature parameters r.
/// @param s ECDSA signature parameters s.
/// @return Validity of order signature.
function isValidSignature(
address signer,
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s)
public
constant
returns (bool)
{
bytes32 signedData = keccak256("\x19Ethereum Signed Message:\n32", hash);
return edverify(signer, abi.encodePacked(signedData), abi.encodePacked(v, r, s));
}
/// @dev Checks if rounding error > 0.1%.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to multiply with numerator/denominator.
/// @return Rounding error is present.
function isRoundingError(uint numerator, uint denominator, uint target)
public
constant
returns (bool)
{
uint remainder = mulmod(target, numerator, denominator);
if (remainder == 0) return false; // No rounding error.
uint errPercentageTimes1000000 = safeDiv(
safeMul(remainder, 1000000),
safeMul(numerator, target)
);
return errPercentageTimes1000000 > 1000;
}
/// @dev Calculates partial value given a numerator and denominator.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target.
function getPartialAmount(uint numerator, uint denominator, uint target)
public
constant
returns (uint)
{
return safeDiv(safeMul(numerator, target), denominator);
}
/// @dev Calculates the sum of values already filled and cancelled for a given order.
/// @param orderHash The Keccak-256 hash of the given order.
/// @return Sum of values already filled and cancelled.
function getUnavailableTakerTokenAmount(bytes32 orderHash)
public
constant
returns (uint)
{
return safeAdd(filled[orderHash], cancelled[orderHash]);
}
/*
* Internal functions
*/
/// @dev Transfers a token using TokenTransferProxy transferFrom function.
/// @param token Address of token to transferFrom.
/// @param from Address transfering token.
/// @param to Address receiving token.
/// @param value Amount of token to transfer.
/// @return Success of token transfer.
function transferViaTokenTransferProxy(
address token,
address from,
address to,
uint value)
internal
returns (bool)
{
return TokenTransferProxy(TOKEN_TRANSFER_PROXY_CONTRACT).transferFrom(token, from, to, value);
}
/// @dev Checks if any order transfers will fail.
/// @param order Order struct of params that will be checked.
/// @param fillTakerTokenAmount Desired amount of takerToken to fill.
/// @return Predicted result of transfers.
function isTransferable(Order order, uint fillTakerTokenAmount)
internal
constant // The called token contracts may attempt to change state, but will not be able to due to gas limits on getBalance and getAllowance.
returns (bool)
{
address taker = msg.sender;
uint fillMakerTokenAmount = getPartialAmount(fillTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount);
if (order.feeRecipient != address(0)) {
bool isMakerTokenZRX = order.makerToken == ZRX_TOKEN_CONTRACT;
bool isTakerTokenZRX = order.takerToken == ZRX_TOKEN_CONTRACT;
uint paidMakerFee = getPartialAmount(fillTakerTokenAmount, order.takerTokenAmount, order.makerFee);
uint paidTakerFee = getPartialAmount(fillTakerTokenAmount, order.takerTokenAmount, order.takerFee);
uint requiredMakerZRX = isMakerTokenZRX ? safeAdd(fillMakerTokenAmount, paidMakerFee) : paidMakerFee;
uint requiredTakerZRX = isTakerTokenZRX ? safeAdd(fillTakerTokenAmount, paidTakerFee) : paidTakerFee;
if ( getBalance(ZRX_TOKEN_CONTRACT, order.maker) < requiredMakerZRX
|| getAllowance(ZRX_TOKEN_CONTRACT, order.maker) < requiredMakerZRX
|| getBalance(ZRX_TOKEN_CONTRACT, taker) < requiredTakerZRX
|| getAllowance(ZRX_TOKEN_CONTRACT, taker) < requiredTakerZRX
) return false;
if (!isMakerTokenZRX && ( getBalance(order.makerToken, order.maker) < fillMakerTokenAmount // Don't double check makerToken if ZRX
|| getAllowance(order.makerToken, order.maker) < fillMakerTokenAmount)
) return false;
if (!isTakerTokenZRX && ( getBalance(order.takerToken, taker) < fillTakerTokenAmount // Don't double check takerToken if ZRX
|| getAllowance(order.takerToken, taker) < fillTakerTokenAmount)
) return false;
} else if ( getBalance(order.makerToken, order.maker) < fillMakerTokenAmount
|| getAllowance(order.makerToken, order.maker) < fillMakerTokenAmount
|| getBalance(order.takerToken, taker) < fillTakerTokenAmount
|| getAllowance(order.takerToken, taker) < fillTakerTokenAmount
) return false;
return true;
}
/// @dev Get token balance of an address.
/// @param token Address of token.
/// @param owner Address of owner.
/// @return Token balance of owner.
function getBalance(address token, address owner)
internal
constant // The called token contract may attempt to change state, but will not be able to due to an added gas limit.
returns (uint)
{
return Token(token).balanceOf.gas(EXTERNAL_QUERY_GAS_LIMIT)(owner); // Limit gas to prevent reentrancy
}
/// @dev Get allowance of token given to TokenTransferProxy by an address.
/// @param token Address of token.
/// @param owner Address of owner.
/// @return Allowance of token given to TokenTransferProxy by owner.
function getAllowance(address token, address owner)
internal
constant // The called token contract may attempt to change state, but will not be able to due to an added gas limit.
returns (uint)
{
return Token(token).allowance.gas(EXTERNAL_QUERY_GAS_LIMIT)(owner, TOKEN_TRANSFER_PROXY_CONTRACT); // Limit gas to prevent reentrancy
}
}
| Verifies that an order signature is valid. signer address of signer. hash Signed Keccak-256 hash. v ECDSA signature parameter v. r ECDSA signature parameters r. s ECDSA signature parameters s. return Validity of order signature. | function isValidSignature(
address signer,
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s)
public
constant
returns (bool)
{
bytes32 signedData = keccak256("\x19Ethereum Signed Message:\n32", hash);
return edverify(signer, abi.encodePacked(signedData), abi.encodePacked(v, r, s));
}
| 12,596,806 |
./partial_match/1/0x82a90C0FF84F8cEe692C9C6C7351DA28bB331154/sources/lib/mip21-toolkit/src/conduits/RwaSwapOutputConduit.sol | Revokes `usr` operator access from this contract. usr The user address./ | function nope(address usr) external auth {
can[usr] = 0;
emit Nope(usr);
}
| 3,691,851 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "hardhat/console.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "./OutfitNFT.sol";
// import "@openzeppelin/contracts/introspection/IERC165.sol";
//import "./Royalty.sol";
//PR: contract FancyBee is ERC721, ERC2981ContractWideRoyalties {
contract FancyBee is ERC721 {
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
address internal fancyDAO;
uint totalBeeSupply = 5;
string originalURI;
mapping (uint256=>address) outfitNFT; // maps beeIds to outfit contract
mapping (uint256=>uint256) outfitTokenID; // maps beeIds to outfitIds
constructor(string memory tokenName, string memory symbol) ERC721(tokenName, symbol) {
_setBaseURI("ipfs://");
// fancyDAO = DAOAddress;
//PR: _setRoyalties(msg.sender, 1000); // Set caller (DAO?) as Receiver and Roaylty as 10%
}
// Modifier to check that the token is not <= 0.
modifier TIDoutOfRange(uint256 _tokenID) {
require (_tokenID>0, "TokenID out of range");
_;
}
function mintToken(address owner, string memory metadataURI)
public
returns (uint256)
{
// require( balanceOf(msg.sender) == 0, "Sorry, only one bee per person." );
require( totalSupply() < totalBeeSupply, "Sorry only 5 are available at this time. ");
_tokenIds.increment();
uint256 id = _tokenIds.current();
_safeMint(owner, id);
_setTokenURI(id, metadataURI);
originalURI = metadataURI;
return id;
}
// When changing the metadata w/ Web3. Must be formatted like : bafy.../metadata.json
function setTokenURI(uint256 _tokenId, string memory _tokenURI) external TIDoutOfRange(_tokenId) returns (string memory) {
_setTokenURI(_tokenId, _tokenURI);
return tokenURI(_tokenId);
}
// function royaltyInfo(uint256 _tokenId, uint256 _price) external view TIDoutOfRange(_tokenId) returns (address receiver, uint256 amount){
// return (fancyDAO, _price/10);
// }
// Returns True if the token exists, else false.
function tokenExists(uint256 _tokenId) external view returns (bool){
return _exists(_tokenId);
}
// Called by the DAO to attach an outfit to a bee.
function attachOutfit(uint256 _beeID, address _outfitContract, uint256 _outfitID) public {
require(msg.sender == fancyDAO, "Not fancyDAO");
require(OutfitNFT(_outfitContract).isOwnedBy(_beeID), "Bee is not owner"); //check the outfit is ours
outfitNFT[_beeID] = _outfitContract;
outfitTokenID[_beeID] = _outfitID;
}
} | Returns True if the token exists, else false. | function tokenExists(uint256 _tokenId) external view returns (bool){
return _exists(_tokenId);
}
| 7,298,424 |
./partial_match/1/0x740392312D99A4eCEE6549AEB8fa6Eb0a579e8F8/sources/TraderPaired.sol | Approve exit of investment _traderAddress trader address _investorAddress investor address _signer Signer address _investmentId investment id _token token address _amount transaction amount | function approveExit(address _traderAddress, address _investorAddress, address _signer, uint256 _investmentId, address _token, uint256 _amount)
public
whenNotPaused
onlyWallet
returns (uint256[3] memory payouts)
{
_Trader memory _trader = traders[_traderAddress];
_Investor memory _investor = investors[_investorAddress];
require(_trader.user == _traderAddress);
require(_investor.user == _investorAddress);
uint256[5] memory _result = IPairedInvestments(pairedInvestments).approveExit(
_traderAddress,
_investorAddress,
_signer,
_investmentId,
_amount);
_Allocation storage allocation = allocations[_traderAddress][_token];
if (_result[4] == 0) {
allocation.invested = allocation.invested.sub(_result[3]);
}
payouts[0] = _result[0];
payouts[1] = _result[1];
payouts[2] = _result[2];
emit ApproveExit(
_investmentId,
msg.sender,
_traderAddress,
_investorAddress,
_signer,
allocation.invested,
allocation.total,
now
);
}
| 16,110,636 |
// 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;
/**
* @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);
}
// contracts/Anonymice.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "./ICheeth.sol";
import "./AnonymiceLibrary.sol";
contract Anonymice is ERC721Enumerable {
/*
___ _
/ _ \ (_)
/ /_\ \_ __ ___ _ __ _ _ _ __ ___ _ ___ ___
| _ | '_ \ / _ \| '_ \| | | | '_ ` _ \| |/ __/ _ \
| | | | | | | (_) | | | | |_| | | | | | | | (_| __/
\_| |_/_| |_|\___/|_| |_|\__, |_| |_| |_|_|\___\___|
__/ |
|___/
*/
using AnonymiceLibrary for uint8;
struct Trait {
string traitName;
string traitType;
string pixels;
uint256 pixelCount;
}
//Mappings
mapping(uint256 => Trait[]) public traitTypes;
mapping(string => bool) hashToMinted;
mapping(uint256 => string) internal tokenIdToHash;
//uint256s
uint256 MAX_SUPPLY = 10000;
uint256 MINTS_PER_TIER = 2000;
uint256 SEED_NONCE = 0;
//string arrays
string[] LETTERS = [
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"y",
"z"
];
//uint arrays
uint16[][8] TIERS;
//address
address cheethAddress;
address _owner;
constructor() ERC721("Anonymice", "MICE") {
_owner = msg.sender;
//Declare all the rarity tiers
//Hat
TIERS[0] = [50, 150, 200, 300, 400, 500, 600, 900, 1200, 5700];
//whiskers
TIERS[1] = [200, 800, 1000, 3000, 5000];
//Neck
TIERS[2] = [300, 800, 900, 1000, 7000];
//Earrings
TIERS[3] = [50, 200, 300, 300, 9150];
//Eyes
TIERS[4] = [50, 100, 400, 450, 500, 700, 1800, 2000, 2000, 2000];
//Mouth
TIERS[5] = [1428, 1428, 1428, 1429, 1429, 1429, 1429];
//Nose
TIERS[6] = [2000, 2000, 2000, 2000, 2000];
//Character
TIERS[7] = [20, 70, 721, 1000, 1155, 1200, 1300, 1434, 1541, 1559];
}
/*
__ __ _ _ _ ___ _ _
| \/ (_)_ _| |_(_)_ _ __ _ | __| _ _ _ __| |_(_)___ _ _ ___
| |\/| | | ' \ _| | ' \/ _` | | _| || | ' \/ _| _| / _ \ ' \(_-<
|_| |_|_|_||_\__|_|_||_\__, | |_| \_,_|_||_\__|\__|_\___/_||_/__/
|___/
*/
/**
* @dev Converts a digit from 0 - 10000 into its corresponding rarity based on the given rarity tier.
* @param _randinput The input from 0 - 10000 to use for rarity gen.
* @param _rarityTier The tier to use.
*/
function rarityGen(uint256 _randinput, uint8 _rarityTier)
internal
view
returns (string memory)
{
uint16 currentLowerBound = 0;
for (uint8 i = 0; i < TIERS[_rarityTier].length; i++) {
uint16 thisPercentage = TIERS[_rarityTier][i];
if (
_randinput >= currentLowerBound &&
_randinput < currentLowerBound + thisPercentage
) return i.toString();
currentLowerBound = currentLowerBound + thisPercentage;
}
revert();
}
/**
* @dev Generates a 9 digit hash from a tokenId, address, and random number.
* @param _t The token id to be used within the hash.
* @param _a The address to be used within the hash.
* @param _c The custom nonce to be used within the hash.
*/
function hash(
uint256 _t,
address _a,
uint256 _c
) internal returns (string memory) {
require(_c < 10);
// This will generate a 9 character string.
//The last 8 digits are random, the first is 0, due to the mouse not being burned.
string memory currentHash = "0";
for (uint8 i = 0; i < 8; i++) {
SEED_NONCE++;
uint16 _randinput = uint16(
uint256(
keccak256(
abi.encodePacked(
block.timestamp,
block.difficulty,
_t,
_a,
_c,
SEED_NONCE
)
)
) % 10000
);
currentHash = string(
abi.encodePacked(currentHash, rarityGen(_randinput, i))
);
}
if (hashToMinted[currentHash]) return hash(_t, _a, _c + 1);
return currentHash;
}
/**
* @dev Returns the current cheeth cost of minting.
*/
function currentCheethCost() public view returns (uint256) {
uint256 _totalSupply = totalSupply();
if (_totalSupply <= 2000) return 0;
if (_totalSupply > 2000 && _totalSupply <= 4000)
return 1000000000000000000;
if (_totalSupply > 4000 && _totalSupply <= 6000)
return 2000000000000000000;
if (_totalSupply > 6000 && _totalSupply <= 8000)
return 3000000000000000000;
if (_totalSupply > 8000 && _totalSupply <= 10000)
return 4000000000000000000;
revert();
}
/**
* @dev Mint internal, this is to avoid code duplication.
*/
function mintInternal() internal {
uint256 _totalSupply = totalSupply();
require(_totalSupply < MAX_SUPPLY);
require(!AnonymiceLibrary.isContract(msg.sender));
uint256 thisTokenId = _totalSupply;
tokenIdToHash[thisTokenId] = hash(thisTokenId, msg.sender, 0);
hashToMinted[tokenIdToHash[thisTokenId]] = true;
_mint(msg.sender, thisTokenId);
}
/**
* @dev Mints new tokens.
*/
function mintMouse() public {
if (totalSupply() < MINTS_PER_TIER) return mintInternal();
//Burn this much cheeth
ICheeth(cheethAddress).burnFrom(msg.sender, currentCheethCost());
return mintInternal();
}
/**
* @dev Burns and mints new.
* @param _tokenId The token to burn.
*/
function burnForMint(uint256 _tokenId) public {
require(ownerOf(_tokenId) == msg.sender);
//Burn token
_transfer(
msg.sender,
0x000000000000000000000000000000000000dEaD,
_tokenId
);
mintInternal();
}
/*
____ ___ ____ ___ _____ __ __ ____ __ ______ ____ ___ ____ _____
| \ / _] / || \ | || | || \ / ] || |/ \ | \ / ___/
| D ) / [_ | o || \ | __|| | || _ | / /| | | || || _ ( \_
| / | _]| || D | | |_ | | || | |/ / |_| |_| | || O || | |\__ |
| \ | [_ | _ || | | _] | : || | / \_ | | | || || | |/ \ |
| . \| || | || | | | | || | \ | | | | || || | |\ |
|__|\_||_____||__|__||_____| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___|
*/
/**
* @dev Helper function to reduce pixel size within contract
*/
function letterToNumber(string memory _inputLetter)
internal
view
returns (uint8)
{
for (uint8 i = 0; i < LETTERS.length; i++) {
if (
keccak256(abi.encodePacked((LETTERS[i]))) ==
keccak256(abi.encodePacked((_inputLetter)))
) return (i + 1);
}
revert();
}
/**
* @dev Hash to SVG function
*/
function hashToSVG(string memory _hash)
public
view
returns (string memory)
{
string memory svgString;
bool[24][24] memory placedPixels;
for (uint8 i = 0; i < 9; i++) {
uint8 thisTraitIndex = AnonymiceLibrary.parseInt(
AnonymiceLibrary.substring(_hash, i, i + 1)
);
for (
uint16 j = 0;
j < traitTypes[i][thisTraitIndex].pixelCount;
j++
) {
string memory thisPixel = AnonymiceLibrary.substring(
traitTypes[i][thisTraitIndex].pixels,
j * 4,
j * 4 + 4
);
uint8 x = letterToNumber(
AnonymiceLibrary.substring(thisPixel, 0, 1)
);
uint8 y = letterToNumber(
AnonymiceLibrary.substring(thisPixel, 1, 2)
);
if (placedPixels[x][y]) continue;
svgString = string(
abi.encodePacked(
svgString,
"<rect class='c",
AnonymiceLibrary.substring(thisPixel, 2, 4),
"' x='",
x.toString(),
"' y='",
y.toString(),
"'/>"
)
);
placedPixels[x][y] = true;
}
}
svgString = string(
abi.encodePacked(
'<svg id="mouse-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> ',
svgString,
"<style>rect{width:1px;height:1px;} #mouse-svg{shape-rendering: crispedges;} .c00{fill:#000000}.c01{fill:#B1ADAC}.c02{fill:#D7D7D7}.c03{fill:#FFA6A6}.c04{fill:#FFD4D5}.c05{fill:#B9AD95}.c06{fill:#E2D6BE}.c07{fill:#7F625A}.c08{fill:#A58F82}.c09{fill:#4B1E0B}.c10{fill:#6D2C10}.c11{fill:#D8D8D8}.c12{fill:#F5F5F5}.c13{fill:#433D4B}.c14{fill:#8D949C}.c15{fill:#05FF00}.c16{fill:#01C700}.c17{fill:#0B8F08}.c18{fill:#421C13}.c19{fill:#6B392A}.c20{fill:#A35E40}.c21{fill:#DCBD91}.c22{fill:#777777}.c23{fill:#848484}.c24{fill:#ABABAB}.c25{fill:#BABABA}.c26{fill:#C7C7C7}.c27{fill:#EAEAEA}.c28{fill:#0C76AA}.c29{fill:#0E97DB}.c30{fill:#10A4EC}.c31{fill:#13B0FF}.c32{fill:#2EB9FE}.c33{fill:#54CCFF}.c34{fill:#50C0F2}.c35{fill:#54CCFF}.c36{fill:#72DAFF}.c37{fill:#B6EAFF}.c38{fill:#FFFFFF}.c39{fill:#954546}.c40{fill:#0B87F7}.c41{fill:#FF2626}.c42{fill:#180F02}.c43{fill:#2B2319}.c44{fill:#FBDD4B}.c45{fill:#F5B923}.c46{fill:#CC8A18}.c47{fill:#3C2203}.c48{fill:#53320B}.c49{fill:#7B501D}.c50{fill:#FFE646}.c51{fill:#FFD627}.c52{fill:#F5B700}.c53{fill:#242424}.c54{fill:#4A4A4A}.c55{fill:#676767}.c56{fill:#F08306}.c57{fill:#FCA30E}.c58{fill:#FEBC0E}.c59{fill:#FBEC1C}.c60{fill:#14242F}.c61{fill:#B06837}.c62{fill:#8F4B0E}.c63{fill:#D88227}.c64{fill:#B06837}</style></svg>"
)
);
return svgString;
}
/**
* @dev Hash to metadata function
*/
function hashToMetadata(string memory _hash)
public
view
returns (string memory)
{
string memory metadataString;
for (uint8 i = 0; i < 9; i++) {
uint8 thisTraitIndex = AnonymiceLibrary.parseInt(
AnonymiceLibrary.substring(_hash, i, i + 1)
);
metadataString = string(
abi.encodePacked(
metadataString,
'{"trait_type":"',
traitTypes[i][thisTraitIndex].traitType,
'","value":"',
traitTypes[i][thisTraitIndex].traitName,
'"}'
)
);
if (i != 8)
metadataString = string(abi.encodePacked(metadataString, ","));
}
return string(abi.encodePacked("[", metadataString, "]"));
}
/**
* @dev Returns the SVG and metadata for a token Id
* @param _tokenId The tokenId to return the SVG and metadata for.
*/
function tokenURI(uint256 _tokenId)
public
view
override
returns (string memory)
{
require(_exists(_tokenId));
string memory tokenHash = _tokenIdToHash(_tokenId);
return
string(
abi.encodePacked(
"data:application/json;base64,",
AnonymiceLibrary.encode(
bytes(
string(
abi.encodePacked(
'{"name": "Anonymice #',
AnonymiceLibrary.toString(_tokenId),
'", "description": "Anonymice is a collection of 10,000 unique mice. All the metadata and images are generated and stored 100% on-chain. No IPFS, no API. Just the Ethereum blockchain.", "image": "data:image/svg+xml;base64,',
AnonymiceLibrary.encode(
bytes(hashToSVG(tokenHash))
),
'","attributes":',
hashToMetadata(tokenHash),
"}"
)
)
)
)
)
);
}
/**
* @dev Returns a hash for a given tokenId
* @param _tokenId The tokenId to return the hash for.
*/
function _tokenIdToHash(uint256 _tokenId)
public
view
returns (string memory)
{
string memory tokenHash = tokenIdToHash[_tokenId];
//If this is a burned token, override the previous hash
if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) {
tokenHash = string(
abi.encodePacked(
"1",
AnonymiceLibrary.substring(tokenHash, 1, 9)
)
);
}
return tokenHash;
}
/**
* @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs.
* @param _wallet The wallet to get the tokens of.
*/
function walletOfOwner(address _wallet)
public
view
returns (uint256[] memory)
{
uint256 tokenCount = balanceOf(_wallet);
uint256[] memory tokensId = new uint256[](tokenCount);
for (uint256 i; i < tokenCount; i++) {
tokensId[i] = tokenOfOwnerByIndex(_wallet, i);
}
return tokensId;
}
/*
___ __ __ ____ ___ ____ _____ __ __ ____ __ ______ ____ ___ ____ _____
/ \ | |__| || \ / _]| \ | || | || \ / ] || |/ \ | \ / ___/
| || | | || _ | / [_ | D ) | __|| | || _ | / /| | | || || _ ( \_
| O || | | || | || _]| / | |_ | | || | |/ / |_| |_| | || O || | |\__ |
| || ` ' || | || [_ | \ | _] | : || | / \_ | | | || || | |/ \ |
| | \ / | | || || . \ | | | || | \ | | | | || || | |\ |
\___/ \_/\_/ |__|__||_____||__|\_| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___|
*/
/**
* @dev Clears the traits.
*/
function clearTraits() public onlyOwner {
for (uint256 i = 0; i < 9; i++) {
delete traitTypes[i];
}
}
/**
* @dev Add a trait type
* @param _traitTypeIndex The trait type index
* @param traits Array of traits to add
*/
function addTraitType(uint256 _traitTypeIndex, Trait[] memory traits)
public
onlyOwner
{
for (uint256 i = 0; i < traits.length; i++) {
traitTypes[_traitTypeIndex].push(
Trait(
traits[i].traitName,
traits[i].traitType,
traits[i].pixels,
traits[i].pixelCount
)
);
}
return;
}
/**
* @dev Sets the cheeth ERC20 address
* @param _cheethAddress The cheeth address
*/
function setCheethAddress(address _cheethAddress) public onlyOwner {
cheethAddress = _cheethAddress;
}
/**
* @dev Transfers ownership
* @param _newOwner The new owner
*/
function transferOwnership(address _newOwner) public onlyOwner {
_owner = _newOwner;
}
/**
* @dev Modifier to only allow owner to call functions
*/
modifier onlyOwner() {
require(_owner == msg.sender);
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library AnonymiceLibrary {
string internal constant TABLE =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return "";
// load the table into memory
string memory table = TABLE;
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((data.length + 2) / 3);
// add some extra buffer at the end required for the writing
string memory result = new string(encodedLen + 32);
assembly {
// set the actual output length
mstore(result, encodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 3 bytes at a time
for {
} lt(dataPtr, endPtr) {
} {
dataPtr := add(dataPtr, 3)
// read 3 bytes
let input := mload(dataPtr)
// write 4 characters
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(6, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(input, 0x3F))))
)
resultPtr := add(resultPtr, 1)
}
// padding with '='
switch mod(mload(data), 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
}
return result;
}
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
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);
}
function parseInt(string memory _a)
internal
pure
returns (uint8 _parsedInt)
{
bytes memory bresult = bytes(_a);
uint8 mint = 0;
for (uint8 i = 0; i < bresult.length; i++) {
if (
(uint8(uint8(bresult[i])) >= 48) &&
(uint8(uint8(bresult[i])) <= 57)
) {
mint *= 10;
mint += uint8(bresult[i]) - 48;
}
}
return mint;
}
function substring(
string memory str,
uint256 startIndex,
uint256 endIndex
) internal pure returns (string memory) {
bytes memory strBytes = bytes(str);
bytes memory result = new bytes(endIndex - startIndex);
for (uint256 i = startIndex; i < endIndex; i++) {
result[i - startIndex] = strBytes[i];
}
return string(result);
}
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;
}
}
// contracts/ICheeth.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface ICheeth is IERC20 {
function burnFrom(address account, uint256 amount) external;
}
| Hash to SVG function/ | function hashToSVG(string memory _hash)
public
view
returns (string memory)
{
string memory svgString;
bool[24][24] memory placedPixels;
for (uint8 i = 0; i < 9; i++) {
uint8 thisTraitIndex = AnonymiceLibrary.parseInt(
AnonymiceLibrary.substring(_hash, i, i + 1)
);
for (
uint16 j = 0;
j < traitTypes[i][thisTraitIndex].pixelCount;
j++
) {
string memory thisPixel = AnonymiceLibrary.substring(
traitTypes[i][thisTraitIndex].pixels,
j * 4,
j * 4 + 4
);
uint8 x = letterToNumber(
AnonymiceLibrary.substring(thisPixel, 0, 1)
);
uint8 y = letterToNumber(
AnonymiceLibrary.substring(thisPixel, 1, 2)
);
if (placedPixels[x][y]) continue;
svgString = string(
abi.encodePacked(
svgString,
"<rect class='c",
AnonymiceLibrary.substring(thisPixel, 2, 4),
"' x='",
x.toString(),
"' y='",
y.toString(),
"'/>"
)
);
placedPixels[x][y] = true;
}
}
svgString = string(
abi.encodePacked(
svgString,
)
);
return svgString;
}
| 5,731,679 |
./full_match/137/0x9E30F3C8BF0309A169347d8762efc53FDb3d941e/sources/contracts/ART_SALE.sol | Call Chainlink VRF to get random number | function getStartingIndex() external onlyOwner {
require(startingIndex == 0, "startingIndex is set already");
require(block.timestamp >= startTimestamp, "Sale is inactive");
require(totalSupply() > MAX_SUPPLY / 5, "Need at least 1/5 supply sold");
requestRandomness(KEY_HASH, LINK_FEE);
}
| 4,698,637 |
./full_match/80001/0x1F60b3be173EA9B5D1301Dd39f8A7cA70B4ABee4/sources/contracts/padisah.sol | 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];
}
| 5,578,023 |
./full_match/1/0x7924743bdD32d1fD1769F703d712eEeCCB59aEfE/sources/contracts/NftKeysV1.sol | Destroys token with ID This has to be overridden even though it is not used tokenId Token ID | function _burn(
uint256 tokenId
) internal virtual override(ERC721Royalty, ERC721) {
ERC721Royalty._burn(tokenId);
}
| 2,933,114 |
./full_match/42/0x43Db1564c757410B031791C65bE972F4f861de15/sources/browser/LAOLAND.sol | Internal function that burns an amount of the token of a given account, deducting from the sender's allowance for said account. Uses the internal burn function. Emits an Approval event (reflecting the reduced allowance). account The account whose tokens will be burnt. value The amount that will be burnt./ | function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowances[account][msg.sender] - value);
}
| 16,274,908 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./interfaces/IBMIStaking.sol";
import "./interfaces/IContractsRegistry.sol";
import "./interfaces/ILiquidityBridge.sol";
import "./interfaces/ILiquidityMining.sol";
import "./interfaces/tokens/ISTKBMIToken.sol";
import "./interfaces/tokens/IVBMI.sol";
import "./interfaces/tokens/erc20permit-upgradeable/IERC20PermitUpgradeable.sol";
import "./abstract/AbstractDependant.sol";
import "./Globals.sol";
contract BMIStaking is IBMIStaking, OwnableUpgradeable, AbstractDependant {
using SafeMath for uint256;
IERC20 public bmiToken;
ISTKBMIToken public stkBMIToken;
uint256 public lastUpdateBlock;
uint256 public rewardPerBlock;
uint256 public totalPool;
address public legacyBMIStakingAddress;
ILiquidityMining public liquidityMining;
address public bmiCoverStakingAddress;
address public liquidityMiningStakingAddress;
mapping(address => WithdrawalInfo) private withdrawalsInfo;
IERC20 public vBMI;
uint256 internal constant WITHDRAWING_LOCKUP_DURATION = 90 days;
uint256 internal constant WITHDRAWING_COOLDOWN_DURATION = 8 days;
uint256 internal constant WITHDRAWAL_PHASE_DURATION = 2 days;
address public liquidityBridgeAddress;
bool public isMigrating;
bool public isPaused;
modifier onlyLiquidityBridge() {
require(
_msgSender() == liquidityBridgeAddress || _msgSender() == address(this),
"BMS: not authorized"
);
_;
}
modifier notMigrating() {
require(!isMigrating, "BMIS: Operation paused while migrating");
_;
}
modifier notPaused() {
require(!isPaused, "BMIS: Operation paused");
_;
}
modifier updateRewardPool() {
_updateRewardPool();
_;
}
modifier onlyStaking() {
require(
_msgSender() == bmiCoverStakingAddress ||
_msgSender() == liquidityMiningStakingAddress ||
_msgSender() == legacyBMIStakingAddress ||
_msgSender() == liquidityBridgeAddress,
"BMIStaking: Not a staking contract"
);
_;
}
function __BMIStaking_init(uint256 _rewardPerBlock) external initializer {
__Ownable_init();
lastUpdateBlock = block.number;
rewardPerBlock = _rewardPerBlock;
}
function setDependencies(IContractsRegistry _contractsRegistry)
external
override
onlyInjectorOrZero
{
legacyBMIStakingAddress = _contractsRegistry.getLegacyBMIStakingContract();
bmiToken = IERC20(_contractsRegistry.getBMIContract());
stkBMIToken = ISTKBMIToken(_contractsRegistry.getSTKBMIContract());
liquidityMining = ILiquidityMining(_contractsRegistry.getLiquidityMiningContract());
bmiCoverStakingAddress = _contractsRegistry.getBMICoverStakingContract();
liquidityMiningStakingAddress = _contractsRegistry.getLiquidityMiningStakingContract();
vBMI = IERC20(_contractsRegistry.getVBMIContract());
liquidityBridgeAddress = _contractsRegistry.getLiquidityBridgeContract();
}
function stakeWithPermit(
uint256 _amountBMI,
uint8 _v,
bytes32 _r,
bytes32 _s
) external override {
IERC20PermitUpgradeable(address(bmiToken)).permit(
_msgSender(),
address(this),
_amountBMI,
MAX_INT,
_v,
_r,
_s
);
bmiToken.transferFrom(_msgSender(), address(this), _amountBMI);
_stake(_msgSender(), _amountBMI);
}
function stakeFor(address _user, uint256 _amountBMI) external override onlyStaking {
require(_amountBMI > 0, "BMIStaking: can't stake 0 tokens");
_stake(_user, _amountBMI);
}
function stake(uint256 _amountBMI) external override {
require(_amountBMI > 0, "BMIStaking: can't stake 0 tokens");
bmiToken.transferFrom(_msgSender(), address(this), _amountBMI);
_stake(_msgSender(), _amountBMI);
}
/// @notice checks when the unlockPeriod expires (90 days)
/// @return exact timestamp of the unlock time or 0 if LME is not started or unlock period is reached
function maturityAt() external view override returns (uint256) {
uint256 maturityDate =
liquidityMining.startLiquidityMiningTime().add(WITHDRAWING_LOCKUP_DURATION);
return maturityDate < block.timestamp ? 0 : maturityDate;
}
// It is unlocked after 90 days
function isBMIRewardUnlocked() public view override returns (bool) {
uint256 liquidityMiningStartTime = liquidityMining.startLiquidityMiningTime();
return
liquidityMiningStartTime == 0 ||
liquidityMiningStartTime.add(WITHDRAWING_LOCKUP_DURATION) <= block.timestamp;
}
// There is a second withdrawal phase of 48 hours to actually receive the rewards.
// If a user misses this period, in order to withdraw he has to wait for 10 days again.
// It will return:
// 0 if cooldown time didn't start or if phase duration (48hs) has expired
// #coolDownTimeEnd Time when user can withdraw.
function whenCanWithdrawBMIReward(address _address) public view override returns (uint256) {
return
withdrawalsInfo[_address].coolDownTimeEnd.add(WITHDRAWAL_PHASE_DURATION) >=
block.timestamp
? withdrawalsInfo[_address].coolDownTimeEnd
: 0;
}
/*
* Before a withdraw, it is needed to wait 90 days after LiquidityMining started.
* And after 90 days, user can request to withdraw and wait 10 days.
* After 10 days, user can withdraw, but user has 48hs to withdraw. After 48hs,
* user will need to request to withdraw again and wait for more 10 days before
* being able to withdraw.
*/
function unlockTokensToWithdraw(uint256 _amountBMIUnlock) public override notPaused {
_unlockTokensToWithdraw(_msgSender(), _amountBMIUnlock);
}
function _unlockTokensToWithdraw(address _sender, uint256 _amountBMIUnlock) internal {
require(_amountBMIUnlock > 0, "BMIStaking: can't unlock 0 tokens");
require(isBMIRewardUnlocked(), "BMIStaking: lock up time didn't end");
uint256 _amountStkBMIUnlock = _convertToStkBMI(_amountBMIUnlock);
require(
stkBMIToken.balanceOf(_sender) >= _amountStkBMIUnlock,
"BMIStaking: not enough BMI to unlock"
);
withdrawalsInfo[_sender] = WithdrawalInfo(
block.timestamp.add(WITHDRAWING_COOLDOWN_DURATION),
_amountBMIUnlock
);
}
function setPause(bool _pause) public onlyOwner {
isPaused = _pause;
}
/// @notice migrates stkBMI to V2
function migrate() external notPaused {
_migrateStakeToV2(_msgSender());
}
/// @notice Migrates stakes to V2
function migrateStakeToV2(address _user)
public
override
onlyLiquidityBridge
returns (uint256 amountBMI, uint256 _amountStkBMI)
{
return _migrateStakeToV2(_user);
}
function _migrateStakeToV2(address _user)
internal
returns (uint256 amountBMI, uint256 _amountStkBMI)
{
IVBMI vBMIContract = IVBMI(address(vBMI));
uint256 _vbmiBalance = vBMIContract.balanceOf(_user);
if (_vbmiBalance > 0) {
vBMIContract.ejectUsersBMI(_user, _vbmiBalance);
}
uint256 _stkBMItoUnlock = stkBMIToken.balanceOf(_user);
uint256 _bmiAmount = _convertToBMI(_stkBMItoUnlock);
address _newBMIStakingAddress = 0x55978a6F6A4cFA00D5a8b442e93E42c025D0890C;
require(
bmiToken.balanceOf(address(this)) >= _bmiAmount,
"Withdraw: failed to transfer BMI tokens"
);
if (_bmiAmount > 0) {
stkBMIToken.burn(_user, _stkBMItoUnlock);
totalPool = totalPool.sub(_bmiAmount);
bmiToken.transfer(_newBMIStakingAddress, _bmiAmount);
ILiquidityBridge(liquidityBridgeAddress).migrateUserBMIStake(_user, _bmiAmount);
emit BMIMigratedToV2(_bmiAmount, _stkBMItoUnlock, _user);
}
amountBMI = _bmiAmount;
}
// User can withdraw after unlock period is over, when 10 days passed
// after user asked to unlock stkBMI and before 48hs that stkBMI are unlocked.
function withdraw() external override updateRewardPool {
//it will revert (equal to 0) here if passed 48hs after unlock period, if
//lockup period didn't start or didn't passed 90 days or if unlock didn't start
uint256 _whenCanWithdrawBMIReward = whenCanWithdrawBMIReward(_msgSender());
require(_whenCanWithdrawBMIReward != 0, "BMIStaking: unlock not started/exp");
require(_whenCanWithdrawBMIReward <= block.timestamp, "BMIStaking: cooldown not reached");
(uint256 amountBMI, uint256 _amountStkBMI) = _withdraw(_msgSender(), _msgSender());
}
function _withdraw(address _sender, address _destiny)
internal
updateRewardPool
returns (uint256 amountBMI, uint256 _amountStkBMI)
{
uint256 amountBMI = withdrawalsInfo[_sender].amountBMIRequested;
delete withdrawalsInfo[_sender];
require(bmiToken.balanceOf(address(this)) >= amountBMI, "BMIStaking: !enough BMI tokens");
uint256 _amountStkBMI = _convertToStkBMI(amountBMI);
require(
stkBMIToken.balanceOf(_sender) >= _amountStkBMI,
"BMIStaking: !enough stkBMI to withdraw"
);
stkBMIToken.burn(_sender, _amountStkBMI);
totalPool = totalPool.sub(amountBMI);
bmiToken.transfer(_destiny, amountBMI);
emit BMIWithdrawn(amountBMI, _amountStkBMI, _msgSender());
}
/// @notice Getting withdraw information
/// @return _amountBMIRequested is amount of bmi tokens requested to unlock
/// @return _amountStkBMI is amount of stkBMI that will burn
/// @return _unlockPeriod is its timestamp when user can withdraw
/// returns 0 if it didn't unlocked yet. User has 48hs to withdraw
/// @return _availableFor is the end date if withdraw period has already begun
/// or 0 if it is expired or didn't start
function getWithdrawalInfo(address _userAddr)
external
view
override
returns (
uint256 _amountBMIRequested,
uint256 _amountStkBMI,
uint256 _unlockPeriod,
uint256 _availableFor
)
{
// if whenCanWithdrawBMIReward() returns > 0 it was unlocked or is not expired
_unlockPeriod = whenCanWithdrawBMIReward(_userAddr);
_amountBMIRequested = withdrawalsInfo[_userAddr].amountBMIRequested;
_amountStkBMI = _convertToStkBMI(_amountBMIRequested);
uint256 endUnlockPeriod = _unlockPeriod.add(WITHDRAWAL_PHASE_DURATION);
_availableFor = _unlockPeriod <= block.timestamp ? endUnlockPeriod : 0;
}
function addToPool(uint256 _amount) external override onlyStaking updateRewardPool {
totalPool = totalPool.add(_amount);
}
function stakingReward(uint256 _amount) external view override returns (uint256) {
return _convertToBMI(_amount);
}
function getStakedBMI(address _address) external view override returns (uint256) {
uint256 balance = stkBMIToken.balanceOf(_address).add(vBMI.balanceOf(_address));
return balance > 0 ? _convertToBMI(balance) : 0;
}
/// @notice returns APY% with 10**5 precision
function getAPY() external view override returns (uint256) {
return rewardPerBlock.mul(BLOCKS_PER_YEAR.mul(10**7)).div(totalPool.add(APY_TOKENS));
}
function setRewardPerBlock(uint256 _amount) external override onlyOwner updateRewardPool {
rewardPerBlock = _amount;
}
function revokeRewardPool(uint256 _amount) external override onlyOwner updateRewardPool {
require(_amount > 0, "BMIStaking: Amount is zero");
require(_amount <= totalPool, "BMIStaking: Amount is greater than the pool");
require(
_amount <= bmiToken.balanceOf(address(this)),
"BMIStaking: Amount is greater than the balance"
);
totalPool = totalPool.sub(_amount);
bmiToken.transfer(_msgSender(), _amount);
emit RewardPoolRevoked(_msgSender(), _amount);
}
function revokeUnusedRewardPool() external override onlyOwner updateRewardPool {
uint256 contractBalance = bmiToken.balanceOf(address(this));
require(contractBalance > totalPool, "BMIStaking: No unused tokens revoke");
uint256 unusedTokens = contractBalance.sub(totalPool);
bmiToken.transfer(_msgSender(), unusedTokens);
emit UnusedRewardPoolRevoked(_msgSender(), unusedTokens);
}
function _updateRewardPool() internal {
if (totalPool == 0) {
lastUpdateBlock = block.number;
}
totalPool = totalPool.add(_calculateReward());
lastUpdateBlock = block.number;
}
function _stake(address _staker, uint256 _amountBMI) internal updateRewardPool {
uint256 amountStkBMI = _convertToStkBMI(_amountBMI);
stkBMIToken.mint(_staker, amountStkBMI);
totalPool = totalPool.add(_amountBMI);
emit StakedBMI(_amountBMI, amountStkBMI, _staker);
}
function _convertToStkBMI(uint256 _amount) internal view returns (uint256) {
uint256 stkBMITokenTS = stkBMIToken.totalSupply();
uint256 stakingPool = totalPool.add(_calculateReward());
if (stakingPool > 0 && stkBMITokenTS > 0) {
_amount = stkBMITokenTS.mul(_amount).div(stakingPool);
}
return _amount;
}
function _convertToBMI(uint256 _amount) internal view returns (uint256) {
uint256 stkBMITokenTS = stkBMIToken.totalSupply();
uint256 stakingPool = totalPool.add(_calculateReward());
return stkBMITokenTS > 0 ? stakingPool.mul(_amount).div(stkBMITokenTS) : 0;
}
function _calculateReward() internal view returns (uint256) {
uint256 blocksPassed = block.number.sub(lastUpdateBlock);
return rewardPerBlock.mul(blocksPassed);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* COPIED FROM https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/tree/release-v3.4/contracts/drafts
* @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 IERC20PermitUpgradeable {
/**
* @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.7.4;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
interface IVBMI is IERC20Upgradeable {
function lockStkBMI(uint256 amount) external;
function unlockStkBMI(uint256 amount) external;
function ejectUsersBMI(address _user, uint256 _amount) external;
function slashUserTokens(address user, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
interface ISTKBMIToken is IERC20Upgradeable {
function mint(address account, uint256 amount) external;
function burn(address account, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface ILiquidityMining {
struct TeamDetails {
string teamName;
address referralLink;
uint256 membersNumber;
uint256 totalStakedAmount;
uint256 totalReward;
}
struct UserInfo {
address userAddr;
string teamName;
uint256 stakedAmount;
uint256 mainNFT; // 0 or NFT index if available
uint256 platinumNFT; // 0 or NFT index if available
}
struct UserRewardsInfo {
string teamName;
uint256 totalBMIReward; // total BMI reward
uint256 availableBMIReward; // current claimable BMI reward
uint256 incomingPeriods; // how many month are incoming
uint256 timeToNextDistribution; // exact time left to next distribution
uint256 claimedBMI; // actual number of claimed BMI
uint256 mainNFTAvailability; // 0 or NFT index if available
uint256 platinumNFTAvailability; // 0 or NFT index if available
bool claimedNFTs; // true if user claimed NFTs
}
struct MyTeamInfo {
TeamDetails teamDetails;
uint256 myStakedAmount;
uint256 teamPlace;
}
struct UserTeamInfo {
address teamAddr;
uint256 stakedAmount;
uint256 countOfRewardedMonth;
bool isNFTDistributed;
}
struct TeamInfo {
string name;
uint256 totalAmount;
address[] teamLeaders;
}
function startLiquidityMiningTime() external view returns (uint256);
function getTopTeams() external view returns (TeamDetails[] memory teams);
function getTopUsers() external view returns (UserInfo[] memory users);
function getAllTeamsLength() external view returns (uint256);
function getAllTeamsDetails(uint256 _offset, uint256 _limit)
external
view
returns (TeamDetails[] memory _teamDetailsArr);
function getMyTeamsLength() external view returns (uint256);
function getMyTeamMembers(uint256 _offset, uint256 _limit)
external
view
returns (address[] memory _teamMembers, uint256[] memory _memberStakedAmount);
function getAllUsersLength() external view returns (uint256);
function getAllUsersInfo(uint256 _offset, uint256 _limit)
external
view
returns (UserInfo[] memory _userInfos);
function getMyTeamInfo() external view returns (MyTeamInfo memory _myTeamInfo);
function getRewardsInfo(address user)
external
view
returns (UserRewardsInfo memory userRewardInfo);
function createTeam(string calldata _teamName) external;
function deleteTeam() external;
function joinTheTeam(address _referralLink) external;
function getSlashingPercentage() external view returns (uint256);
function investSTBL(uint256 _tokensAmount, address _policyBookAddr) external;
function distributeNFT() external;
function checkPlatinumNFTReward(address _userAddr) external view returns (uint256);
function checkMainNFTReward(address _userAddr) external view returns (uint256);
function distributeBMIReward() external;
function getTotalUserBMIReward(address _userAddr) external view returns (uint256);
function checkAvailableBMIReward(address _userAddr) external view returns (uint256);
/// @notice checks if liquidity mining event is lasting (startLiquidityMining() has been called)
/// @return true if LM is started and not ended, false otherwise
function isLMLasting() external view returns (bool);
/// @notice checks if liquidity mining event is finished. In order to be finished, it has to be started
/// @return true if LM is finished, false if event is still going or not started
function isLMEnded() external view returns (bool);
function getEndLMTime() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface ILiquidityBridge {
event BMIMigratedToV2(
address indexed recipient,
uint256 amountBMI,
uint256 rewardsBMI,
uint256 burnedStkBMI
);
event MigratedBMIStakers(uint256 migratedCount);
function migrateUserBMIStake(address _sender, uint256 _amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface IContractsRegistry {
function liquidityBridgeImplementation() external view returns (address);
function getUniswapRouterContract() external view returns (address);
function getUniswapBMIToETHPairContract() external view returns (address);
function getWETHContract() external view returns (address);
function getUSDTContract() external view returns (address);
function getBMIContract() external view returns (address);
function getPriceFeedContract() external view returns (address);
function getPolicyBookRegistryContract() external view returns (address);
function getPolicyBookFabricContract() external view returns (address);
function getBMICoverStakingContract() external view returns (address);
function getLegacyRewardsGeneratorContract() external view returns (address);
function getRewardsGeneratorContract() external view returns (address);
function getBMIUtilityNFTContract() external view returns (address);
function getLiquidityMiningContract() external view returns (address);
function getClaimingRegistryContract() external view returns (address);
function getPolicyRegistryContract() external view returns (address);
function getLiquidityRegistryContract() external view returns (address);
function getClaimVotingContract() external view returns (address);
function getReinsurancePoolContract() external view returns (address);
function getLiquidityBridgeContract() external view returns (address);
function getContractsRegistryV2Contract() external view returns (address);
function getPolicyBookAdminContract() external view returns (address);
function getPolicyQuoteContract() external view returns (address);
function getLegacyBMIStakingContract() external view returns (address);
function getBMIStakingContract() external view returns (address);
function getSTKBMIContract() external view returns (address);
function getVBMIContract() external view returns (address);
function getLegacyLiquidityMiningStakingContract() external view returns (address);
function getLiquidityMiningStakingContract() external view returns (address);
function getReputationSystemContract() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "./tokens/ISTKBMIToken.sol";
interface IBMIStaking {
event StakedBMI(uint256 stakedBMI, uint256 mintedStkBMI, address indexed recipient);
event BMIWithdrawn(uint256 amountBMI, uint256 burnedStkBMI, address indexed recipient);
event UnusedRewardPoolRevoked(address recipient, uint256 amount);
event RewardPoolRevoked(address recipient, uint256 amount);
event BMIMigratedToV2(uint256 amountBMI, uint256 burnedStkBMI, address indexed recipient);
struct WithdrawalInfo {
uint256 coolDownTimeEnd;
uint256 amountBMIRequested;
}
function stakeWithPermit(
uint256 _amountBMI,
uint8 _v,
bytes32 _r,
bytes32 _s
) external;
function stakeFor(address _user, uint256 _amountBMI) external;
function stake(uint256 _amountBMI) external;
function maturityAt() external view returns (uint256);
function isBMIRewardUnlocked() external view returns (bool);
function whenCanWithdrawBMIReward(address _address) external view returns (uint256);
function unlockTokensToWithdraw(uint256 _amountBMIUnlock) external;
function withdraw() external;
function migrateStakeToV2(address _user)
external
returns (uint256 amountBMI, uint256 _amountStkBMI);
/// @notice Getting withdraw information
/// @return _amountBMIRequested is amount of bmi tokens requested to unlock
/// @return _amountStkBMI is amount of stkBMI that will burn
/// @return _unlockPeriod is its timestamp when user can withdraw
/// returns 0 if it didn't unlocked yet. User has 48hs to withdraw
/// @return _availableFor is the end date if withdraw period has already begun
/// or 0 if it is expired or didn't start
function getWithdrawalInfo(address _userAddr)
external
view
returns (
uint256 _amountBMIRequested,
uint256 _amountStkBMI,
uint256 _unlockPeriod,
uint256 _availableFor
);
function addToPool(uint256 _amount) external;
function stakingReward(uint256 _amount) external view returns (uint256);
function getStakedBMI(address _address) external view returns (uint256);
function getAPY() external view returns (uint256);
function setRewardPerBlock(uint256 _amount) external;
function revokeRewardPool(uint256 _amount) external;
function revokeUnusedRewardPool() external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "../interfaces/IContractsRegistry.sol";
abstract contract AbstractDependant {
/// @dev keccak256(AbstractDependant.setInjector(address)) - 1
bytes32 private constant _INJECTOR_SLOT =
0xd6b8f2e074594ceb05d47c27386969754b6ad0c15e5eb8f691399cd0be980e76;
modifier onlyInjectorOrZero() {
address _injector = injector();
require(_injector == address(0) || _injector == msg.sender, "Dependant: Not an injector");
_;
}
function setInjector(address _injector) external onlyInjectorOrZero {
bytes32 slot = _INJECTOR_SLOT;
assembly {
sstore(slot, _injector)
}
}
/// @dev has to apply onlyInjectorOrZero() modifier
function setDependencies(IContractsRegistry) external virtual;
function injector() public view returns (address _injector) {
bytes32 slot = _INJECTOR_SLOT;
assembly {
_injector := sload(slot)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
uint256 constant SECONDS_IN_THE_YEAR = 365 * 24 * 60 * 60; // 365 days * 24 hours * 60 minutes * 60 seconds
uint256 constant MAX_INT = type(uint256).max;
uint256 constant DECIMALS18 = 10**18;
uint256 constant PRECISION = 10**25;
uint256 constant PERCENTAGE_100 = 100 * PRECISION;
uint256 constant BLOCKS_PER_DAY = 6450;
uint256 constant BLOCKS_PER_YEAR = BLOCKS_PER_DAY * 365;
uint256 constant APY_TOKENS = DECIMALS18;
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, 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 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
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../GSN/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
} | keccak256(AbstractDependant.setInjector(address)) - 1 | function stakeWithPermit(
uint256 _amountBMI,
uint8 _v,
bytes32 _r,
bytes32 _s
) external;
function stakeFor(address _user, uint256 _amountBMI) external;
function stake(uint256 _amountBMI) external;
function maturityAt() external view returns (uint256);
function isBMIRewardUnlocked() external view returns (bool);
function whenCanWithdrawBMIReward(address _address) external view returns (uint256);
function unlockTokensToWithdraw(uint256 _amountBMIUnlock) external;
function withdraw() external;
function migrateStakeToV2(address _user)
external
returns (uint256 amountBMI, uint256 _amountStkBMI);
function getWithdrawalInfo(address _userAddr)
external
view
returns (
uint256 _amountBMIRequested,
uint256 _amountStkBMI,
uint256 _unlockPeriod,
uint256 _availableFor
);
function addToPool(uint256 _amount) external;
function stakingReward(uint256 _amount) external view returns (uint256);
function getStakedBMI(address _address) external view returns (uint256);
function getAPY() external view returns (uint256);
function setRewardPerBlock(uint256 _amount) external;
function revokeRewardPool(uint256 _amount) external;
function revokeUnusedRewardPool() external;
}
pragma solidity ^0.7.4;
import "../interfaces/IContractsRegistry.sol";
modifier onlyInjectorOrZero() {
address _injector = injector();
require(_injector == address(0) || _injector == msg.sender, "Dependant: Not an injector");
_;
}
| 10,143,040 |
./partial_match/1/0x9078976c0b05ffed53b792dBF406af49faBbb925/sources/ONEPIECE.sol | 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, "SafeMathHelper: subtraction overflow");
}
| 2,828,217 |
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _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 msg.sender == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* > Note: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: openzeppelin-solidity/contracts/access/Roles.sol
pragma solidity ^0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// File: contracts/membership/ManagerRole.sol
/**
* @title Manager Role
* @dev This contract is developed based on the Manager contract of OpenZeppelin.
* The key difference is the management of the manager roles is restricted to one owner
* account. At least one manager should exist in any situation.
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract ManagerRole is Ownable {
using Roles for Roles.Role;
using SafeMath for uint256;
event ManagerAdded(address indexed account);
event ManagerRemoved(address indexed account);
Roles.Role private managers;
uint256 private _numManager;
constructor() internal {
_addManager(msg.sender);
_numManager = 1;
}
/**
* @notice Only manager can take action
*/
modifier onlyManager() {
require(isManager(msg.sender), "The account is not a manager");
_;
}
/**
* @notice This function allows to add managers in batch with control of the number of
* interations
* @param accounts The accounts to be added in batch
*/
// solhint-disable-next-line
function addManagers(address[] calldata accounts) external onlyOwner {
uint256 length = accounts.length;
require(length <= 256, "too many accounts");
for (uint256 i = 0; i < length; i++) {
_addManager(accounts[i]);
}
}
/**
* @notice Add an account to the list of managers,
* @param account The account address whose manager role needs to be removed.
*/
function removeManager(address account) external onlyOwner {
_removeManager(account);
}
/**
* @notice Check if an account is a manager
* @param account The account to be checked if it has a manager role
* @return true if the account is a manager. Otherwise, false
*/
function isManager(address account) public view returns (bool) {
return managers.has(account);
}
/**
*@notice Get the number of the current managers
*/
function numManager() public view returns (uint256) {
return _numManager;
}
/**
* @notice Add an account to the list of managers,
* @param account The account that needs to tbe added as a manager
*/
function addManager(address account) public onlyOwner {
require(account != address(0), "account is zero");
_addManager(account);
}
/**
* @notice Renounce the manager role
* @dev This function was not explicitly required in the specs. There should be at
* least one manager at any time. Therefore, at least two when one manage renounces
* themselves.
*/
function renounceManager() public {
require(_numManager >= 2, "Managers are fewer than 2");
_removeManager(msg.sender);
}
/** OVERRIDE
* @notice Allows the current owner to relinquish control of the contract.
* @dev 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 {
revert("Cannot renounce ownership");
}
/**
* @notice Internal function to be called when adding a manager
* @param account The address of the manager-to-be
*/
function _addManager(address account) internal {
_numManager = _numManager.add(1);
managers.add(account);
emit ManagerAdded(account);
}
/**
* @notice Internal function to remove one account from the manager list
* @param account The address of the to-be-removed manager
*/
function _removeManager(address account) internal {
_numManager = _numManager.sub(1);
managers.remove(account);
emit ManagerRemoved(account);
}
}
// File: contracts/membership/PausableManager.sol
/**
* @title Pausable Manager Role
* @dev This manager can also pause a contract. This contract is developed based on the
* Pause contract of OpenZeppelin.
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract PausableManager is ManagerRole {
event BePaused(address manager);
event BeUnpaused(address manager);
bool private _paused; // If the crowdsale contract is paused, controled by the manager...
constructor() internal {
_paused = false;
}
/**
* @notice Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "not paused");
_;
}
/**
* @notice Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "paused");
_;
}
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns(bool) {
return _paused;
}
/**
* @notice called by the owner to pause, triggers stopped state
*/
function pause() public onlyManager whenNotPaused {
_paused = true;
emit BePaused(msg.sender);
}
/**
* @notice called by the owner to unpause, returns to normal state
*/
function unpause() public onlyManager whenPaused {
_paused = false;
emit BeUnpaused(msg.sender);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see `ERC20Detailed`.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through `transferFrom`. This is
* zero by default.
*
* This value changes when `approve` or `transferFrom` are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* > 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-solidity/contracts/utils/Address.sol
pragma solidity ^0.5.0;
/**
* @dev Collection of functions related to the address type,
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* > It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// 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);
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");
}
}
}
// File: contracts/property/Reclaimable.sol
/**
* @title Reclaimable
* @dev This contract gives owner right to recover any ERC20 tokens accidentally sent to
* the token contract. The recovered token will be sent to the owner of token.
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract Reclaimable is Ownable {
using SafeERC20 for IERC20;
/**
* @notice Let the owner to retrieve other tokens accidentally sent to this contract.
* @dev This function is suitable when no token of any kind shall be stored under
* the address of the inherited contract.
* @param tokenToBeRecovered address of the token to be recovered.
*/
function reclaimToken(IERC20 tokenToBeRecovered) external onlyOwner {
uint256 balance = tokenToBeRecovered.balanceOf(address(this));
tokenToBeRecovered.safeTransfer(owner(), balance);
}
}
// File: contracts/property/CounterGuard.sol
/**
* @title modifier contract that guards certain properties only triggered once
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract CounterGuard {
/**
* @notice Controle if a boolean attribute (false by default) was updated to true.
* @dev This attribute is designed specifically for recording an action.
* @param criterion The boolean attribute that records if an action has taken place
*/
modifier onlyOnce(bool criterion) {
require(criterion == false, "Already been set");
_;
}
}
// File: contracts/property/ValidAddress.sol
/**
* @title modifier contract that checks if the address is valid
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract ValidAddress {
/**
* @notice Check if the address is not zero
*/
modifier onlyValidAddress(address _address) {
require(_address != address(0), "Not a valid address");
_;
}
/**
* @notice Check if the address is not the sender's address
*/
modifier isSenderNot(address _address) {
require(_address != msg.sender, "Address is the same as the sender");
_;
}
/**
* @notice Check if the address is the sender's address
*/
modifier isSender(address _address) {
require(_address == msg.sender, "Address is different from the sender");
_;
}
}
// File: contracts/vault/IVault.sol
/*
* @title Interface for basic vaults
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract IVault {
/**
* @notice Adding beneficiary to the vault
* @param beneficiary The account that receives token
* @param value The amount of token allocated
*/
function receiveFor(address beneficiary, uint256 value) public;
/**
* @notice Update the releaseTime for vaults
* @param roundEndTime The new releaseTime
*/
function updateReleaseTime(uint256 roundEndTime) public;
}
// File: contracts/vault/BasicVault.sol
/**
* @title Vault for private sale, presale, and SAFT
* @dev Inspired by the TokenTimelock contract of OpenZeppelin
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract BasicVault is IVault, Reclaimable, CounterGuard, ValidAddress, PausableManager {
using SafeERC20 for IERC20;
using SafeMath for uint256;
// ERC20 basic token contract being held
IERC20 private _token;
// The following info can only been updated by the crowdsale contract.
// amount of tokens that each beneficiary deposits into this vault
mapping(address=>uint256) private _balances;
// what a vault should contain
uint256 private _totalBalance;
// timestamp of the possible update
uint256 private _updateTime;
// timestamp when token release is enabled
uint256 private _releaseTime;
// if the _releaseTime is effective
bool private _knownReleaseTime;
address private _crowdsale;
event Received(address indexed owner, uint256 value);
event Released(address indexed owner, uint256 value);
event ReleaseTimeUpdated(address indexed account, uint256 updateTime, uint256 releaseTime);
/**
* @notice When timing is correct.
*/
modifier readyToRelease {
require(_knownReleaseTime && (block.timestamp >= _releaseTime), "Not ready to release");
_;
}
/**
* @notice When timing is correct.
*/
modifier saleNotEnd {
require(!_knownReleaseTime || (block.timestamp < _updateTime), "Cannot modifiy anymore");
_;
}
/**
* @notice Only crowdsale contract could take actions
*/
modifier onlyCrowdsale {
require(msg.sender == _crowdsale, "The caller is not the crowdsale contract");
_;
}
/**
* @notice Create a vault
* @dev Upon the creation of the contract, the ownership should be transferred to the
* crowdsale contract.
* @param token The address of the token contract
* @param crowdsale The address of the crowdsale contract
* @param knownWhenToRelease If the release time is known at creation time
* @param updateTime The timestamp before which information is still updatable in this
* contract
* @param releaseTime The timestamp after which investors could claim their belongings.
*/
/* solhint-disable */
constructor(
IERC20 token,
address crowdsale,
bool knownWhenToRelease,
uint256 updateTime,
uint256 releaseTime
)
public
onlyValidAddress(crowdsale)
isSenderNot(crowdsale)
{
_token = token;
_crowdsale = crowdsale;
_knownReleaseTime = knownWhenToRelease;
_updateTime = updateTime;
_releaseTime = releaseTime;
}
/* solhint-enable */
/** OVERRIDE
* @notice Let token owner to get the other tokens accidentally sent to this token address.
* @dev This function allows the contract to hold certain amount of IvoToken, of
* which the token address is defined in the constructor of the contract.
* @param tokenToBeRecovered address of the token to be recovered.
*/
function reclaimToken(IERC20 tokenToBeRecovered) external onlyOwner {
// only if the token is not the IVO token
uint256 balance = tokenToBeRecovered.balanceOf(address(this));
if (tokenToBeRecovered == _token) {
tokenToBeRecovered.safeTransfer(owner(), balance.sub(_totalBalance));
} else {
tokenToBeRecovered.safeTransfer(owner(), balance);
}
}
/**
* @notice Give back the balance of a beneficiary
* @param beneficiary The address of the beneficiary
* @return The balance of the beneficiary
*/
function balanceOf(address beneficiary) public view returns (uint256) {
return _balances[beneficiary];
}
/**
* @return the total amount of token being held in this vault
*/
function totalBalance() public view returns(uint256) {
return _totalBalance;
}
/**
* @return the token being held.
*/
function token() public view returns(IERC20) {
return _token;
}
/**
* @return the address of the crowdsale contract.
*/
function crowdsale() public view returns(address) {
return _crowdsale;
}
/**
* @return the time when the tokens are released.
*/
function releaseTime() public view returns(uint256) {
return _releaseTime;
}
/**
* @return the time before when the update is still acceptable.
*/
function updateTime() public view returns(uint256) {
return _updateTime;
}
/**
* @return the if the release time is known.
*/
function knownReleaseTime() public view returns(bool) {
return _knownReleaseTime;
}
/**
* @notice function called by either crowdsale contract or the token minter, depending
* on the type of the vault.
* @param beneficiary The actual token owner once it gets released
* @param value The amount of token associated to the beneficiary
*/
function receiveFor(address beneficiary, uint256 value)
public
saleNotEnd
onlyManager
{
_receiveFor(beneficiary, value);
}
/**
* @notice Transfers tokens held by the vault to beneficiary.
*/
function release() public readyToRelease {
_releaseFor(msg.sender, _balances[msg.sender]);
}
/**
* @notice Transfers tokens held by the vault to beneficiary, who is differnt from the
* msg.sender
* @param account The account address for whom the vault releases the IVO token.
*/
function releaseFor(address account) public readyToRelease {
_releaseFor(account, _balances[account]);
}
/**
* @notice Disable the update release time function
* @dev By default this functionality is banned, only certain vaults can
* updateReleaseTime and thus override this function.
*/
// solhint-disable-next-line
function updateReleaseTime(uint256 newTime) public {
revert("cannot update release time");
}
/**
* @notice The vault receives tokens on behalf of an account
* @param account The account address
* @param value The acount received
*/
function _receiveFor(address account, uint256 value) internal {
_balances[account] = _balances[account].add(value);
_totalBalance = _totalBalance.add(value);
emit Received(account, value);
}
/**
* @notice The vault releases tokens on behalf of an account
* @param account The account address
* @param amount The amount of token to be released
*/
function _releaseFor(address account, uint256 amount) internal {
require(amount > 0 && _balances[account] >= amount, "the account does not have enough amount");
_balances[account] = _balances[account].sub(amount);
_totalBalance = _totalBalance.sub(amount);
_token.safeTransfer(account, amount);
emit Released(account, amount);
}
/**
* @notice Only updatable when this release time was not set up previously
* @param newUpdateTime The timestamp before which information is still updatable in this vault
* @param newReleaseTime The timestamp before which token cannot be retrieved.
*/
function _updateReleaseTime(uint256 newUpdateTime, uint256 newReleaseTime)
internal
onlyOnce(_knownReleaseTime)
{
_knownReleaseTime = true;
_updateTime = newUpdateTime;
_releaseTime = newReleaseTime;
emit ReleaseTimeUpdated(msg.sender, newUpdateTime, newReleaseTime);
}
/**
* @notice Directly transfer the ownership to an address of Invao managing team
* This owner does not necessarily be the manage of the contract.
* @param newOwner The address of the new owner of the contract
*/
function roleSetup(address newOwner) internal {
_removeManager(msg.sender);
transferOwnership(newOwner);
}
}
// File: contracts/crowdsale/IIvoCrowdsale.sol
/**
* @title Interface of IVO Crowdale
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract IIvoCrowdsale {
/**
* @return The starting time of the crowdsale.
*/
function startingTime() public view returns(uint256);
}
// File: contracts/vault/AdvisorsVesting.sol
/**
* @title Vesting contract for advisors
* @author Validity Labs AG <[email protected]>
*/
// solhint-disable-next-line compiler-fixed, compiler-gt-0_5
pragma solidity ^0.5.0;
contract AdvisorsVesting is BasicVault {
using SafeERC20 for IERC20;
using SafeMath for uint256;
/*** PRE-DEPLOYMENT CONFIGURED CONSTANTS */
uint256 private constant ALLOCATION = 1500000 ether;
// 180 days after the crowdsale starts
uint256 private constant CLIFF_DURATION = 180 days;
// A default time, doesn't really matter
uint256 private constant DEFAULT_RELEASETIME = 9999 days;
// 360 days of vesting duration
uint256 private constant VESTING_DURATION = 360 days;
mapping(address=>uint256) private _initialBalances;
/**
* @notice Create a vesting vault for investors
* @dev Upon the creation of the contract, the ownership should be transferred to the
* crowdsale contract.
* @param token The address of the token contract
* @param crowdsale The address of the crowdsale contract
* @param updateTime The timestamp before which information is still updatable in this
* contract
* @param newOwner The address of the new owner of this contract.
*/
/* solhint-disable */
constructor(
IERC20 token,
address crowdsale,
uint256 updateTime,
address newOwner
)
public
BasicVault(token, crowdsale, true, updateTime, updateTime.add(CLIFF_DURATION))
{
require(updateTime == IIvoCrowdsale(crowdsale).startingTime(), "Update time not correct");
roleSetup(newOwner);
}
/* solhint-enable */
/**
* @notice Check if the maximum allocation has been reached
* @dev Revert if the allocated amount has been reached/exceeded
* @param additional The amount of token to be added.
*/
modifier capNotReached(uint256 additional) {
require(totalBalance().add(additional) <= ALLOCATION, "exceed the maximum allocation");
_;
}
/**
* @notice Add advisors in batch.
* @param amounts Amounts of token purchased
* @param beneficiaries Recipients of the token purchase
*/
// solhint-disable-next-line
function batchReceiveFor(address[] calldata beneficiaries, uint256[] calldata amounts)
external
{
uint256 length = amounts.length;
require(beneficiaries.length == length, "length !=");
require(length <= 256, "To long, please consider shorten the array");
for (uint256 i = 0; i < length; i++) {
receiveFor(beneficiaries[i], amounts[i]);
}
}
/** OVERRIDE
* @notice Let token owner to get the other tokens accidentally sent to this token address.
* @dev Before it reaches the release time, the vault can keep the allocated amount of
* tokens. Since INVAO managers could still add SAFT investors during the SEED-ROUND,
* the allocated amount of tokens stays in the SAFT vault during that period. Once the
* SEED round ends, this vault can only hold max. totalBalance.
* @param tokenToBeRecovered address of the token to be recovered.
*/
function reclaimToken(IERC20 tokenToBeRecovered) external onlyOwner {
// only if the token is not the IVO token
uint256 balance = tokenToBeRecovered.balanceOf(address(this));
if (tokenToBeRecovered == this.token()) {
if (block.timestamp <= this.updateTime()) {
tokenToBeRecovered.safeTransfer(owner(), balance.sub(ALLOCATION));
} else {
tokenToBeRecovered.safeTransfer(owner(), balance.sub(this.totalBalance()));
}
} else {
tokenToBeRecovered.safeTransfer(owner(), balance);
}
}
/**
* @notice Give back the balance of a beneficiary before vesting
* @param beneficiary The address of the beneficiary
* @return The balance of the beneficiary
*/
function initialBalanceOf(address beneficiary) public view returns (uint256) {
return _initialBalances[beneficiary];
}
/**
* @notice Adding investors to the vesting contract
* @dev An INVAO manager can do so before the SEED-ROUND sale ends
* (a.k.a the start of the crowdsale)
* @param beneficiary The actual token owner once it gets released
* @param value The amount of token associated to the beneficiary
*/
function receiveFor(address beneficiary, uint256 value)
public
capNotReached(value)
{
_initialBalances[beneficiary] = _initialBalances[beneficiary].add(value);
super.receiveFor(beneficiary, value);
}
/** OVERRIDE
* @notice Transfers tokens held by the vault to beneficiary.
*/
function release() public readyToRelease {
uint256 releasedAmount = getAmountToBeReleased(msg.sender);
_releaseFor(msg.sender, releasedAmount);
}
/** OVERRIDE
* @notice Transfers tokens held by the vault to beneficiary, who is differnt from the
* msg.sender
* @param account The account address for whom the vault releases the IVO token.
*/
function releaseFor(address account) public readyToRelease {
uint256 releasedAmount = getAmountToBeReleased(account);
_releaseFor(account, releasedAmount);
}
/**
* @notice Directly transfer the ownership to an address of Invao managing team
* @dev This new owner is also the manage of the contract.
* @param newOwner The address of the contract's new owner
*/
function roleSetup(address newOwner) internal {
addManager(newOwner);
super.roleSetup(newOwner);
}
/**
* @notice calculate the amount of tokens ready to be released
* @param account The address of the advisor.
* @return The amount to be released per account at the moment of calling
*/
function getAmountToBeReleased(address account) internal view returns (uint256) {
uint256 timeFromUpdate = block.timestamp.sub(updateTime());
if (timeFromUpdate < VESTING_DURATION) {
return _initialBalances[account].mul(timeFromUpdate).div(VESTING_DURATION)
.sub(_initialBalances[account].sub(balanceOf(account)));
} else {
return balanceOf(account);
}
}
} | return the total amount of token being held in this vault/ | function totalBalance() public view returns(uint256) {
return _totalBalance;
}
| 12,574,897 |
pragma solidity >0.5.4;
import "@daostack/arc/contracts/controller/Avatar.sol";
import "./SchemeGuard.sol";
import "../../identity/Identity.sol";
import "../../identity/IdentityGuard.sol";
/**
* @dev Contract for letting scheme add itself to identity
* to allow transferring GoodDollar without paying fees
* and transfer ownership to Avatar
*/
contract FeelessScheme is SchemeGuard, IdentityGuard {
/* @dev Constructor
* @param _identity The identity contract
* @param _avatar The avatar of the DAO
*/
constructor(Identity _identity, Avatar _avatar)
public
SchemeGuard(_avatar)
IdentityGuard(_identity)
{}
/* @dev Internal function to add contract to identity.
* Can only be called if scheme is registered.
*/
function addRights() internal onlyRegistered {
controller.genericCall(
address(identity),
abi.encodeWithSignature("addContract(address)", address(this)),
avatar,
0
);
transferOwnership(address(avatar));
}
/* @dev Internal function to remove contract from identity.
* Can only be called if scheme is registered.
*/
function removeRights() internal onlyRegistered {
controller.genericCall(
address(identity),
abi.encodeWithSignature("removeContract(address)", address(this)),
avatar,
0
);
}
}
| Internal function to add contract to identity. Can only be called if scheme is registered./ | function addRights() internal onlyRegistered {
controller.genericCall(
address(identity),
abi.encodeWithSignature("addContract(address)", address(this)),
avatar,
0
);
transferOwnership(address(avatar));
}
| 12,962,703 |
pragma solidity ^0.4.24;
/**
* @title LotteryInterface
*/
interface LotteryInterface {
function claimReward(address playerAddress, uint256 tokenAmount) external returns (bool);
function calculateLotteryContributionPercentage() external constant returns (uint256);
function getNumLottery() external constant returns (uint256);
function isActive() external constant returns (bool);
function getCurrentTicketMultiplierHonor() external constant returns (uint256);
function getCurrentLotteryTargetBalance() external constant returns (uint256, uint256);
}
/**
* @title SettingInterface
*/
interface SettingInterface {
function uintSettings(bytes32 name) external constant returns (uint256);
function boolSettings(bytes32 name) external constant returns (bool);
function isActive() external constant returns (bool);
function canBet(uint256 rewardValue, uint256 betValue, uint256 playerNumber, uint256 houseEdge) external constant returns (bool);
function isExchangeAllowed(address playerAddress, uint256 tokenAmount) external constant returns (bool);
/******************************************/
/* SPINWIN ONLY METHODS */
/******************************************/
function spinwinSetUintSetting(bytes32 name, uint256 value) external;
function spinwinIncrementUintSetting(bytes32 name) external;
function spinwinSetBoolSetting(bytes32 name, bool value) external;
function spinwinAddFunds(uint256 amount) external;
function spinwinUpdateTokenToWeiExchangeRate() external;
function spinwinRollDice(uint256 betValue) external;
function spinwinUpdateWinMetric(uint256 playerProfit) external;
function spinwinUpdateLoseMetric(uint256 betValue, uint256 tokenRewardValue) external;
function spinwinUpdateLotteryContributionMetric(uint256 lotteryContribution) external;
function spinwinUpdateExchangeMetric(uint256 exchangeAmount) external;
/******************************************/
/* SPINLOTTERY ONLY METHODS */
/******************************************/
function spinlotterySetUintSetting(bytes32 name, uint256 value) external;
function spinlotteryIncrementUintSetting(bytes32 name) external;
function spinlotterySetBoolSetting(bytes32 name, bool value) external;
function spinlotteryUpdateTokenToWeiExchangeRate() external;
function spinlotterySetMinBankroll(uint256 _minBankroll) external returns (bool);
}
/**
* @title TokenInterface
*/
interface TokenInterface {
function getTotalSupply() external constant returns (uint256);
function getBalanceOf(address account) external constant returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
function approve(address _spender, uint256 _value) external returns (bool success);
function approveAndCall(address _spender, uint256 _value, bytes _extraData) external returns (bool success);
function burn(uint256 _value) external returns (bool success);
function burnFrom(address _from, uint256 _value) external returns (bool success);
function mintTransfer(address _to, uint _value) external returns (bool);
function burnAt(address _at, uint _value) external returns (bool);
}
// https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
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 generates a public event on the blockchain that will notify clients
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
/**
* 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 returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in 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(_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 in 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;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in 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) {
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;
}
}
contract developed {
address public developer;
/**
* Constructor
*/
constructor() public {
developer = msg.sender;
}
/**
* @dev Checks only developer address is calling
*/
modifier onlyDeveloper {
require(msg.sender == developer);
_;
}
/**
* @dev Allows developer to switch developer address
* @param _developer The new developer address to be set
*/
function changeDeveloper(address _developer) public onlyDeveloper {
developer = _developer;
}
/**
* @dev Allows developer to withdraw ERC20 Token
*/
function withdrawToken(address tokenContractAddress) public onlyDeveloper {
TokenERC20 _token = TokenERC20(tokenContractAddress);
if (_token.balanceOf(this) > 0) {
_token.transfer(developer, _token.balanceOf(this));
}
}
}
contract escaped {
address public escapeActivator;
/**
* Constructor
*/
constructor() public {
escapeActivator = 0xB15C54b4B9819925Cd2A7eE3079544402Ac33cEe;
}
/**
* @dev Checks only escapeActivator address is calling
*/
modifier onlyEscapeActivator {
require(msg.sender == escapeActivator);
_;
}
/**
* @dev Allows escapeActivator to switch escapeActivator address
* @param _escapeActivator The new escapeActivator address to be set
*/
function changeAddress(address _escapeActivator) public onlyEscapeActivator {
escapeActivator = _escapeActivator;
}
}
/**
* @title SpinLottery
*/
contract SpinLottery is developed, escaped, LotteryInterface {
using SafeMath for uint256;
/**
* @dev Game variables
*/
address public owner;
address public spinwinAddress;
bool public contractKilled;
bool public gamePaused;
uint256 public numLottery;
uint256 public lotteryTarget;
uint256 public totalBankroll;
uint256 public totalBuyTickets;
uint256 public totalTokenWagered;
uint256 public lotteryTargetIncreasePercentage;
uint256 public lastBlockNumber;
uint256 public lastLotteryTotalBlocks;
uint256 public currentTicketMultiplier;
uint256 public currentTicketMultiplierHonor;
uint256 public currentTicketMultiplierBlockNumber;
uint256 public maxBlockSecurityCount;
uint256 public blockSecurityCount;
uint256 public currentTicketMultiplierBlockSecurityCount;
uint256 public ticketMultiplierModifier;
uint256 public avgLotteryHours; // Average hours needed to complete a lottery
uint256 public totalLotteryHours; // Total accumulative lottery hours
uint256 public minBankrollDecreaseRate; // The rate to use to decrease spinwin's min bankroll
uint256 public minBankrollIncreaseRate; // The rate to use to increase spinwin's min bankroll
uint256 public lotteryContributionPercentageModifier; // The lottery contribution percentage modifier, used to calculate lottery contribution percentage
uint256 public rateConfidenceModifier; // The rate confidence modifier, used to calculate lottery contribution percentage
uint256 public currentLotteryPaceModifier; // The current lottery pace modifier, used to calculate lottery contribution percentage
uint256 public maxLotteryContributionPercentage; // The maximum percent that we can contribute to the lottery
uint256 constant public PERCENTAGE_DIVISOR = 1000000;
uint256 constant public TWO_DECIMALS = 100; // To account for calculation with 2 decimal points
uint256 constant public CURRENCY_DIVISOR = 10 ** 18;
uint256 public startLotteryRewardPercentage; // The percentage of blocks that we want to reward player for starting next lottery
uint256 internal lotteryContribution;
uint256 internal carryOverContribution;
uint256 public minRewardBlocksAmount;
TokenInterface internal _spintoken;
SettingInterface internal _setting;
struct Lottery {
uint256 lotteryTarget;
uint256 bankroll;
uint256 tokenWagered;
uint256 lotteryResult;
uint256 totalBlocks;
uint256 totalBlocksRewarded;
uint256 startTimestamp;
uint256 endTimestamp;
address winnerPlayerAddress;
bool ended;
bool cashedOut;
}
struct Ticket {
bytes32 ticketId;
uint256 numLottery;
address playerAddress;
uint256 minNumber;
uint256 maxNumber;
bool claimed;
}
mapping (uint256 => Lottery) public lotteries;
mapping (bytes32 => Ticket) public tickets;
mapping (uint256 => mapping (address => uint256)) public playerTokenWagered;
mapping (address => uint256) public playerPendingWithdrawals;
mapping (uint256 => mapping (address => uint256)) public playerTotalBlocks;
mapping (uint256 => mapping (address => uint256)) public playerTotalBlocksRewarded;
/**
* @dev Log when new lottery is created
*/
event LogCreateLottery(uint256 indexed numLottery, uint256 lotteryBankrollGoal);
/**
* @dev Log when lottery is ended
*/
event LogEndLottery(uint256 indexed numLottery, uint256 lotteryResult);
/**
* @dev Log when spinwin adds some funds
*/
event LogAddBankRoll(uint256 indexed numLottery, uint256 amount);
/**
* @dev Log when player buys ticket
* Ticket type
* 1 = normal purchase
* 2 = Spinwin Reward
* 3 = Start Lottery Reward
*/
event LogBuyTicket(uint256 indexed numLottery, bytes32 indexed ticketId, address indexed playerAddress, uint256 tokenAmount, uint256 ticketMultiplier, uint256 minNumber, uint256 maxNumber, uint256 ticketType);
/**
* @dev Log when player claims lotto ticket
*
* Status:
* 0: Lose
* 1: Win
* 2: Win + Failed send
*/
event LogClaimTicket(uint256 indexed numLottery, bytes32 indexed ticketId, address indexed playerAddress, uint256 lotteryResult, uint256 playerMinNumber, uint256 playerMaxNumber, uint256 winningReward, uint256 status);
/**
* @dev Log when player withdraw balance
*
* Status:
* 0 = failed
* 1 = success
*/
event LogPlayerWithdrawBalance(address indexed playerAddress, uint256 withdrawAmount, uint256 status);
/**
* @dev Log when current ticket multiplier is updated
*/
event LogUpdateCurrentTicketMultiplier(uint256 currentTicketMultiplier, uint256 currentTicketMultiplierBlockNumber);
/**
* @dev Log when developer set contract to emergency mode
*/
event LogEscapeHatch();
/**
* Constructor
*/
constructor(address _settingAddress, address _tokenAddress, address _spinwinAddress) public {
_setting = SettingInterface(_settingAddress);
_spintoken = TokenInterface(_tokenAddress);
spinwinAddress = _spinwinAddress;
lastLotteryTotalBlocks = 100 * CURRENCY_DIVISOR; // init last lottery total blocks (10^20 blocks)
devSetLotteryTargetIncreasePercentage(150000); // init lottery target increase percentage (15%);
devSetMaxBlockSecurityCount(256); // init max block security count (256)
devSetBlockSecurityCount(3); // init block security count (3)
devSetCurrentTicketMultiplierBlockSecurityCount(3); // init current ticket multiplier block security count (3)
devSetTicketMultiplierModifier(300); // init ticket multiplier modifier (3)
devSetMinBankrollDecreaseRate(80); // init min bankroll decrease rate (0.8)
devSetMinBankrollIncreaseRate(170); // init min bankroll increase rate (1.7)
devSetLotteryContributionPercentageModifier(10); // init lottery contribution percentage modifier (0.1)
devSetRateConfidenceModifier(200); // init rate confidence modifier (2)
devSetCurrentLotteryPaceModifier(200); // init current lottery pace modifier (2)
devSetStartLotteryRewardPercentage(10000); // init start lottery reward percentage (1%)
devSetMinRewardBlocksAmount(1); // init min reward blocks amount (1)
devSetMaxLotteryContributionPercentage(100); // init max lottery contribution percentage (1)
_createNewLottery(); // start lottery
}
/**
* @dev Checks if the contract is currently alive
*/
modifier contractIsAlive {
require(contractKilled == false);
_;
}
/**
* @dev Checks if the game is currently active
*/
modifier gameIsActive {
require(gamePaused == false);
_;
}
/**
* @dev Checks only spinwin address is calling
*/
modifier onlySpinwin {
require(msg.sender == spinwinAddress);
_;
}
/******************************************/
/* DEVELOPER ONLY METHODS */
/******************************************/
/**
* @dev Allows developer to set lotteryTarget
* @param _lotteryTarget The new lottery target value to be set
*/
function devSetLotteryTarget(uint256 _lotteryTarget) public onlyDeveloper {
require (_lotteryTarget >= 0);
lotteryTarget = _lotteryTarget;
Lottery storage _lottery = lotteries[numLottery];
_lottery.lotteryTarget = lotteryTarget;
}
/**
* @dev Allows developer to set lottery target increase percentage
* @param _lotteryTargetIncreasePercentage The new value to be set
* 1% = 10000
*/
function devSetLotteryTargetIncreasePercentage(uint256 _lotteryTargetIncreasePercentage) public onlyDeveloper {
lotteryTargetIncreasePercentage = _lotteryTargetIncreasePercentage;
}
/**
* @dev Allows developer to set block security count
* @param _blockSecurityCount The new value to be set
*/
function devSetBlockSecurityCount(uint256 _blockSecurityCount) public onlyDeveloper {
require (_blockSecurityCount > 0);
blockSecurityCount = _blockSecurityCount;
}
/**
* @dev Allows developer to set max block security count
* @param _maxBlockSecurityCount The new value to be set
*/
function devSetMaxBlockSecurityCount(uint256 _maxBlockSecurityCount) public onlyDeveloper {
require (_maxBlockSecurityCount > 0);
maxBlockSecurityCount = _maxBlockSecurityCount;
}
/**
* @dev Allows developer to set current ticket multiplier block security count
* @param _currentTicketMultiplierBlockSecurityCount The new value to be set
*/
function devSetCurrentTicketMultiplierBlockSecurityCount(uint256 _currentTicketMultiplierBlockSecurityCount) public onlyDeveloper {
require (_currentTicketMultiplierBlockSecurityCount > 0);
currentTicketMultiplierBlockSecurityCount = _currentTicketMultiplierBlockSecurityCount;
}
/**
* @dev Allows developer to set ticket multiplier modifier
* @param _ticketMultiplierModifier The new value to be set (in two decimals)
* 1 = 100
*/
function devSetTicketMultiplierModifier(uint256 _ticketMultiplierModifier) public onlyDeveloper {
require (_ticketMultiplierModifier > 0);
ticketMultiplierModifier = _ticketMultiplierModifier;
}
/**
* @dev Allows developer to set min bankroll decrease rate
* @param _minBankrollDecreaseRate The new value to be set (in two decimals)
* 1 = 100
*/
function devSetMinBankrollDecreaseRate(uint256 _minBankrollDecreaseRate) public onlyDeveloper {
require (_minBankrollDecreaseRate >= 0);
minBankrollDecreaseRate = _minBankrollDecreaseRate;
}
/**
* @dev Allows developer to set min bankroll increase rate
* @param _minBankrollIncreaseRate The new value to be set (in two decimals)
* 1 = 100
*/
function devSetMinBankrollIncreaseRate(uint256 _minBankrollIncreaseRate) public onlyDeveloper {
require (_minBankrollIncreaseRate > minBankrollDecreaseRate);
minBankrollIncreaseRate = _minBankrollIncreaseRate;
}
/**
* @dev Allows developer to set lottery contribution percentage modifier
* @param _lotteryContributionPercentageModifier The new value to be set (in two decimals)
* 1 = 100
*/
function devSetLotteryContributionPercentageModifier(uint256 _lotteryContributionPercentageModifier) public onlyDeveloper {
lotteryContributionPercentageModifier = _lotteryContributionPercentageModifier;
}
/**
* @dev Allows developer to set rate confidence modifier
* @param _rateConfidenceModifier The new value to be set (in two decimals)
* 1 = 100
*/
function devSetRateConfidenceModifier(uint256 _rateConfidenceModifier) public onlyDeveloper {
rateConfidenceModifier = _rateConfidenceModifier;
}
/**
* @dev Allows developer to set current lottery pace modifier
* @param _currentLotteryPaceModifier The new value to be set (in two decimals)
* 1 = 100
*/
function devSetCurrentLotteryPaceModifier(uint256 _currentLotteryPaceModifier) public onlyDeveloper {
currentLotteryPaceModifier = _currentLotteryPaceModifier;
}
/**
* @dev Allows developer to pause the game
* @param paused The new paused value to be set
*/
function devPauseGame(bool paused) public onlyDeveloper {
gamePaused = paused;
}
/**
* @dev Allows developer to start new lottery (only when current lottery is ended)
* @return Return true if success
*/
function devStartLottery() public onlyDeveloper returns (bool) {
Lottery memory _currentLottery = lotteries[numLottery];
require (_currentLottery.ended == true);
_createNewLottery();
return true;
}
/**
* @dev Allows developer to end current lottery
* @param _startNextLottery Boolean value whether or not we should start next lottery
* @return Return true if success
*/
function devEndLottery(bool _startNextLottery) public onlyDeveloper returns (bool) {
_endLottery();
if (_startNextLottery) {
_createNewLottery();
}
return true;
}
/**
* @dev Allows developer to set start lottery reward percentage
* @param _startLotteryRewardPercentage The new value to be set
* 1% = 10000
*/
function devSetStartLotteryRewardPercentage(uint256 _startLotteryRewardPercentage) public onlyDeveloper {
startLotteryRewardPercentage = _startLotteryRewardPercentage;
}
/**
* @dev Allows developer to set start lottery min reward blocks amount
* @param _minRewardBlocksAmount The new value to be set
*/
function devSetMinRewardBlocksAmount(uint256 _minRewardBlocksAmount) public onlyDeveloper {
minRewardBlocksAmount = _minRewardBlocksAmount;
}
/**
* @dev Allows developer to set max lottery contribution percentage
* @param _maxLotteryContributionPercentage The new value to be set
* 1 = 100
*/
function devSetMaxLotteryContributionPercentage(uint256 _maxLotteryContributionPercentage) public onlyDeveloper {
maxLotteryContributionPercentage = _maxLotteryContributionPercentage;
}
/******************************************/
/* ESCAPE ACTIVATOR ONLY METHODS */
/******************************************/
/**
* @dev Allows escapeActivator to trigger emergency mode. Will end current lottery and stop the game.
* @return Return true if success
*/
function escapeHatch() public
onlyEscapeActivator
contractIsAlive
returns (bool) {
contractKilled = true;
_endLottery();
emit LogEscapeHatch();
return true;
}
/******************************************/
/* SPINWIN ONLY METHODS */
/******************************************/
/**
* @dev Allows spinwin to buy ticket on behalf of playerAddress as part of claiming spinwin reward
* @param playerAddress The player address to be rewarded
* @param tokenAmount The amount of token to be spent
* @return The ticket ID
*/
function claimReward(address playerAddress, uint256 tokenAmount) public
contractIsAlive
gameIsActive
onlySpinwin
returns (bool) {
return _buyTicket(playerAddress, tokenAmount, 2);
}
/******************************************/
/* PUBLIC METHODS */
/******************************************/
/**
* @dev Add funds to the contract
* If the bankroll goal is reached, we want to end current lottery and start new lottery.
*/
function () payable public
contractIsAlive
gameIsActive {
// Update the last block number
lastBlockNumber = block.number;
Lottery storage _currentLottery = lotteries[numLottery];
if (_currentLottery.bankroll.add(msg.value) > lotteryTarget) {
lotteryContribution = lotteryTarget.sub(_currentLottery.bankroll);
carryOverContribution = carryOverContribution.add(msg.value.sub(lotteryContribution));
} else {
lotteryContribution = msg.value;
}
// Safely update bankroll
if (lotteryContribution > 0) {
_currentLottery.bankroll = _currentLottery.bankroll.add(lotteryContribution);
totalBankroll = totalBankroll.add(lotteryContribution);
emit LogAddBankRoll(numLottery, lotteryContribution);
}
}
/**
* @dev Player buys lottery ticket
* @param tokenAmount The amount of token to spend
* @return Return the ticket ID
*/
function buyTicket(uint tokenAmount) public
contractIsAlive
gameIsActive
returns (bool) {
require (_spintoken.burnAt(msg.sender, tokenAmount));
return _buyTicket(msg.sender, tokenAmount, 1);
}
/**
* @dev Player claims lottery ticket
* @param ticketId The ticket ID to be claimed
* @return Return true if success
*/
function claimTicket(bytes32 ticketId) public
gameIsActive
returns (bool) {
Ticket storage _ticket = tickets[ticketId];
require(_ticket.claimed == false && _ticket.playerAddress == msg.sender);
Lottery storage _lottery = lotteries[_ticket.numLottery];
require(_lottery.ended == true && _lottery.cashedOut == false && _lottery.bankroll > 0 && _lottery.totalBlocks.add(_lottery.totalBlocksRewarded) > 0 && _lottery.lotteryResult > 0);
// Mark this ticket as claimed
_ticket.claimed = true;
uint256 status = 0; // status = failed
if (_lottery.lotteryResult >= _ticket.minNumber && _lottery.lotteryResult <= _ticket.maxNumber) {
uint256 lotteryReward = _lottery.bankroll;
// Check if contract has enough bankroll to payout
require(totalBankroll >= lotteryReward);
// Safely adjust totalBankroll
totalBankroll = totalBankroll.sub(lotteryReward);
_lottery.bankroll = 0;
_lottery.winnerPlayerAddress = msg.sender;
_lottery.cashedOut = true;
if (!msg.sender.send(lotteryReward)) {
status = 2; // status = win + failed send
// If send failed, let player withdraw via playerWithdrawPendingTransactions
playerPendingWithdrawals[msg.sender] = playerPendingWithdrawals[msg.sender].add(lotteryReward);
} else {
status = 1; // status = win
}
}
emit LogClaimTicket(_ticket.numLottery, ticketId, msg.sender, _lottery.lotteryResult, _ticket.minNumber, _ticket.maxNumber, lotteryReward, status);
return true;
}
/**
* @dev Allows player to withdraw balance in case of a failed win send
* @return Return true if success
*/
function playerWithdrawPendingTransactions() public
gameIsActive {
require(playerPendingWithdrawals[msg.sender] > 0);
uint256 withdrawAmount = playerPendingWithdrawals[msg.sender];
playerPendingWithdrawals[msg.sender] = 0;
// External call to untrusted contract
uint256 status = 1; // status = success
if (!msg.sender.send(withdrawAmount)) {
status = 0; // status = failed
/*
* If send failed, revert playerPendingWithdrawals[msg.sender] = 0
* so that player can try to withdraw again later
*/
playerPendingWithdrawals[msg.sender] = withdrawAmount;
}
emit LogPlayerWithdrawBalance(msg.sender, withdrawAmount, status);
}
/**
* @dev Calculates number of blocks the player will get when he/she buys the lottery ticket
* based on player's entered token amount and current multiplier honor
* @return ticketMultiplier The ticket multiplier during this transaction
* @return numBlocks The lotto block count for this ticket
*/
function calculateNumBlocks(uint256 tokenAmount) public constant returns (uint256 ticketMultiplier, uint256 numBlocks) {
return (currentTicketMultiplierHonor, currentTicketMultiplierHonor.mul(tokenAmount).div(TWO_DECIMALS));
}
/**
* @dev Get current num lottery
* @return Current num lottery
*/
function getNumLottery() public constant returns (uint256) {
return numLottery;
}
/**
* @dev Check if contract is active
* @return Current state of contract
*/
function isActive() public constant returns (bool) {
if (gamePaused == true || contractKilled == true) {
return false;
} else {
return true;
}
}
/**
* @dev Determines the lottery contribution percentage
* @return lotteryContributionPercentage (in two decimals)
*/
function calculateLotteryContributionPercentage() public
contractIsAlive
gameIsActive
constant returns (uint256) {
Lottery memory _currentLottery = lotteries[numLottery];
uint256 currentTotalLotteryHours = _getHoursBetween(_currentLottery.startTimestamp, now);
uint256 currentWeiToLotteryRate = 0;
// To prevent division by 0
if (currentTotalLotteryHours > 0) {
/*
* currentWeiToLotteryRate = _currentLottery.bankroll / currentTotalLotteryHours;
* But since we need to account for decimal points
* currentWeiToLotteryRate = (_currentLottery.bankroll * TWO_DECIMALS)/currentTotalLotteryHours;
* currentWeiToLotteryRate needs to be divided by TWO_DECIMALS later on
*/
currentWeiToLotteryRate = (_currentLottery.bankroll.mul(TWO_DECIMALS)).div(currentTotalLotteryHours);
}
uint256 predictedCurrentLotteryHours = currentTotalLotteryHours;
// To prevent division by 0
if (currentWeiToLotteryRate > 0) {
/*
* predictedCurrentLotteryHours = currentTotalLotteryHours + ((lotteryTarget - _currentLottery.bankroll)/currentWeiToLotteryRate);
* Let temp = (lotteryTarget - _currentLottery.bankroll)/currentWeiToLotteryRate;
* Since we need to account for decimal points
* temp = ((lotteryTarget - _currentLottery.bankroll)*TWO_DECIMALS)/currentWeiToLotteryRate;
* But currentWeiToLotteryRate is already in decimals
* temp = ((lotteryTarget - _currentLottery.bankroll)*TWO_DECIMALS)/(currentWeiToLotteryRate/TWO_DECIMALS);
* temp = ((lotteryTarget - _currentLottery.bankroll)*TWO_DECIMALS*TWO_DECIMALS)/currentWeiToLotteryRate;
* predictedCurrentLotteryHours = currentTotalLotteryHours + (temp/TWO_DECIMALS);
*/
uint256 temp = (lotteryTarget.sub(_currentLottery.bankroll)).mul(TWO_DECIMALS).mul(TWO_DECIMALS).div(currentWeiToLotteryRate);
predictedCurrentLotteryHours = currentTotalLotteryHours.add(temp.div(TWO_DECIMALS));
}
uint256 currentLotteryPace = 0;
// To prevent division by 0
if (avgLotteryHours > 0) {
/*
* currentLotteryPace = predictedCurrentLotteryHours/avgLotteryHours;
* But since we need to account for decimal points
* currentLotteryPace = (predictedCurrentLotteryHours*TWO_DECIMALS)/avgLotteryHours;
* But avgLotteryHours is already in decimals so we need to divide it by TWO_DECIMALS as well
* currentLotteryPace = (predictedCurrentLotteryHours*TWO_DECIMALS)/(avgLotteryHours/TWO_DECIMALS);
* OR
* currentLotteryPace = (predictedCurrentLotteryHours*TWO_DECIMALS*TWO_DECIMALS)/avgLotteryHours;
* currentLotteryPace needs to be divided by TWO_DECIMALS later on
*/
currentLotteryPace = (predictedCurrentLotteryHours.mul(TWO_DECIMALS).mul(TWO_DECIMALS)).div(avgLotteryHours);
}
uint256 percentageOverTarget = 0;
// To prevent division by 0
if (_setting.uintSettings('minBankroll') > 0) {
/*
* percentageOverTarget = _spinwin.contractBalance() / _spinwin.minBankroll();
* But since we need to account for decimal points
* percentageOverTarget = (_spinwin.contractBalance()*TWO_DECIMALS) / _spinwin.minBankroll();
* percentageOverTarget needs to be divided by TWO_DECIMALS later on
*/
percentageOverTarget = (_setting.uintSettings('contractBalance').mul(TWO_DECIMALS)).div(_setting.uintSettings('minBankroll'));
}
currentTotalLotteryHours = currentTotalLotteryHours.mul(TWO_DECIMALS); // So that it has two decimals
uint256 rateConfidence = 0;
// To prevent division by 0
if (avgLotteryHours.add(currentTotalLotteryHours) > 0) {
/*
* rateConfidence = currentTotalLotteryHours / (avgLotteryHours + currentTotalLotteryHours);
* But since we need to account for decimal points
* rateConfidence = (currentTotalLotteryHours*TWO_DECIMALS) / (avgLotteryHours + currentTotalLotteryHours);
* rateConfidence needs to be divided by TWO_DECIMALS later on
*/
rateConfidence = currentTotalLotteryHours.mul(TWO_DECIMALS).div(avgLotteryHours.add(currentTotalLotteryHours));
}
/*
* lotteryContributionPercentage = 0.1 + (1-(1/percentageOverTarget))+(rateConfidence*2*(currentLotteryPace/(currentLotteryPace+2)))
* Replace the static number with modifier variables (that are already in decimals, so 0.1 is actually 10, 2 is actually 200)
* lotteryContributionPercentage = lotteryContributionPercentageModifier + (1-(1/percentageOverTarget)) + (rateConfidence*rateConfidenceModifier*(currentLotteryPace/(currentLotteryPace+currentLotteryPaceModifier)));
*
* Split to 3 sections
* lotteryContributionPercentage = calc1 + calc2 + calc3
* calc1 = lotteryContributionPercentageModifier
* calc2 = (1-(1/percentageOverTarget))
* calc3 = (rateConfidence*rateConfidenceModifier*(currentLotteryPace/(currentLotteryPace+currentLotteryPaceModifier)))
*/
uint256 lotteryContributionPercentage = lotteryContributionPercentageModifier;
/*
* calc2 = 1-(1/percentageOverTarget)
* Since percentageOverTarget is already in two decimals
* calc2 = 1-(1/(percentageOverTarget/TWO_DECIMALS))
* calc2 = 1-(TWO_DECIMALS/percentageOverTarget)
* mult TWO_DECIMALS/TWO_DECIMALS to calculate fraction
* calc2 = (TWO_DECIMALS-((TWO_DECIMALS*TWO_DECIMALS)/percentageOverTarget))/TWO_DECIMALS
* since lotteryContributionPercentage needs to be in decimals, we can take out the division by TWO_DECIMALS
* calc2 = TWO_DECIMALS-((TWO_DECIMALS*TWO_DECIMALS)/percentageOverTarget)
*/
// To prevent division by 0
if (percentageOverTarget > 0) {
lotteryContributionPercentage = lotteryContributionPercentage.add(TWO_DECIMALS.sub((TWO_DECIMALS.mul(TWO_DECIMALS)).div(percentageOverTarget)));
} else {
lotteryContributionPercentage = lotteryContributionPercentage.add(TWO_DECIMALS);
}
/*
* calc3 = rateConfidence*rateConfidenceModifier*(currentLotteryPace/(currentLotteryPace+currentLotteryPaceModifier))
* But since rateConfidence, rateConfidenceModifier are already in decimals, we need to divide them by TWO_DECIMALS
* calc3 = (rateConfidence/TWO_DECIMALS)*(rateConfidenceModifier/TWO_DECIMALS)*(currentLotteryPace/(currentLotteryPace+currentLotteryPaceModifier))
* since we need to account for decimal points, mult the numerator `currentLotteryPace` with TWO_DECIMALS
* calc3 = (rateConfidence/TWO_DECIMALS)*(rateConfidenceModifier/TWO_DECIMALS)*((currentLotteryPace*TWO_DECIMALS)/(currentLotteryPace+currentLotteryPaceModifier))
* OR
* calc3 = (rateConfidence*rateConfidenceModifier*currentLotteryPace)/(TWO_DECIMALS*(currentLotteryPace+currentLotteryPaceModifier))
*/
// To prevent division by 0
if (currentLotteryPace.add(currentLotteryPaceModifier) > 0) {
lotteryContributionPercentage = lotteryContributionPercentage.add((rateConfidence.mul(rateConfidenceModifier).mul(currentLotteryPace)).div(TWO_DECIMALS.mul(currentLotteryPace.add(currentLotteryPaceModifier))));
}
if (lotteryContributionPercentage > maxLotteryContributionPercentage) {
lotteryContributionPercentage = maxLotteryContributionPercentage;
}
return lotteryContributionPercentage;
}
/**
* @dev Allows player to start next lottery and reward player a percentage of last lottery total blocks
*/
function startNextLottery() public
contractIsAlive
gameIsActive {
Lottery storage _currentLottery = lotteries[numLottery];
require (_currentLottery.bankroll >= lotteryTarget && _currentLottery.totalBlocks.add(_currentLottery.totalBlocksRewarded) > 0);
uint256 startLotteryRewardBlocks = calculateStartLotteryRewardBlocks();
_endLottery();
_createNewLottery();
// If we have carry over contribution from prev contribution
// add it to the next lottery
if (carryOverContribution > 0) {
_currentLottery = lotteries[numLottery];
if (_currentLottery.bankroll.add(carryOverContribution) > lotteryTarget) {
lotteryContribution = lotteryTarget.sub(_currentLottery.bankroll);
carryOverContribution = carryOverContribution.sub(lotteryContribution);
} else {
lotteryContribution = carryOverContribution;
carryOverContribution = 0;
}
// Safely update bankroll
_currentLottery.bankroll = _currentLottery.bankroll.add(lotteryContribution);
totalBankroll = totalBankroll.add(lotteryContribution);
emit LogAddBankRoll(numLottery, lotteryContribution);
}
_buyTicket(msg.sender, startLotteryRewardBlocks, 3);
}
/**
* @dev Calculate start lottery reward blocks amount
* @return The reward blocks amount
*/
function calculateStartLotteryRewardBlocks() public constant returns (uint256) {
uint256 totalRewardBlocks = lastLotteryTotalBlocks.mul(startLotteryRewardPercentage).div(PERCENTAGE_DIVISOR);
if (totalRewardBlocks == 0) {
totalRewardBlocks = minRewardBlocksAmount;
}
return totalRewardBlocks;
}
/**
* @dev Get current ticket multiplier honor
* @return Current ticket multiplier honor
*/
function getCurrentTicketMultiplierHonor() public constant returns (uint256) {
return currentTicketMultiplierHonor;
}
/**
* @dev Get current lottery target and bankroll
* @return Current lottery target
* @return Current lottery bankroll
*/
function getCurrentLotteryTargetBalance() public constant returns (uint256, uint256) {
Lottery memory _lottery = lotteries[numLottery];
return (_lottery.lotteryTarget, _lottery.bankroll);
}
/*****************************************/
/* INTERNAL METHODS */
/******************************************/
/**
* @dev Creates new lottery
*/
function _createNewLottery() internal returns (bool) {
numLottery++;
lotteryTarget = _setting.uintSettings('minBankroll').add(_setting.uintSettings('minBankroll').mul(lotteryTargetIncreasePercentage).div(PERCENTAGE_DIVISOR));
Lottery storage _lottery = lotteries[numLottery];
_lottery.lotteryTarget = lotteryTarget;
_lottery.startTimestamp = now;
_updateCurrentTicketMultiplier();
emit LogCreateLottery(numLottery, lotteryTarget);
return true;
}
/**
* @dev Ends current lottery
*/
function _endLottery() internal returns (bool) {
Lottery storage _currentLottery = lotteries[numLottery];
require (_currentLottery.totalBlocks.add(_currentLottery.totalBlocksRewarded) > 0);
uint256 blockNumberDifference = block.number - lastBlockNumber;
uint256 targetBlockNumber = 0;
if (blockNumberDifference < maxBlockSecurityCount.sub(blockSecurityCount)) {
targetBlockNumber = lastBlockNumber.add(blockSecurityCount);
} else {
targetBlockNumber = lastBlockNumber.add(maxBlockSecurityCount.mul(blockNumberDifference.div(maxBlockSecurityCount))).add(blockSecurityCount);
}
_currentLottery.lotteryResult = _generateRandomNumber(_currentLottery.totalBlocks.add(_currentLottery.totalBlocksRewarded), targetBlockNumber);
// If contract is killed, we don't want any leftover eth sits in the contract
// Add the carry over contribution to current lottery
if (contractKilled == true && carryOverContribution > 0) {
lotteryTarget = lotteryTarget.add(carryOverContribution);
_currentLottery.lotteryTarget = lotteryTarget;
_currentLottery.bankroll = _currentLottery.bankroll.add(carryOverContribution);
totalBankroll = totalBankroll.add(carryOverContribution);
emit LogAddBankRoll(numLottery, carryOverContribution);
}
_currentLottery.endTimestamp = now;
_currentLottery.ended = true;
uint256 endingLotteryHours = _getHoursBetween(_currentLottery.startTimestamp, now);
totalLotteryHours = totalLotteryHours.add(endingLotteryHours);
/*
* avgLotteryHours = totalLotteryHours/numLottery
* But since we are doing division in integer, needs to account for the decimal points
* avgLotteryHours = totalLotteryHours * TWO_DECIMALS / numLottery; // TWO_DECIMALS = 100
* avgLotteryHours needs to be divided by TWO_DECIMALS again later on
*/
avgLotteryHours = totalLotteryHours.mul(TWO_DECIMALS).div(numLottery);
lastLotteryTotalBlocks = _currentLottery.totalBlocks.add(_currentLottery.totalBlocksRewarded);
// Update spinwin's min bankroll
if (_setting.boolSettings('contractKilled') == false && _setting.boolSettings('gamePaused') == false) {
uint256 lotteryPace = 0;
if (endingLotteryHours > 0) {
/*
* lotteryPace = avgLotteryHours/endingLotteryHours
* Mult avgLotteryHours with TWO_DECIMALS to account for two decimal points
* lotteryPace = (avgLotteryHours * TWO_DECIMALS) / endingLotteryHours
* But from previous calculation, we already know that avgLotteryHours is already in decimals
* So, lotteryPace = ((avgLotteryHours*TWO_DECIMALS)/endingLotteryHours)/TWO_DECIMALS
* lotteryPace needs to be divided by TWO_DECIMALS again later on
*/
lotteryPace = avgLotteryHours.mul(TWO_DECIMALS).div(endingLotteryHours).div(TWO_DECIMALS);
}
uint256 newMinBankroll = 0;
if (lotteryPace <= minBankrollDecreaseRate) {
// If the pace is too slow, then we want to decrease spinwin min bankroll
newMinBankroll = _setting.uintSettings('minBankroll').mul(minBankrollDecreaseRate).div(TWO_DECIMALS);
} else if (lotteryPace <= minBankrollIncreaseRate) {
// If the pace is too fast, then we want to increase spinwin min bankroll
newMinBankroll = _setting.uintSettings('minBankroll').mul(minBankrollIncreaseRate).div(TWO_DECIMALS);
} else {
// Otherwise, set new min bankroll according to the lottery pace
newMinBankroll = _setting.uintSettings('minBankroll').mul(lotteryPace).div(TWO_DECIMALS);
}
_setting.spinlotterySetMinBankroll(newMinBankroll);
}
emit LogEndLottery(numLottery, _currentLottery.lotteryResult);
}
/**
* @dev Buys ticket
* @param _playerAddress The player address that buys this ticket
* @param _tokenAmount The amount of SPIN token to spend
* @param _ticketType Is this a normal purchase / part of spinwin's reward program / start lottery reward?
* 1 = normal purchase
* 2 = spinwin reward
* 3 = start lottery reward
* @return Return true if success
*/
function _buyTicket(address _playerAddress, uint256 _tokenAmount, uint256 _ticketType) internal returns (bool) {
require (_ticketType >=1 && _ticketType <= 3);
totalBuyTickets++;
Lottery storage _currentLottery = lotteries[numLottery];
if (_ticketType > 1) {
uint256 _ticketMultiplier = TWO_DECIMALS; // Ticket multiplier is 1
uint256 _numBlocks = _tokenAmount;
_tokenAmount = 0; // Set token amount to 0 since we are not charging player any SPIN
} else {
_currentLottery.tokenWagered = _currentLottery.tokenWagered.add(_tokenAmount);
totalTokenWagered = totalTokenWagered.add(_tokenAmount);
(_ticketMultiplier, _numBlocks) = calculateNumBlocks(_tokenAmount);
}
// Generate ticketId
bytes32 _ticketId = keccak256(abi.encodePacked(this, _playerAddress, numLottery, totalBuyTickets));
Ticket storage _ticket = tickets[_ticketId];
_ticket.ticketId = _ticketId;
_ticket.numLottery = numLottery;
_ticket.playerAddress = _playerAddress;
_ticket.minNumber = _currentLottery.totalBlocks.add(_currentLottery.totalBlocksRewarded).add(1);
_ticket.maxNumber = _currentLottery.totalBlocks.add(_currentLottery.totalBlocksRewarded).add(_numBlocks);
playerTokenWagered[numLottery][_playerAddress] = playerTokenWagered[numLottery][_playerAddress].add(_tokenAmount);
if (_ticketType > 1) {
_currentLottery.totalBlocksRewarded = _currentLottery.totalBlocksRewarded.add(_numBlocks);
playerTotalBlocksRewarded[numLottery][_playerAddress] = playerTotalBlocksRewarded[numLottery][_playerAddress].add(_numBlocks);
} else {
_currentLottery.totalBlocks = _currentLottery.totalBlocks.add(_numBlocks);
playerTotalBlocks[numLottery][_playerAddress] = playerTotalBlocks[numLottery][_playerAddress].add(_numBlocks);
}
emit LogBuyTicket(numLottery, _ticket.ticketId, _ticket.playerAddress, _tokenAmount, _ticketMultiplier, _ticket.minNumber, _ticket.maxNumber, _ticketType);
// Safely update current ticket multiplier
_updateCurrentTicketMultiplier();
// Call spinwin update token to wei exchange rate
_setting.spinlotteryUpdateTokenToWeiExchangeRate();
return true;
}
/**
* @dev Updates current ticket multiplier
*/
function _updateCurrentTicketMultiplier() internal returns (bool) {
// Safely update current ticket multiplier
Lottery memory _currentLottery = lotteries[numLottery];
if (lastLotteryTotalBlocks > _currentLottery.totalBlocks.add(_currentLottery.totalBlocksRewarded)) {
/*
* currentTicketMultiplier = 1 + (ticketMultiplierModifier * ((lastLotteryTotalBlocks-currentLotteryBlocks)/lastLotteryTotalBlocks))
* Since we are calculating in decimals so 1 is actually 100 or TWO_DECIMALS
* currentTicketMultiplier = TWO_DECIMALS + (ticketMultiplierModifier * ((lastLotteryTotalBlocks-currentLotteryBlocks)/lastLotteryTotalBlocks))
* Let temp = (lastLotteryTotalBlocks-currentLotteryBlocks)/lastLotteryTotalBlocks
* To account for decimal points, we mult (lastLotteryTotalBlocks-currentLotteryBlocks) with TWO_DECIMALS
* temp = ((lastLotteryTotalBlocks-currentLotteryBlocks)*TWO_DECIMALS)/lastLotteryTotalBlocks
* We need to divide temp with TWO_DECIMALS later
*
* currentTicketMultiplier = TWO_DECIMALS + ((ticketMultiplierModifier * temp)/TWO_DECIMALS);
*/
uint256 temp = (lastLotteryTotalBlocks.sub(_currentLottery.totalBlocks.add(_currentLottery.totalBlocksRewarded))).mul(TWO_DECIMALS).div(lastLotteryTotalBlocks);
currentTicketMultiplier = TWO_DECIMALS.add(ticketMultiplierModifier.mul(temp).div(TWO_DECIMALS));
} else {
currentTicketMultiplier = TWO_DECIMALS;
}
if (block.number > currentTicketMultiplierBlockNumber.add(currentTicketMultiplierBlockSecurityCount) || _currentLottery.tokenWagered == 0) {
currentTicketMultiplierHonor = currentTicketMultiplier;
currentTicketMultiplierBlockNumber = block.number;
emit LogUpdateCurrentTicketMultiplier(currentTicketMultiplierHonor, currentTicketMultiplierBlockNumber);
}
return true;
}
/**
* @dev Generates random number between 1 to maxNumber based on targetBlockNumber
* @return The random number integer between 1 to maxNumber
*/
function _generateRandomNumber(uint256 maxNumber, uint256 targetBlockNumber) internal constant returns (uint256) {
uint256 randomNumber = 0;
for (uint256 i = 1; i < blockSecurityCount; i++) {
randomNumber = ((uint256(keccak256(abi.encodePacked(randomNumber, blockhash(targetBlockNumber-i), numLottery + totalBuyTickets + totalTokenWagered))) % maxNumber)+1);
}
return randomNumber;
}
/**
* @dev Get hours between two timestamp
* @param _startTimestamp Starting timestamp
* @param _endTimestamp End timestamp
* @return Hours in between starting and ending timestamp
*/
function _getHoursBetween(uint256 _startTimestamp, uint256 _endTimestamp) internal pure returns (uint256) {
uint256 _timestampDiff = _endTimestamp.sub(_startTimestamp);
uint256 _hours = 0;
while(_timestampDiff >= 3600) {
_timestampDiff -= 3600;
_hours++;
}
return _hours;
}
} | Allows player to withdraw balance in case of a failed win send return Return true if success/ External call to untrusted contract | function playerWithdrawPendingTransactions() public
gameIsActive {
require(playerPendingWithdrawals[msg.sender] > 0);
uint256 withdrawAmount = playerPendingWithdrawals[msg.sender];
playerPendingWithdrawals[msg.sender] = 0;
if (!msg.sender.send(withdrawAmount)) {
playerPendingWithdrawals[msg.sender] = withdrawAmount;
emit LogPlayerWithdrawBalance(msg.sender, withdrawAmount, status);
}
| 12,551,523 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.6;
pragma experimental ABIEncoderV2;
import "./NumericalMath.sol";
import "./FixidityLib.sol";
import "https://github.com/smartcontractkit/chainlink/blob/master/evm-contracts/src/v0.6/VRFConsumerBase.sol";
import "https://github.com/jstat17/Random-Walk-NFT/blob/main/openzeppelin-contracts/token/ERC721/ERC721.sol";
/**
* @title RandomWalkNFT
* @author John Michael Statheros (GitHub: jstat17)
* @notice Contract for creating random walk map NFTs.
*/
contract RandomWalkNFT is ERC721, VRFConsumerBase {
bytes32 internal keyHash = 0x2ed0feb3e7fd2022120aa84fab1945545a9f2ffc9076fd6156fa96eaff4c1311;
address internal vrfCoordinator = 0xb3dCcb4Cf7a26f6cf6B120Cf5A73875B7BBc655B;
address internal linkToken = 0x01BE23585060835E02B77ef475b0Cc51aA1e0709;
uint256 internal fee;
int256 public randomResult;
struct RandomWalk {
string name;
uint256 ID;
uint256 nodes;
int256[] x;
int256[] y;
}
RandomWalk[] private randomWalks;
mapping(bytes32 => string) public requestToMapName;
mapping(bytes32 => address) public requestToSender;
mapping(bytes32 => uint256) public requestToTokenID;
mapping(bytes32 => uint256) public requestToNodes;
mapping(address => bytes32) public senderToRequest;
struct Walker {
int256 x;
int256 y;
int256 currAngle;
int256 angle_orig;
uint8 digits;
}
/**
* Constructor inherits VRFConsumerBase
*
* Network: Kovan
* Chainlink VRF Coordinator address: 0xdD3782915140c8f3b190B5D67eAc6dc5760C46E9
* LINK token address: 0xa36085F69e2889c224210F603D836748e7dC0088
* Key Hash: 0x6c3699283bda56ad74f6b855546325b68d482e983852a7a82979cc4807b641f4
*
* Network: Rinkeby
* Chainlink VRF Coordinator address: 0xb3dCcb4Cf7a26f6cf6B120Cf5A73875B7BBc655B
* LINK token address: 0x01be23585060835e02b77ef475b0cc51aa1e0709
* Key Hash: 0x2ed0feb3e7fd2022120aa84fab1945545a9f2ffc9076fd6156fa96eaff4c1311
*/
constructor ()
//constructor (address _VRFCoordinator, address _LinkToken, bytes32 _keyHash)
ERC721("Random Walk","RWalk")
VRFConsumerBase(vrfCoordinator, linkToken)
//VRFConsumerBase(_VRFCoordinator, _LinkToken)
public {
//vrfCoordinator = _VRFCoordinator;
//keyHash = _keyHash;
fee = 0.1 * 10**18; // 0.1 LINK
}
/**
* @notice This function must be called AFTER calling
* the requestRandomWalk function.This will then
* generate the random walk as an NFT and the sender
* will have it added to their wallet and show up
* in etherscan as an ERC721.
* @return success -> true if successful
*/
function generateRandomWalkNFT() public returns(bool success) {
bytes32 requestID = senderToRequest[msg.sender];
require(requestID != 0x0000000000000000000000000000000000000000000000000000000000000000);
uint256 newID = randomWalks.length;
requestToTokenID[requestID] = newID;
int256[] memory xs = new int256[](requestToNodes[requestID]);
int256[] memory ys = new int256[](requestToNodes[requestID]);
xs[0] = 0;
ys[0] = 0;
// Constants:
int256 _2pi = FixidityLib.multiply(FixidityLib.newFixed(2), NumericalMath.pi());
int256 _pi_on_2 = FixidityLib.multiply(FixidityLib.divide(1, 2), NumericalMath.pi());
int256 _pi_on_4 = FixidityLib.multiply(FixidityLib.divide(1, 4), NumericalMath.pi());
// Struct to store walker details:
Walker memory walker;
walker.x = 0;
walker.y = 0;
// Starting angle between 0 and 2π rad:
walker.angle_orig = NumericalMath.convBtwUpLo(randomResult, 0, _2pi);
walker.digits = FixidityLib.digits();
// Create all nodes of the walk:
for (uint256 _i = 1; _i < requestToNodes[requestID]; _i++) {
// Get new angle to walk towards
if (_i == 1) {
walker.currAngle = walker.angle_orig;
} else {
randomResult = NumericalMath.callKeccak256(abi.encodePacked(randomResult));
walker.currAngle = FixidityLib.add(walker.currAngle, FixidityLib.subtract(NumericalMath.getRandomNum(randomResult, 0, _pi_on_2), _pi_on_4));
}
// Walk forwards in the new angle by 1 unit
walker.x = FixidityLib.add(walker.x, NumericalMath.cos(walker.currAngle, walker.digits));
walker.y = FixidityLib.add(walker.y, NumericalMath.sin(walker.currAngle, walker.digits));
// Add new location as a node
xs[_i] = walker.x;
ys[_i] = walker.y;
}
// Add new Random Walk:
randomWalks.push(
RandomWalk(
requestToMapName[requestID],
newID,
requestToNodes[requestID],
xs,
ys
)
);
_safeMint(requestToSender[requestID], newID);
senderToRequest[msg.sender] = 0x0000000000000000000000000000000000000000000000000000000000000000;
return true;
}
/** The user enters an integer seed and the number
* of walk nodes, then a random number is
* generated by the VRF oracle and reserved
* for the specific user that interacted with this
* function.
* @param userProvidedSeed: the integer seed
* @param nodes: the number of nodes in the walk
* @return requestID: the ID of the specific
* request generated
*/
function requestRandomWalk(uint256 userProvidedSeed, uint256 nodes) public returns(bytes32) {
bytes32 requestID = requestRandomness(keyHash, fee, userProvidedSeed); // get a random number from the oracle
requestToMapName[requestID] = string(abi.encodePacked(uint2str(nodes), "-node walk"));
requestToSender[requestID] = msg.sender;
requestToNodes[requestID] = nodes;
//senderToRequest[msg.sender] = requestID;
return requestID;
}
/**
* @notice This is the function that the VRF
* oracle interacts with.
* @param requestID: the ID of the request of
* the user done in requestRandomWalk function
* @param randomness: the VRF oracle's generated
* random number
*/
function fulfillRandomness(bytes32 requestID, uint256 randomness) internal override {
randomResult = FixidityLib.abs(int256(randomness));
senderToRequest[requestToSender[requestID]] = requestID;
}
/**
* @notice Set the token URI for an NFT so that it can be viewed
* in a market like opensea.
* @param tokenID: the ID of the specific NFT
* @param _tokenURI: the token URI
*/
function setTokenURI(uint256 tokenID, string memory _tokenURI) public {
require(
_isApprovedOrOwner(_msgSender(), tokenID),
"ERC721: transfer caller is not owner nor approved"
);
_setTokenURI(tokenID, _tokenURI);
}
/**
* @notice Input the unique token ID for an NFT
* and all the details of it will be returned.
* @param tokenID: the ID of the desired NFT
* @return details of the NFT
*/
function seeRandomWalk(uint256 tokenID) public view returns(RandomWalk memory) {
return randomWalks[tokenID];
}
/**
* @notice Function that converts a uint256 to a string.
* Works for ^0.8.0 and below.
* @param _i: uint256
* @return _uintAsString
* @dev created by Barnabas Ujvari (stackoverflow)
* https://stackoverflow.com/questions/47129173/how-to-convert-uint-to-string-in-solidity
*/
function uint2str(uint256 _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);
}
} | Set the token URI for an NFT so that it can be viewed in a market like opensea. tokenID: the ID of the specific NFT _tokenURI: the token URI/ | function setTokenURI(uint256 tokenID, string memory _tokenURI) public {
require(
_isApprovedOrOwner(_msgSender(), tokenID),
"ERC721: transfer caller is not owner nor approved"
);
_setTokenURI(tokenID, _tokenURI);
}
| 5,478,213 |
pragma solidity ^0.5.0;
contract TrustMe {
// TrustMe events
event newProject(string name, string description, uint stakeToSell, uint projectValuation, uint finishCriteria);
event investment(address investor, string projectName, uint amount, uint stakeBuyed);
event projectWithdraw(string name, uint balance);
// PROJECT STRUCTURE MODEL
struct Project {
string name;
string description;
string headerHash;
uint stakeToSell;
uint availableStake;
uint projectValuation;
uint finishCriteria;
bool availableToInvest;
address payable ownerAddress;
uint balance;
bool validProject;
}
mapping(address => uint[]) private projects; //projects storage
Project[] private projectsStorage; //projects order by address
// ask only for investor
modifier onlyInvestor(uint projectIndex) {
require(
!contains(projectIndex,projects[msg.sender]),
"The investor can't be the same person who published the project"
);
_;
}
// ask only for investor
modifier accomplishFinishCriteria(uint projectIndex) {
require(
projectsStorage[projectIndex].balance >= ((projectsStorage[projectIndex].stakeToSell * projectsStorage[projectIndex].finishCriteria) / 100),
"The project does not accomplish the finish criteria"
);
_;
}
// ask if the project is available to invest
modifier availableToBuy(uint projectIndex){
require(
projectsStorage[projectIndex].availableToInvest,
"This project is stopped by his owner"
);
require(
projectsStorage[projectIndex].availableStake <= msg.value,
"You can't buy a higher value than available"
);
_;
}
// ask if the project has founds
modifier withFounds(uint projectIndex){
require(projectsStorage[projectIndex].balance != 0, 'You have no founds in that project');
_;
}
// ask if msg address has project
modifier entrepeurWithProjects(uint projectIndex){
require(contains(projectIndex,projects[msg.sender]),'This Project does not belongs to you!');
// require(projectsStorage[projectIndex].validProject,'This Project does not exist');
_;
}
// check if elements exists in array
function contains(
uint element,
uint[] memory arrayToSearch
) private pure returns(bool success) {
for(uint i = 0; i<arrayToSearch.length; i++) {
if(arrayToSearch[i] == element)return true;
}
return false;
}
// adding a new project
function addProject (
string memory name,
string memory description,
uint stakeToSell,
uint projectValuation,
uint finishCriteria,
string memory headerHash
) public returns(
string memory message
){
projects[msg.sender].push(projectsStorage.length);
projectsStorage.push(
Project({
name: name,
description: description,
stakeToSell: stakeToSell,
availableStake: stakeToSell,
projectValuation: projectValuation,
finishCriteria: finishCriteria,
headerHash: headerHash,
availableToInvest: true,
ownerAddress: msg.sender,
balance: 0,
validProject: true
})
);
emit newProject(name, description, stakeToSell, projectValuation, finishCriteria);
return("Successfully Added Project");
}
// get all projects count
function getProjectsCount() public view returns (uint){
return projectsStorage.length;
}
// get all address projects count
function getAddressProjectsIndexes () public view returns (
uint[] memory
) {
return projects[msg.sender];
}
// get specific project
function getProject (
uint projectIndex
) public view returns (
string memory name,
string memory headerHash,
string memory description,
uint stakeToSell,
uint availableStake,
uint projectValuation,
uint finishCriteria,
bool availableToInvest,
address owner,
uint projectBalance
) {
Project memory projectToReturn = projectsStorage[projectIndex];
return (
projectToReturn.name,
projectToReturn.headerHash,
projectToReturn.description,
projectToReturn.stakeToSell,
projectToReturn.availableStake,
projectToReturn.projectValuation,
projectToReturn.finishCriteria,
projectToReturn.availableToInvest,
projectToReturn.ownerAddress,
projectToReturn.balance
);
}
// invest in project
function investInProject(
uint projectIndex,
uint projectStakeVal
) public onlyInvestor(projectIndex) availableToBuy(projectIndex) payable {
projectsStorage[projectIndex].availableStake -= projectStakeVal;
projectsStorage[projectIndex].balance += msg.value;
emit investment(msg.sender, projectsStorage[projectIndex].name, msg.value, projectStakeVal);
}
// stop project investment round
function stopProjectInvestmentRound(
uint projectIndex
) public entrepeurWithProjects(projectIndex) accomplishFinishCriteria(projectIndex) returns (
string memory message,
bool success
) {
if (projectsStorage[projectIndex].availableToInvest) {
projectsStorage[projectIndex].availableToInvest = false;
return ('Project successfully Stopped', true);
} else {
return ('Project already Stopped', false);
}
}
// withdraw project balance
function withdrawProjectBalance(
uint projectIndex
) public withFounds(projectIndex) accomplishFinishCriteria(projectIndex) entrepeurWithProjects(projectIndex) payable{
Project memory projectToWithdraw = projectsStorage[projectIndex];
projectToWithdraw.ownerAddress.transfer(projectToWithdraw.balance);
projectToWithdraw.balance = 0;
emit projectWithdraw(projectToWithdraw.name, projectToWithdraw.balance);
}
} | get all address projects count | function getAddressProjectsIndexes () public view returns (
uint[] memory
) {
return projects[msg.sender];
}
| 12,551,253 |
./full_match/4/0xbdB88734C86D0613Daad4218865A2d5474F13173/sources/browser/OroNetwork.sol | Shows latest USDC price for given asset/ Asset Price USDC Price Converting to gram | function toUSDC(address assetAdd, uint256 asset)
public
view
returns(uint256) {
if (asset == 0)
return 0;
uint256 value;
return value;
}
| 728,319 |
./full_match/80001/0xf2F9Dc580289FC127D88f6A6FeF19b0e3c99BBCd/sources/contracts/ClearingHouse.sol | @inheritdoc IClearingHouse input requirement checks: maker: in _cancelExcessOrders() baseToken: in Exchange.settleFunding() orderIds: in OrderBook.removeLiquidityByIds() | function cancelExcessOrders(
address maker,
address baseToken,
bytes32[] calldata orderIds
) external override whenNotPaused nonReentrant {
_checkMarketOpen(baseToken);
_cancelExcessOrders(maker, baseToken, orderIds);
}
| 9,453,994 |
./partial_match/3/0x9BEA3F2Ac6bF212E6F63270B3d918E2B711518E9/sources/Flashloan.sol | /bytes memory data = ""; | function flashloan(address _asset, bytes memory data) public onlyOwner {
uint amount = 1 ether;
ILendingPool lendingPool = ILendingPool(addressesProvider.getLendingPool());
lendingPool.flashLoan(address(this), _asset, amount, data);
}
| 5,229,391 |
./full_match/42/0x9978Bc141d6fb9E9b3E0E63EfEAaa359c8355081/sources/contracts/FRToken.sol | Sets a new reserve factor for the protocol (requires fresh interest accrual) Admin function to set a new reserve factor return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ Check caller is admin Verify market's block number equals current block number Check newReserveFactor ≤ maxReserveFactor | function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED_I, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH_VI, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT_II, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
| 16,224,255 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract UnidirectionalPaymentChannelHub {
struct PaymentChannel {
address payable sender;
address payable recipient;
address tokenAddress;
uint256 expiration;
uint256 amount;
bool open;
}
// SENDER => RECEIVER => TOKEN_ADDRESS => CHANNELID
mapping (address => mapping (address => mapping (address => bytes32))) public usersToId;
mapping (bytes32 => PaymentChannel) public idToChannel;
event ChannelOpened(
address sender,
address recipient,
uint256 expiration,
address tokenAddress,
uint256 tokenAmount,
bytes32 channelId
);
event ChannelClosed(
address sender,
address recipient,
address tokenAddress,
uint256 amountToSender,
uint256 amountToRecipient,
bytes32 channelId
);
event ChannelExtended(
address sender,
address recipient,
address tokenAddress,
uint256 newExpiration,
bytes32 channelId
);
event TimeoutClaimed(
address sender,
address recipient,
address tokenAddress,
uint256 tokenAmount,
bytes32 channelId
);
// proxy, add ownership?
constructor() {}
function open(
address payable recipient,
uint256 duration,
address tokenAddress,
uint256 tokenAmount
)
payable
public
{
require(msg.sender != recipient, "Sender and recipient cannot be the same address");
require(recipient != address(0), "Recipient can't be zero");
// If channel already exists, it has to be closed for you to create a new one
// TODO Make it possible to open multiple channels???
if (_channelExists(msg.sender, recipient, tokenAddress)) {
bytes32 id = usersToId[msg.sender][recipient][tokenAddress];
require (
idToChannel[id].open == false,
"Contract between these addresses using this token is already open"
);
}
uint256 amount;
// If ERC20 is being sent
if (tokenAddress != address(0)) {
require(msg.value == 0, "Ether and ERC20 tokens cannot be used together");
amount = tokenAmount;
ERC20 erc20 = ERC20(tokenAddress);
require(
erc20.transferFrom(msg.sender, address(this), tokenAmount),
"Tokens could not be transferred"
);
}
// If ether is being sent
else {
require(msg.value > 0, "Ether must be supplied");
require (tokenAmount == 0, "Ether and ERC20 tokens cannot be used together");
amount = msg.value;
}
bytes32 id = keccak256(abi.encodePacked(msg.sender, recipient, block.timestamp));
PaymentChannel memory newChannel = PaymentChannel(
payable(msg.sender),
recipient,
tokenAddress,
block.timestamp + duration,
amount,
true
);
usersToId[msg.sender][recipient][tokenAddress] = id;
idToChannel[id] = newChannel;
emit ChannelOpened(
msg.sender,
recipient,
block.timestamp + duration,
tokenAddress,
amount,
id
);
}
/// the recipient can close the channel at any time by presenting a
/// signed amount from the sender. the recipient will be sent that amount,
/// and the remainder will go back to the sender
function close(address sender, address recipient, address tokenAddress, uint256 amount, bytes memory signature) public {
require(_channelExists(sender, recipient, tokenAddress), "Channel does not exist");
bytes32 id = usersToId[sender][recipient][tokenAddress];
PaymentChannel storage channel = idToChannel[id];
require(channel.open = true, "Channel not open");
require(msg.sender == channel.recipient, "Only recipient can close the channel");
require(amount <= channel.amount, "Signed amount is higher than payment channel balance");
require(isValidSignature(sender, recipient, tokenAddress, amount, signature), "Not a valid signature");
channel.open = false;
// ERC20 Token
if (tokenAddress != address(0)) {
ERC20 erc20 = ERC20(tokenAddress);
require(
erc20.transfer(channel.recipient, amount),
"Tokens could not be transferred to recipient"
);
require(
erc20.transfer(channel.sender, channel.amount - amount),
"Tokens could not be transferred to recipient"
);
}
// Ether
else {
channel.recipient.transfer(amount);
channel.sender.transfer(channel.amount - amount);
}
emit ChannelClosed(
channel.sender,
channel.recipient,
channel.tokenAddress,
channel.amount - amount,
amount,
id
);
}
/// the sender can extend the expiration at any time
function extend(address recipient, address tokenAddress, uint256 newExpiration) public {
require(_channelExists(msg.sender, recipient, tokenAddress), "Channel does not exist");
bytes32 id = usersToId[msg.sender][recipient][tokenAddress];
PaymentChannel storage channel = idToChannel[id];
require(msg.sender == channel.sender);
require(newExpiration > channel.expiration);
channel.expiration = newExpiration;
emit ChannelExtended(
channel.sender,
channel.recipient,
channel.tokenAddress,
newExpiration,
id
);
}
/// if the timeout is reached without the recipient closing the channel,
/// then the Ether is released back to the sender.
function claimTimeout(address recipient, address tokenAddress) public {
require(_channelExists(msg.sender, recipient, tokenAddress), "Channel does not exist");
bytes32 id = usersToId[msg.sender][recipient][tokenAddress];
PaymentChannel storage channel = idToChannel[id];
require(block.timestamp >= channel.expiration);
require (msg.sender == channel.sender);
require(channel.open == true);
channel.open = false;
// ERC20 Token
if (tokenAddress != address(0)) {
ERC20 erc20 = ERC20(tokenAddress);
require(
erc20.transfer(channel.sender, channel.amount),
"Tokens could not be transferred"
);
}
// Ether
else {
channel.sender.transfer(channel.amount);
}
emit TimeoutClaimed(
channel.sender,
channel.recipient,
channel.tokenAddress,
channel.amount,
id
);
}
function isValidSignature(address sender, address recipient, address tokenAddress, uint256 amount, bytes memory signature)
public
view
returns (bool)
{
require(_channelExists(sender, recipient, tokenAddress), "Channel does not exist");
bytes32 id = usersToId[sender][recipient][tokenAddress];
PaymentChannel memory channel = idToChannel[id];
bytes32 message = prefixed(keccak256(abi.encodePacked(this, id, amount)));
// check that the signature is from the payment sender
return recoverSigner(message, signature) == channel.sender;
}
function getUsersToId(address sender, address recipient, address tokenAddress) external view returns(bytes32) {
return usersToId[sender][recipient][tokenAddress];
}
function getIdToChannel(bytes32 id) external view returns(PaymentChannel memory) {
return idToChannel[id];
}
function getPaymentChannel(address sender, address recipient, address tokenAddress) external view returns(PaymentChannel memory) {
require(_channelExists(sender, recipient, tokenAddress), "Channel does not exist");
bytes32 id = usersToId[sender][recipient][tokenAddress];
PaymentChannel memory channel = idToChannel[id];
return channel;
}
function _channelExists(address sender, address recipient, address tokenAddress) internal view returns(bool exists) {
// If there is no struct, all values will be 0 including sender
return usersToId[sender][recipient][tokenAddress] != bytes32(0);
}
function splitSignature(bytes memory sig)
internal
pure
returns (uint8 v, bytes32 r, bytes32 s)
{
require(sig.length == 65);
assembly {
// first 32 bytes, after the length prefix
r := mload(add(sig, 32))
// second 32 bytes
s := mload(add(sig, 64))
// final byte (first byte of the next 32 bytes)
v := byte(0, mload(add(sig, 96)))
}
return (v, r, s);
}
function recoverSigner(bytes32 message, bytes memory sig)
internal
pure
returns (address)
{
(uint8 v, bytes32 r, bytes32 s) = splitSignature(sig);
return ecrecover(message, v, r, s);
}
/// builds a prefixed hash to mimic the behavior of eth_sign.
function prefixed(bytes32 hash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
} | the recipient can close the channel at any time by presenting a signed amount from the sender. the recipient will be sent that amount, and the remainder will go back to the sender ERC20 Token Ether | function close(address sender, address recipient, address tokenAddress, uint256 amount, bytes memory signature) public {
require(_channelExists(sender, recipient, tokenAddress), "Channel does not exist");
bytes32 id = usersToId[sender][recipient][tokenAddress];
PaymentChannel storage channel = idToChannel[id];
require(channel.open = true, "Channel not open");
require(msg.sender == channel.recipient, "Only recipient can close the channel");
require(amount <= channel.amount, "Signed amount is higher than payment channel balance");
require(isValidSignature(sender, recipient, tokenAddress, amount, signature), "Not a valid signature");
channel.open = false;
if (tokenAddress != address(0)) {
ERC20 erc20 = ERC20(tokenAddress);
require(
erc20.transfer(channel.recipient, amount),
"Tokens could not be transferred to recipient"
);
require(
erc20.transfer(channel.sender, channel.amount - amount),
"Tokens could not be transferred to recipient"
);
}
else {
channel.recipient.transfer(amount);
channel.sender.transfer(channel.amount - amount);
}
emit ChannelClosed(
channel.sender,
channel.recipient,
channel.tokenAddress,
channel.amount - amount,
amount,
id
);
}
| 14,064,838 |
./partial_match/1/0xa6Ec49E06C25F63292bac1Abc1896451A0f4cFB7/sources/ERC20Plus.sol | Check the proof of an address if valid for merkle root _to address to check for proof _merkleProof Proof of the address to validate against root and leaf/ | function isAllowlisted(address _to, bytes32[] calldata _merkleProof) public view returns(bool) {
if(merkleRoot == 0) revert ValueCannotBeZero();
bytes32 leaf = keccak256(abi.encodePacked(_to));
return MerkleProof.verify(_merkleProof, merkleRoot, leaf);
}
| 15,666,034 |
./partial_match/1/0xa4Bc10991e2721762E30B50Ea6D6b3A1B76750D9/sources/EverBurn.sol | approve the Uniswap Router to spend the contract's WETH calculate the amount of Token B that will be received | function buyAndBurnEvermoon(uint256 amountETH) internal {
address[] memory path = new address[](2);
path[0] = uniswapV2Router.WETH();
path[1] = evermoon;
IERC20(uniswapV2Router.WETH()).approve(address(uniswapV2Router), amountETH);
uint[] memory amounts = uniswapV2Router.getAmountsOut(amountETH, path);
uint amountEvermoonMin = amounts[amounts.length - 1];
path,
address(this),
block.timestamp
);
uint256 evermoonBalance = IERC20(evermoon).balanceOf(address(this));
IERC20(evermoon).transfer(deadAddress, evermoonBalance);
evermoonBurntAmount += evermoonBalance;
}
| 9,139,665 |
pragma solidity 0.4.25;
// https://github.com/ethereum/EIPs/issues/20
interface TRC20 {
function totalSupply() external view returns (uint supply);
function balanceOf(address _owner) external view returns (uint balance);
function transfer(address _to, uint _value) external returns (bool success);
function transferFrom(address _from, address _to, uint _value) external returns (bool success);
function approve(address _spender, uint _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint remaining);
function decimals() external view returns(uint digits);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
/// @title Reserve contract
interface ReserveInterface {
function trade(
TRC20 srcToken,
uint srcAmount,
TRC20 destToken,
address destAddress,
uint conversionRate,
uint feeInWei,
bool validate
)
external
payable
returns(bool);
function getConversionRate(TRC20 src, TRC20 dest, uint srcQty, uint blockNumber) external view returns(uint);
}
/// @title Kyber Network interface
interface NetworkInterface {
function maxGasPrice() external view returns(uint);
function getUserCapInWei(address user) external view returns(uint);
function getUserCapInTokenWei(address user, TRC20 token) external view returns(uint);
function enabled() external view returns(bool);
function info(bytes32 id) external view returns(uint);
function getExpectedRate(TRC20 src, TRC20 dest, uint srcQty) external view
returns (uint expectedRate, uint slippageRate);
function getExpectedFeeRate(TRC20 token, uint srcQty) external view
returns (uint expectedRate, uint slippageRate);
function swap(address trader, TRC20 src, uint srcAmount, TRC20 dest, address destAddress,
uint maxDestAmount, uint minConversionRate, address walletId) external payable returns(uint);
function payTxFee(address trader, TRC20 src, uint srcAmount, address destAddress,
uint maxDestAmount, uint minConversionRate) external payable returns(uint);
}
interface ExpectedRateInterface {
function getExpectedRate(TRC20 src, TRC20 dest, uint srcQty) external view
returns (uint expectedRate, uint slippageRate);
function getExpectedFeeRate(TRC20 token, uint srcQty) external view
returns (uint expectedRate, uint slippageRate);
}
contract PermissionGroups {
address public admin;
address public pendingAdmin;
mapping(address=>bool) internal operators;
mapping(address=>bool) internal alerters;
address[] internal operatorsGroup;
address[] internal alertersGroup;
uint constant internal MAX_GROUP_SIZE = 50;
constructor() public {
admin = msg.sender;
}
modifier onlyAdmin() {
require(msg.sender == admin);
_;
}
modifier onlyOperator() {
require(operators[msg.sender]);
_;
}
modifier onlyAlerter() {
require(alerters[msg.sender]);
_;
}
function getOperators () external view returns(address[] memory) {
return operatorsGroup;
}
function getAlerters () external view returns(address[] memory) {
return alertersGroup;
}
event TransferAdminPending(address pendingAdmin);
/**
* @dev Allows the current admin to set the pendingAdmin address.
* @param newAdmin The address to transfer ownership to.
*/
function transferAdmin(address newAdmin) public onlyAdmin {
require(newAdmin != address(0));
emit TransferAdminPending(pendingAdmin);
pendingAdmin = newAdmin;
}
/**
* @dev Allows the current admin to set the admin in one tx. Useful initial deployment.
* @param newAdmin The address to transfer ownership to.
*/
function transferAdminQuickly(address newAdmin) public onlyAdmin {
require(newAdmin != address(0));
emit TransferAdminPending(newAdmin);
emit AdminClaimed(newAdmin, admin);
admin = newAdmin;
}
event AdminClaimed( address newAdmin, address previousAdmin);
/**
* @dev Allows the pendingAdmin address to finalize the change admin process.
*/
function claimAdmin() public {
require(pendingAdmin == msg.sender);
emit AdminClaimed(pendingAdmin, admin);
admin = pendingAdmin;
pendingAdmin = address(0);
}
event AlerterAdded (address newAlerter, bool isAdd);
function addAlerter(address newAlerter) public onlyAdmin {
require(!alerters[newAlerter]); // prevent duplicates.
require(alertersGroup.length < MAX_GROUP_SIZE);
emit AlerterAdded(newAlerter, true);
alerters[newAlerter] = true;
alertersGroup.push(newAlerter);
}
function removeAlerter (address alerter) public onlyAdmin {
require(alerters[alerter]);
alerters[alerter] = false;
for (uint i = 0; i < alertersGroup.length; ++i) {
if (alertersGroup[i] == alerter) {
alertersGroup[i] = alertersGroup[alertersGroup.length - 1];
alertersGroup.length--;
emit AlerterAdded(alerter, false);
break;
}
}
}
event OperatorAdded(address newOperator, bool isAdd);
function addOperator(address newOperator) public onlyAdmin {
require(!operators[newOperator]); // prevent duplicates.
require(operatorsGroup.length < MAX_GROUP_SIZE);
emit OperatorAdded(newOperator, true);
operators[newOperator] = true;
operatorsGroup.push(newOperator);
}
function removeOperator (address operator) public onlyAdmin {
require(operators[operator]);
operators[operator] = false;
for (uint i = 0; i < operatorsGroup.length; ++i) {
if (operatorsGroup[i] == operator) {
operatorsGroup[i] = operatorsGroup[operatorsGroup.length - 1];
operatorsGroup.length -= 1;
emit OperatorAdded(operator, false);
break;
}
}
}
}
/**
* @title Contracts that should be able to recover tokens or tomos
*/
contract Withdrawable is PermissionGroups {
event TokenWithdraw(TRC20 token, uint amount, address sendTo);
/**
* @dev Withdraw all TRC20 compatible tokens
* @param token TRC20 The address of the token contract
*/
function withdrawToken(TRC20 token, uint amount, address sendTo) external onlyAdmin {
require(token.transfer(sendTo, amount));
emit TokenWithdraw(token, amount, sendTo);
}
event TomoWithdraw(uint amount, address sendTo);
/**
* @dev Withdraw Tomos
*/
function withdrawTomo(uint amount, address sendTo) external onlyAdmin {
sendTo.transfer(amount);
emit TomoWithdraw(amount, sendTo);
}
}
contract WhiteListInterface {
function getUserCapInWei(address user) external view returns (uint userCapWei);
}
/// @title constants contract
contract Utils {
TRC20 constant internal TOMO_TOKEN_ADDRESS = TRC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
uint constant internal PRECISION = (10**18);
uint constant internal MAX_QTY = (10**28); // 10B tokens
uint constant internal MAX_RATE = (PRECISION * 10**6); // up to 1M tokens per TOMO
uint constant internal MAX_DECIMALS = 18;
uint constant internal TOMO_DECIMALS = 18;
mapping(address=>uint) internal decimals;
function setDecimals(TRC20 token) internal {
if (token == TOMO_TOKEN_ADDRESS) decimals[token] = TOMO_DECIMALS;
else decimals[token] = token.decimals();
}
function getDecimals(TRC20 token) internal view returns(uint) {
if (token == TOMO_TOKEN_ADDRESS) return TOMO_DECIMALS; // save storage access
uint tokenDecimals = decimals[token];
// technically, there might be token with decimals 0
// moreover, very possible that old tokens have decimals 0
// these tokens will just have higher gas fees.
if(tokenDecimals == 0) return token.decimals();
return tokenDecimals;
}
function calcDstQty(uint srcQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) {
require(srcQty <= MAX_QTY);
require(rate <= MAX_RATE);
if (dstDecimals >= srcDecimals) {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
return (srcQty * rate * (10**(dstDecimals - srcDecimals))) / PRECISION;
} else {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
return (srcQty * rate) / (PRECISION * (10**(srcDecimals - dstDecimals)));
}
}
function calcSrcQty(uint dstQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) {
require(dstQty <= MAX_QTY);
require(rate <= MAX_RATE);
//source quantity is rounded up. to avoid dest quantity being too low.
uint numerator;
uint denominator;
if (srcDecimals >= dstDecimals) {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
numerator = (PRECISION * dstQty * (10**(srcDecimals - dstDecimals)));
denominator = rate;
} else {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
numerator = (PRECISION * dstQty);
denominator = (rate * (10**(dstDecimals - srcDecimals)));
}
return (numerator + denominator - 1) / denominator; //avoid rounding down errors
}
}
contract Utils2 is Utils {
/// @dev get the balance of a user.
/// @param token The token type
/// @return The balance
function getBalance(TRC20 token, address user) public view returns(uint) {
if (token == TOMO_TOKEN_ADDRESS)
return user.balance;
else
return token.balanceOf(user);
}
function getDecimalsSafe(TRC20 token) internal returns(uint) {
if (decimals[token] == 0) {
setDecimals(token);
}
return decimals[token];
}
function calcDestAmount(TRC20 src, TRC20 dest, uint srcAmount, uint rate) internal view returns(uint) {
return calcDstQty(srcAmount, getDecimals(src), getDecimals(dest), rate);
}
function calcSrcAmount(TRC20 src, TRC20 dest, uint destAmount, uint rate) internal view returns(uint) {
return calcSrcQty(destAmount, getDecimals(src), getDecimals(dest), rate);
}
function calcRateFromQty(uint srcAmount, uint destAmount, uint srcDecimals, uint dstDecimals)
internal pure returns(uint)
{
require(srcAmount <= MAX_QTY);
require(destAmount <= MAX_QTY);
if (dstDecimals >= srcDecimals) {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
return (destAmount * PRECISION / ((10 ** (dstDecimals - srcDecimals)) * srcAmount));
} else {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
return (destAmount * PRECISION * (10 ** (srcDecimals - dstDecimals)) / srcAmount);
}
}
}
/// @title Network interface
interface NetworkProxyInterface {
function maxGasPrice() external view returns(uint);
function getUserCapInWei(address user) external view returns(uint);
function getUserCapInTokenWei(address user, TRC20 token) external view returns(uint);
function enabled() external view returns(bool);
function info(bytes32 id) external view returns(uint);
function getExpectedRate(TRC20 src, TRC20 dest, uint srcQty) external view
returns (uint expectedRate, uint slippageRate);
function getExpectedFeeRate(TRC20 token, uint srcQty) external view
returns (uint expectedRate, uint slippageRate);
function swap(TRC20 src, uint srcAmount, TRC20 dest, address destAddress, uint maxDestAmount,
uint minConversionRate, address walletId) external payable returns(uint);
function payTxFee(TRC20 src, uint srcAmount, address destAddress, uint maxDestAmount,
uint minConversionRate) external payable returns(uint);
}
/// @title simple interface for Network
interface SimpleNetworkInterface {
function swapTokenToToken(TRC20 src, uint srcAmount, TRC20 dest, uint minConversionRate) external returns(uint);
function swapTomoToToken(TRC20 token, uint minConversionRate) external payable returns(uint);
function swapTokenToTomo(TRC20 token, uint srcAmount, uint minConversionRate) external returns(uint);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @title Network proxy for main contract
contract NetworkProxy is NetworkProxyInterface, SimpleNetworkInterface, Withdrawable, Utils2 {
NetworkInterface public networkContract;
mapping(address=>bool) public payFeeCallers;
constructor(address _admin) public {
require(_admin != address(0));
admin = _admin;
}
/// @notice use token address TOMO_TOKEN_ADDRESS for TOMO
/// @dev makes a trade between src and dest token and send dest token to destAddress
/// @param src Src token
/// @param srcAmount amount of src tokens
/// @param dest Destination token
/// @param destAddress Address to send tokens to
/// @param maxDestAmount A limit on the amount of dest tokens
/// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled.
/// @param walletId is the wallet ID to send part of the fees
/// @return amount of actual dest tokens
function trade(
TRC20 src,
uint srcAmount,
TRC20 dest,
address destAddress,
uint maxDestAmount,
uint minConversionRate,
address walletId
)
public
payable
returns(uint)
{
return swap(
src,
srcAmount,
dest,
destAddress,
maxDestAmount,
minConversionRate,
walletId
);
}
event AddPayFeeCaller(address caller, bool add);
function addPayFeeCaller(address caller, bool add) public onlyAdmin {
if (add) {
require(payFeeCallers[caller] == false);
payFeeCallers[caller] = true;
} else {
require(payFeeCallers[caller] == true);
payFeeCallers[caller] = false;
}
emit AddPayFeeCaller(caller, add);
}
/// @notice use token address TOMO_TOKEN_ADDRESS for TOMO
/// @dev makes a trade for transaction fee
/// @param src Src token
/// @param srcAmount amount of src tokens
/// @param destAddress Address to send tokens to
/// @param maxDestAmount A limit on the amount of dest tokens
/// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled.
/// @return amount of actual dest tokens
function payTxFee(
TRC20 src,
uint srcAmount,
address destAddress,
uint maxDestAmount,
uint minConversionRate
)
public
payable
returns(uint)
{
require(src == TOMO_TOKEN_ADDRESS || msg.value == 0);
require(payFeeCallers[msg.sender] == true, "payTxFee: Sender is not callable this function");
TRC20 dest = TOMO_TOKEN_ADDRESS;
UserBalance memory userBalanceBefore;
userBalanceBefore.srcBalance = getBalance(src, msg.sender);
userBalanceBefore.destBalance = getBalance(dest, destAddress);
if (src == TOMO_TOKEN_ADDRESS) {
userBalanceBefore.srcBalance += msg.value;
} else {
require(src.transferFrom(msg.sender, networkContract, srcAmount), "payTxFee: Transer token to network contract");
}
uint reportedDestAmount = networkContract.payTxFee.value(msg.value)(
msg.sender,
src,
srcAmount,
destAddress,
maxDestAmount,
minConversionRate
);
TradeOutcome memory tradeOutcome = calculateTradeOutcome(
userBalanceBefore.srcBalance,
userBalanceBefore.destBalance,
src,
dest,
destAddress
);
require(reportedDestAmount == tradeOutcome.userDeltaDestAmount, "Report dest amount is different from user delta dest amount");
require(tradeOutcome.userDeltaDestAmount <= maxDestAmount, "userDetalDestAmount > maxDestAmount");
require(tradeOutcome.actualRate >= minConversionRate, "actualRate < minConversionRate");
emit ExecuteTrade(msg.sender, src, dest, tradeOutcome.userDeltaSrcAmount, tradeOutcome.userDeltaDestAmount);
return tradeOutcome.userDeltaDestAmount;
}
/// @notice use token address TOMO_TOKEN_ADDRESS for TOMO
/// @dev makes a trade for transaction fee
/// @dev auto set maxDestAmount and minConversionRate
/// @param src Src token
/// @param srcAmount amount of src tokens
/// @param destAddress Address to send tokens to
/// @return amount of actual dest tokens
function payTxFeeFast(TRC20 src, uint srcAmount, address destAddress) external payable returns(uint) {
require(payFeeCallers[msg.sender] == true);
payTxFee(
src,
srcAmount,
destAddress,
MAX_QTY,
0
);
}
/// @dev makes a trade between src and dest token and send dest tokens to msg sender
/// @param src Src token
/// @param srcAmount amount of src tokens
/// @param dest Destination token
/// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled.
/// @return amount of actual dest tokens
function swapTokenToToken(
TRC20 src,
uint srcAmount,
TRC20 dest,
uint minConversionRate
)
public
returns(uint)
{
return swap(
src,
srcAmount,
dest,
msg.sender,
MAX_QTY,
minConversionRate,
0
);
}
/// @dev makes a trade from Tomo to token. Sends token to msg sender
/// @param token Destination token
/// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled.
/// @return amount of actual dest tokens
function swapTomoToToken(TRC20 token, uint minConversionRate) public payable returns(uint) {
return swap(
TOMO_TOKEN_ADDRESS,
msg.value,
token,
msg.sender,
MAX_QTY,
minConversionRate,
0
);
}
/// @dev makes a trade from token to Tomo, sends Tomo to msg sender
/// @param token Src token
/// @param srcAmount amount of src tokens
/// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled.
/// @return amount of actual dest tokens
function swapTokenToTomo(TRC20 token, uint srcAmount, uint minConversionRate) public returns(uint) {
return swap(
token,
srcAmount,
TOMO_TOKEN_ADDRESS,
msg.sender,
MAX_QTY,
minConversionRate,
0
);
}
struct UserBalance {
uint srcBalance;
uint destBalance;
}
event ExecuteTrade(address indexed trader, TRC20 src, TRC20 dest, uint actualSrcAmount, uint actualDestAmount);
/// @notice use token address TOMO_TOKEN_ADDRESS for tomo
/// @dev makes a trade between src and dest token and send dest token to destAddress
/// @param src Src token
/// @param srcAmount amount of src tokens
/// @param dest Destination token
/// @param destAddress Address to send tokens to
/// @param maxDestAmount A limit on the amount of dest tokens
/// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled.
/// @param walletId is the wallet ID to send part of the fees
/// @return amount of actual dest tokens
function swap(
TRC20 src,
uint srcAmount,
TRC20 dest,
address destAddress,
uint maxDestAmount,
uint minConversionRate,
address walletId
)
public
payable
returns(uint)
{
require(src == TOMO_TOKEN_ADDRESS || msg.value == 0);
UserBalance memory userBalanceBefore;
userBalanceBefore.srcBalance = getBalance(src, msg.sender);
userBalanceBefore.destBalance = getBalance(dest, destAddress);
if (src == TOMO_TOKEN_ADDRESS) {
userBalanceBefore.srcBalance += msg.value;
} else {
require(src.transferFrom(msg.sender, networkContract, srcAmount), "swap: Can not transfer token to contract");
}
uint reportedDestAmount = networkContract.swap.value(msg.value)(
msg.sender,
src,
srcAmount,
dest,
destAddress,
maxDestAmount,
minConversionRate,
walletId
);
TradeOutcome memory tradeOutcome = calculateTradeOutcome(
userBalanceBefore.srcBalance,
userBalanceBefore.destBalance,
src,
dest,
destAddress
);
require(reportedDestAmount == tradeOutcome.userDeltaDestAmount);
require(tradeOutcome.userDeltaDestAmount <= maxDestAmount);
require(tradeOutcome.actualRate >= minConversionRate);
emit ExecuteTrade(msg.sender, src, dest, tradeOutcome.userDeltaSrcAmount, tradeOutcome.userDeltaDestAmount);
return tradeOutcome.userDeltaDestAmount;
}
event NetworkSet(address newNetworkContract, address oldNetworkContract);
function setNetworkContract(NetworkInterface _networkContract) public onlyAdmin {
require(_networkContract != address(0));
emit NetworkSet(_networkContract, networkContract);
networkContract = _networkContract;
}
function getExpectedRate(TRC20 src, TRC20 dest, uint srcQty)
public view
returns(uint expectedRate, uint slippageRate)
{
return networkContract.getExpectedRate(src, dest, srcQty);
}
function getExpectedFeeRate(TRC20 token, uint srcQty)
public view
returns (uint expectedRate, uint slippageRate)
{
return networkContract.getExpectedFeeRate(token, srcQty);
}
function getUserCapInWei(address user) public view returns(uint) {
return networkContract.getUserCapInWei(user);
}
function getUserCapInTokenWei(address user, TRC20 token) public view returns(uint) {
return networkContract.getUserCapInTokenWei(user, token);
}
function maxGasPrice() public view returns(uint) {
return networkContract.maxGasPrice();
}
function enabled() public view returns(bool) {
return networkContract.enabled();
}
function info(bytes32 field) public view returns(uint) {
return networkContract.info(field);
}
struct TradeOutcome {
uint userDeltaSrcAmount;
uint userDeltaDestAmount;
uint actualRate;
}
function calculateTradeOutcome (uint srcBalanceBefore, uint destBalanceBefore, TRC20 src, TRC20 dest,
address destAddress)
internal returns(TradeOutcome memory outcome)
{
uint userSrcBalanceAfter;
uint userDestBalanceAfter;
userSrcBalanceAfter = getBalance(src, msg.sender);
userDestBalanceAfter = getBalance(dest, destAddress);
//protect from underflow
require(userDestBalanceAfter > destBalanceBefore, "userDestBalanceAfter <= destBalanceBefore");
require(srcBalanceBefore > userSrcBalanceAfter, "srcBalanceBefore <= userSrcBalanceAfter");
outcome.userDeltaDestAmount = userDestBalanceAfter - destBalanceBefore;
outcome.userDeltaSrcAmount = srcBalanceBefore - userSrcBalanceAfter;
outcome.actualRate = calcRateFromQty(
outcome.userDeltaSrcAmount,
outcome.userDeltaDestAmount,
getDecimalsSafe(src),
getDecimalsSafe(dest)
);
}
}
| get the balance of a user. token The token type return The balance | function getBalance(TRC20 token, address user) public view returns(uint) {
if (token == TOMO_TOKEN_ADDRESS)
return user.balance;
else
return token.balanceOf(user);
}
| 1,804,195 |
./full_match/1/0x40Cd77D9aa9e0b2D485259415eA05486B201c514/sources/contracts/nfts/ValidatorNft.sol | Returns the validators that are active (may contain validator that are yet active on beacon chain)/ | function activeValidators() external view returns (bytes[] memory) {
uint256 total = _nextTokenId();
uint256 tokenIdsIdx;
bytes[] memory validators = new bytes[](total);
TokenOwnership memory ownership;
for (uint256 i = _startTokenId(); i < total; ++i) {
ownership = _ownershipAt(i);
if (ownership.burned) {
continue;
}
validators[tokenIdsIdx++] = _validators[i];
}
return validators;
}
| 16,606,208 |
./full_match/5/0x583b09559F81656D81dD9AeC42E088Ed5b86631e/sources/project_/contracts/MetawinCollectibleRewardsSale.sol | [Admin] Unpause the contract/ | function unpauseContract() external onlyRole(DEFAULT_ADMIN_ROLE) {
_unpause();
}
| 1,930,668 |
./full_match/1/0x6ccfD65b0b14F67259C77Ca6267104e058dDB292/sources/contracts/tokenBridge/TokenBridge.sol | Contract will be used as proxy implementation. _messageService The address of the MessageService contract. _tokenBeacon The address of the tokenBeacon. _sourceChainId The source chain id of the current layer _targetChainId The target chaind id of the targeted layer _reservedTokens The list of reserved tokens to be set/ | function initialize(
address _securityCouncil,
address _messageService,
address _tokenBeacon,
uint256 _sourceChainId,
uint256 _targetChainId,
address[] calldata _reservedTokens
) external nonZeroAddress(_securityCouncil) nonZeroAddress(_messageService) nonZeroAddress(_tokenBeacon) initializer {
__Pausable_init();
__Ownable2Step_init();
__MessageServiceBase_init(_messageService);
__ReentrancyGuard_init();
tokenBeacon = _tokenBeacon;
sourceChainId = _sourceChainId;
targetChainId = _targetChainId;
unchecked {
for (uint256 i; i < _reservedTokens.length; ) {
if (_reservedTokens[i] == EMPTY) revert ZeroAddressNotAllowed();
setReserved(_reservedTokens[i]);
++i;
}
}
_transferOwnership(_securityCouncil);
}
| 2,969,309 |
// File: @openzeppelin/contracts/utils/Context.sol
// 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/Ownable.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address internal _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @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 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/math/SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
pragma solidity >=0.6.0 <0.8.0;
/**
* @title WhiteList
*
* @dev Contract for checking whitelisted addresses.
*/
interface WhiteList {
/**
* @dev Query whether the the given `account` is on this list or not.
*
* @param account The account address being queried
* @return True if the account is on the list, otherwise false
*/
function onList(address account) external view returns (bool) ;
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/utils/Pausable.sol
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 virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// File: contracts/rewards/rewardStation.sol
pragma solidity 0.6.12;
import "./ECRecovery.sol";
contract rewardStation is Ownable, Pausable {
using SafeMath for uint256;
struct UserInfo {
uint256 totalrewarded; // total amount of given rewards to a user (not as a referral)
uint256 totalAsReferralRewarded; // total amount of given rewards to the user as a referral.
address referral; // The address of the user's referral.
uint256 lastRewardedTime; // keeps track of the reward time.
uint256 lastUserActionTime; // keeps track of the last user action time
uint256 lastRewardDay; // keeps track of the last user reward day
uint256 todaysWithrawals; // keeps track of the daily withdrawals
bool claimed1stReward; // check if reward is claimed;
uint256 unClaimedReferralRewards; // store total rewards as referralRewards
}
IERC20 public token; // Frac token
WhiteList public whiteList; // only whitelisted users are eligiable for reward tokens.
mapping(address => UserInfo) public userInfo;
mapping(uint256 => bool) usedNonces;
address public admin; // address of the admin user
address public mainDistributer; // address of the main pool that holds all the rewards to be given.
// Whether or not this contract has been initialized.
bool private _initialized;
uint256 public MAX_REWARD_AMOUNT; // maximum rewards could be given to a user in a single transaction.
uint256 public MAX_REFERRAL_REWARD_AMOUNT; // maximum referral rewards could be given to a user in a single transaction.
uint256 public rewardAmount ; // Fixed reward amount
uint256 public referralRewardAmount ; // Fixed referral reward amount
uint256 private dailyLimit;
uint256 private dailyLimitPeriod;
/**
* @dev To set the fixed amount of given rewards.
*
* @param _rewardsAmount is the fixed value to be set as rewards
*/
function setRewardAmount(uint256 _rewardsAmount) external onlyOwner {
require(_rewardsAmount <= MAX_REWARD_AMOUNT, "Reward amount exceeds limit");
rewardAmount = _rewardsAmount ;
}
/**
* @dev To set the fixed amount of given referral rewards.
*
* @param _referralRewardAmount is the fixed value to be set as referral rewards
*/
function setReferralRewardAmount(uint256 _referralRewardAmount) external onlyOwner {
require(_referralRewardAmount <= MAX_REFERRAL_REWARD_AMOUNT, "Referral reward amount exceeds limit");
referralRewardAmount = _referralRewardAmount ;
}
/**
* @dev To set the amount of allowd withdrawal daily amount
*
* @param _limit is the value to be set as daily limit
*/
function setDailyLimit(uint256 _limit) external onlyOwner {
require(_limit > 0, "limit must be greater than zero.");
dailyLimit = _limit ;
}
/**
* @dev To set the period of time-based allowd withdrawals
*
* @param _t is the period in seconds to be set
*/
function setwithrawalPeriod(uint256 _t) external onlyOwner {
require(_t > 0, "period must be greater than zero.");
dailyLimitPeriod = _t ;
}
event Claimed(address indexed addr, uint256 amount);
event Rewarded(address indexed addr, uint256 amount);
event ClaimedWithReferral(address indexed addr, uint256 rewardAmount, address indexed referralAddress, uint256 referralRewardAmount);
event RewardedWithReferral(address indexed addr, uint256 rewardAmount, address indexed referralAddress, uint256 referralRewardAmount);
event Pause();
event Unpause();
/**
* @notice Constructor
* @param _token : FRAC token contract
* @param _mainDistributer : address of the main rewards pool
* @param _admin : address of the admin
* @param _whitelist : address of the whiteList
* @param _rewardVal : amount of rewards by fixedValue
* @param _refRewardVal : amount of referralReward by fixdValue
* @param _maxRewardAmount : limit of rewards to be givien in a single transaction
* @param _maxReferralRewardAmount : limit of referralRewards to be given in a single transaction
*/
function initialize(
IERC20 _token,
address _mainDistributer,
address _admin,
WhiteList _whitelist,
uint256 _rewardVal,
uint256 _refRewardVal,
uint256 _maxRewardAmount,
uint256 _maxReferralRewardAmount
) public {
require(!_initialized);
token = _token;
mainDistributer = _mainDistributer;
admin = _admin;
_owner = msg.sender;
whiteList = _whitelist;
rewardAmount = _rewardVal;
referralRewardAmount = _refRewardVal;
MAX_REWARD_AMOUNT = _maxRewardAmount;
MAX_REFERRAL_REWARD_AMOUNT = _maxReferralRewardAmount;
_initialized = true;
}
/**
* @return True if the contract has been initialized, otherwise false
*/
function initialized() external view returns (bool) {
return _initialized;
}
/**
* @notice Checks if the msg.sender is the admin address
*/
modifier onlyAdmin() {
require(msg.sender == admin, "admin: wut?");
_;
}
/**
* @notice Checks if the msg.sender is a contract or a proxy
*/
modifier notContract() {
require(!_isContract(msg.sender), "contract not allowed");
require(msg.sender == tx.origin, "proxy contract not allowed");
_;
}
/**
* @notice Sets admin address
* @dev Only callable by the contract owner.
*/
function setAdmin(address _admin) external onlyOwner {
require(_admin != address(0), "Cannot be zero address");
admin = _admin;
}
/**
* @notice Sets the rewards pool
* @dev Only callable by the contract owner.
*/
function setMainDistributer(address _mainDist) external onlyAdmin {
require(_mainDist != address(0), "Cannot be zero address");
mainDistributer = _mainDist;
}
/**
* @notice Sets WhiteList address
* @dev Only callable by the contract admin.
*/
function setWhiteList(WhiteList _wl) external onlyAdmin {
require(address(_wl) != address(0), "Cannot be zero address");
whiteList = _wl;
}
/**
* @notice Sets MAX_REWARD_AMOUNT address
* @dev Only callable by the contract admin.
* @param _maxRewardsAmount : the new value of MAX_REWARD_AMOUNT
*/
function setMaxRewardsAmount(uint256 _maxRewardsAmount) external onlyAdmin {
MAX_REWARD_AMOUNT = _maxRewardsAmount;
}
/**
* @notice Sets MAX_REFERRAL_REWARD_AMOUNT address
* @dev Only callable by the contract admin.
* @param _maxReferralRewardsAmount : the new value of MAX_REFERRAL_REWARD_AMOUNT
*/
function setMaxReferralRewardsAmount(uint256 _maxReferralRewardsAmount) external onlyAdmin {
MAX_REFERRAL_REWARD_AMOUNT = _maxReferralRewardsAmount;
}
/**
* @notice Withdraw unexpected tokens sent to the rewards token
*/
function inCaseTokensGetStuck(address _token) external onlyAdmin {
require(_token != address(token), "Token cannot be same as deposit token");
uint256 amount = IERC20(_token).balanceOf(address(this));
IERC20(_token).transfer(msg.sender, amount);
}
/**
* @notice Triggers stopped state
* @dev Only possible when contract not paused.
*/
function pause() external onlyAdmin whenNotPaused {
_pause();
emit Pause();
}
/**
* @notice Returns to normal state
* @dev Only possible when contract is paused.
*/
function unpause() external onlyAdmin whenPaused {
_unpause();
emit Unpause();
}
/**
* @notice give rewards to an address. All rewards are static values set with the fixed amounts.
* @param _addr is the address to be rewarded
*/
function reward(address _addr) external notContract onlyAdmin {
require(whiteList.onList(_addr) ,"The address to be rewarded is not whiteListed");
require(rewardAmount <= token.balanceOf(mainDistributer), "Not enough tokens in the reserve");
UserInfo storage user = userInfo[_addr];
token.transferFrom(mainDistributer, _addr, rewardAmount);
user.lastUserActionTime = block.timestamp;
user.lastRewardedTime = block.timestamp;
user.totalrewarded = SafeMath.add(user.totalrewarded, rewardAmount);
emit Rewarded(_addr, rewardAmount);
}
/**
* @notice give rewards to an address and rewards its referral address too. All rewards are static values set with the fixed amounts.
* @param _addr is the address to be rewarded
* @param _referral is the referral address that would be rewarded too
*/
function rewardWithReferral(address _addr, address _referral) external notContract onlyAdmin {
require(whiteList.onList(_addr) ,"The address to be rewarded is not whiteListed");
require(whiteList.onList(_referral) ,"The referral is not whiteListed");
require(SafeMath.add(rewardAmount,referralRewardAmount) <= token.balanceOf(mainDistributer), "Not enough tokens in the reserve");
UserInfo storage user = userInfo[_addr];
require(user.referral == address(0), "First 'Reward with Referral' has been granted to user!");
UserInfo storage userReferral = userInfo[_referral];
token.transferFrom(mainDistributer, _addr, rewardAmount);
token.transferFrom(mainDistributer, _referral, referralRewardAmount);
user.referral = _referral;
user.lastRewardedTime = block.timestamp;
user.lastUserActionTime = block.timestamp;
user.totalrewarded = SafeMath.add(user.totalrewarded, rewardAmount);
userReferral.totalAsReferralRewarded = SafeMath.add(userReferral.totalAsReferralRewarded, referralRewardAmount);
userReferral.lastUserActionTime = block.timestamp;
emit RewardedWithReferral(_addr, rewardAmount, _referral, referralRewardAmount);
}
/**
* @notice transfer all accumulated amounts of rewards that belongs to an address and claimed by the user.
* @param _rewardsAmount is the amount of claimed accumulated rewards
* @param nonce is the transaction ID
* @param sig is the siginture generated from the backend system for verification
*/
function claim(uint256 _rewardsAmount, uint256 nonce, bytes memory sig) external notContract {
require(whiteList.onList(msg.sender) ,"The address to be rewarded is not whiteListed");
require(_rewardsAmount<MAX_REWARD_AMOUNT ,"The rewarded amount axceeds the maximum limit");
UserInfo storage user = userInfo[msg.sender];
//-----2021-11-02------To set daily limits------------------------
uint256 dateDiff;
dateDiff = SafeMath.sub(block.timestamp,user.lastRewardDay);
if(dateDiff>dailyLimitPeriod)
{
user.todaysWithrawals = 0;
user.lastRewardDay = block.timestamp;
}
require(SafeMath.add(user.todaysWithrawals,_rewardsAmount)<dailyLimit, "with this amount you would acceed the daily limit! Please decrease the amount or contact SpeedProp.");
//----------------------------------------------------------------
require(_rewardsAmount <= token.balanceOf(mainDistributer), "Not enough tokens in the reserve");
// recreates the message that was signed on the client.
bytes32 message = hashFun(msg.sender, address(this), _rewardsAmount, nonce);
require(ECDSA.recover(message, sig)==admin, "Invalid signature");
require(!usedNonces[nonce], "Transaction ID is already Claimed");
usedNonces[nonce] = true;
token.transferFrom(mainDistributer, msg.sender, _rewardsAmount);
user.totalrewarded = SafeMath.add(user.totalrewarded, _rewardsAmount);
user.todaysWithrawals = SafeMath.add(user.todaysWithrawals, _rewardsAmount);
user.lastRewardedTime = block.timestamp;
user.lastUserActionTime = block.timestamp;
emit Claimed(msg.sender, _rewardsAmount);
}
/**
* @notice transfer all accumulated amounts of rewards that belongs to an address and claimed by the user. and also, reward the mentioned referral.
* @param _rewardsAmount is the amount of claimed accumulated rewards
* @param nonce is the transaction ID
* @param sig is the siginture generated from the backend system for verification
* @param _referral is the address of the referral to be rewarded.
*/
function claimWithReferral(uint256 _rewardsAmount, uint256 nonce, bytes memory sig, address _referral) external notContract {
require(whiteList.onList(msg.sender) ,"The address to be rewarded is not whiteListed");
require(whiteList.onList(_referral) ,"The referral is not whiteListed");
require(_rewardsAmount<MAX_REWARD_AMOUNT ,"The rewarded amount axceeds the maximum limit");
UserInfo storage user = userInfo[msg.sender];
require(user.referral == address(0), "First 'Reward with Referral' has been granted to user!");
//-----2021-11-02------To set daily limits------------------------
uint256 dateDiff;
dateDiff = SafeMath.sub(block.timestamp,user.lastRewardDay);
if(dateDiff>dailyLimitPeriod)
{
user.todaysWithrawals = 0;
user.lastRewardDay = block.timestamp;
}
require(SafeMath.add(user.todaysWithrawals,_rewardsAmount)<dailyLimit, "with this amount you would acceed the daily limit! Please decrease the amount or contact SpeedProp.");
//----------------------------------------------------------------
require(_rewardsAmount <= token.balanceOf(mainDistributer), "Not enough tokens in the reserve");
// recreates the message that was signed on the client.
bytes32 message = hashFun(msg.sender, address(this), _rewardsAmount, nonce);
require(ECDSA.recover(message, sig)==admin, "Invalid signature");
require(!usedNonces[nonce], "Transaction ID is already Claimed");
usedNonces[nonce] = true;
token.transferFrom(mainDistributer, msg.sender, _rewardsAmount);
token.transferFrom(mainDistributer, _referral, referralRewardAmount);
user.totalrewarded = SafeMath.add(user.totalrewarded, _rewardsAmount);
user.todaysWithrawals = SafeMath.add(user.todaysWithrawals, _rewardsAmount);
user.lastRewardedTime = block.timestamp;
user.lastUserActionTime = block.timestamp;
UserInfo storage userReferral = userInfo[_referral];
userReferral.totalAsReferralRewarded = SafeMath.add(userReferral.totalAsReferralRewarded, referralRewardAmount);
userReferral.lastRewardedTime = block.timestamp;
userReferral.lastUserActionTime = block.timestamp;
emit ClaimedWithReferral(msg.sender, rewardAmount, _referral, referralRewardAmount);
}
function hashFun (address receiver, address poolContract, uint256 amount, uint256 nonce) internal pure returns (bytes32)
{
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
return keccak256(abi.encode(prefix, keccak256(abi.encode(receiver, poolContract, amount, nonce))));
}
/**
* @notice Checks if address is a contract
* @dev It prevents contract from being targetted
*/
function _isContract(address addr) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(addr)
}
return size > 0;
}
}
| To set the amount of allowd withdrawal daily amount _limit is the value to be set as daily limit/ | function setDailyLimit(uint256 _limit) external onlyOwner {
require(_limit > 0, "limit must be greater than zero.");
dailyLimit = _limit ;
}
| 12,918,949 |
./full_match/8217/0xe41066e28Ff95244741262Bd877015Edf3f8a9a0/sources/contracts/StKlay.sol | Unpauses functionality Emits a `Unpaused` event/ | function unpause() external onlyRole(ROLE_PAUSER) {
_unpause();
}
| 13,229,562 |
./full_match/421613/0x230a9e216E7d5DDFcB0ff52e3E217e642fbf67ad/sources/contracts/Material.sol | random = random + (random / (i + 1) + random (random - i)) + i i; | function getRewardUnits(
uint256 _chestId,
uint256 _amountToOpen
) internal returns (uint256[] memory tokenIds, uint256[] memory amounts) {
tokenIds = new uint256[](6);
amounts = new uint256[](6);
for (uint256 i = 0; i < tokenIds.length; i++) {
tokenIds[i] = i;
amounts[i] = i + 1;
}
uint256[5] memory _lotteryWeightSoul = [uint256(50), 30, 15, 4, 1];
uint256[5] memory _amountsSoul = [uint256(1), 5, 10, 50, 100];
uint256[5] memory _lotteryWeightMaterial = [uint256(50), 30, 8, 8, 4];
uint256[5] memory _amountsMaterial = [uint256(5), 1, 1, 1, 1];
uint256 sum = 0;
for (uint256 i = 0; i < _lotteryWeightSoul.length; i++) {
sum += _lotteryWeightSoul[i];
}
uint256 random = generateRandomValue();
for (uint256 i = 0; i < _amountToOpen; i++) {
uint256 r = random % sum;
uint256 index = 0;
uint256 s = 0;
for (uint256 ii = 0; ii < _lotteryWeightSoul.length; ii++) {
s += _lotteryWeightSoul[ii];
if (s > r) {
break;
}
index++;
}
amounts[0] = amounts[0] + _amountsSoul[index];
index = 0;
s = 0;
for (uint256 ii = 0; ii < _lotteryWeightMaterial.length; ii++) {
s += _lotteryWeightMaterial[ii];
if (s > r) {
break;
}
index++;
}
amounts[index+1] = amounts[index+1] + _amountsMaterial[index];
}
for (uint256 i = 0; i < _amounts.length; i++) {
uint256 amount = _amounts[i];
if (amount > 0) {
tokenIds[tokenIds.length] = i;
amounts[amounts.length] = amount;
}
}*/
return (tokenIds, amounts);
}
| 11,582,333 |
pragma solidity ^0.4.11;
contract SafeMath {
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
function assert(bool assertion) internal {
if (!assertion) throw;
}
}
contract ERC20Token {
function balanceOf(address _address) constant returns (uint balance);
function transfer(address _to, uint _value) returns (bool success);
}
contract ReputationTokenInterface {
function issueTokens(address forAddress, uint tokenCount) returns (bool success);
function burnTokens(address forAddress) returns (bool success);
function lockTokens(address forAddress, uint tokenCount) returns (bool success);
function unlockTokens(address forAddress, uint tokenCount) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function nonLockedTokensCount(address forAddress) constant returns (uint tokenCount);
}
contract AbstractENS {
function owner(bytes32 node) constant returns(address);
function resolver(bytes32 node) constant returns(address);
function ttl(bytes32 node) constant returns(uint64);
function setOwner(bytes32 node, address owner);
function setSubnodeOwner(bytes32 node, bytes32 label, address owner);
function setResolver(bytes32 node, address resolver);
function setTTL(bytes32 node, uint64 ttl);
// Logged when the owner of a node assigns a new owner to a subnode.
event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner);
// Logged when the owner of a node transfers ownership to a new account.
event Transfer(bytes32 indexed node, address owner);
// Logged when the resolver for a node changes.
event NewResolver(bytes32 indexed node, address resolver);
// Logged when the TTL of a node changes
event NewTTL(bytes32 indexed node, uint64 ttl);
}
contract Registrar {
function transfer(bytes32, address){
return;
}
}
contract Ledger is SafeMath {
// who deployed Ledger
address public mainAddress;
address public whereToSendFee;
address public repTokenAddress;
address public ensRegistryAddress;
address public registrarAddress;
mapping (address => mapping(uint => address)) lrsPerUser;
mapping (address => uint) lrsCountPerUser;
uint public totalLrCount = 0;
mapping (uint => address) lrs;
// 0.01 ETH
uint public borrowerFeeAmount = 10000000000000000;
modifier byAnyone(){
_;
}
function Ledger(address whereToSendFee_,address repTokenAddress_,address ensRegistryAddress_, address registrarAddress_){
mainAddress = msg.sender;
whereToSendFee = whereToSendFee_;
repTokenAddress = repTokenAddress_;
ensRegistryAddress = ensRegistryAddress_;
registrarAddress = registrarAddress_;
}
function getRepTokenAddress()constant returns(address out){
out = repTokenAddress;
return;
}
function getFeeSum()constant returns(uint out){
out = borrowerFeeAmount;
return;
}
/// Must be called by Borrower
// tokens as a collateral
function createNewLendingRequest()payable byAnyone returns(address out){
out = newLr(0);
}
// domain as a collateral
function createNewLendingRequestEns()payable byAnyone returns(address out){
out = newLr(1);
}
// reputation as a collateral
function createNewLendingRequestRep()payable byAnyone returns(address out){
out = newLr(2);
}
function newLr(int collateralType)payable byAnyone returns(address out){
// 1 - send Fee to wherToSendFee
uint feeAmount = borrowerFeeAmount;
if(msg.value<feeAmount){
throw;
}
if(!whereToSendFee.call.gas(200000).value(feeAmount)()){
throw;
}
// 2 - create new LR
// will be in state 'WaitingForData'
out = new LendingRequest(mainAddress,msg.sender,whereToSendFee,collateralType,ensRegistryAddress,registrarAddress);
// 3 - add to list
uint currentCount = lrsCountPerUser[msg.sender];
lrsPerUser[msg.sender][currentCount] = out;
lrsCountPerUser[msg.sender]++;
lrs[totalLrCount] = out;
totalLrCount++;
}
function getLrCount()constant returns(uint out){
out = totalLrCount;
return;
}
function getLr(uint index) constant returns (address out){
out = lrs[index];
return;
}
function getLrCountForUser(address a)constant returns(uint out){
out = lrsCountPerUser[a];
return;
}
function getLrForUser(address a,uint index) constant returns (address out){
out = lrsPerUser[a][index];
return;
}
function getLrFundedCount()constant returns(uint out){
out = 0;
for(uint i=0; i<totalLrCount; ++i){
LendingRequest lr = LendingRequest(lrs[i]);
if(lr.getState()==LendingRequest.State.WaitingForPayback){
out++;
}
}
return;
}
function getLrFunded(uint index) constant returns (address out){
uint indexFound = 0;
for(uint i=0; i<totalLrCount; ++i){
LendingRequest lr = LendingRequest(lrs[i]);
if(lr.getState()==LendingRequest.State.WaitingForPayback){
if(indexFound==index){
out = lrs[i];
return;
}
indexFound++;
}
}
return;
}
function addRepTokens(address potentialBorrower, uint weiSum){
ReputationTokenInterface repToken = ReputationTokenInterface(repTokenAddress);
LendingRequest lr = LendingRequest(msg.sender);
// we`ll check is msg.sender is a real our LendingRequest
if(lr.borrower()==potentialBorrower && address(this)==lr.creator()){// we`ll take a lr contract and check address a – is he a borrower for this contract?
uint repTokens = (weiSum/10);
repToken.issueTokens(potentialBorrower,repTokens);
}
}
function lockRepTokens(address potentialBorrower, uint weiSum){
ReputationTokenInterface repToken = ReputationTokenInterface(repTokenAddress);
LendingRequest lr = LendingRequest(msg.sender);
// we`ll check is msg.sender is a real our LendingRequest
if(lr.borrower()==potentialBorrower && address(this)==lr.creator()){// we`ll take a lr contract and check address a – is he a borrower for this contract?
uint repTokens = (weiSum);
repToken.lockTokens(potentialBorrower,repTokens);
}
}
function unlockRepTokens(address potentialBorrower, uint weiSum){
ReputationTokenInterface repToken = ReputationTokenInterface(repTokenAddress);
LendingRequest lr = LendingRequest(msg.sender);
// we`ll check is msg.sender is a real our LendingRequest
if(lr.borrower()==potentialBorrower && address(this)==lr.creator()){// we`ll take a lr contract and check address a – is he a borrower for this contract?
uint repTokens = (weiSum);
repToken.unlockTokens(potentialBorrower,repTokens);
}
}
function burnRepTokens(address potentialBorrower){
ReputationTokenInterface repToken = ReputationTokenInterface(repTokenAddress);
LendingRequest lr = LendingRequest(msg.sender);
// we`ll check is msg.sender is a real our LendingRequest
if(lr.borrower()==potentialBorrower && address(this)==lr.creator()){// we`ll take a lr contract and check address a – is he a borrower for this contract?
repToken.burnTokens(potentialBorrower);
}
}
function approveRepTokens(address potentialBorrower,uint weiSum) returns (bool success){
ReputationTokenInterface repToken = ReputationTokenInterface(repTokenAddress);
success = repToken.nonLockedTokensCount(potentialBorrower) >= weiSum;
return;
}
function() payable{
createNewLendingRequest();
}
}
contract LendingRequest is SafeMath {
string public name = "LendingRequest";
address public creator = 0x0;
address public registrarAddress;
// 0.01 ETH
uint public lenderFeeAmount = 10000000000000000;
Ledger ledger;
// who deployed Ledger
address public mainAddress = 0x0;
enum State {
WaitingForData,
// borrower set data
WaitingForTokens,
Cancelled,
// wneh tokens received from borrower
WaitingForLender,
// when money received from Lender
WaitingForPayback,
Default,
Finished
}
enum Type {
TokensCollateral,
EnsCollateral,
RepCollateral
}
// Contract fields:
State public currentState = State.WaitingForData;
Type public currentType = Type.TokensCollateral;
address public whereToSendFee = 0x0;
uint public start = 0;
// This must be set by borrower:
address public borrower = 0x0;
uint public wanted_wei = 0;
uint public token_amount = 0;
uint public premium_wei = 0;
string public token_name = "";
bytes32 public ens_domain_hash;
string public token_infolink = "";
address public token_smartcontract_address = 0x0;
uint public days_to_lend = 0;
// this is an address of AbstractENS contract
address public ensRegistryAddress = 0;
address public lender = 0x0;
// Access methods:
function getBorrower()constant returns(address out){
out = borrower;
}
function getWantedWei()constant returns(uint out){
out = wanted_wei;
}
function getPremiumWei()constant returns(uint out){
out = premium_wei;
}
function getTokenAmount()constant returns(uint out){
out = token_amount;
}
function getTokenName()constant returns(string out){
out = token_name;
}
function getTokenInfoLink()constant returns(string out){
out = token_infolink;
}
function getTokenSmartcontractAddress()constant returns(address out){
out = token_smartcontract_address;
}
function getDaysToLen()constant returns(uint out){
out = days_to_lend;
}
function getState()constant returns(State out){
out = currentState;
return;
}
function getLender()constant returns(address out){
out = lender;
}
function isEns()constant returns(bool out){
out = (currentType==Type.EnsCollateral);
}
function isRep()constant returns(bool out){
out = (currentType==Type.RepCollateral);
}
function getEnsDomainHash()constant returns(bytes32 out){
out = ens_domain_hash;
}
///
modifier byAnyone(){
_;
}
modifier onlyByLedger(){
if(Ledger(msg.sender)!=ledger)
throw;
_;
}
modifier onlyByMain(){
if(msg.sender!=mainAddress)
throw;
_;
}
modifier byLedgerOrMain(){
if((msg.sender!=mainAddress) && (Ledger(msg.sender)!=ledger))
throw;
_;
}
modifier byLedgerMainOrBorrower(){
if((msg.sender!=mainAddress) && (Ledger(msg.sender)!=ledger) && (msg.sender!=borrower))
throw;
_;
}
modifier onlyByLender(){
if(msg.sender!=lender)
throw;
_;
}
modifier onlyInState(State state){
if(currentState!=state)
throw;
_;
}
function LendingRequest(address mainAddress_,address borrower_,address whereToSendFee_, int contractType, address ensRegistryAddress_, address registrarAddress_){
ledger = Ledger(msg.sender);
mainAddress = mainAddress_;
whereToSendFee = whereToSendFee_;
registrarAddress = registrarAddress_;
borrower = borrower_;
creator = msg.sender;
// collateral: tokens or ENS domain?
if (contractType==0){
currentType = Type.TokensCollateral;
}else if(contractType==1){
currentType = Type.EnsCollateral;
}else if(contractType==2){
currentType = Type.RepCollateral;
} else {
throw;
}
ensRegistryAddress = ensRegistryAddress_;
}
function changeLedgerAddress(address new_)onlyByLedger{
ledger = Ledger(new_);
}
function changeMainAddress(address new_)onlyByMain{
mainAddress = new_;
}
//
function setData(uint wanted_wei_, uint token_amount_, uint premium_wei_,
string token_name_, string token_infolink_, address token_smartcontract_address_, uint days_to_lend_, bytes32 ens_domain_hash_)
byLedgerMainOrBorrower onlyInState(State.WaitingForData)
{
wanted_wei = wanted_wei_;
premium_wei = premium_wei_;
token_amount = token_amount_; // will be ZERO if isCollateralEns is true
token_name = token_name_;
token_infolink = token_infolink_;
token_smartcontract_address = token_smartcontract_address_;
days_to_lend = days_to_lend_;
ens_domain_hash = ens_domain_hash_;
if(currentType==Type.RepCollateral){
if(ledger.approveRepTokens(borrower, wanted_wei)){
ledger.lockRepTokens(borrower, wanted_wei);
currentState = State.WaitingForLender;
}
} else {
currentState = State.WaitingForTokens;
}
}
function cancell() byLedgerMainOrBorrower {
// 1 - check current state
if((currentState!=State.WaitingForData) && (currentState!=State.WaitingForLender))
throw;
if(currentState==State.WaitingForLender){
// return tokens back to Borrower
releaseToBorrower();
}
currentState = State.Cancelled;
}
// Should check if tokens are 'trasferred' to this contracts address and controlled
function checkTokens()byLedgerMainOrBorrower onlyInState(State.WaitingForTokens){
if(currentType!=Type.TokensCollateral){
throw;
}
ERC20Token token = ERC20Token(token_smartcontract_address);
uint tokenBalance = token.balanceOf(this);
if(tokenBalance >= token_amount){
// we are ready to search someone
// to give us the money
currentState = State.WaitingForLender;
}
}
function checkDomain() onlyInState(State.WaitingForTokens){
// Use 'ens_domain_hash' to check whether this domain is transferred to this address
AbstractENS ens = AbstractENS(ensRegistryAddress);
if(ens.owner(ens_domain_hash)==address(this)){
// we are ready to search someone
// to give us the money
currentState = State.WaitingForLender;
return;
}
}
// This function is called when someone sends money to this contract directly.
//
// If someone is sending at least 'wanted_wei' amount of money in WaitingForLender state
// -> then it means it's a Lender.
//
// If someone is sending at least 'wanted_wei' amount of money in WaitingForPayback state
// -> then it means it's a Borrower returning money back.
function() payable {
if(currentState==State.WaitingForLender){
waitingForLender();
}else if(currentState==State.WaitingForPayback){
waitingForPayback();
}
}
// If no lenders -> borrower can cancel the LR
function returnTokens() byLedgerMainOrBorrower onlyInState(State.WaitingForLender){
// tokens are released back to borrower
releaseToBorrower();
currentState = State.Finished;
}
function waitingForLender()payable onlyInState(State.WaitingForLender){
if(msg.value<safeAdd(wanted_wei,lenderFeeAmount)){
throw;
}
// send platform fee first
if(!whereToSendFee.call.gas(200000).value(lenderFeeAmount)()){
throw;
}
// if you sent this -> you are the lender
lender = msg.sender;
// ETH is sent to borrower in full
// Tokens are kept inside of this contract
if(!borrower.call.gas(200000).value(wanted_wei)()){
throw;
}
currentState = State.WaitingForPayback;
start = now;
}
// if time hasn't passed yet - Borrower can return loan back
// and get his tokens back
//
// anyone can call this (not only the borrower)
function waitingForPayback()payable onlyInState(State.WaitingForPayback){
if(msg.value<safeAdd(wanted_wei,premium_wei)){
throw;
}
// ETH is sent back to lender in full with premium!!!
if(!lender.call.gas(2000000).value(msg.value)()){
throw;
}
releaseToBorrower(); // tokens are released back to borrower
ledger.addRepTokens(borrower,wanted_wei);
currentState = State.Finished; // finished
}
// How much should lender send
function getNeededSumByLender()constant returns(uint out){
uint total = safeAdd(wanted_wei,lenderFeeAmount);
out = total;
return;
}
// How much should borrower return to release tokens
function getNeededSumByBorrower()constant returns(uint out){
uint total = safeAdd(wanted_wei,premium_wei);
out = total;
return;
}
// After time has passed but lender hasn't returned the loan -> move tokens to lender
// anyone can call this (not only the lender)
function requestDefault()onlyInState(State.WaitingForPayback){
if(now < (start + days_to_lend * 1 days)){
throw;
}
releaseToLender(); // tokens are released to the lender
// ledger.addRepTokens(lender,wanted_wei); // Only Lender get Reputation tokens
currentState = State.Default;
}
function releaseToLender() internal {
if(currentType==Type.EnsCollateral){
AbstractENS ens = AbstractENS(ensRegistryAddress);
Registrar registrar = Registrar(registrarAddress);
ens.setOwner(ens_domain_hash,lender);
registrar.transfer(ens_domain_hash,lender);
}else if (currentType==Type.RepCollateral){
ledger.unlockRepTokens(borrower, wanted_wei);
}else{
ERC20Token token = ERC20Token(token_smartcontract_address);
uint tokenBalance = token.balanceOf(this);
token.transfer(lender,tokenBalance);
}
ledger.burnRepTokens(borrower);
}
function releaseToBorrower() internal {
if(currentType==Type.EnsCollateral){
AbstractENS ens = AbstractENS(ensRegistryAddress);
Registrar registrar = Registrar(registrarAddress);
ens.setOwner(ens_domain_hash,borrower);
registrar.transfer(ens_domain_hash,borrower);
}else if (currentType==Type.RepCollateral){
ledger.unlockRepTokens(borrower, wanted_wei);
}else{
ERC20Token token = ERC20Token(token_smartcontract_address);
uint tokenBalance = token.balanceOf(this);
token.transfer(borrower,tokenBalance);
}
}
}
| we`ll check is msg.sender is a real our LendingRequest | function lockRepTokens(address potentialBorrower, uint weiSum){
ReputationTokenInterface repToken = ReputationTokenInterface(repTokenAddress);
LendingRequest lr = LendingRequest(msg.sender);
uint repTokens = (weiSum);
repToken.lockTokens(potentialBorrower,repTokens);
}
| 6,415,415 |
./partial_match/137/0x725A581c9fC882f0C66c112B1CFf2AeAF502AA36/sources/BaseAuthorizer.sol | Change the caller. _caller the caller which calls the authorizer. | function setCaller(address _caller) external onlyOwner {
require(_caller != address(0), "Invalid caller");
caller = _caller;
emit CallerSet(_caller);
}
| 3,527,985 |
/**
*Submitted for verification at Etherscan.io on 2022-04-20
*/
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
}
/// @author RetreebInc
/// @title Interface Staking Platform with fixed APY and lockup
interface IStakingPlatform {
/**
* @notice function that start the staking
* @dev set `startPeriod` to the current current `block.timestamp`
* set `lockupPeriod` which is `block.timestamp` + `lockupDuration`
* and `endPeriod` which is `startPeriod` + `stakingDuration`
*/
function startStaking() external;
/**
* @notice function that allows a user to deposit tokens
* @dev user must first approve the amount to deposit before calling this function,
* cannot exceed the `maxAmountStaked`
* @param amount, the amount to be deposited
* @dev `endPeriod` to equal 0 (Staking didn't started yet),
* or `endPeriod` more than current `block.timestamp` (staking not finished yet)
* @dev `totalStaked + amount` must be less than `stakingMax`
* @dev that the amount deposited should greater than 0
*/
function deposit(uint amount) external;
/**
* @notice function that allows a user to withdraw its initial deposit
* @dev must be called only when `block.timestamp` >= `endPeriod`
* @dev `block.timestamp` higher than `lockupPeriod` (lockupPeriod finished)
* withdraw reset all states variable for the `msg.sender` to 0, and claim rewards
* if rewards to claim
*/
function withdrawAll() external;
/**
* @notice function that allows a user to withdraw its initial deposit
* @param amount, amount to withdraw
* @dev `block.timestamp` must be higher than `lockupPeriod` (lockupPeriod finished)
* @dev `amount` must be higher than `0`
* @dev `amount` must be lower or equal to the amount staked
* withdraw reset all states variable for the `msg.sender` to 0, and claim rewards
* if rewards to claim
*/
function withdraw(uint amount) external;
/**
* @notice function that returns the amount of total Staked tokens
* for a specific user
* @param stakeHolder, address of the user to check
* @return uint amount of the total deposited Tokens by the caller
*/
function amountStaked(address stakeHolder) external view returns (uint);
/**
* @notice function that returns the amount of total Staked tokens
* on the smart contract
* @return uint amount of the total deposited Tokens
*/
function totalDeposited() external view returns (uint);
/**
* @notice function that returns the amount of pending rewards
* that can be claimed by the user
* @param stakeHolder, address of the user to be checked
* @return uint amount of claimable rewards
*/
function rewardOf(address stakeHolder) external view returns (uint);
/**
* @notice function that claims pending rewards
* @dev transfer the pending rewards to the `msg.sender`
*/
function claimRewards() external;
/**
* @dev Emitted when `amount` tokens are deposited into
* staking platform
*/
event Deposit(address indexed owner, uint amount);
/**
* @dev Emitted when user withdraw deposited `amount`
*/
event Withdraw(address indexed owner, uint amount);
/**
* @dev Emitted when `stakeHolder` claim rewards
*/
event Claim(address indexed stakeHolder, uint amount);
/**
* @dev Emitted when staking has started
*/
event StartStaking(uint startPeriod, uint lockupPeriod, uint endingPeriod);
}
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
// OpenZeppelin Contracts v4.4.1 (utils/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;
}
}
/**
* @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);
}
}
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @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");
}
}
}
/// @author RetreebInc
/// @title Staking Platform with fixed APY and lockup
contract StakingPlatform is IStakingPlatform, Ownable {
using SafeERC20 for IERC20;
IERC20 public immutable token;
IERC20 public immutable tokenExtra;
uint256 public immutable fixedAPY;
uint public immutable stakingDuration;
uint public immutable lockupDuration;
uint public immutable stakingMax;
uint public startPeriod;
uint public lockupPeriod;
uint public endPeriod;
uint private _totalStaked;
uint internal _precision = 1E6;
mapping(address => uint) public staked;
mapping(address => uint) private _rewardsToClaim;
mapping(address => uint) public _userStartTime;
/**
* @notice constructor contains all the parameters of the staking platform
* @dev all parameters are immutable
*/
constructor(address _token, address _tokenExtra, uint256 _fixedAPY, uint _durationInDays, uint _lockDurationInDays, uint _maxAmountStaked) {
stakingDuration = _durationInDays * 1 days;
lockupDuration = _lockDurationInDays * 1 days;
token = IERC20(_token);
tokenExtra = IERC20(_tokenExtra);
fixedAPY = _fixedAPY;
stakingMax = _maxAmountStaked;
}
/**
* @notice function that start the staking
* @dev set `startPeriod` to the current current `block.timestamp`
* set `lockupPeriod` which is `block.timestamp` + `lockupDuration`
* and `endPeriod` which is `startPeriod` + `stakingDuration`
*/
function startStaking() external override onlyOwner {
require(startPeriod == 0, "Staking has already started");
startPeriod = block.timestamp;
lockupPeriod = block.timestamp + lockupDuration;
endPeriod = block.timestamp + stakingDuration;
emit StartStaking(startPeriod, lockupDuration, endPeriod);
}
/**
* @notice function that allows a user to deposit tokens
* @dev user must first approve the amount to deposit before calling this function,
* cannot exceed the `maxAmountStaked`
* @param amount, the amount to be deposited
* @dev `endPeriod` to equal 0 (Staking didn't started yet),
* or `endPeriod` more than current `block.timestamp` (staking not finished yet)
* @dev `totalStaked + amount` must be less than `stakingMax`
* @dev that the amount deposited should greater than 0
*/
function deposit(uint amount) external override {
require(endPeriod == 0 || endPeriod > block.timestamp, "Staking period ended");
require(_totalStaked + amount <= stakingMax, "Amount staked exceeds MaxStake");
require(amount > 0, "Amount must be greater than 0");
if (_userStartTime[_msgSender()] == 0) {
_userStartTime[_msgSender()] = block.timestamp;
}
_updateRewards();
staked[_msgSender()] += amount;
_totalStaked += amount;
token.safeTransferFrom(_msgSender(), address(this), amount);
emit Deposit(_msgSender(), amount);
}
/**
* @notice function that allows a user to withdraw its initial deposit
* @param amount, amount to withdraw
* @dev `block.timestamp` must be higher than `lockupPeriod` (lockupPeriod finished)
* @dev `amount` must be higher than `0`
* @dev `amount` must be lower or equal to the amount staked
* withdraw reset all states variable for the `msg.sender` to 0, and claim rewards
* if rewards to claim
*/
function withdraw(uint amount) external override {
require(block.timestamp >= lockupPeriod, "No withdraw until lockup ends");
require(amount > 0, "Amount must be greater than 0");
require(amount <= staked[_msgSender()], "Amount higher than stakedAmount");
_updateRewards();
if (_rewardsToClaim[_msgSender()] > 0) {
_claimRewards();
}
_totalStaked -= amount;
staked[_msgSender()] -= amount;
token.safeTransfer(_msgSender(), amount);
emit Withdraw(_msgSender(), amount);
}
/**
* @notice function that allows a user to withdraw its initial deposit
* @dev must be called only when `block.timestamp` >= `lockupPeriod`
* @dev `block.timestamp` higher than `lockupPeriod` (lockupPeriod finished)
* withdraw reset all states variable for the `msg.sender` to 0, and claim rewards
* if rewards to claim
*/
function withdrawAll() external override {
require(block.timestamp >= lockupPeriod, "No withdraw until lockup ends");
_updateRewards();
if (_rewardsToClaim[_msgSender()] > 0) {
_claimRewards();
}
_userStartTime[_msgSender()] = 0;
_totalStaked -= staked[_msgSender()];
uint stakedBalance = staked[_msgSender()];
staked[_msgSender()] = 0;
token.safeTransfer(_msgSender(), stakedBalance);
emit Withdraw(_msgSender(), stakedBalance);
}
/**
* @notice claim all remaining balance on the contract
* Residual balance is all the remaining tokens that have not been distributed
* (e.g, in case the number of stakeholders is not sufficient)
* @dev Can only be called one year after the end of the staking period
* Cannot claim initial stakeholders deposit
*/
function withdrawResidualBalance() external onlyOwner {
uint balance = token.balanceOf(address(this));
uint residualBalance = balance - (_totalStaked);
require(residualBalance > 0, "No residual Balance to withdraw");
token.safeTransfer(owner(), residualBalance);
}
function withdrawResidualBalanceExtra() external onlyOwner {
uint balanceExtra = tokenExtra.balanceOf(address(this));
require(balanceExtra > 0, "No residual Balance to withdraw");
tokenExtra.safeTransfer(owner(), balanceExtra);
}
/**
* @notice function that returns the amount of total Staked tokens
* for a specific user
* @param stakeHolder, address of the user to check
* @return uint amount of the total deposited Tokens by the caller
*/
function amountStaked(address stakeHolder) external view override returns (uint){
return staked[stakeHolder];
}
/**
* @notice function that returns the amount of total Staked tokens
* on the smart contract
* @return uint amount of the total deposited Tokens
*/
function totalDeposited() external view override returns (uint) {
return _totalStaked;
}
/**
* @notice function that returns the amount of pending rewards
* that can be claimed by the user
* @param stakeHolder, address of the user to be checked
* @return uint amount of claimable rewards
*/
function rewardOf(address stakeHolder) external view override returns (uint){
return _calculateRewards(stakeHolder);
}
/**
* @notice function that claims pending rewards
* @dev transfer the pending rewards to the `msg.sender`
*/
function claimRewards() external override {
_claimRewards();
}
/**
* @notice calculate rewards based on the `fixedAPY`, `_percentageTimeRemaining()`
* @dev the higher is the precision and the more the time remaining will be precise
* @param stakeHolder, address of the user to be checked
* @return uint amount of claimable tokens of the specified address
*/
function _calculateRewards(address stakeHolder) internal view returns (uint){
if (startPeriod == 0 || staked[stakeHolder] == 0) {
return 0;
}
return
(((staked[stakeHolder] * fixedAPY) *
_percentageTimeRemaining(stakeHolder)) / (_precision * 100)) +
_rewardsToClaim[stakeHolder];
}
/**
* @notice function that returns the remaining time in seconds of the staking period
* @dev the higher is the precision and the more the time remaining will be precise
* @param stakeHolder, address of the user to be checked
* @return uint percentage of time remaining * precision
*/
function _percentageTimeRemaining(address stakeHolder) internal view returns (uint){
bool early = startPeriod > _userStartTime[stakeHolder];
uint startTime;
if (endPeriod > block.timestamp) {
startTime = early ? startPeriod : _userStartTime[stakeHolder];
uint timeRemaining = stakingDuration -
(block.timestamp - startTime);
return
(_precision * (stakingDuration - timeRemaining)) /
stakingDuration;
}
startTime = early
? 0
: stakingDuration - (endPeriod - _userStartTime[stakeHolder]);
return (_precision * (stakingDuration - startTime)) / stakingDuration;
}
/**
* @notice internal function that claims pending rewards
* @dev transfer the pending rewards to the user address
*/
function _claimRewards() private {
_updateRewards();
uint rewardsToClaim = _rewardsToClaim[_msgSender()];
require(rewardsToClaim > 0, "Nothing to claim");
_rewardsToClaim[_msgSender()] = 0;
token.safeTransfer(_msgSender(), rewardsToClaim); //Transfer main token.
tokenExtra.safeTransfer(_msgSender(), rewardsToClaim); //Transfer extra token.
emit Claim(_msgSender(), rewardsToClaim);
}
/**
* @notice function that update pending rewards
* and shift them to rewardsToClaim
* @dev update rewards claimable
* and check the time spent since deposit for the `msg.sender`
*/
function _updateRewards() private {
_rewardsToClaim[_msgSender()] = _calculateRewards(_msgSender());
_userStartTime[_msgSender()] = (block.timestamp >= endPeriod)
? endPeriod
: block.timestamp;
}
} | function that allows a user to deposit tokens user must first approve the amount to deposit before calling this function, cannot exceed the `maxAmountStaked` amount, the amount to be deposited `endPeriod` to equal 0 (Staking didn't started yet), or `endPeriod` more than current `block.timestamp` (staking not finished yet) `totalStaked + amount` must be less than `stakingMax` that the amount deposited should greater than 0/ | function deposit(uint amount) external override {
require(endPeriod == 0 || endPeriod > block.timestamp, "Staking period ended");
require(_totalStaked + amount <= stakingMax, "Amount staked exceeds MaxStake");
require(amount > 0, "Amount must be greater than 0");
if (_userStartTime[_msgSender()] == 0) {
_userStartTime[_msgSender()] = block.timestamp;
}
_updateRewards();
staked[_msgSender()] += amount;
_totalStaked += amount;
token.safeTransferFrom(_msgSender(), address(this), amount);
emit Deposit(_msgSender(), amount);
}
| 10,678,982 |
/**
*Submitted for verification at Etherscan.io on 2021-03-15
*/
// File: openzeppelin-solidity/contracts/GSN/Context.sol
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: openzeppelin-solidity/contracts/introspection/IERC165.sol
pragma solidity ^0.5.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-solidity/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.5.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
contract IERC721 is IERC165 {
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);
/**
* @dev Returns the number of NFTs in `owner`'s account.
*/
function balanceOf(address owner) public view returns (uint256 balance);
/**
* @dev Returns the owner of the NFT specified by `tokenId`.
*/
function ownerOf(uint256 tokenId) public view returns (address owner);
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
*
*
* Requirements:
* - `from`, `to` cannot be zero.
* - `tokenId` must be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this
* NFT by either {approve} or {setApprovalForAll}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public;
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
* Requirements:
* - If the caller is not `from`, it must be approved to move this NFT by
* either {approve} or {setApprovalForAll}.
*/
function transferFrom(address from, address to, uint256 tokenId) public;
function approve(address to, uint256 tokenId) public;
function getApproved(uint256 tokenId) public view returns (address operator);
function setApprovalForAll(address operator, bool _approved) public;
function isApprovedForAll(address owner, address operator) public view returns (bool);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public;
}
// File: openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.5.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a {IERC721-safeTransferFrom}. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data)
public returns (bytes4);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: openzeppelin-solidity/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: openzeppelin-solidity/contracts/drafts/Counters.sol
pragma solidity ^0.5.0;
/**
* @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);
}
}
// File: openzeppelin-solidity/contracts/introspection/ERC165.sol
pragma solidity ^0.5.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.5.0;
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping (uint256 => address) private _tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => Counters.Counter) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
constructor () public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
}
/**
* @dev Gets the balance of the specified address.
* @param owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address owner) public view returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _ownedTokensCount[owner].current();
}
/**
* @dev Gets the owner of the specified token ID.
* @param tokenId uint256 ID of the token to query the owner of
* @return address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 tokenId) public view returns (address) {
address owner = _tokenOwner[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @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 {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @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) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @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 {
require(to != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][to] = approved;
emit ApprovalForAll(_msgSender(), 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 _operatorApprovals[owner][operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address.
* Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
* Requires the msg.sender to be the owner, approved, or operator.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address from, address to, uint256 tokenId) public {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transferFrom(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 {IERC721Receiver-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 {IERC721Receiver-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 _msgSender() 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 memory _data) public {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransferFrom(from, to, tokenId, _data);
}
/**
* @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 memory _data) internal {
_transferFrom(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether the specified token exists.
* @param tokenId uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
/**
* @dev Returns whether the given spender can transfer a given token ID.
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* 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.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _safeMint(address to, uint256 tokenId) internal {
_safeMint(to, tokenId, "");
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* 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.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
* @param _data bytes data to send along with a safe transfer check
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, uint256 tokenId) internal {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].increment();
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {_burn} instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own");
_clearApproval(tokenId);
_ownedTokensCount[owner].decrement();
_tokenOwner[tokenId] = address(0);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* @param tokenId uint256 ID of the token being burned
*/
function _burn(uint256 tokenId) internal {
_burn(ownerOf(tokenId), tokenId);
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
* @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) internal {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_clearApproval(tokenId);
_ownedTokensCount[from].decrement();
_ownedTokensCount[to].increment();
_tokenOwner[tokenId] = to;
emit Transfer(from, 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.
*
* This is an internal detail of the `ERC721` contract and its use is deprecated.
* @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)
internal returns (bool)
{
if (!to.isContract()) {
return true;
}
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = to.call(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
));
if (!success) {
if (returndata.length > 0) {
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert("ERC721: transfer to non ERC721Receiver implementer");
}
} else {
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
}
/**
* @dev Private function to clear current approval of a given token ID.
* @param tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(uint256 tokenId) private {
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
// File: openzeppelin-solidity/contracts/token/ERC721/IERC721Enumerable.sol
pragma solidity ^0.5.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract IERC721Enumerable is IERC721 {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId);
function tokenByIndex(uint256 index) public view returns (uint256);
}
// File: openzeppelin-solidity/contracts/token/ERC721/ERC721Enumerable.sol
pragma solidity ^0.5.0;
/**
* @title ERC-721 Non-Fungible Token with optional enumeration extension logic
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => 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;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Constructor function.
*/
constructor () public {
// register the supported interface to conform to ERC721Enumerable via ERC165
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner.
* @param owner address owning the tokens list to be accessed
* @param index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) {
require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev Gets the total amount of tokens stored by the contract.
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return _allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens.
* @param index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 index) public view returns (uint256) {
require(index < totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to transferFrom, this imposes no restrictions on msg.sender.
* @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) internal {
super._transferFrom(from, to, tokenId);
_removeTokenFromOwnerEnumeration(from, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to address the beneficiary that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, uint256 tokenId) internal {
super._mint(to, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
_addTokenToAllTokensEnumeration(tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {ERC721-_burn} instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
_removeTokenFromOwnerEnumeration(owner, tokenId);
// Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund
_ownedTokensIndex[tokenId] = 0;
_removeTokenFromAllTokensEnumeration(tokenId);
}
/**
* @dev Gets the list of token IDs of the requested owner.
* @param owner address owning the tokens
* @return uint256[] List of token IDs owned by the requested address
*/
function _tokensOfOwner(address owner) internal view returns (uint256[] storage) {
return _ownedTokens[owner];
}
/**
* @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 {
_ownedTokensIndex[tokenId] = _ownedTokens[to].length;
_ownedTokens[to].push(tokenId);
}
/**
* @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 = _ownedTokens[from].length.sub(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
_ownedTokens[from].length--;
// Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by
// lastTokenId, or just over the end of the array if the token was the last one).
}
/**
* @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.sub(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
_allTokens.length--;
_allTokensIndex[tokenId] = 0;
}
}
// File: openzeppelin-solidity/contracts/token/ERC721/IERC721Metadata.sol
pragma solidity ^0.5.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: openzeppelin-solidity/contracts/token/ERC721/ERC721Metadata.sol
pragma solidity ^0.5.0;
contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Base URI
string private _baseURI;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/**
* @dev Constructor function
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
}
/**
* @dev Gets the token name.
* @return string representing the token name
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the URI for a given token ID. May return an empty string.
*
* If the token's URI is non-empty and a base URI was set (via
* {_setBaseURI}), it will be added to the token ID's URI as a prefix.
*
* Reverts if the token ID does not exist.
*/
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
// Even if there is a base URI, it is only appended to non-empty token-specific URIs
if (bytes(_tokenURI).length == 0) {
return "";
} else {
// abi.encodePacked is being used to concatenate strings
return string(abi.encodePacked(_baseURI, _tokenURI));
}
}
/**
* @dev Internal function to set the token URI for a given token.
*
* Reverts if the token ID does not exist.
*
* TIP: if all token IDs share a prefix (e.g. if your URIs look like
* `http://api.myproject.com/token/<id>`), use {_setBaseURI} to store
* it and save gas.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI}.
*
* _Available since v2.5.0._
*/
function _setBaseURI(string memory baseURI) internal {
_baseURI = baseURI;
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a preffix in {tokenURI} to each token's URI, when
* they are non-empty.
*
* _Available since v2.5.0._
*/
function baseURI() external view returns (string memory) {
return _baseURI;
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use _burn(uint256) instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// File: openzeppelin-solidity/contracts/token/ERC721/ERC721Full.sol
pragma solidity ^0.5.0;
/**
* @title Full ERC721 Token
* @dev This implementation includes all the required and some optional functionality of the ERC721 standard
* Moreover, it includes approve all functionality using operator terminology.
*
* See https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata {
constructor (string memory name, string memory symbol) public ERC721Metadata(name, symbol) {
// solhint-disable-previous-line no-empty-blocks
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/Strings.sol
pragma solidity ^0.5.0;
library Strings {
// via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (uint i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (uint i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (uint i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (uint i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string memory _a, string memory _b) internal pure returns (string memory) {
return strConcat(_a, _b, "", "", "");
}
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 - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
}
// File: contracts/ERC721Tradable.sol
pragma solidity ^0.5.0;
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
/**
* @title ERC721Tradable
* ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality.
*/
contract ERC721Tradable is ERC721Full, Ownable {
using Strings for string;
address proxyRegistryAddress;
string public baseURI;
mapping (uint256 => string) private _properties;
constructor(
string memory _name,
string memory _symbol,
address _proxyRegistryAddress,
string memory _baseURI
) public ERC721Full(_name, _symbol) {
setBaseURI(_baseURI);
proxyRegistryAddress = _proxyRegistryAddress;
}
/**
* @dev Mints a token to an address with a tokenURI.
* @param to address of the future owner of the token
*/
function mint(address to, uint256 tokenId, string memory properties) public onlyOwner {
_mint(to, tokenId);
_properties[tokenId] = properties;
}
function properties(uint256 tokenId) public view returns (string memory) {
return _properties[tokenId];
}
function baseTokenURI() public view returns (string memory) {
return baseURI;
}
function setBaseURI(string memory uri) public onlyOwner {
baseURI = uri;
}
function tokenURI(uint256 tokenId) external view returns (string memory) {
return Strings.strConcat(baseTokenURI(), Strings.uint2str(tokenId), properties(tokenId));
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.
*/
function isApprovedForAll(address owner, address operator)
public
view
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);
}
}
// File: contracts/WeblinItem.sol
pragma solidity ^0.5.0;
/**
* @title WeblinItem
* WeblinItem - a contract for my non-fungible WeblinItems.
*/
contract WeblinItem is ERC721Tradable {
constructor(address _proxyRegistryAddress, string memory _baseURI)
public
ERC721Tradable("WeblinItem", "WI", _proxyRegistryAddress, _baseURI)
{
}
function contractURI() public view returns (string memory) {
return baseTokenURI();
}
} | Mints a token to an address with a tokenURI. to address of the future owner of the token/ | function mint(address to, uint256 tokenId, string memory properties) public onlyOwner {
_mint(to, tokenId);
_properties[tokenId] = properties;
}
| 2,057,111 |
pragma solidity ^0.4.24;
/** @title PEpsilon
* @author Daniel Babbev
*
* This contract implements a p + epsilon attack against the Kleros court.
* The attack is described by VitaliK Buterin here: https://blog.ethereum.org/2015/01/28/p-epsilon-attack/
*/
contract PEpsilon {
Pinakion public pinakion;
Kleros public court;
uint public balance;
uint public disputeID;
uint public desiredOutcome;
uint public epsilon;
bool public settled;
uint public maxAppeals; // The maximum number of appeals this cotracts promises to pay
mapping (address => uint) public withdraw; // We'll use a withdraw pattern here to avoid multiple sends when a juror has voted multiple times.
address public attacker;
uint public remainingWithdraw; // Here we keep the total amount bribed jurors have available for withdraw.
modifier onlyBy(address _account) {require(msg.sender == _account); _;}
event AmountShift(uint val, uint epsilon ,address juror);
event Log(uint val, address addr, string message);
/** @dev Constructor.
* @param _pinakion The PNK contract.
* @param _kleros The Kleros court.
* @param _disputeID The dispute we are targeting.
* @param _desiredOutcome The desired ruling of the dispute.
* @param _epsilon Jurors will be paid epsilon more for voting for the desiredOutcome.
* @param _maxAppeals The maximum number of appeals this contract promises to pay out
*/
constructor(Pinakion _pinakion, Kleros _kleros, uint _disputeID, uint _desiredOutcome, uint _epsilon, uint _maxAppeals) public {
pinakion = _pinakion;
court = _kleros;
disputeID = _disputeID;
desiredOutcome = _desiredOutcome;
epsilon = _epsilon;
attacker = msg.sender;
maxAppeals = _maxAppeals;
}
/** @dev Callback of approveAndCall - transfer pinakions in the contract. Should be called by the pinakion contract. TRUSTED.
* The attacker has to deposit sufficiently large amount of PNK to cover the payouts to the jurors.
* @param _from The address making the transfer.
* @param _amount Amount of tokens to transfer to this contract (in basic units).
*/
function receiveApproval(address _from, uint _amount, address, bytes) public onlyBy(pinakion) {
require(pinakion.transferFrom(_from, this, _amount));
balance += _amount;
}
/** @dev Jurors can withdraw their PNK from here
*/
function withdrawJuror() {
withdrawSelect(msg.sender);
}
/** @dev Withdraw the funds of a given juror
* @param _juror The address of the juror
*/
function withdrawSelect(address _juror) {
uint amount = withdraw[_juror];
withdraw[_juror] = 0;
balance = sub(balance, amount); // Could underflow
remainingWithdraw = sub(remainingWithdraw, amount);
// The juror receives d + p + e (deposit + p + epsilon)
require(pinakion.transfer(_juror, amount));
}
/**
* @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 The attacker can withdraw their PNK from here after the bribe has been settled.
*/
function withdrawAttacker(){
require(settled);
if (balance > remainingWithdraw) {
// The remaning balance of PNK after settlement is transfered to the attacker.
uint amount = balance - remainingWithdraw;
balance = remainingWithdraw;
require(pinakion.transfer(attacker, amount));
}
}
/** @dev Settles the p + e bribe with the jurors.
* If the dispute is ruled differently from desiredOutcome:
* The jurors who voted for desiredOutcome receive p + d + e in rewards from this contract.
* If the dispute is ruled as in desiredOutcome:
* The jurors don't receive anything from this contract.
*/
function settle() public {
require(court.disputeStatus(disputeID) == Arbitrator.DisputeStatus.Solved); // The case must be solved.
require(!settled); // This function can be executed only once.
settled = true; // settle the bribe
// From the dispute we get the # of appeals and the available choices
var (, , appeals, choices, , , ,) = court.disputes(disputeID);
if (court.currentRuling(disputeID) != desiredOutcome){
// Calculate the redistribution amounts.
uint amountShift = court.getStakePerDraw();
uint winningChoice = court.getWinningChoice(disputeID, appeals);
// Rewards are calculated as per the one shot token reparation.
for (uint i=0; i <= (appeals > maxAppeals ? maxAppeals : appeals); i++){ // Loop each appeal and each vote.
// Note that we don't check if the result was a tie becuse we are getting a funny compiler error: "stack is too deep" if we check.
// TODO: Account for ties
if (winningChoice != 0){
// votesLen is the length of the votes per each appeal. There is no getter function for that, so we have to calculate it here.
// We must end up with the exact same value as if we would have called dispute.votes[i].length
uint votesLen = 0;
for (uint c = 0; c <= choices; c++) { // Iterate for each choice of the dispute.
votesLen += court.getVoteCount(disputeID, i, c);
}
emit Log(amountShift, 0x0 ,"stakePerDraw");
emit Log(votesLen, 0x0, "votesLen");
uint totalToRedistribute = 0;
uint nbCoherent = 0;
// Now we will use votesLen as a substitute for dispute.votes[i].length
for (uint j=0; j < votesLen; j++){
uint voteRuling = court.getVoteRuling(disputeID, i, j);
address voteAccount = court.getVoteAccount(disputeID, i, j);
emit Log(voteRuling, voteAccount, "voted");
if (voteRuling != winningChoice){
totalToRedistribute += amountShift;
if (voteRuling == desiredOutcome){ // If the juror voted as we desired.
// Transfer this juror back the penalty.
withdraw[voteAccount] += amountShift + epsilon;
remainingWithdraw += amountShift + epsilon;
emit AmountShift(amountShift, epsilon, voteAccount);
}
} else {
nbCoherent++;
}
}
// toRedistribute is the amount each juror received when he voted coherently.
uint toRedistribute = (totalToRedistribute - amountShift) / (nbCoherent + 1);
// We use votesLen again as a substitute for dispute.votes[i].length
for (j = 0; j < votesLen; j++){
voteRuling = court.getVoteRuling(disputeID, i, j);
voteAccount = court.getVoteAccount(disputeID, i, j);
if (voteRuling == desiredOutcome){
// Add the coherent juror reward to the total payout.
withdraw[voteAccount] += toRedistribute;
remainingWithdraw += toRedistribute;
emit AmountShift(toRedistribute, 0, voteAccount);
}
}
}
}
}
}
}
/**
* @title Kleros
* @author Clément Lesaege - <[email protected]>
* This code implements a simple version of Kleros.
* Bug Bounties: This code hasn't undertaken a bug bounty program yet.
*/
pragma solidity ^0.4.24;
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public;
}
/// @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);
}
contract Controlled {
/// @notice The address of the controller is the only address that can call
/// a function with this modifier
modifier onlyController { require(msg.sender == controller); _; }
address public controller;
function Controlled() public { controller = msg.sender;}
/// @notice Changes the controller of the contract
/// @param _newController The new controller of the contract
function changeController(address _newController) public onlyController {
controller = _newController;
}
}
/// @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 Pinakion is Controlled {
string public name; //The Token's name: e.g. DigixDAO Tokens
uint8 public decimals; //Number of decimals of the smallest unit
string public symbol; //An identifier: e.g. REP
string public version = 'MMT_0.2'; //An arbitrary versioning scheme
/// @dev `Checkpoint` is the structure that attaches a block number to a
/// given value, the block number attached is the one that last changed the
/// value
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint128 fromBlock;
// `value` is the amount of tokens at a specific block number
uint128 value;
}
// `parentToken` is the Token address that was cloned to produce this token;
// it will be 0x0 for a token that was not cloned
Pinakion 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 Pinakion
/// @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
function Pinakion(
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 = Pinakion(_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] -= _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) {
Transfer(_from, _to, _amount); // Follow the spec to louch the event when transfer 0
return;
}
require(parentSnapShotBlock < block.number);
// Do not allow transfer to 0x0 or the token contract itself
require((_to != 0) && (_to != address(this)));
// If the amount being transfered is more than the balance of the
// account the transfer throws
var previousBalanceFrom = balanceOfAt(_from, block.number);
require(previousBalanceFrom >= _amount);
// Alerts the token controller of the transfer
if (isContract(controller)) {
require(TokenController(controller).onTransfer(_from, _to, _amount));
}
// First update the balance array with the new value for the address
// sending the tokens
updateValueAtNow(balances[_from], previousBalanceFrom - _amount);
// Then update the balance array with the new value for the address
// receiving the tokens
var previousBalanceTo = balanceOfAt(_to, block.number);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
// An event to make the transfer easy to find on the blockchain
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 the standard version to allow backward compatibility.
/// @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);
// 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;
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);
}
}
////////////////
// Clone Token Method
////////////////
/// @notice Creates a new clone token with the initial distribution being
/// this token at `_snapshotBlock`
/// @param _cloneTokenName Name of the clone token
/// @param _cloneDecimalUnits Number of decimals of the smallest unit
/// @param _cloneTokenSymbol Symbol of the clone token
/// @param _snapshotBlock Block when the distribution of the parent token is
/// copied to set the initial distribution of the new clone token;
/// if the block is zero than the actual block, the current block is used
/// @param _transfersEnabled True if transfers are allowed in the clone
/// @return The address of the new MiniMeToken Contract
function createCloneToken(
string _cloneTokenName,
uint8 _cloneDecimalUnits,
string _cloneTokenSymbol,
uint _snapshotBlock,
bool _transfersEnabled
) public returns(address) {
if (_snapshotBlock == 0) _snapshotBlock = block.number;
Pinakion cloneToken = tokenFactory.createCloneToken(
this,
_snapshotBlock,
_cloneTokenName,
_cloneDecimalUnits,
_cloneTokenSymbol,
_transfersEnabled
);
cloneToken.changeController(msg.sender);
// An event to make the token easy to find on the blockchain
NewCloneToken(address(cloneToken), _snapshotBlock);
return address(cloneToken);
}
////////////////
// Generate and destroy tokens
////////////////
/// @notice Generates `_amount` tokens that are assigned to `_owner`
/// @param _owner The address that will be assigned the new tokens
/// @param _amount The quantity of tokens generated
/// @return True if the tokens are generated correctly
function generateTokens(address _owner, uint _amount
) public onlyController returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_owner], previousBalanceTo + _amount);
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
) onlyController public returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
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 onlyController {
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-1].fromBlock)
return checkpoints[checkpoints.length-1].value;
if (_block < checkpoints[0].fromBlock) return 0;
// Binary search of the value in the array
uint min = 0;
uint max = checkpoints.length-1;
while (max > min) {
uint mid = (max + min + 1)/ 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
/// @dev `updateValueAtNow` used to update the `balances` map and the
/// `totalSupplyHistory`
/// @param checkpoints The history of data being updated
/// @param _value The new number of tokens
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value
) internal {
if ((checkpoints.length == 0)
|| (checkpoints[checkpoints.length -1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
/// @dev Internal function to determine if an address is a contract
/// @param _addr The address being queried
/// @return True if `_addr` is a contract
function isContract(address _addr) 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));
}
//////////
// 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 onlyController {
if (_token == 0x0) {
controller.transfer(this.balance);
return;
}
Pinakion token = Pinakion(_token);
uint balance = token.balanceOf(this);
token.transfer(controller, balance);
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 (Pinakion) {
Pinakion newToken = new Pinakion(
this,
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.changeController(msg.sender);
return newToken;
}
}
contract RNG{
/** @dev Contribute to the reward of a random number.
* @param _block Block the random number is linked to.
*/
function contribute(uint _block) public payable;
/** @dev Request a random number.
* @param _block Block linked to the request.
*/
function requestRN(uint _block) public payable {
contribute(_block);
}
/** @dev Get the random number.
* @param _block Block the random number is linked to.
* @return RN Random Number. If the number is not ready or has not been required 0 instead.
*/
function getRN(uint _block) public returns (uint RN);
/** @dev Get a uncorrelated random number. Act like getRN but give a different number for each sender.
* This is to prevent users from getting correlated numbers.
* @param _block Block the random number is linked to.
* @return RN Random Number. If the number is not ready or has not been required 0 instead.
*/
function getUncorrelatedRN(uint _block) public returns (uint RN) {
uint baseRN=getRN(_block);
if (baseRN==0)
return 0;
else
return uint(keccak256(msg.sender,baseRN));
}
}
/** Simple Random Number Generator returning the blockhash.
* Allows saving the random number for use in the future.
* It allows the contract to still access the blockhash even after 256 blocks.
* The first party to call the save function gets the reward.
*/
contract BlockHashRNG is RNG {
mapping (uint => uint) public randomNumber; // randomNumber[block] is the random number for this block, 0 otherwise.
mapping (uint => uint) public reward; // reward[block] is the amount to be paid to the party w.
/** @dev Contribute to the reward of a random number.
* @param _block Block the random number is linked to.
*/
function contribute(uint _block) public payable { reward[_block]+=msg.value; }
/** @dev Return the random number. If it has not been saved and is still computable compute it.
* @param _block Block the random number is linked to.
* @return RN Random Number. If the number is not ready or has not been requested 0 instead.
*/
function getRN(uint _block) public returns (uint RN) {
RN=randomNumber[_block];
if (RN==0){
saveRN(_block);
return randomNumber[_block];
}
else
return RN;
}
/** @dev Save the random number for this blockhash and give the reward to the caller.
* @param _block Block the random number is linked to.
*/
function saveRN(uint _block) public {
if (blockhash(_block) != 0x0)
randomNumber[_block] = uint(blockhash(_block));
if (randomNumber[_block] != 0) { // If the number is set.
uint rewardToSend = reward[_block];
reward[_block] = 0;
msg.sender.send(rewardToSend); // Note that the use of send is on purpose as we don't want to block in case msg.sender has a fallback issue.
}
}
}
/** Random Number Generator returning the blockhash with a backup behaviour.
* Allows saving the random number for use in the future.
* It allows the contract to still access the blockhash even after 256 blocks.
* The first party to call the save function gets the reward.
* If no one calls the contract within 256 blocks, the contract fallback in returning the blockhash of the previous block.
*/
contract BlockHashRNGFallback is BlockHashRNG {
/** @dev Save the random number for this blockhash and give the reward to the caller.
* @param _block Block the random number is linked to.
*/
function saveRN(uint _block) public {
if (_block<block.number && randomNumber[_block]==0) {// If the random number is not already set and can be.
if (blockhash(_block)!=0x0) // Normal case.
randomNumber[_block]=uint(blockhash(_block));
else // The contract was not called in time. Fallback to returning previous blockhash.
randomNumber[_block]=uint(blockhash(block.number-1));
}
if (randomNumber[_block] != 0) { // If the random number is set.
uint rewardToSend=reward[_block];
reward[_block]=0;
msg.sender.send(rewardToSend); // Note that the use of send is on purpose as we don't want to block in case the msg.sender has a fallback issue.
}
}
}
/** @title Arbitrable
* Arbitrable abstract contract.
* When developing arbitrable contracts, we need to:
* -Define the action taken when a ruling is received by the contract. We should do so in executeRuling.
* -Allow dispute creation. For this a function must:
* -Call arbitrator.createDispute.value(_fee)(_choices,_extraData);
* -Create the event Dispute(_arbitrator,_disputeID,_rulingOptions);
*/
contract Arbitrable{
Arbitrator public arbitrator;
bytes public arbitratorExtraData; // Extra data to require particular dispute and appeal behaviour.
modifier onlyArbitrator {require(msg.sender==address(arbitrator)); _;}
/** @dev To be raised when a ruling is given.
* @param _arbitrator The arbitrator giving the ruling.
* @param _disputeID ID of the dispute in the Arbitrator contract.
* @param _ruling The ruling which was given.
*/
event Ruling(Arbitrator indexed _arbitrator, uint indexed _disputeID, uint _ruling);
/** @dev To be emmited when meta-evidence is submitted.
* @param _metaEvidenceID Unique identifier of meta-evidence.
* @param _evidence A link to the meta-evidence JSON.
*/
event MetaEvidence(uint indexed _metaEvidenceID, string _evidence);
/** @dev To be emmited when a dispute is created to link the correct meta-evidence to the disputeID
* @param _arbitrator The arbitrator of the contract.
* @param _disputeID ID of the dispute in the Arbitrator contract.
* @param _metaEvidenceID Unique identifier of meta-evidence.
*/
event Dispute(Arbitrator indexed _arbitrator, uint indexed _disputeID, uint _metaEvidenceID);
/** @dev To be raised when evidence are submitted. Should point to the ressource (evidences are not to be stored on chain due to gas considerations).
* @param _arbitrator The arbitrator of the contract.
* @param _disputeID ID of the dispute in the Arbitrator contract.
* @param _party The address of the party submiting the evidence. Note that 0x0 refers to evidence not submitted by any party.
* @param _evidence A URI to the evidence JSON file whose name should be its keccak256 hash followed by .json.
*/
event Evidence(Arbitrator indexed _arbitrator, uint indexed _disputeID, address _party, string _evidence);
/** @dev Constructor. Choose the arbitrator.
* @param _arbitrator The arbitrator of the contract.
* @param _arbitratorExtraData Extra data for the arbitrator.
*/
constructor(Arbitrator _arbitrator, bytes _arbitratorExtraData) public {
arbitrator = _arbitrator;
arbitratorExtraData = _arbitratorExtraData;
}
/** @dev Give a ruling for a dispute. Must be called by the arbitrator.
* The purpose of this function is to ensure that the address calling it has the right to rule on the contract.
* @param _disputeID ID of the dispute in the Arbitrator contract.
* @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision".
*/
function rule(uint _disputeID, uint _ruling) public onlyArbitrator {
emit Ruling(Arbitrator(msg.sender),_disputeID,_ruling);
executeRuling(_disputeID,_ruling);
}
/** @dev Execute a ruling of a dispute.
* @param _disputeID ID of the dispute in the Arbitrator contract.
* @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision".
*/
function executeRuling(uint _disputeID, uint _ruling) internal;
}
/** @title Arbitrator
* Arbitrator abstract contract.
* When developing arbitrator contracts we need to:
* -Define the functions for dispute creation (createDispute) and appeal (appeal). Don't forget to store the arbitrated contract and the disputeID (which should be unique, use nbDisputes).
* -Define the functions for cost display (arbitrationCost and appealCost).
* -Allow giving rulings. For this a function must call arbitrable.rule(disputeID,ruling).
*/
contract Arbitrator{
enum DisputeStatus {Waiting, Appealable, Solved}
modifier requireArbitrationFee(bytes _extraData) {require(msg.value>=arbitrationCost(_extraData)); _;}
modifier requireAppealFee(uint _disputeID, bytes _extraData) {require(msg.value>=appealCost(_disputeID, _extraData)); _;}
/** @dev To be raised when a dispute can be appealed.
* @param _disputeID ID of the dispute.
*/
event AppealPossible(uint _disputeID);
/** @dev To be raised when a dispute is created.
* @param _disputeID ID of the dispute.
* @param _arbitrable The contract which created the dispute.
*/
event DisputeCreation(uint indexed _disputeID, Arbitrable _arbitrable);
/** @dev To be raised when the current ruling is appealed.
* @param _disputeID ID of the dispute.
* @param _arbitrable The contract which created the dispute.
*/
event AppealDecision(uint indexed _disputeID, Arbitrable _arbitrable);
/** @dev Create a dispute. Must be called by the arbitrable contract.
* Must be paid at least arbitrationCost(_extraData).
* @param _choices Amount of choices the arbitrator can make in this dispute.
* @param _extraData Can be used to give additional info on the dispute to be created.
* @return disputeID ID of the dispute created.
*/
function createDispute(uint _choices, bytes _extraData) public requireArbitrationFee(_extraData) payable returns(uint disputeID) {}
/** @dev Compute the cost of arbitration. It is recommended not to increase it often, as it can be highly time and gas consuming for the arbitrated contracts to cope with fee augmentation.
* @param _extraData Can be used to give additional info on the dispute to be created.
* @return fee Amount to be paid.
*/
function arbitrationCost(bytes _extraData) public constant returns(uint fee);
/** @dev Appeal a ruling. Note that it has to be called before the arbitrator contract calls rule.
* @param _disputeID ID of the dispute to be appealed.
* @param _extraData Can be used to give extra info on the appeal.
*/
function appeal(uint _disputeID, bytes _extraData) public requireAppealFee(_disputeID,_extraData) payable {
emit AppealDecision(_disputeID, Arbitrable(msg.sender));
}
/** @dev Compute the cost of appeal. It is recommended not to increase it often, as it can be higly time and gas consuming for the arbitrated contracts to cope with fee augmentation.
* @param _disputeID ID of the dispute to be appealed.
* @param _extraData Can be used to give additional info on the dispute to be created.
* @return fee Amount to be paid.
*/
function appealCost(uint _disputeID, bytes _extraData) public constant returns(uint fee);
/** @dev Return the status of a dispute.
* @param _disputeID ID of the dispute to rule.
* @return status The status of the dispute.
*/
function disputeStatus(uint _disputeID) public constant returns(DisputeStatus status);
/** @dev Return the current ruling of a dispute. This is useful for parties to know if they should appeal.
* @param _disputeID ID of the dispute.
* @return ruling The ruling which has been given or the one which will be given if there is no appeal.
*/
function currentRuling(uint _disputeID) public constant returns(uint ruling);
}
contract Kleros is Arbitrator, ApproveAndCallFallBack {
// **************************** //
// * Contract variables * //
// **************************** //
// Variables which should not change after initialization.
Pinakion public pinakion;
uint public constant NON_PAYABLE_AMOUNT = (2**256 - 2) / 2; // An astronomic amount, practically can't be paid.
// Variables which will subject to the governance mechanism.
// Note they will only be able to be changed during the activation period (because a session assumes they don't change after it).
RNG public rng; // Random Number Generator used to draw jurors.
uint public arbitrationFeePerJuror = 0.05 ether; // The fee which will be paid to each juror.
uint16 public defaultNumberJuror = 3; // Number of drawn jurors unless specified otherwise.
uint public minActivatedToken = 0.1 * 1e18; // Minimum of tokens to be activated (in basic units).
uint[5] public timePerPeriod; // The minimum time each period lasts (seconds).
uint public alpha = 2000; // alpha in ‱ (1 / 10 000).
uint constant ALPHA_DIVISOR = 1e4; // Amount we need to divided alpha in ‱ to get the float value of alpha.
uint public maxAppeals = 5; // Number of times a dispute can be appealed. When exceeded appeal cost becomes NON_PAYABLE_AMOUNT.
// Initially, the governor will be an address controlled by the Kleros team. At a later stage,
// the governor will be switched to a governance contract with liquid voting.
address public governor; // Address of the governor contract.
// Variables changing during day to day interaction.
uint public session = 1; // Current session of the court.
uint public lastPeriodChange; // The last time we changed of period (seconds).
uint public segmentSize; // Size of the segment of activated tokens.
uint public rnBlock; // The block linked with the RN which is requested.
uint public randomNumber; // Random number of the session.
enum Period {
Activation, // When juror can deposit their tokens and parties give evidences.
Draw, // When jurors are drawn at random, note that this period is fast.
Vote, // Where jurors can vote on disputes.
Appeal, // When parties can appeal the rulings.
Execution // When where token redistribution occurs and Kleros call the arbitrated contracts.
}
Period public period;
struct Juror {
uint balance; // The amount of tokens the contract holds for this juror.
uint atStake; // Total number of tokens the jurors can loose in disputes they are drawn in. Those tokens are locked. Note that we can have atStake > balance but it should be statistically unlikely and does not pose issues.
uint lastSession; // Last session the tokens were activated.
uint segmentStart; // Start of the segment of activated tokens.
uint segmentEnd; // End of the segment of activated tokens.
}
mapping (address => Juror) public jurors;
struct Vote {
address account; // The juror who casted the vote.
uint ruling; // The ruling which was given.
}
struct VoteCounter {
uint winningChoice; // The choice which currently has the highest amount of votes. Is 0 in case of a tie.
uint winningCount; // The number of votes for winningChoice. Or for the choices which are tied.
mapping (uint => uint) voteCount; // voteCount[choice] is the number of votes for choice.
}
enum DisputeState {
Open, // The dispute is opened but the outcome is not available yet (this include when jurors voted but appeal is still possible).
Resolving, // The token repartition has started. Note that if it's done in just one call, this state is skipped.
Executable, // The arbitrated contract can be called to enforce the decision.
Executed // Everything has been done and the dispute can't be interacted with anymore.
}
struct Dispute {
Arbitrable arbitrated; // Contract to be arbitrated.
uint session; // First session the dispute was schedule.
uint appeals; // Number of appeals.
uint choices; // The number of choices available to the jurors.
uint16 initialNumberJurors; // The initial number of jurors.
uint arbitrationFeePerJuror; // The fee which will be paid to each juror.
DisputeState state; // The state of the dispute.
Vote[][] votes; // The votes in the form vote[appeals][voteID].
VoteCounter[] voteCounter; // The vote counters in the form voteCounter[appeals].
mapping (address => uint) lastSessionVote; // Last session a juror has voted on this dispute. Is 0 if he never did.
uint currentAppealToRepartition; // The current appeal we are repartitioning.
AppealsRepartitioned[] appealsRepartitioned; // Track a partially repartitioned appeal in the form AppealsRepartitioned[appeal].
}
enum RepartitionStage { // State of the token repartition if oneShotTokenRepartition would throw because there are too many votes.
Incoherent,
Coherent,
AtStake,
Complete
}
struct AppealsRepartitioned {
uint totalToRedistribute; // Total amount of tokens we have to redistribute.
uint nbCoherent; // Number of coherent jurors for session.
uint currentIncoherentVote; // Current vote for the incoherent loop.
uint currentCoherentVote; // Current vote we need to count.
uint currentAtStakeVote; // Current vote we need to count.
RepartitionStage stage; // Use with multipleShotTokenRepartition if oneShotTokenRepartition would throw.
}
Dispute[] public disputes;
// **************************** //
// * Events * //
// **************************** //
/** @dev Emitted when we pass to a new period.
* @param _period The new period.
* @param _session The current session.
*/
event NewPeriod(Period _period, uint indexed _session);
/** @dev Emitted when a juror wins or loses tokens.
* @param _account The juror affected.
* @param _disputeID The ID of the dispute.
* @param _amount The amount of parts of token which was won. Can be negative for lost amounts.
*/
event TokenShift(address indexed _account, uint _disputeID, int _amount);
/** @dev Emited when a juror wins arbitration fees.
* @param _account The account affected.
* @param _disputeID The ID of the dispute.
* @param _amount The amount of weis which was won.
*/
event ArbitrationReward(address indexed _account, uint _disputeID, uint _amount);
// **************************** //
// * Modifiers * //
// **************************** //
modifier onlyBy(address _account) {require(msg.sender == _account); _;}
modifier onlyDuring(Period _period) {require(period == _period); _;}
modifier onlyGovernor() {require(msg.sender == governor); _;}
/** @dev Constructor.
* @param _pinakion The address of the pinakion contract.
* @param _rng The random number generator which will be used.
* @param _timePerPeriod The minimal time for each period (seconds).
* @param _governor Address of the governor contract.
*/
constructor(Pinakion _pinakion, RNG _rng, uint[5] _timePerPeriod, address _governor) public {
pinakion = _pinakion;
rng = _rng;
lastPeriodChange = now;
timePerPeriod = _timePerPeriod;
governor = _governor;
}
// **************************** //
// * Functions interacting * //
// * with Pinakion contract * //
// **************************** //
/** @dev Callback of approveAndCall - transfer pinakions of a juror in the contract. Should be called by the pinakion contract. TRUSTED.
* @param _from The address making the transfer.
* @param _amount Amount of tokens to transfer to Kleros (in basic units).
*/
function receiveApproval(address _from, uint _amount, address, bytes) public onlyBy(pinakion) {
require(pinakion.transferFrom(_from, this, _amount));
jurors[_from].balance += _amount;
}
/** @dev Withdraw tokens. Note that we can't withdraw the tokens which are still atStake.
* Jurors can't withdraw their tokens if they have deposited some during this session.
* This is to prevent jurors from withdrawing tokens they could loose.
* @param _value The amount to withdraw.
*/
function withdraw(uint _value) public {
Juror storage juror = jurors[msg.sender];
require(juror.atStake <= juror.balance); // Make sure that there is no more at stake than owned to avoid overflow.
require(_value <= juror.balance-juror.atStake);
require(juror.lastSession != session);
juror.balance -= _value;
require(pinakion.transfer(msg.sender,_value));
}
// **************************** //
// * Court functions * //
// * Modifying the state * //
// **************************** //
/** @dev To call to go to a new period. TRUSTED.
*/
function passPeriod() public {
require(now-lastPeriodChange >= timePerPeriod[uint8(period)]);
if (period == Period.Activation) {
rnBlock = block.number + 1;
rng.requestRN(rnBlock);
period = Period.Draw;
} else if (period == Period.Draw) {
randomNumber = rng.getUncorrelatedRN(rnBlock);
require(randomNumber != 0);
period = Period.Vote;
} else if (period == Period.Vote) {
period = Period.Appeal;
} else if (period == Period.Appeal) {
period = Period.Execution;
} else if (period == Period.Execution) {
period = Period.Activation;
++session;
segmentSize = 0;
rnBlock = 0;
randomNumber = 0;
}
lastPeriodChange = now;
NewPeriod(period, session);
}
/** @dev Deposit tokens in order to have chances of being drawn. Note that once tokens are deposited,
* there is no possibility of depositing more.
* @param _value Amount of tokens (in basic units) to deposit.
*/
function activateTokens(uint _value) public onlyDuring(Period.Activation) {
Juror storage juror = jurors[msg.sender];
require(_value <= juror.balance);
require(_value >= minActivatedToken);
require(juror.lastSession != session); // Verify that tokens were not already activated for this session.
juror.lastSession = session;
juror.segmentStart = segmentSize;
segmentSize += _value;
juror.segmentEnd = segmentSize;
}
/** @dev Vote a ruling. Juror must input the draw ID he was drawn.
* Note that the complexity is O(d), where d is amount of times the juror was drawn.
* Since being drawn multiple time is a rare occurrence and that a juror can always vote with less weight than it has, it is not a problem.
* But note that it can lead to arbitration fees being kept by the contract and never distributed.
* @param _disputeID The ID of the dispute the juror was drawn.
* @param _ruling The ruling given.
* @param _draws The list of draws the juror was drawn. Draw numbering starts at 1 and the numbers should be increasing.
*/
function voteRuling(uint _disputeID, uint _ruling, uint[] _draws) public onlyDuring(Period.Vote) {
Dispute storage dispute = disputes[_disputeID];
Juror storage juror = jurors[msg.sender];
VoteCounter storage voteCounter = dispute.voteCounter[dispute.appeals];
require(dispute.lastSessionVote[msg.sender] != session); // Make sure juror hasn't voted yet.
require(_ruling <= dispute.choices);
// Note that it throws if the draws are incorrect.
require(validDraws(msg.sender, _disputeID, _draws));
dispute.lastSessionVote[msg.sender] = session;
voteCounter.voteCount[_ruling] += _draws.length;
if (voteCounter.winningCount < voteCounter.voteCount[_ruling]) {
voteCounter.winningCount = voteCounter.voteCount[_ruling];
voteCounter.winningChoice = _ruling;
} else if (voteCounter.winningCount==voteCounter.voteCount[_ruling] && _draws.length!=0) { // Verify draw length to be non-zero to avoid the possibility of setting tie by casting 0 votes.
voteCounter.winningChoice = 0; // It's currently a tie.
}
for (uint i = 0; i < _draws.length; ++i) {
dispute.votes[dispute.appeals].push(Vote({
account: msg.sender,
ruling: _ruling
}));
}
juror.atStake += _draws.length * getStakePerDraw();
uint feeToPay = _draws.length * dispute.arbitrationFeePerJuror;
msg.sender.transfer(feeToPay);
ArbitrationReward(msg.sender, _disputeID, feeToPay);
}
/** @dev Steal part of the tokens and the arbitration fee of a juror who failed to vote.
* Note that a juror who voted but without all his weight can't be penalized.
* It is possible to not penalize with the maximum weight.
* But note that it can lead to arbitration fees being kept by the contract and never distributed.
* @param _jurorAddress Address of the juror to steal tokens from.
* @param _disputeID The ID of the dispute the juror was drawn.
* @param _draws The list of draws the juror was drawn. Numbering starts at 1 and the numbers should be increasing.
*/
function penalizeInactiveJuror(address _jurorAddress, uint _disputeID, uint[] _draws) public {
Dispute storage dispute = disputes[_disputeID];
Juror storage inactiveJuror = jurors[_jurorAddress];
require(period > Period.Vote);
require(dispute.lastSessionVote[_jurorAddress] != session); // Verify the juror hasn't voted.
dispute.lastSessionVote[_jurorAddress] = session; // Update last session to avoid penalizing multiple times.
require(validDraws(_jurorAddress, _disputeID, _draws));
uint penality = _draws.length * minActivatedToken * 2 * alpha / ALPHA_DIVISOR;
penality = (penality < inactiveJuror.balance) ? penality : inactiveJuror.balance; // Make sure the penality is not higher than the balance.
inactiveJuror.balance -= penality;
TokenShift(_jurorAddress, _disputeID, -int(penality));
jurors[msg.sender].balance += penality / 2; // Give half of the penalty to the caller.
TokenShift(msg.sender, _disputeID, int(penality / 2));
jurors[governor].balance += penality / 2; // The other half to the governor.
TokenShift(governor, _disputeID, int(penality / 2));
msg.sender.transfer(_draws.length*dispute.arbitrationFeePerJuror); // Give the arbitration fees to the caller.
}
/** @dev Execute all the token repartition.
* Note that this function could consume to much gas if there is too much votes.
* It is O(v), where v is the number of votes for this dispute.
* In the next version, there will also be a function to execute it in multiple calls
* (but note that one shot execution, if possible, is less expensive).
* @param _disputeID ID of the dispute.
*/
function oneShotTokenRepartition(uint _disputeID) public onlyDuring(Period.Execution) {
Dispute storage dispute = disputes[_disputeID];
require(dispute.state == DisputeState.Open);
require(dispute.session+dispute.appeals <= session);
uint winningChoice = dispute.voteCounter[dispute.appeals].winningChoice;
uint amountShift = getStakePerDraw();
for (uint i = 0; i <= dispute.appeals; ++i) {
// If the result is not a tie, some parties are incoherent. Note that 0 (refuse to arbitrate) winning is not a tie.
// Result is a tie if the winningChoice is 0 (refuse to arbitrate) and the choice 0 is not the most voted choice.
// Note that in case of a "tie" among some choices including 0, parties who did not vote 0 are considered incoherent.
if (winningChoice!=0 || (dispute.voteCounter[dispute.appeals].voteCount[0] == dispute.voteCounter[dispute.appeals].winningCount)) {
uint totalToRedistribute = 0;
uint nbCoherent = 0;
// First loop to penalize the incoherent votes.
for (uint j = 0; j < dispute.votes[i].length; ++j) {
Vote storage vote = dispute.votes[i][j];
if (vote.ruling != winningChoice) {
Juror storage juror = jurors[vote.account];
uint penalty = amountShift<juror.balance ? amountShift : juror.balance;
juror.balance -= penalty;
TokenShift(vote.account, _disputeID, int(-penalty));
totalToRedistribute += penalty;
} else {
++nbCoherent;
}
}
if (nbCoherent == 0) { // No one was coherent at this stage. Give the tokens to the governor.
jurors[governor].balance += totalToRedistribute;
TokenShift(governor, _disputeID, int(totalToRedistribute));
} else { // otherwise, redistribute them.
uint toRedistribute = totalToRedistribute / nbCoherent; // Note that few fractions of tokens can be lost but due to the high amount of decimals we don't care.
// Second loop to redistribute.
for (j = 0; j < dispute.votes[i].length; ++j) {
vote = dispute.votes[i][j];
if (vote.ruling == winningChoice) {
juror = jurors[vote.account];
juror.balance += toRedistribute;
TokenShift(vote.account, _disputeID, int(toRedistribute));
}
}
}
}
// Third loop to lower the atStake in order to unlock tokens.
for (j = 0; j < dispute.votes[i].length; ++j) {
vote = dispute.votes[i][j];
juror = jurors[vote.account];
juror.atStake -= amountShift; // Note that it can't underflow due to amountShift not changing between vote and redistribution.
}
}
dispute.state = DisputeState.Executable; // Since it was solved in one shot, go directly to the executable step.
}
/** @dev Execute token repartition on a dispute for a specific number of votes.
* This should only be called if oneShotTokenRepartition will throw because there are too many votes (will use too much gas).
* Note that There are 3 iterations per vote. e.g. A dispute with 1 appeal (2 sessions) and 3 votes per session will have 18 iterations
* @param _disputeID ID of the dispute.
* @param _maxIterations the maxium number of votes to repartition in this iteration
*/
function multipleShotTokenRepartition(uint _disputeID, uint _maxIterations) public onlyDuring(Period.Execution) {
Dispute storage dispute = disputes[_disputeID];
require(dispute.state <= DisputeState.Resolving);
require(dispute.session+dispute.appeals <= session);
dispute.state = DisputeState.Resolving; // Mark as resolving so oneShotTokenRepartition cannot be called on dispute.
uint winningChoice = dispute.voteCounter[dispute.appeals].winningChoice;
uint amountShift = getStakePerDraw();
uint currentIterations = 0; // Total votes we have repartitioned this iteration.
for (uint i = dispute.currentAppealToRepartition; i <= dispute.appeals; ++i) {
// Allocate space for new AppealsRepartitioned.
if (dispute.appealsRepartitioned.length < i+1) {
dispute.appealsRepartitioned.length++;
}
// If the result is a tie, no parties are incoherent and no need to move tokens. Note that 0 (refuse to arbitrate) winning is not a tie.
if (winningChoice==0 && (dispute.voteCounter[dispute.appeals].voteCount[0] != dispute.voteCounter[dispute.appeals].winningCount)) {
// If ruling is a tie we can skip to at stake.
dispute.appealsRepartitioned[i].stage = RepartitionStage.AtStake;
}
// First loop to penalize the incoherent votes.
if (dispute.appealsRepartitioned[i].stage == RepartitionStage.Incoherent) {
for (uint j = dispute.appealsRepartitioned[i].currentIncoherentVote; j < dispute.votes[i].length; ++j) {
if (currentIterations >= _maxIterations) {
return;
}
Vote storage vote = dispute.votes[i][j];
if (vote.ruling != winningChoice) {
Juror storage juror = jurors[vote.account];
uint penalty = amountShift<juror.balance ? amountShift : juror.balance;
juror.balance -= penalty;
TokenShift(vote.account, _disputeID, int(-penalty));
dispute.appealsRepartitioned[i].totalToRedistribute += penalty;
} else {
++dispute.appealsRepartitioned[i].nbCoherent;
}
++dispute.appealsRepartitioned[i].currentIncoherentVote;
++currentIterations;
}
dispute.appealsRepartitioned[i].stage = RepartitionStage.Coherent;
}
// Second loop to reward coherent voters
if (dispute.appealsRepartitioned[i].stage == RepartitionStage.Coherent) {
if (dispute.appealsRepartitioned[i].nbCoherent == 0) { // No one was coherent at this stage. Give the tokens to the governor.
jurors[governor].balance += dispute.appealsRepartitioned[i].totalToRedistribute;
TokenShift(governor, _disputeID, int(dispute.appealsRepartitioned[i].totalToRedistribute));
dispute.appealsRepartitioned[i].stage = RepartitionStage.AtStake;
} else { // Otherwise, redistribute them.
uint toRedistribute = dispute.appealsRepartitioned[i].totalToRedistribute / dispute.appealsRepartitioned[i].nbCoherent; // Note that few fractions of tokens can be lost but due to the high amount of decimals we don't care.
// Second loop to redistribute.
for (j = dispute.appealsRepartitioned[i].currentCoherentVote; j < dispute.votes[i].length; ++j) {
if (currentIterations >= _maxIterations) {
return;
}
vote = dispute.votes[i][j];
if (vote.ruling == winningChoice) {
juror = jurors[vote.account];
juror.balance += toRedistribute;
TokenShift(vote.account, _disputeID, int(toRedistribute));
}
++currentIterations;
++dispute.appealsRepartitioned[i].currentCoherentVote;
}
dispute.appealsRepartitioned[i].stage = RepartitionStage.AtStake;
}
}
if (dispute.appealsRepartitioned[i].stage == RepartitionStage.AtStake) {
// Third loop to lower the atStake in order to unlock tokens.
for (j = dispute.appealsRepartitioned[i].currentAtStakeVote; j < dispute.votes[i].length; ++j) {
if (currentIterations >= _maxIterations) {
return;
}
vote = dispute.votes[i][j];
juror = jurors[vote.account];
juror.atStake -= amountShift; // Note that it can't underflow due to amountShift not changing between vote and redistribution.
++currentIterations;
++dispute.appealsRepartitioned[i].currentAtStakeVote;
}
dispute.appealsRepartitioned[i].stage = RepartitionStage.Complete;
}
if (dispute.appealsRepartitioned[i].stage == RepartitionStage.Complete) {
++dispute.currentAppealToRepartition;
}
}
dispute.state = DisputeState.Executable;
}
// **************************** //
// * Court functions * //
// * Constant and Pure * //
// **************************** //
/** @dev Return the amount of jurors which are or will be drawn in the dispute.
* The number of jurors is doubled and 1 is added at each appeal. We have proven the formula by recurrence.
* This avoid having a variable number of jurors which would be updated in order to save gas.
* @param _disputeID The ID of the dispute we compute the amount of jurors.
* @return nbJurors The number of jurors which are drawn.
*/
function amountJurors(uint _disputeID) public view returns (uint nbJurors) {
Dispute storage dispute = disputes[_disputeID];
return (dispute.initialNumberJurors + 1) * 2**dispute.appeals - 1;
}
/** @dev Must be used to verify that a juror has been draw at least _draws.length times.
* We have to require the user to specify the draws that lead the juror to be drawn.
* Because doing otherwise (looping through all draws) could consume too much gas.
* @param _jurorAddress Address of the juror we want to verify draws.
* @param _disputeID The ID of the dispute the juror was drawn.
* @param _draws The list of draws the juror was drawn. It draw numbering starts at 1 and the numbers should be increasing.
* Note that in most cases this list will just contain 1 number.
* @param valid true if the draws are valid.
*/
function validDraws(address _jurorAddress, uint _disputeID, uint[] _draws) public view returns (bool valid) {
uint draw = 0;
Juror storage juror = jurors[_jurorAddress];
Dispute storage dispute = disputes[_disputeID];
uint nbJurors = amountJurors(_disputeID);
if (juror.lastSession != session) return false; // Make sure that the tokens were deposited for this session.
if (dispute.session+dispute.appeals != session) return false; // Make sure there is currently a dispute.
if (period <= Period.Draw) return false; // Make sure that jurors are already drawn.
for (uint i = 0; i < _draws.length; ++i) {
if (_draws[i] <= draw) return false; // Make sure that draws are always increasing to avoid someone inputing the same multiple times.
draw = _draws[i];
if (draw > nbJurors) return false;
uint position = uint(keccak256(randomNumber, _disputeID, draw)) % segmentSize; // Random position on the segment for draw.
require(position >= juror.segmentStart);
require(position < juror.segmentEnd);
}
return true;
}
// **************************** //
// * Arbitrator functions * //
// * Modifying the state * //
// **************************** //
/** @dev Create a dispute. Must be called by the arbitrable contract.
* Must be paid at least arbitrationCost().
* @param _choices Amount of choices the arbitrator can make in this dispute.
* @param _extraData Null for the default number. Otherwise, first 16 bytes will be used to return the number of jurors.
* @return disputeID ID of the dispute created.
*/
function createDispute(uint _choices, bytes _extraData) public payable returns (uint disputeID) {
uint16 nbJurors = extraDataToNbJurors(_extraData);
require(msg.value >= arbitrationCost(_extraData));
disputeID = disputes.length++;
Dispute storage dispute = disputes[disputeID];
dispute.arbitrated = Arbitrable(msg.sender);
if (period < Period.Draw) // If drawing did not start schedule it for the current session.
dispute.session = session;
else // Otherwise schedule it for the next one.
dispute.session = session+1;
dispute.choices = _choices;
dispute.initialNumberJurors = nbJurors;
dispute.arbitrationFeePerJuror = arbitrationFeePerJuror; // We store it as the general fee can be changed through the governance mechanism.
dispute.votes.length++;
dispute.voteCounter.length++;
DisputeCreation(disputeID, Arbitrable(msg.sender));
return disputeID;
}
/** @dev Appeal a ruling. Note that it has to be called before the arbitrator contract calls rule.
* @param _disputeID ID of the dispute to be appealed.
* @param _extraData Standard but not used by this contract.
*/
function appeal(uint _disputeID, bytes _extraData) public payable onlyDuring(Period.Appeal) {
super.appeal(_disputeID,_extraData);
Dispute storage dispute = disputes[_disputeID];
require(msg.value >= appealCost(_disputeID, _extraData));
require(dispute.session+dispute.appeals == session); // Dispute of the current session.
require(dispute.arbitrated == msg.sender);
dispute.appeals++;
dispute.votes.length++;
dispute.voteCounter.length++;
}
/** @dev Execute the ruling of a dispute which is in the state executable. UNTRUSTED.
* @param disputeID ID of the dispute to execute the ruling.
*/
function executeRuling(uint disputeID) public {
Dispute storage dispute = disputes[disputeID];
require(dispute.state == DisputeState.Executable);
dispute.state = DisputeState.Executed;
dispute.arbitrated.rule(disputeID, dispute.voteCounter[dispute.appeals].winningChoice);
}
// **************************** //
// * Arbitrator functions * //
// * Constant and pure * //
// **************************** //
/** @dev Compute the cost of arbitration. It is recommended not to increase it often,
* as it can be highly time and gas consuming for the arbitrated contracts to cope with fee augmentation.
* @param _extraData Null for the default number. Other first 16 bits will be used to return the number of jurors.
* @return fee Amount to be paid.
*/
function arbitrationCost(bytes _extraData) public view returns (uint fee) {
return extraDataToNbJurors(_extraData) * arbitrationFeePerJuror;
}
/** @dev Compute the cost of appeal. It is recommended not to increase it often,
* as it can be highly time and gas consuming for the arbitrated contracts to cope with fee augmentation.
* @param _disputeID ID of the dispute to be appealed.
* @param _extraData Is not used there.
* @return fee Amount to be paid.
*/
function appealCost(uint _disputeID, bytes _extraData) public view returns (uint fee) {
Dispute storage dispute = disputes[_disputeID];
if(dispute.appeals >= maxAppeals) return NON_PAYABLE_AMOUNT;
return (2*amountJurors(_disputeID) + 1) * dispute.arbitrationFeePerJuror;
}
/** @dev Compute the amount of jurors to be drawn.
* @param _extraData Null for the default number. Other first 16 bits will be used to return the number of jurors.
* Note that it does not check that the number of jurors is odd, but users are advised to choose a odd number of jurors.
*/
function extraDataToNbJurors(bytes _extraData) internal view returns (uint16 nbJurors) {
if (_extraData.length < 2)
return defaultNumberJuror;
else
return (uint16(_extraData[0]) << 8) + uint16(_extraData[1]);
}
/** @dev Compute the minimum activated pinakions in alpha.
* Note there may be multiple draws for a single user on a single dispute.
*/
function getStakePerDraw() public view returns (uint minActivatedTokenInAlpha) {
return (alpha * minActivatedToken) / ALPHA_DIVISOR;
}
// **************************** //
// * Constant getters * //
// **************************** //
/** @dev Getter for account in Vote.
* @param _disputeID ID of the dispute.
* @param _appeals Which appeal (or 0 for the initial session).
* @param _voteID The ID of the vote for this appeal (or initial session).
* @return account The address of the voter.
*/
function getVoteAccount(uint _disputeID, uint _appeals, uint _voteID) public view returns (address account) {
return disputes[_disputeID].votes[_appeals][_voteID].account;
}
/** @dev Getter for ruling in Vote.
* @param _disputeID ID of the dispute.
* @param _appeals Which appeal (or 0 for the initial session).
* @param _voteID The ID of the vote for this appeal (or initial session).
* @return ruling The ruling given by the voter.
*/
function getVoteRuling(uint _disputeID, uint _appeals, uint _voteID) public view returns (uint ruling) {
return disputes[_disputeID].votes[_appeals][_voteID].ruling;
}
/** @dev Getter for winningChoice in VoteCounter.
* @param _disputeID ID of the dispute.
* @param _appeals Which appeal (or 0 for the initial session).
* @return winningChoice The currently winning choice (or 0 if it's tied). Note that 0 can also be return if the majority refuses to arbitrate.
*/
function getWinningChoice(uint _disputeID, uint _appeals) public view returns (uint winningChoice) {
return disputes[_disputeID].voteCounter[_appeals].winningChoice;
}
/** @dev Getter for winningCount in VoteCounter.
* @param _disputeID ID of the dispute.
* @param _appeals Which appeal (or 0 for the initial session).
* @return winningCount The amount of votes the winning choice (or those who are tied) has.
*/
function getWinningCount(uint _disputeID, uint _appeals) public view returns (uint winningCount) {
return disputes[_disputeID].voteCounter[_appeals].winningCount;
}
/** @dev Getter for voteCount in VoteCounter.
* @param _disputeID ID of the dispute.
* @param _appeals Which appeal (or 0 for the initial session).
* @param _choice The choice.
* @return voteCount The amount of votes the winning choice (or those who are tied) has.
*/
function getVoteCount(uint _disputeID, uint _appeals, uint _choice) public view returns (uint voteCount) {
return disputes[_disputeID].voteCounter[_appeals].voteCount[_choice];
}
/** @dev Getter for lastSessionVote in Dispute.
* @param _disputeID ID of the dispute.
* @param _juror The juror we want to get the last session he voted.
* @return lastSessionVote The last session the juror voted.
*/
function getLastSessionVote(uint _disputeID, address _juror) public view returns (uint lastSessionVote) {
return disputes[_disputeID].lastSessionVote[_juror];
}
/** @dev Is the juror drawn in the draw of the dispute.
* @param _disputeID ID of the dispute.
* @param _juror The juror.
* @param _draw The draw. Note that it starts at 1.
* @return drawn True if the juror is drawn, false otherwise.
*/
function isDrawn(uint _disputeID, address _juror, uint _draw) public view returns (bool drawn) {
Dispute storage dispute = disputes[_disputeID];
Juror storage juror = jurors[_juror];
if (juror.lastSession != session
|| (dispute.session+dispute.appeals != session)
|| period<=Period.Draw
|| _draw>amountJurors(_disputeID)
|| _draw==0
|| segmentSize==0
) {
return false;
} else {
uint position = uint(keccak256(randomNumber,_disputeID,_draw)) % segmentSize;
return (position >= juror.segmentStart) && (position < juror.segmentEnd);
}
}
/** @dev Return the current ruling of a dispute. This is useful for parties to know if they should appeal.
* @param _disputeID ID of the dispute.
* @return ruling The current ruling which will be given if there is no appeal. If it is not available, return 0.
*/
function currentRuling(uint _disputeID) public view returns (uint ruling) {
Dispute storage dispute = disputes[_disputeID];
return dispute.voteCounter[dispute.appeals].winningChoice;
}
/** @dev Return the status of a dispute.
* @param _disputeID ID of the dispute to rule.
* @return status The status of the dispute.
*/
function disputeStatus(uint _disputeID) public view returns (DisputeStatus status) {
Dispute storage dispute = disputes[_disputeID];
if (dispute.session+dispute.appeals < session) // Dispute of past session.
return DisputeStatus.Solved;
else if(dispute.session+dispute.appeals == session) { // Dispute of current session.
if (dispute.state == DisputeState.Open) {
if (period < Period.Appeal)
return DisputeStatus.Waiting;
else if (period == Period.Appeal)
return DisputeStatus.Appealable;
else return DisputeStatus.Solved;
} else return DisputeStatus.Solved;
} else return DisputeStatus.Waiting; // Dispute for future session.
}
// **************************** //
// * Governor Functions * //
// **************************** //
/** @dev General call function where the contract execute an arbitrary call with data and ETH following governor orders.
* @param _data Transaction data.
* @param _value Transaction value.
* @param _target Transaction target.
*/
function executeOrder(bytes32 _data, uint _value, address _target) public onlyGovernor {
_target.call.value(_value)(_data);
}
/** @dev Setter for rng.
* @param _rng An instance of RNG.
*/
function setRng(RNG _rng) public onlyGovernor {
rng = _rng;
}
/** @dev Setter for arbitrationFeePerJuror.
* @param _arbitrationFeePerJuror The fee which will be paid to each juror.
*/
function setArbitrationFeePerJuror(uint _arbitrationFeePerJuror) public onlyGovernor {
arbitrationFeePerJuror = _arbitrationFeePerJuror;
}
/** @dev Setter for defaultNumberJuror.
* @param _defaultNumberJuror Number of drawn jurors unless specified otherwise.
*/
function setDefaultNumberJuror(uint16 _defaultNumberJuror) public onlyGovernor {
defaultNumberJuror = _defaultNumberJuror;
}
/** @dev Setter for minActivatedToken.
* @param _minActivatedToken Minimum of tokens to be activated (in basic units).
*/
function setMinActivatedToken(uint _minActivatedToken) public onlyGovernor {
minActivatedToken = _minActivatedToken;
}
/** @dev Setter for timePerPeriod.
* @param _timePerPeriod The minimum time each period lasts (seconds).
*/
function setTimePerPeriod(uint[5] _timePerPeriod) public onlyGovernor {
timePerPeriod = _timePerPeriod;
}
/** @dev Setter for alpha.
* @param _alpha Alpha in ‱.
*/
function setAlpha(uint _alpha) public onlyGovernor {
alpha = _alpha;
}
/** @dev Setter for maxAppeals.
* @param _maxAppeals Number of times a dispute can be appealed. When exceeded appeal cost becomes NON_PAYABLE_AMOUNT.
*/
function setMaxAppeals(uint _maxAppeals) public onlyGovernor {
maxAppeals = _maxAppeals;
}
/** @dev Setter for governor.
* @param _governor Address of the governor contract.
*/
function setGovernor(address _governor) public onlyGovernor {
governor = _governor;
}
} | Return the amount of jurors which are or will be drawn in the dispute. The number of jurors is doubled and 1 is added at each appeal. We have proven the formula by recurrence. This avoid having a variable number of jurors which would be updated in order to save gas. _disputeID The ID of the dispute we compute the amount of jurors. return nbJurors The number of jurors which are drawn./ | function amountJurors(uint _disputeID) public view returns (uint nbJurors) {
Dispute storage dispute = disputes[_disputeID];
return (dispute.initialNumberJurors + 1) * 2**dispute.appeals - 1;
}
| 1,073,830 |
pragma solidity ^0.4.18;
// File: zeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
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;
}
}
// File: authorizable/contracts/Authorizable.sol
/**
* @title Authorizable
* @author Francesco Sullo <[email protected]>
* @dev The Authorizable contract provides governance.
*/
contract Authorizable /** 0.1.6 */ is Ownable {
uint public totalAuthorized;
mapping(address => uint) public authorized;
address[] internal __authorized;
event AuthorizedAdded(address _authorizer, address _authorized, uint _level);
event AuthorizedRemoved(address _authorizer, address _authorized);
uint public maxLevel = 64;
uint public authorizerLevel = 56;
bool public selfRevoke = true;
mapping (uint => bool) public selfRevokeException;
/**
* @dev Set the range of levels accepted by the contract
* @param _maxLevel The max level acceptable
* @param _authorizerLevel The minimum level to qualify a wallet as authorizer
*/
function setLevels(uint _maxLevel, uint _authorizerLevel) external onlyOwner {
// this must be called before authorizing any address
require(totalAuthorized == 0);
require(_maxLevel > 0 && _authorizerLevel > 0);
require(_maxLevel >= _authorizerLevel);
maxLevel = _maxLevel;
authorizerLevel = _authorizerLevel;
}
/**
* @dev Allows to decide if users will be able to self revoke their level
* @param _selfRevoke The new value
*/
function setSelfRevoke(bool _selfRevoke) onlyOwner external {
selfRevoke = _selfRevoke;
}
/**
* @dev Allows to set exceptions to selfRevoke when this is true
* @param _level The level not allowed to self-revoke
* @param _isActive `true` adds the lock, `false` removes it
*/
function addSelfRevokeException(uint _level, bool _isActive) onlyOwner external {
selfRevokeException[_level] = _isActive;
}
/**
* @dev Throws if called by any account which is not authorized.
*/
modifier onlyAuthorized() {
require(authorized[msg.sender] > 0);
_;
}
/**
* @dev Throws if called by any account which is not
* authorized at a specific level.
* @param _level Level required
*/
modifier onlyAuthorizedAtLevel(uint _level) {
require(authorized[msg.sender] == _level);
_;
}
/**
* @dev Throws if called by any account which is not authorized
* at some of the specified levels.
* @param _levels Levels required
*/
modifier onlyAuthorizedAtLevels(uint[] _levels) {
require(__hasLevel(authorized[msg.sender], _levels));
_;
}
/**
* @dev Throws if called by any account which has
* a level of authorization not in the interval
* @param _minLevel Minimum level required
* @param _maxLevel Maximum level required
*/
modifier onlyAuthorizedAtLevelsWithin(uint _minLevel, uint _maxLevel) {
require(authorized[msg.sender] >= _minLevel && authorized[msg.sender] <= _maxLevel);
_;
}
/**
* @dev same modifiers above, but including the owner
*/
modifier onlyOwnerOrAuthorized() {
require(msg.sender == owner || authorized[msg.sender] > 0);
_;
}
modifier onlyOwnerOrAuthorizedAtLevel(uint _level) {
require(msg.sender == owner || authorized[msg.sender] == _level);
_;
}
modifier onlyOwnerOrAuthorizedAtLevels(uint[] _levels) {
require(msg.sender == owner || __hasLevel(authorized[msg.sender], _levels));
_;
}
modifier onlyOwnerOrAuthorizedAtLevelsIn(uint _minLevel, uint _maxLevel) {
require(msg.sender == owner || (authorized[msg.sender] >= _minLevel && authorized[msg.sender] <= _maxLevel));
_;
}
/**
* @dev Throws if called by anyone who is not an authorizer.
*/
modifier onlyAuthorizer() {
require(msg.sender == owner || authorized[msg.sender] >= authorizerLevel);
_;
}
/**
* @dev Allows to add a new authorized address, or remove it, setting _level to 0
* @param _address The address to be authorized
* @param _level The level of authorization
*/
function authorize(address _address, uint _level) onlyAuthorizer external {
__authorize(_address, _level);
}
/**
* @dev Allows to add a list of new authorized addresses.
* Useful, for example, with whitelists
* @param _addresses Array of addresses to be authorized
* @param _level The level of authorization
*/
function authorizeBatch(address[] _addresses, uint _level) onlyAuthorizer external {
require(_level > 0);
for (uint i = 0; i < _addresses.length; i++) {
__authorize(_addresses[i], _level);
}
}
/**
* @dev Allows to remove all the authorizations. Callable by the owner only.
* We check the gas to avoid going out of gas when there are tons of
* authorized addresses (for example when used for a whitelist).
* If at the end of the operation there are still authorized
* wallets the operation must be repeated.
*/
function deAuthorizeAll() onlyOwner external {
for (uint i = 0; i < __authorized.length && msg.gas > 33e3; i++) {
if (__authorized[i] != address(0)) {
__authorize(__authorized[i], 0);
}
}
}
/**
* @dev Allows to remove all the authorizations at a specific level.
* @param _level The level of authorization
*/
function deAuthorizeAllAtLevel(uint _level) onlyAuthorizer external {
for (uint i = 0; i < __authorized.length && msg.gas > 33e3; i++) {
if (__authorized[i] != address(0) && authorized[__authorized[i]] == _level) {
__authorize(__authorized[i], 0);
}
}
}
/**
* @dev Allows an authorized to de-authorize itself.
*/
function deAuthorize() onlyAuthorized external {
require(selfRevoke == true && selfRevokeException[authorized[msg.sender]] == false);
__authorize(msg.sender, 0);
}
/**
* @dev Performs the actual authorization/de-authorization
* If there's no change, it doesn't emit any event, to reduce gas usage.
* @param _address The address to be authorized
* @param _level The level of authorization. 0 to remove it.
*/
function __authorize(address _address, uint _level) internal {
require(_address != address(0));
require(_level <= maxLevel);
uint i;
if (_level > 0 && authorized[_address] != _level) {
bool alreadyIndexed = false;
for (i = 0; i < __authorized.length; i++) {
if (__authorized[i] == _address) {
alreadyIndexed = true;
break;
}
}
if (alreadyIndexed == false) {
bool emptyFound = false;
// before we try to reuse an empty element of the array
for (i = 0; i < __authorized.length; i++) {
if (__authorized[i] == 0) {
__authorized[i] = _address;
emptyFound = true;
break;
}
}
if (emptyFound == false) {
__authorized.push(_address);
}
totalAuthorized++;
}
AuthorizedAdded(msg.sender, _address, _level);
authorized[_address] = _level;
} else if (_level == 0 && authorized[_address] > 0) {
for (i = 0; i < __authorized.length; i++) {
if (__authorized[i] == _address) {
__authorized[i] = address(0);
totalAuthorized--;
AuthorizedRemoved(msg.sender, _address);
delete authorized[_address];
break;
}
}
}
}
/**
* @dev Check is a level is included in an array of levels. Used by modifiers
* @param _level Level to be checked
* @param _levels Array of required levels
*/
function __hasLevel(uint _level, uint[] _levels) internal pure returns (bool) {
bool has = false;
for (uint i; i < _levels.length; i++) {
if (_level == _levels[i]) {
has = true;
break;
}
}
return has;
}
/**
* @dev Allows a wallet to check if it is authorized
*/
function amIAuthorized() external constant returns (bool) {
return authorized[msg.sender] > 0;
}
/**
* @dev Allows any authorizer to get the list of the authorized wallets
*/
function getAuthorized() external onlyAuthorizer constant returns (address[]) {
return __authorized;
}
}
// File: 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) {
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;
}
}
// File: contracts/SubscriptionStore.sol
contract SubscriptionStore is Authorizable {
using SafeMath for uint;
mapping(uint8 => uint) public tiers;
struct Subscription {
uint lastTransactionId;
uint expirationTimestamp;
}
mapping(address => Subscription) public subscription;
// events
event newSubscription(address _address, uint _txId, bool _result);
function SubscriptionStore() public {
tiers[0] = 30 days;
tiers[1] = 1 years;
}
function setTier(uint8 _tier, uint _duration) external onlyAuthorized {
require(tiers[_tier] == 0);
// There is no requirement for the _duration because
// setting the _duration to 0 is equivalent to remove the tier
tiers[_tier] = _duration;
}
function setSubscription(address _address, uint _txId, uint8 _tier) external onlyAuthorized {
require(_address != address(0));
if (tiers[_tier] != 0) {
uint expirationDate;
if (subscription[_address].expirationTimestamp != 0) {
// subscription renew/extension
expirationDate = subscription[_address].expirationTimestamp.add(tiers[_tier]);
} else {
expirationDate = now + tiers[_tier];
}
subscription[_address] = Subscription(_txId, expirationDate);
newSubscription(_address, _txId, true);
} else {
// this avoid to revert, so that we have a listenable event if the tier does not exist
newSubscription(_address, _txId, false);
}
}
function getLastTransactionId(address _address) external constant returns (uint){
return subscription[_address].lastTransactionId;
}
function getExpirationTimestamp(address _address) external constant returns (uint){
return subscription[_address].expirationTimestamp;
}
}
| Allows to remove all the authorizations at a specific level. _level The level of authorization/ | function deAuthorizeAllAtLevel(uint _level) onlyAuthorizer external {
for (uint i = 0; i < __authorized.length && msg.gas > 33e3; i++) {
if (__authorized[i] != address(0) && authorized[__authorized[i]] == _level) {
__authorize(__authorized[i], 0);
}
}
}
| 7,270,167 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Library used to query support of an interface declared via {IERC165}.
*
* Note that these functions return the actual result of the query: they do not
* `revert` if an interface is not supported. It is up to the caller to decide
* what to do in these cases.
*/
library ERC165Checker {
// As per the EIP-165 spec, no interface should ever match 0xffffffff
bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Returns true if `account` supports the {IERC165} interface,
*/
function supportsERC165(address account) internal view returns (bool) {
// Any contract that implements ERC165 must explicitly indicate support of
// InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
return _supportsERC165Interface(account, _INTERFACE_ID_ERC165) &&
!_supportsERC165Interface(account, _INTERFACE_ID_INVALID);
}
/**
* @dev Returns true if `account` supports the interface defined by
* `interfaceId`. Support for {IERC165} itself is queried automatically.
*
* See {IERC165-supportsInterface}.
*/
function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
// query support of both ERC165 as per the spec and support of _interfaceId
return supportsERC165(account) &&
_supportsERC165Interface(account, interfaceId);
}
/**
* @dev Returns a boolean array where each value corresponds to the
* interfaces passed in and whether they're supported or not. This allows
* you to batch check interfaces for a contract where your expectation
* is that some interfaces may not be supported.
*
* See {IERC165-supportsInterface}.
*
* _Available since v3.4._
*/
function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) {
// an array of booleans corresponding to interfaceIds and whether they're supported or not
bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);
// query support of ERC165 itself
if (supportsERC165(account)) {
// query support of each interface in interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]);
}
}
return interfaceIdsSupported;
}
/**
* @dev Returns true if `account` supports all the interfaces defined in
* `interfaceIds`. Support for {IERC165} itself is queried automatically.
*
* Batch-querying can lead to gas savings by skipping repeated checks for
* {IERC165} support.
*
* See {IERC165-supportsInterface}.
*/
function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
// query support of ERC165 itself
if (!supportsERC165(account)) {
return false;
}
// query support of each interface in _interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
if (!_supportsERC165Interface(account, interfaceIds[i])) {
return false;
}
}
// all interfaces supported
return true;
}
/**
* @notice Query if a contract implements an interface, does not check ERC165 support
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return true if the contract at account indicates support of the interface with
* identifier interfaceId, false otherwise
* @dev Assumes that account contains a contract that supports ERC165, otherwise
* the behavior of this method is undefined. This precondition can be checked
* with {supportsERC165}.
* Interface identification is specified in ERC-165.
*/
function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) {
// success determines whether the staticcall succeeded and result determines
// whether the contract at account indicates support of _interfaceId
(bool success, bool result) = _callERC165SupportsInterface(account, interfaceId);
return (success && result);
}
/**
* @notice Calls the function with selector 0x01ffc9a7 (ERC165) and suppresses throw
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return success true if the STATICCALL succeeded, false otherwise
* @return result true if the STATICCALL succeeded and the contract at account
* indicates support of the interface with identifier interfaceId, false otherwise
*/
function _callERC165SupportsInterface(address account, bytes4 interfaceId)
private
view
returns (bool, bool)
{
bytes memory encodedParams = abi.encodeWithSelector(_INTERFACE_ID_ERC165, interfaceId);
(bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams);
if (result.length < 32) return (false, false);
return (success, abi.decode(result, (bool)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "./IVaultHandler.sol";
import "./Orchestrator.sol";
/**
* @title ERC-20 TCAP Vault
* @author Cryptex.finance
* @notice Contract in charge of handling the TCAP Vault and stake using a Collateral ERC20
*/
contract ERC20VaultHandler is IVaultHandler {
/**
* @notice Constructor
* @param _orchestrator address
* @param _divisor uint256
* @param _ratio uint256
* @param _burnFee uint256
* @param _liquidationPenalty uint256
* @param _tcapOracle address
* @param _tcapAddress address
* @param _collateralAddress address
* @param _collateralOracle address
* @param _ethOracle address
* @param _rewardHandler address
* @param _treasury address
*/
constructor(
Orchestrator _orchestrator,
uint256 _divisor,
uint256 _ratio,
uint256 _burnFee,
uint256 _liquidationPenalty,
address _tcapOracle,
TCAP _tcapAddress,
address _collateralAddress,
address _collateralOracle,
address _ethOracle,
address _rewardHandler,
address _treasury
)
IVaultHandler(
_orchestrator,
_divisor,
_ratio,
_burnFee,
_liquidationPenalty,
_tcapOracle,
_tcapAddress,
_collateralAddress,
_collateralOracle,
_ethOracle,
_rewardHandler,
_treasury
)
{}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/SafeCast.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/introspection/IERC165.sol";
import "./TCAP.sol";
import "./Orchestrator.sol";
import "./oracles/ChainlinkOracle.sol";
interface IRewardHandler {
function stake(address _staker, uint256 amount) external;
function withdraw(address _staker, uint256 amount) external;
function getRewardFromVault(address _staker) external;
}
/**
* @title TCAP Vault Handler Abstract Contract
* @author Cryptex.Finance
* @notice Contract in charge of handling the TCAP Token and stake
*/
abstract contract IVaultHandler is
Ownable,
AccessControl,
ReentrancyGuard,
Pausable,
IERC165
{
/// @notice Open Zeppelin libraries
using SafeMath for uint256;
using SafeCast for int256;
using Counters for Counters.Counter;
using SafeERC20 for IERC20;
/**
* @notice Vault object created to manage the mint and burns of TCAP tokens
* @param Id, unique identifier of the vault
* @param Collateral, current collateral on vault
* @param Debt, current amount of TCAP tokens minted
* @param Owner, owner of the vault
*/
struct Vault {
uint256 Id;
uint256 Collateral;
uint256 Debt;
address Owner;
}
/// @notice Vault Id counter
Counters.Counter public counter;
/// @notice TCAP Token Address
TCAP public immutable TCAPToken;
/// @notice Total Market Cap/USD Oracle Address
ChainlinkOracle public immutable tcapOracle;
/// @notice Collateral Token Address
IERC20 public immutable collateralContract;
/// @notice Collateral/USD Oracle Address
ChainlinkOracle public immutable collateralPriceOracle;
/// @notice ETH/USD Oracle Address
ChainlinkOracle public immutable ETHPriceOracle;
/// @notice Value used as divisor with the total market cap, just like the S&P 500 or any major financial index would to define the final tcap token price
uint256 public divisor;
/// @notice Minimun ratio required to prevent liquidation of vault
uint256 public ratio;
/// @notice Fee percentage of the total amount to burn charged on ETH when burning TCAP Tokens
uint256 public burnFee;
/// @notice Penalty charged to vault owner when a vault is liquidated, this value goes to the liquidator
uint256 public liquidationPenalty;
/// @notice Address of the contract that gives rewards to minters of TCAP, rewards are only given if address is set in constructor
IRewardHandler public immutable rewardHandler;
/// @notice Address of the treasury contract (usually the timelock) where the funds generated by the protocol are sent
address public treasury;
/// @notice Owner address to Vault Id
mapping(address => uint256) public userToVault;
/// @notice Id To Vault
mapping(uint256 => Vault) public vaults;
/// @notice value used to multiply chainlink oracle for handling decimals
uint256 public constant oracleDigits = 10000000000;
/// @notice Minimum value that the ratio can be set to
uint256 public constant MIN_RATIO = 150;
/// @notice Maximum value that the burn fee can be set to
uint256 public constant MAX_FEE = 10;
/**
* @dev the computed interface ID according to ERC-165. The interface ID is a XOR of interface method selectors.
* setRatio.selector ^
* setBurnFee.selector ^
* setLiquidationPenalty.selector ^
* pause.selector ^
* unpause.selector => 0x9e75ab0c
*/
bytes4 private constant _INTERFACE_ID_IVAULT = 0x9e75ab0c;
/// @dev bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/// @notice An event emitted when the ratio is updated
event NewRatio(address indexed _owner, uint256 _ratio);
/// @notice An event emitted when the burn fee is updated
event NewBurnFee(address indexed _owner, uint256 _burnFee);
/// @notice An event emitted when the liquidation penalty is updated
event NewLiquidationPenalty(
address indexed _owner,
uint256 _liquidationPenalty
);
/// @notice An event emitted when the treasury contract is updated
event NewTreasury(address indexed _owner, address _tresury);
/// @notice An event emitted when a vault is created
event VaultCreated(address indexed _owner, uint256 indexed _id);
/// @notice An event emitted when collateral is added to a vault
event CollateralAdded(
address indexed _owner,
uint256 indexed _id,
uint256 _amount
);
/// @notice An event emitted when collateral is removed from a vault
event CollateralRemoved(
address indexed _owner,
uint256 indexed _id,
uint256 _amount
);
/// @notice An event emitted when tokens are minted
event TokensMinted(
address indexed _owner,
uint256 indexed _id,
uint256 _amount
);
/// @notice An event emitted when tokens are burned
event TokensBurned(
address indexed _owner,
uint256 indexed _id,
uint256 _amount
);
/// @notice An event emitted when a vault is liquidated
event VaultLiquidated(
uint256 indexed _vaultId,
address indexed _liquidator,
uint256 _liquidationCollateral,
uint256 _reward
);
/// @notice An event emitted when a erc20 token is recovered
event Recovered(address _token, uint256 _amount);
/**
* @notice Constructor
* @param _orchestrator address
* @param _divisor uint256
* @param _ratio uint256
* @param _burnFee uint256
* @param _liquidationPenalty uint256
* @param _tcapOracle address
* @param _tcapAddress address
* @param _collateralAddress address
* @param _collateralOracle address
* @param _ethOracle address
* @param _rewardHandler address
* @param _treasury address
*/
constructor(
Orchestrator _orchestrator,
uint256 _divisor,
uint256 _ratio,
uint256 _burnFee,
uint256 _liquidationPenalty,
address _tcapOracle,
TCAP _tcapAddress,
address _collateralAddress,
address _collateralOracle,
address _ethOracle,
address _rewardHandler,
address _treasury
) {
require(
_liquidationPenalty.add(100) < _ratio,
"VaultHandler::constructor: liquidation penalty too high"
);
require(
_ratio >= MIN_RATIO,
"VaultHandler::constructor: ratio lower than MIN_RATIO"
);
require(
_burnFee <= MAX_FEE,
"VaultHandler::constructor: burn fee higher than MAX_FEE"
);
divisor = _divisor;
ratio = _ratio;
burnFee = _burnFee;
liquidationPenalty = _liquidationPenalty;
tcapOracle = ChainlinkOracle(_tcapOracle);
collateralContract = IERC20(_collateralAddress);
collateralPriceOracle = ChainlinkOracle(_collateralOracle);
ETHPriceOracle = ChainlinkOracle(_ethOracle);
TCAPToken = _tcapAddress;
rewardHandler = IRewardHandler(_rewardHandler);
treasury = _treasury;
/// @dev counter starts in 1 as 0 is reserved for empty objects
counter.increment();
/// @dev transfer ownership to orchestrator
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
transferOwnership(address(_orchestrator));
}
/// @notice Reverts if the user hasn't created a vault.
modifier vaultExists() {
require(
userToVault[msg.sender] != 0,
"VaultHandler::vaultExists: no vault created"
);
_;
}
/// @notice Reverts if value is 0.
modifier notZero(uint256 _value) {
require(_value != 0, "VaultHandler::notZero: value can't be 0");
_;
}
/**
* @notice Sets the collateral ratio needed to mint tokens
* @param _ratio uint
* @dev Only owner can call it
*/
function setRatio(uint256 _ratio) external virtual onlyOwner {
require(
_ratio >= MIN_RATIO,
"VaultHandler::setRatio: ratio lower than MIN_RATIO"
);
ratio = _ratio;
emit NewRatio(msg.sender, _ratio);
}
/**
* @notice Sets the burn fee percentage an user pays when burning tcap tokens
* @param _burnFee uint
* @dev Only owner can call it
*/
function setBurnFee(uint256 _burnFee) external virtual onlyOwner {
require(
_burnFee <= MAX_FEE,
"VaultHandler::setBurnFee: burn fee higher than MAX_FEE"
);
burnFee = _burnFee;
emit NewBurnFee(msg.sender, _burnFee);
}
/**
* @notice Sets the liquidation penalty % charged on liquidation
* @param _liquidationPenalty uint
* @dev Only owner can call it
* @dev recommended value is between 1-15% and can't be above 100%
*/
function setLiquidationPenalty(uint256 _liquidationPenalty)
external
virtual
onlyOwner
{
require(
_liquidationPenalty.add(100) < ratio,
"VaultHandler::setLiquidationPenalty: liquidation penalty too high"
);
liquidationPenalty = _liquidationPenalty;
emit NewLiquidationPenalty(msg.sender, _liquidationPenalty);
}
/**
* @notice Sets the treasury contract address where fees are transfered to
* @param _treasury address
* @dev Only owner can call it
*/
function setTreasury(address _treasury) external virtual onlyOwner {
require(
_treasury != address(0),
"VaultHandler::setTreasury: not a valid treasury"
);
treasury = _treasury;
emit NewTreasury(msg.sender, _treasury);
}
/**
* @notice Allows an user to create an unique Vault
* @dev Only one vault per address can be created
*/
function createVault() external virtual whenNotPaused {
require(
userToVault[msg.sender] == 0,
"VaultHandler::createVault: vault already created"
);
uint256 id = counter.current();
userToVault[msg.sender] = id;
Vault memory vault = Vault(id, 0, 0, msg.sender);
vaults[id] = vault;
counter.increment();
emit VaultCreated(msg.sender, id);
}
/**
* @notice Allows users to add collateral to their vaults
* @param _amount of collateral to be added
* @dev _amount should be higher than 0
* @dev ERC20 token must be approved first
*/
function addCollateral(uint256 _amount)
external
virtual
nonReentrant
vaultExists
whenNotPaused
notZero(_amount)
{
require(
collateralContract.transferFrom(msg.sender, address(this), _amount),
"VaultHandler::addCollateral: ERC20 transfer did not succeed"
);
Vault storage vault = vaults[userToVault[msg.sender]];
vault.Collateral = vault.Collateral.add(_amount);
emit CollateralAdded(msg.sender, vault.Id, _amount);
}
/**
* @notice Allows users to remove collateral currently not being used to generate TCAP tokens from their vaults
* @param _amount of collateral to remove
* @dev reverts if the resulting ratio is less than the minimun ratio
* @dev _amount should be higher than 0
* @dev transfers the collateral back to the user
*/
function removeCollateral(uint256 _amount)
external
virtual
nonReentrant
vaultExists
whenNotPaused
notZero(_amount)
{
Vault storage vault = vaults[userToVault[msg.sender]];
uint256 currentRatio = getVaultRatio(vault.Id);
require(
vault.Collateral >= _amount,
"VaultHandler::removeCollateral: retrieve amount higher than collateral"
);
vault.Collateral = vault.Collateral.sub(_amount);
if (currentRatio != 0) {
require(
getVaultRatio(vault.Id) >= ratio,
"VaultHandler::removeCollateral: collateral below min required ratio"
);
}
require(
collateralContract.transfer(msg.sender, _amount),
"VaultHandler::removeCollateral: ERC20 transfer did not succeed"
);
emit CollateralRemoved(msg.sender, vault.Id, _amount);
}
/**
* @notice Uses collateral to generate debt on TCAP Tokens which are minted and assigend to caller
* @param _amount of tokens to mint
* @dev _amount should be higher than 0
* @dev requires to have a vault ratio above the minimum ratio
* @dev if reward handler is set stake to earn rewards
*/
function mint(uint256 _amount)
external
virtual
nonReentrant
vaultExists
whenNotPaused
notZero(_amount)
{
Vault storage vault = vaults[userToVault[msg.sender]];
uint256 collateral = requiredCollateral(_amount);
require(
vault.Collateral >= collateral,
"VaultHandler::mint: not enough collateral"
);
vault.Debt = vault.Debt.add(_amount);
require(
getVaultRatio(vault.Id) >= ratio,
"VaultHandler::mint: collateral below min required ratio"
);
if (address(rewardHandler) != address(0)) {
rewardHandler.stake(msg.sender, _amount);
}
TCAPToken.mint(msg.sender, _amount);
emit TokensMinted(msg.sender, vault.Id, _amount);
}
/**
* @notice Pays the debt of TCAP tokens resulting them on burn, this releases collateral up to minimun vault ratio
* @param _amount of tokens to burn
* @dev _amount should be higher than 0
* @dev A fee of exactly burnFee must be sent as value on ETH
* @dev The fee goes to the treasury contract
* @dev if reward handler is set exit rewards
*/
function burn(uint256 _amount)
external
payable
virtual
nonReentrant
vaultExists
whenNotPaused
notZero(_amount)
{
uint256 fee = getFee(_amount);
require(
msg.value >= fee,
"VaultHandler::burn: burn fee less than required"
);
Vault memory vault = vaults[userToVault[msg.sender]];
_burn(vault.Id, _amount);
if (address(rewardHandler) != address(0)) {
rewardHandler.withdraw(msg.sender, _amount);
rewardHandler.getRewardFromVault(msg.sender);
}
safeTransferETH(treasury, fee);
//send back ETH above fee
safeTransferETH(msg.sender, msg.value.sub(fee));
emit TokensBurned(msg.sender, vault.Id, _amount);
}
/**
* @notice Allow users to burn TCAP tokens to liquidate vaults with vault collateral ratio under the minium ratio, the liquidator receives the staked collateral of the liquidated vault at a premium
* @param _vaultId to liquidate
* @param _maxTCAP max amount of TCAP the liquidator is willing to pay to liquidate vault
* @dev Resulting ratio must be above or equal minimun ratio
* @dev A fee of exactly burnFee must be sent as value on ETH
* @dev The fee goes to the treasury contract
*/
function liquidateVault(uint256 _vaultId, uint256 _maxTCAP)
external
payable
nonReentrant
whenNotPaused
{
Vault storage vault = vaults[_vaultId];
require(vault.Id != 0, "VaultHandler::liquidateVault: no vault created");
uint256 vaultRatio = getVaultRatio(vault.Id);
require(
vaultRatio < ratio,
"VaultHandler::liquidateVault: vault is not liquidable"
);
uint256 requiredTCAP = requiredLiquidationTCAP(vault.Id);
require(
_maxTCAP >= requiredTCAP,
"VaultHandler::liquidateVault: liquidation amount different than required"
);
uint256 fee = getFee(requiredTCAP);
require(
msg.value >= fee,
"VaultHandler::liquidateVault: burn fee less than required"
);
uint256 reward = liquidationReward(vault.Id);
_burn(vault.Id, requiredTCAP);
//Removes the collateral that is rewarded to liquidator
vault.Collateral = vault.Collateral.sub(reward);
// Triggers update of CTX Rewards
if (address(rewardHandler) != address(0)) {
rewardHandler.withdraw(vault.Owner, requiredTCAP);
}
require(
collateralContract.transfer(msg.sender, reward),
"VaultHandler::liquidateVault: ERC20 transfer did not succeed"
);
safeTransferETH(treasury, fee);
//send back ETH above fee
safeTransferETH(msg.sender, msg.value.sub(fee));
emit VaultLiquidated(vault.Id, msg.sender, requiredTCAP, reward);
}
/**
* @notice Allows the owner to Pause the Contract
*/
function pause() external onlyOwner {
_pause();
}
/**
* @notice Allows the owner to Unpause the Contract
*/
function unpause() external onlyOwner {
_unpause();
}
/**
* @notice Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
* @param _tokenAddress address
* @param _tokenAmount uint
* @dev Only owner can call it
*/
function recoverERC20(address _tokenAddress, uint256 _tokenAmount)
external
onlyOwner
{
// Cannot recover the collateral token
require(
_tokenAddress != address(collateralContract),
"Cannot withdraw the collateral tokens"
);
IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/**
* @notice Allows the safe transfer of ETH
* @param _to account to transfer ETH
* @param _value amount of ETH
*/
function safeTransferETH(address _to, uint256 _value) internal {
(bool success, ) = _to.call{value: _value}(new bytes(0));
require(success, "ETHVaultHandler::safeTransferETH: ETH transfer failed");
}
/**
* @notice ERC165 Standard for support of interfaces
* @param _interfaceId bytes of interface
* @return bool
*/
function supportsInterface(bytes4 _interfaceId)
external
pure
override
returns (bool)
{
return (_interfaceId == _INTERFACE_ID_IVAULT ||
_interfaceId == _INTERFACE_ID_ERC165);
}
/**
* @notice Returns the Vault information of specified identifier
* @param _id of vault
* @return Id, Collateral, Owner, Debt
*/
function getVault(uint256 _id)
external
view
virtual
returns (
uint256,
uint256,
address,
uint256
)
{
Vault memory vault = vaults[_id];
return (vault.Id, vault.Collateral, vault.Owner, vault.Debt);
}
/**
* @notice Returns the price of the chainlink oracle multiplied by the digits to get 18 decimals format
* @param _oracle to be the price called
* @return price
*/
function getOraclePrice(ChainlinkOracle _oracle)
public
view
virtual
returns (uint256 price)
{
price = _oracle.getLatestAnswer().toUint256().mul(oracleDigits);
}
/**
* @notice Returns the price of the TCAP token
* @return price of the TCAP Token
* @dev TCAP token is 18 decimals
* @dev oracle totalMarketPrice must be in wei format
* @dev P = T / d
* P = TCAP Token Price
* T = Total Crypto Market Cap
* d = Divisor
*/
function TCAPPrice() public view virtual returns (uint256 price) {
uint256 totalMarketPrice = getOraclePrice(tcapOracle);
price = totalMarketPrice.div(divisor);
}
/**
* @notice Returns the minimal required collateral to mint TCAP token
* @param _amount uint amount to mint
* @return collateral of the TCAP Token
* @dev TCAP token is 18 decimals
* @dev C = ((P * A * r) / 100) / cp
* C = Required Collateral
* P = TCAP Token Price
* A = Amount to Mint
* cp = Collateral Price
* r = Minimun Ratio for Liquidation
* Is only divided by 100 as eth price comes in wei to cancel the additional 0s
*/
function requiredCollateral(uint256 _amount)
public
view
virtual
returns (uint256 collateral)
{
uint256 tcapPrice = TCAPPrice();
uint256 collateralPrice = getOraclePrice(collateralPriceOracle);
collateral = ((tcapPrice.mul(_amount).mul(ratio)).div(100)).div(
collateralPrice
);
}
/**
* @notice Returns the minimal required TCAP to liquidate a Vault
* @param _vaultId of the vault to liquidate
* @return amount required of the TCAP Token
* @dev LT = ((((D * r) / 100) - cTcap) * 100) / (r - (p + 100))
* cTcap = ((C * cp) / P)
* LT = Required TCAP
* D = Vault Debt
* C = Required Collateral
* P = TCAP Token Price
* cp = Collateral Price
* r = Min Vault Ratio
* p = Liquidation Penalty
*/
function requiredLiquidationTCAP(uint256 _vaultId)
public
view
virtual
returns (uint256 amount)
{
Vault memory vault = vaults[_vaultId];
uint256 tcapPrice = TCAPPrice();
uint256 collateralPrice = getOraclePrice(collateralPriceOracle);
uint256 collateralTcap =
(vault.Collateral.mul(collateralPrice)).div(tcapPrice);
uint256 reqDividend =
(((vault.Debt.mul(ratio)).div(100)).sub(collateralTcap)).mul(100);
uint256 reqDivisor = ratio.sub(liquidationPenalty.add(100));
amount = reqDividend.div(reqDivisor);
}
/**
* @notice Returns the Reward for liquidating a vault
* @param _vaultId of the vault to liquidate
* @return rewardCollateral for liquidating Vault
* @dev the returned value is returned as collateral currency
* @dev R = (LT * (p + 100)) / 100
* R = Liquidation Reward
* LT = Required Liquidation TCAP
* p = liquidation penalty
*/
function liquidationReward(uint256 _vaultId)
public
view
virtual
returns (uint256 rewardCollateral)
{
uint256 req = requiredLiquidationTCAP(_vaultId);
uint256 tcapPrice = TCAPPrice();
uint256 collateralPrice = getOraclePrice(collateralPriceOracle);
uint256 reward = (req.mul(liquidationPenalty.add(100)));
rewardCollateral = (reward.mul(tcapPrice)).div(collateralPrice.mul(100));
}
/**
* @notice Returns the Collateral Ratio of the Vault
* @param _vaultId id of vault
* @return currentRatio
* @dev vr = (cp * (C * 100)) / D * P
* vr = Vault Ratio
* C = Vault Collateral
* cp = Collateral Price
* D = Vault Debt
* P = TCAP Token Price
*/
function getVaultRatio(uint256 _vaultId)
public
view
virtual
returns (uint256 currentRatio)
{
Vault memory vault = vaults[_vaultId];
if (vault.Id == 0 || vault.Debt == 0) {
currentRatio = 0;
} else {
uint256 collateralPrice = getOraclePrice(collateralPriceOracle);
currentRatio = (
(collateralPrice.mul(vault.Collateral.mul(100))).div(
vault.Debt.mul(TCAPPrice())
)
);
}
}
/**
* @notice Returns the required fee of ETH to burn the TCAP tokens
* @param _amount to burn
* @return fee
* @dev The returned value is returned in wei
* @dev f = (((P * A * b)/ 100))/ EP
* f = Burn Fee Value
* P = TCAP Token Price
* A = Amount to Burn
* b = Burn Fee %
* EP = ETH Price
*/
function getFee(uint256 _amount) public view virtual returns (uint256 fee) {
uint256 ethPrice = getOraclePrice(ETHPriceOracle);
fee = (TCAPPrice().mul(_amount).mul(burnFee)).div(100).div(ethPrice);
}
/**
* @notice Burns an amount of TCAP Tokens
* @param _vaultId vault id
* @param _amount to burn
*/
function _burn(uint256 _vaultId, uint256 _amount) internal {
Vault storage vault = vaults[_vaultId];
require(
vault.Debt >= _amount,
"VaultHandler::burn: amount greater than debt"
);
vault.Debt = vault.Debt.sub(_amount);
TCAPToken.burn(msg.sender, _amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/introspection/ERC165Checker.sol";
import "./IVaultHandler.sol";
import "./TCAP.sol";
import "./oracles/ChainlinkOracle.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title TCAP Orchestrator
* @author Cryptex.finance
* @notice Orchestrator contract in charge of managing the settings of the vaults, rewards and TCAP token. It acts as the owner of these contracts.
*/
contract Orchestrator is Ownable {
/// @dev Enum which saves the available functions to emergency call.
enum Functions {BURNFEE, LIQUIDATION, PAUSE}
/// @notice Address that can set to 0 the fees or pause the vaults in an emergency event
address public guardian;
/** @dev Interface constants*/
bytes4 private constant _INTERFACE_ID_IVAULT = 0x9e75ab0c;
bytes4 private constant _INTERFACE_ID_TCAP = 0xbd115939;
bytes4 private constant _INTERFACE_ID_CHAINLINK_ORACLE = 0x85be402b;
/// @dev tracks which vault was emergency called
mapping(IVaultHandler => mapping(Functions => bool)) private emergencyCalled;
/// @notice An event emitted when the guardian is updated
event GuardianSet(address indexed _owner, address guardian);
/// @notice An event emitted when a transaction is executed
event TransactionExecuted(
address indexed target,
uint256 value,
string signature,
bytes data
);
/**
* @notice Constructor
* @param _guardian The guardian address
*/
constructor(address _guardian) {
require(
_guardian != address(0),
"Orchestrator::constructor: guardian can't be zero"
);
guardian = _guardian;
}
/// @notice Throws if called by any account other than the guardian
modifier onlyGuardian() {
require(
msg.sender == guardian,
"Orchestrator::onlyGuardian: caller is not the guardian"
);
_;
}
/**
* @notice Throws if vault is not valid.
* @param _vault address
*/
modifier validVault(IVaultHandler _vault) {
require(
ERC165Checker.supportsInterface(address(_vault), _INTERFACE_ID_IVAULT),
"Orchestrator::validVault: not a valid vault"
);
_;
}
/**
* @notice Throws if TCAP Token is not valid
* @param _tcap address
*/
modifier validTCAP(TCAP _tcap) {
require(
ERC165Checker.supportsInterface(address(_tcap), _INTERFACE_ID_TCAP),
"Orchestrator::validTCAP: not a valid TCAP ERC20"
);
_;
}
/**
* @notice Throws if Chainlink Oracle is not valid
* @param _oracle address
*/
modifier validChainlinkOracle(address _oracle) {
require(
ERC165Checker.supportsInterface(
address(_oracle),
_INTERFACE_ID_CHAINLINK_ORACLE
),
"Orchestrator::validChainlinkOrchestrator: not a valid Chainlink Oracle"
);
_;
}
/**
* @notice Sets the guardian of the orchestrator
* @param _guardian address of the guardian
* @dev Only owner can call it
*/
function setGuardian(address _guardian) external onlyOwner {
require(
_guardian != address(0),
"Orchestrator::setGuardian: guardian can't be zero"
);
guardian = _guardian;
emit GuardianSet(msg.sender, _guardian);
}
/**
* @notice Sets the ratio of a vault
* @param _vault address
* @param _ratio value
* @dev Only owner can call it
*/
function setRatio(IVaultHandler _vault, uint256 _ratio)
external
onlyOwner
validVault(_vault)
{
_vault.setRatio(_ratio);
}
/**
* @notice Sets the burn fee of a vault
* @param _vault address
* @param _burnFee value
* @dev Only owner can call it
*/
function setBurnFee(IVaultHandler _vault, uint256 _burnFee)
external
onlyOwner
validVault(_vault)
{
_vault.setBurnFee(_burnFee);
}
/**
* @notice Sets the burn fee to 0, only used on a black swan event
* @param _vault address
* @dev Only guardian can call it
* @dev Validates if _vault is valid
*/
function setEmergencyBurnFee(IVaultHandler _vault)
external
onlyGuardian
validVault(_vault)
{
require(
emergencyCalled[_vault][Functions.BURNFEE] != true,
"Orchestrator::setEmergencyBurnFee: emergency call already used"
);
emergencyCalled[_vault][Functions.BURNFEE] = true;
_vault.setBurnFee(0);
}
/**
* @notice Sets the liquidation penalty of a vault
* @param _vault address
* @param _liquidationPenalty value
* @dev Only owner can call it
*/
function setLiquidationPenalty(
IVaultHandler _vault,
uint256 _liquidationPenalty
) external onlyOwner validVault(_vault) {
_vault.setLiquidationPenalty(_liquidationPenalty);
}
/**
* @notice Sets the liquidation penalty of a vault to 0, only used on a black swan event
* @param _vault address
* @dev Only guardian can call it
* @dev Validates if _vault is valid
*/
function setEmergencyLiquidationPenalty(IVaultHandler _vault)
external
onlyGuardian
validVault(_vault)
{
require(
emergencyCalled[_vault][Functions.LIQUIDATION] != true,
"Orchestrator::setEmergencyLiquidationPenalty: emergency call already used"
);
emergencyCalled[_vault][Functions.LIQUIDATION] = true;
_vault.setLiquidationPenalty(0);
}
/**
* @notice Pauses the Vault
* @param _vault address
* @dev Only guardian can call it
* @dev Validates if _vault is valid
*/
function pauseVault(IVaultHandler _vault)
external
onlyGuardian
validVault(_vault)
{
require(
emergencyCalled[_vault][Functions.PAUSE] != true,
"Orchestrator::pauseVault: emergency call already used"
);
emergencyCalled[_vault][Functions.PAUSE] = true;
_vault.pause();
}
/**
* @notice Unpauses the Vault
* @param _vault address
* @dev Only guardian can call it
* @dev Validates if _vault is valid
*/
function unpauseVault(IVaultHandler _vault)
external
onlyGuardian
validVault(_vault)
{
_vault.unpause();
}
/**
* @notice Enables or disables the TCAP Cap
* @param _tcap address
* @param _enable bool
* @dev Only owner can call it
* @dev Validates if _tcap is valid
*/
function enableTCAPCap(TCAP _tcap, bool _enable)
external
onlyOwner
validTCAP(_tcap)
{
_tcap.enableCap(_enable);
}
/**
* @notice Sets the TCAP maximum minting value
* @param _tcap address
* @param _cap uint value
* @dev Only owner can call it
* @dev Validates if _tcap is valid
*/
function setTCAPCap(TCAP _tcap, uint256 _cap)
external
onlyOwner
validTCAP(_tcap)
{
_tcap.setCap(_cap);
}
/**
* @notice Adds Vault to TCAP ERC20
* @param _tcap address
* @param _vault address
* @dev Only owner can call it
* @dev Validates if _tcap is valid
* @dev Validates if _vault is valid
*/
function addTCAPVault(TCAP _tcap, IVaultHandler _vault)
external
onlyOwner
validTCAP(_tcap)
validVault(_vault)
{
_tcap.addVaultHandler(address(_vault));
}
/**
* @notice Removes Vault to TCAP ERC20
* @param _tcap address
* @param _vault address
* @dev Only owner can call it
* @dev Validates if _tcap is valid
* @dev Validates if _vault is valid
*/
function removeTCAPVault(TCAP _tcap, IVaultHandler _vault)
external
onlyOwner
validTCAP(_tcap)
validVault(_vault)
{
_tcap.removeVaultHandler(address(_vault));
}
/**
* @notice Allows the owner to execute custom transactions
* @param target address
* @param value uint256
* @param signature string
* @param data bytes
* @dev Only owner can call it
*/
function executeTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data
) external payable onlyOwner returns (bytes memory) {
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
} else {
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
require(
target != address(0),
"Orchestrator::executeTransaction: target can't be zero"
);
// solium-disable-next-line security/no-call-value
(bool success, bytes memory returnData) =
target.call{value: value}(callData);
require(
success,
"Orchestrator::executeTransaction: Transaction execution reverted."
);
emit TransactionExecuted(target, value, signature, data);
(target, value, signature, data);
return returnData;
}
/**
* @notice Retrieves the eth stuck on the orchestrator
* @param _to address
* @dev Only owner can call it
*/
function retrieveETH(address _to) external onlyOwner {
require(
_to != address(0),
"Orchestrator::retrieveETH: address can't be zero"
);
uint256 amount = address(this).balance;
payable(_to).transfer(amount);
}
/// @notice Allows the contract to receive ETH
receive() external payable {}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/introspection/IERC165.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./Orchestrator.sol";
/**
* @title Total Market Cap Token
* @author Cryptex.finance
* @notice ERC20 token on the Ethereum Blockchain that provides total exposure to the cryptocurrency sector.
*/
contract TCAP is ERC20, Ownable, IERC165 {
/// @notice Open Zeppelin libraries
using SafeMath for uint256;
/// @notice if enabled TCAP can't be minted if the total supply is above or equal the cap value
bool public capEnabled = false;
/// @notice Maximum value the total supply of TCAP
uint256 public cap;
/**
* @notice Address to Vault Handler
* @dev Only vault handlers can mint and burn TCAP
*/
mapping(address => bool) public vaultHandlers;
/**
* @dev the computed interface ID according to ERC-165. The interface ID is a XOR of interface method selectors.
* mint.selector ^
* burn.selector ^
* setCap.selector ^
* enableCap.selector ^
* transfer.selector ^
* transferFrom.selector ^
* addVaultHandler.selector ^
* removeVaultHandler.selector ^
* approve.selector => 0xbd115939
*/
bytes4 private constant _INTERFACE_ID_TCAP = 0xbd115939;
/// @dev bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/// @notice An event emitted when a vault handler is added
event VaultHandlerAdded(
address indexed _owner,
address indexed _tokenHandler
);
/// @notice An event emitted when a vault handler is removed
event VaultHandlerRemoved(
address indexed _owner,
address indexed _tokenHandler
);
/// @notice An event emitted when the cap value is updated
event NewCap(address indexed _owner, uint256 _amount);
/// @notice An event emitted when the cap is enabled or disabled
event NewCapEnabled(address indexed _owner, bool _enable);
/**
* @notice Constructor
* @param _name uint256
* @param _symbol uint256
* @param _cap uint256
* @param _orchestrator address
*/
constructor(
string memory _name,
string memory _symbol,
uint256 _cap,
Orchestrator _orchestrator
) ERC20(_name, _symbol) {
cap = _cap;
/// @dev transfer ownership to orchestrator
transferOwnership(address(_orchestrator));
}
/// @notice Reverts if called by any account that is not a vault.
modifier onlyVault() {
require(
vaultHandlers[msg.sender],
"TCAP::onlyVault: caller is not a vault"
);
_;
}
/**
* @notice Adds a new address as a vault
* @param _vaultHandler address of a contract with permissions to mint and burn tokens
* @dev Only owner can call it
*/
function addVaultHandler(address _vaultHandler) external onlyOwner {
vaultHandlers[_vaultHandler] = true;
emit VaultHandlerAdded(msg.sender, _vaultHandler);
}
/**
* @notice Removes an address as a vault
* @param _vaultHandler address of the contract to be removed as vault
* @dev Only owner can call it
*/
function removeVaultHandler(address _vaultHandler) external onlyOwner {
vaultHandlers[_vaultHandler] = false;
emit VaultHandlerRemoved(msg.sender, _vaultHandler);
}
/**
* @notice Mints TCAP Tokens
* @param _account address of the receiver of tokens
* @param _amount uint of tokens to mint
* @dev Only vault can call it
*/
function mint(address _account, uint256 _amount) external onlyVault {
_mint(_account, _amount);
}
/**
* @notice Burns TCAP Tokens
* @param _account address of the account which is burning tokens.
* @param _amount uint of tokens to burn
* @dev Only vault can call it
*/
function burn(address _account, uint256 _amount) external onlyVault {
_burn(_account, _amount);
}
/**
* @notice Sets maximum value the total supply of TCAP can have
* @param _cap value
* @dev When capEnabled is true, mint is not allowed to issue tokens that would increase the total supply above or equal the specified capacity.
* @dev Only owner can call it
*/
function setCap(uint256 _cap) external onlyOwner {
cap = _cap;
emit NewCap(msg.sender, _cap);
}
/**
* @notice Enables or Disables the Total Supply Cap.
* @param _enable value
* @dev When capEnabled is true, minting will not be allowed above the max capacity. It can exist a supply above the cap, but it prevents minting above the cap.
* @dev Only owner can call it
*/
function enableCap(bool _enable) external onlyOwner {
capEnabled = _enable;
emit NewCapEnabled(msg.sender, _enable);
}
/**
* @notice ERC165 Standard for support of interfaces
* @param _interfaceId bytes of interface
* @return bool
*/
function supportsInterface(bytes4 _interfaceId)
external
pure
override
returns (bool)
{
return (_interfaceId == _INTERFACE_ID_TCAP ||
_interfaceId == _INTERFACE_ID_ERC165);
}
/**
* @notice executes before each token transfer or mint
* @param _from address
* @param _to address
* @param _amount value to transfer
* @dev See {ERC20-_beforeTokenTransfer}.
* @dev minted tokens must not cause the total supply to go over the cap.
* @dev Reverts if the to address is equal to token address
*/
function _beforeTokenTransfer(
address _from,
address _to,
uint256 _amount
) internal virtual override {
super._beforeTokenTransfer(_from, _to, _amount);
require(
_to != address(this),
"TCAP::transfer: can't transfer to TCAP contract"
);
if (_from == address(0) && capEnabled) {
// When minting tokens
require(
totalSupply().add(_amount) <= cap,
"TCAP::Transfer: TCAP cap exceeded"
);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/introspection/IERC165.sol";
/**
* @title Chainlink Oracle
* @author Cryptex.finance
* @notice Contract in charge or reading the information from a Chainlink Oracle. TCAP contracts read the price directly from this contract. More information can be found on Chainlink Documentation
*/
contract ChainlinkOracle is Ownable, IERC165 {
AggregatorV3Interface internal aggregatorContract;
/*
* setReferenceContract.selector ^
* getLatestAnswer.selector ^
* getLatestTimestamp.selector ^
* getPreviousAnswer.selector ^
* getPreviousTimestamp.selector => 0x85be402b
*/
bytes4 private constant _INTERFACE_ID_CHAINLINK_ORACLE = 0x85be402b;
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @notice Called once the contract is deployed.
* Set the Chainlink Oracle as an aggregator.
*/
constructor(address _aggregator, address _timelock) {
require(_aggregator != address(0) && _timelock != address(0), "address can't be 0");
aggregatorContract = AggregatorV3Interface(_aggregator);
transferOwnership(_timelock);
}
/**
* @notice Changes the reference contract.
* @dev Only owner can call it.
*/
function setReferenceContract(address _aggregator) public onlyOwner() {
aggregatorContract = AggregatorV3Interface(_aggregator);
}
/**
* @notice Returns the latest answer from the reference contract.
* @return price
*/
function getLatestAnswer() public view returns (int256) {
(
uint80 roundID,
int256 price,
,
uint256 timeStamp,
uint80 answeredInRound
) = aggregatorContract.latestRoundData();
require(
timeStamp != 0,
"ChainlinkOracle::getLatestAnswer: round is not complete"
);
require(
answeredInRound >= roundID,
"ChainlinkOracle::getLatestAnswer: stale data"
);
return price;
}
/**
* @notice Returns the latest round from the reference contract.
*/
function getLatestRound()
public
view
returns (
uint80,
int256,
uint256,
uint256,
uint80
)
{
(
uint80 roundID,
int256 price,
uint256 startedAt,
uint256 timeStamp,
uint80 answeredInRound
) = aggregatorContract.latestRoundData();
return (roundID, price, startedAt, timeStamp, answeredInRound);
}
/**
* @notice Returns a given round from the reference contract.
* @param _id of round
*/
function getRound(uint80 _id)
public
view
returns (
uint80,
int256,
uint256,
uint256,
uint80
)
{
(
uint80 roundID,
int256 price,
uint256 startedAt,
uint256 timeStamp,
uint80 answeredInRound
) = aggregatorContract.getRoundData(_id);
return (roundID, price, startedAt, timeStamp, answeredInRound);
}
/**
* @notice Returns the last time the Oracle was updated.
*/
function getLatestTimestamp() public view returns (uint256) {
(, , , uint256 timeStamp, ) = aggregatorContract.latestRoundData();
return timeStamp;
}
/**
* @notice Returns a previous answer updated on the Oracle.
* @param _id of round
* @return price
*/
function getPreviousAnswer(uint80 _id) public view returns (int256) {
(uint80 roundID, int256 price, , , ) = aggregatorContract.getRoundData(_id);
require(
_id <= roundID,
"ChainlinkOracle::getPreviousAnswer: not enough history"
);
return price;
}
/**
* @notice Returns a previous time the Oracle was updated.
* @param _id of round
* @return timeStamp
*/
function getPreviousTimestamp(uint80 _id) public view returns (uint256) {
(uint80 roundID, , , uint256 timeStamp, ) =
aggregatorContract.getRoundData(_id);
require(
_id <= roundID,
"ChainlinkOracle::getPreviousTimestamp: not enough history"
);
return timeStamp;
}
/**
* @notice ERC165 Standard for support of interfaces.
*/
function supportsInterface(bytes4 interfaceId)
external
pure
override
returns (bool)
{
return (interfaceId == _INTERFACE_ID_CHAINLINK_ORACLE ||
interfaceId == _INTERFACE_ID_ERC165);
}
} | Returns the minimal required collateral to mint TCAP token _amount uint amount to mint return collateral of the TCAP Token TCAP token is 18 decimals C = ((P A r) / 100) / cp C = Required Collateral P = TCAP Token Price A = Amount to Mint cp = Collateral Price r = Minimun Ratio for Liquidation Is only divided by 100 as eth price comes in wei to cancel the additional 0s/ | function requiredCollateral(uint256 _amount)
public
view
virtual
returns (uint256 collateral)
{
uint256 tcapPrice = TCAPPrice();
uint256 collateralPrice = getOraclePrice(collateralPriceOracle);
collateral = ((tcapPrice.mul(_amount).mul(ratio)).div(100)).div(
collateralPrice
);
}
| 172,377 |
./partial_match/1/0x520b8e754768EEed9a37d78de76Cd5d75456b92F/sources/contracts/SolidlyV2/ProxyPattern/SolidlyProxy.sol | Fetch the current implementation address return _interfaceAddress Returns the current implementation address/ | function interfaceAddress()
public
view
virtual
returns (address _interfaceAddress)
{
assembly {
_interfaceAddress := sload(IMPLEMENTATION_SLOT)
}
}
| 4,325,632 |
./partial_match/42/0xdaEcc7Ba2C9C9c63c236adDD4Fb6505E31b67dcD/sources/RewardDistributor.sol | recipient The address of staking pool to distribute reward. reward The amount to distribute, with base scalingFactor. duration The period to distribute./ | function addRecipientAndSetReward(
address recipient,
uint256 reward,
uint256 duration
) external onlyOwner {
addRecipient(recipient);
setRecipientRewardAndDuration(recipient, reward, duration);
}
| 9,050,632 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/token/ERC721/ERC721.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol';
import '@openzeppelin/contracts/utils/cryptography/ECDSA.sol';
import '@openzeppelin/contracts/utils/cryptography/MerkleProof.sol';
import '@openzeppelin/contracts/utils/math/SafeMath.sol';
import '@openzeppelin/contracts/utils/Counters.sol';
interface IJigsaw1BadgeContract {
function mintFinalPicture(address _account) external ;
function addMinter( address _account) external ;
function removeMinter( address _account) external ;
function bulkMintFinalPicture(address[] memory _accounts) external;
}
contract Jigsaw1 is ERC721Enumerable, Ownable {
using Counters for Counters.Counter;
using MerkleProof for bytes32[];
using Strings for uint256;
using ECDSA for bytes32;
using SafeMath for uint256;
/// @notice Total Private Sale
uint256 public constant jigsawPresale = 750;
/// @notice Total Fiat Sale
uint256 public constant jigsawFiat = 2000;
/// @notice Total Supply
uint256 public constant jigsawTotal = 5632;
/// @notice allow users to mint up to 2 per wallet during whitelisted sale
uint256 public constant MAX_WHITELISTED_MINTED_NUMBER = 2;
/// @notice allow users to mint up to 10 per wallet
uint256 public constant MAX_MINTED_NUMBER = 10;
/// @notice Token has been minted to the address
mapping(address => uint256) public hasMinted;
/// @notice Address can mint the private sale i.e. whitelisted addresses
mapping(address => bool) public privateSaleEntries;
/// @notice Token Price
uint256 public price = 0.11 ether;
/// below list of properties related to final nft mint on claimReward.
/// @notice maximum final puzzle picture count
address public finalBadgeContractAddress;
uint256 public MAX_FINAL_PUZZLE_PICTURE_NUMBER;
address[] public finalOwners;
uint256[][] public finalOwnersTokenIds ;
uint256 public finalPictureTokenIds;
mapping(address => uint256) public hasReceivedFinalPictureNft;
string private _tokenFinalPictureBaseURI = '';
/// @notice Token Base URI
string private _tokenBaseURI = '';
/// @notice Community Pool - 20% of the mint fee
uint256 public constant communityRatio = 2000;
/// @notice Community Merkle Root
bytes32 public communityRoot;
/// @notice Community Reward Claimed
mapping(address => bool) public isClaimedCommunity;
/// @notice Charity Pool - 20% of the mint fee
uint256 public constant charityRatio = 2000;
/// @notice Charity, Vote amount, Pool address, Reward ratio
struct CharityInfo {
bytes32 charity;
uint256 vote;
address payable pool;
uint256 ratio;
}
/// @notice Charity vote infos
CharityInfo[] public charityInfos;
/// @notice Bored Puzzles - 60% of the mint fee
uint256 public constant boredRatio = 6000;
/// @notice Bored Puzzles Address
address payable public boredAddress;
/// @notice Count of Public Saled Tokens
uint256 public publicCounter;
/// @notice Count of Fiat Saled Tokens
uint256 public fiatCounter;
/// @notice fiatFee is the amount of ETH received on fiat sale
uint256 public fiatFee;
/// @notice Count of Private Saled Tokens
uint256 public privateCounter;
/// @notice Start timestamp for the Private Sale
uint256 public privateSaleBegin = 9999999990;
/// @notice Start timestamp for the Fiat Sale
uint256 public fiatSaleBegin = 9999999991;
/// @notice Start timestamp for the Public Sale
uint256 public publicSaleBegin = 9999999992;
/// @notice Game period
uint256 public constant period = 5 days;
/// @notice Game Started At
uint256 public startedAt;
/// @notice Game Ended At
uint256 public endedAt;
/// @notice Editable for Token Base URI
bool public editable;
/// @notice Total Fee
uint256 public totalFee;
/// @notice Estimated Gas for Mint
uint256 public estimatedGasForMint = 0;
/// claim you nft properties
/// @notice Events
event StartGame(uint256 indexed at);
event EndGame(uint256 indexed at);
event UploadedCommunityRoot();
event ClaimedCommunity(address indexed account, uint256 amount);
event ClaimedCommunityNFT(address indexed account, uint256 tokenId);
event ClaimedCharity(
bytes32 indexed charity,
address indexed pool,
uint256 amount
);
modifier onlyEditable() {
require(editable, 'METADATA_FUNCTIONS_LOCKED');
_;
}
constructor() ERC721('Bored Puzzles Jigsaw1', 'BPJ1') {
editable = true;
}
function safeTransferETH(address payable _to, uint256 _amount)
internal
returns (bool success)
{
if (_amount > address(this).balance) {
(success, ) = _to.call{value: address(this).balance}('');
} else {
(success, ) = _to.call{value: _amount}('');
}
}
///--------------------------------------------------------
/// Public Sale
/// Fiat Sale
/// Private Sale
///--------------------------------------------------------
/**
* @notice Mint on Public Sale
*/
function mint(uint256 _amount) external payable {
require(
block.timestamp >= publicSaleBegin || fiatCounter >= jigsawFiat,
'ER: Public sale is not started'
);
require(totalSupply()+ _amount <= jigsawTotal, 'ER: The sale is sold out');
require(
hasMinted[msg.sender] + _amount <= MAX_MINTED_NUMBER,
'ER: You can not mint more than maximum allowed tokens'
);
// Calculate Mint Fee with Gas Substraction
uint256 mintFee = price*_amount - tx.gasprice * estimatedGasForMint;
require(mintFee <= msg.value, 'ER: Not enough ETH');
/// @notice Return any ETH to be refunded
uint256 refund = msg.value - mintFee;
if (refund > 0) {
require(
safeTransferETH(payable(msg.sender), refund),
'ER: Return any ETH to be refunded'
);
}
publicCounter += _amount;
totalFee += mintFee;
hasMinted[msg.sender] += _amount;
for(uint256 i = 0 ; i < _amount ; i += 1){
_safeMint(msg.sender, totalSupply() + 1);
}
}
/**
* @notice Admin can mint to the users for Fiat Sale
* @param _to Users wallet addresses
*/
function safeMint(address[] memory _to, uint256[] memory _nftCount)
external
payable
onlyOwner{
require(
block.timestamp >= fiatSaleBegin || privateCounter >= jigsawPresale,
'ER: Fiat sale is not started'
);
require(
block.timestamp < publicSaleBegin,
'ER: Fiat sale is currently closed'
);
uint256 totalAccounts = _to.length;
for (uint256 i = 0; i < totalAccounts; i++) {
address to = _to[i];
uint256 totalTokensToMint = _nftCount[i];
//minting multiple tokens for individual
for (uint256 j = 0; j < totalTokensToMint; j++) {
if (hasMinted[to] < MAX_MINTED_NUMBER) {
require(
totalSupply() < jigsawTotal,
'ER: The sale is sold out'
);
require(
fiatCounter < jigsawFiat,
'ER: Not enough Jigsaws left for the fiat sale'
);
fiatCounter++;
hasMinted[to] += 1;
//as tx.gasprice is price for the
uint256 mintFee = price - tx.gasprice * estimatedGasForMint;
totalFee += mintFee;
fiatFee += price;
_safeMint(to, totalSupply() + 1);
} else break;
}
}
// totalFee -= tx.gasprice * estimatedGasForMint;
// totalFee += msg.value;
}
/**
* @notice Mint on Private Sale i.e. during whitelist sale period
*/
function privateMint(uint256 _amount) external payable {
require(
block.timestamp >= privateSaleBegin,
'ER: Private sale is not started'
);
require(
block.timestamp < fiatSaleBegin,
'ER: Private sale is currently closed'
);
require(
privateSaleEntries[msg.sender],
'ER: You are not qualified for the presale'
);
require(totalSupply() + _amount <= jigsawTotal, 'ER: The sale is sold out');
require(
privateCounter + _amount <= jigsawPresale,
'ER: Not enough Jigsaws left for the presale'
);
require(
hasMinted[msg.sender] + _amount <= MAX_WHITELISTED_MINTED_NUMBER,
'ER: You have already minted maximum for whitelisted sale'
);
// Calculate Mint Fee with Gas Substraction
uint256 mintFee = price*_amount - tx.gasprice * estimatedGasForMint;
require(mintFee <= msg.value, 'ER: Not enough ETH');
/// @notice Return any ETH to be refunded
uint256 refund = msg.value - mintFee;
if (refund > 0) {
require(
safeTransferETH(payable(msg.sender), refund),
'ER: Return any ETH to be refunded'
);
}
privateCounter += _amount;
totalFee += mintFee;
hasMinted[msg.sender] += _amount;
for(uint256 i = 0 ; i < _amount ; i += 1){
_safeMint(msg.sender, totalSupply() + 1);
}
}
///--------------------------------------------------------
/// Insert private buyers
/// Remove private buyers
///--------------------------------------------------------
/**
* @notice Admin can insert the addresses to mint the presale
* @param privateEntries Addresses for the presale
*/
function insertPrivateSalers(address[] calldata privateEntries)
external
onlyOwner
{
for (uint256 i = 0; i < privateEntries.length; i++) {
require(privateEntries[i] != address(0), 'ER: Null Address');
require(
!privateSaleEntries[privateEntries[i]],
'ER: Duplicate Entry'
);
privateSaleEntries[privateEntries[i]] = true;
}
}
/**
* @notice Admin can stop the addresses to not mint the presale
* @param privateEntries Addresses for the non-presale
*/
function removePrivateSalers(address[] calldata privateEntries)
external
onlyOwner
{
for (uint256 i = 0; i < privateEntries.length; i++) {
require(privateEntries[i] != address(0), 'ER: Null Address');
privateSaleEntries[privateEntries[i]] = false;
}
}
///--------------------------------------------------------
/// Sales Begin Timestamp
/// Start Game
/// End Game
///--------------------------------------------------------
/**
* @notice Admin can set the privateSaleBegin, fiatSaleBegin, publicSaleBegin timestamp
* @param _privateSaleBegin Timestamp to begin the private sale
* @param _fiatSaleBegin Timestamp to begin the fiat sale
* @param _publicSaleBegin Timestamp to begin the public sale
*/
function setSalesBegin(
uint256 _privateSaleBegin,
uint256 _fiatSaleBegin,
uint256 _publicSaleBegin) external onlyOwner {
require(
_privateSaleBegin < _fiatSaleBegin &&
_fiatSaleBegin < _publicSaleBegin,
'ER: Invalid timestamp for sales'
);
privateSaleBegin = _privateSaleBegin;
fiatSaleBegin = _fiatSaleBegin;
publicSaleBegin = _publicSaleBegin;
}
function getSalesBeginTimestamp()
external
view
returns (uint256,uint256,uint256,uint256) {
return (
privateSaleBegin,
fiatSaleBegin,
publicSaleBegin,
block.timestamp
);
}
/**
* @notice Admin can start the game
* @param _boredAddress Bored Puzzles address
*/
function startGame(address payable _boredAddress) external onlyOwner {
require(
_boredAddress != address(0),
'ER: Invalid Bored Puzzle address'
);
require(startedAt == 0, 'ER: Game is already began');
startedAt = block.timestamp;
boredAddress = _boredAddress;
uint256 amount = ((totalFee * boredRatio) -fiatFee) / 1e4;
require(
safeTransferETH(boredAddress, amount),
'ER: ETH transfer to Bored Puzzles failed'
);
emit StartGame(startedAt);
}
/**
* @notice Admin can end the game
*/
function endGame() external onlyOwner {
require(startedAt > 0, 'ER: Game is not started yet');
require(endedAt == 0, 'ER: Game is has already ended');
endedAt = block.timestamp;
(address[] memory _owners, uint256[][] memory _tokenIds) = grabAllOwners();
setSnapshotFinalPlayers(_owners, _tokenIds);
emit EndGame(endedAt);
airdropFinalPictureToFinalOwners();
}
function setSnapshotFinalPlayers(address[] memory _owners, uint256[][] memory _tokenIds) internal {
MAX_FINAL_PUZZLE_PICTURE_NUMBER = _owners.length;
finalOwners = _owners;
finalOwnersTokenIds = _tokenIds;
}
function getSnapshotFinalPlayers() public view returns (address[] memory, uint256[][] memory) {
return (finalOwners, finalOwnersTokenIds);
}
///--------------------------------------------------------
/// Upload Coummunity Merkle Root
/// Claim the Community Reward
/// Upload Charity Vote Result
///--------------------------------------------------------
/**
* @notice Admin can upload the Community root
* @param _communityRoot Community Distribution Merkle Root
*/
function uploadCommunityRoot(bytes32 _communityRoot) external onlyOwner {
require(endedAt > 0, 'ER: Game is not ended yet');
require(
communityRoot == bytes32(0),
'ER: Community Root is already set'
);
communityRoot = _communityRoot;
emit UploadedCommunityRoot();
}
function setGameStartandEndTime(
uint256 _startedAt,
uint256 _endedAt,
uint256 _totalFee ) public onlyOwner {
startedAt = _startedAt;
endedAt = _endedAt;
totalFee = _totalFee;
}
/**
@notice Calculates communityAmount and charityAmount, used in internal calls.
*/
function getCommunityAmount()
public
view
returns (uint256 _communityAmount, uint256 _charityAmount){
uint256 delayPeriod;
if ((endedAt - startedAt) > period) {
delayPeriod = (endedAt - startedAt) - period;
}
uint256 delaySeconds = delayPeriod % 1 days;
uint256 delayDays = delayPeriod / 1 days;
uint256 transferenceAmount;
uint256 tempCommunityAmount = (totalFee * communityRatio) / 1e4;
if (delayPeriod >= 0 days && delayPeriod < 1 days) {
transferenceAmount =
(totalFee * communityRatio * delaySeconds * 500) /
(1 days * 1e8);
} else if (delayPeriod >= 1 days && delayPeriod < 2 days) {
transferenceAmount = (totalFee * communityRatio * 500) / (1e8);
transferenceAmount +=
(totalFee * communityRatio * delaySeconds * 1000) /
(1 days * 1e8);
} else {
transferenceAmount = (totalFee * communityRatio * 500) / (1e8);
transferenceAmount += (totalFee * communityRatio * 1000) / (1e8);
transferenceAmount +=
(totalFee *
communityRatio *
1500 *
((delayDays.sub(2) * 86400).add(delaySeconds))) /
(1 days * 1e8);
}
uint256 communityAmount = tempCommunityAmount - transferenceAmount;
uint256 charityAmount = (totalFee * (communityRatio + charityRatio)) /
1e4 -
communityAmount;
return (communityAmount, charityAmount);
}
/**
@notice Claim the community reward
@param _account Receiver address
@param _percent Reward percent
@param _proof Merkle proof data
*/
function claimCommunity(
address _account,
uint256 _percent,
bytes32[] memory _proof
) external {
require(endedAt > 0, 'ER: Game is not ended yet');
require(!isClaimedCommunity[_account], 'ER: Community claimed already');
bytes32 leaf = keccak256(abi.encodePacked(_account, _percent));
require(MerkleProof.verify(_proof, communityRoot, leaf), "ER: Community claim wrong proof");
(uint256 communityAmount, ) = getCommunityAmount();
uint256 amount = (communityAmount * _percent) / 1e4;
isClaimedCommunity[_account] = true;
if (safeTransferETH(payable(_account), amount)) {
emit ClaimedCommunity(_account, amount);
}
}
/**
@notice Mint final pictures to owners on endGame.
*/
function airdropFinalPictureToFinalOwners() internal {
require(endedAt > 0, 'ER: Game has not ended yet');
// require(isAccountWhitelisted(_account), 'ER: You are not authorized to get final picture NFT');
require(
finalPictureTokenIds + finalOwners.length <= MAX_FINAL_PUZZLE_PICTURE_NUMBER,
'ER: Final puzzle pictures exceeded quota'
);
finalPictureTokenIds += MAX_FINAL_PUZZLE_PICTURE_NUMBER ;
IJigsaw1BadgeContract badgeContract = IJigsaw1BadgeContract(finalBadgeContractAddress);
badgeContract.bulkMintFinalPicture(finalOwners);
}
//it checks if account is whitelisted to get the final nft picture nft on claim rewards
function isAccountWhitelisted(address _account) internal view returns (bool) {
for(uint256 i = 0; i < finalOwners.length ; i++){
if(finalOwners[i] == _account) return true;
}
return false;
}
/**
* @notice Admin can upload the Charity vote result
* @param _charityInfos Charity vote result
*/
function uploadCharityInfos(CharityInfo[] memory _charityInfos)
external
onlyOwner {
require(endedAt > 0, 'ER: Game is not ended yet');
require(_charityInfos.length > 0, 'ER: Invalid Charity Info');
require(charityInfos.length == 0, 'Er: Charity Info is already set');
(, uint256 charityAmount) = getCommunityAmount();
uint256 maxVote;
uint256 count;
uint256 length = _charityInfos.length;
for (uint256 i = 0; i < length; i++) {
uint256 vote = _charityInfos[i].vote;
if (maxVote == vote) {
count++;
} else if (maxVote < vote) {
maxVote = vote;
count = 1;
}
}
for (uint256 i = 0; i < length; i++) {
CharityInfo memory info = _charityInfos[i];
if (info.vote == maxVote) {
info.ratio = 1e4 / count;
uint256 amount = charityAmount / count;
if (safeTransferETH(info.pool, amount)) {
emit ClaimedCharity(info.charity, info.pool, amount);
}
} else {
info.ratio = 0;
}
charityInfos.push(info);
}
}
///--------------------------------------------------------
/// Token Editable
/// Token BaseURI
/// Token Mint Gas
///--------------------------------------------------------
/**
* @notice Admin can set price of nft
* @param _amount is latest price of nft
*/
function setPrice(uint256 _amount) external onlyOwner {
price = _amount;
}
/**
* @notice Admin can enable/disable the editable
* @param _editable Can Edit
*/
function setEditable(bool _editable) external onlyOwner {
editable = _editable;
}
/**
* @notice Admin can set the Token Base URI but it should be editable
* @param _URI Token Base URI
*/
function setBaseURI(string memory _URI) external onlyOwner onlyEditable {
_tokenBaseURI = _URI;
}
function getBaseURI() external view returns (string memory) {
return _baseURI();
}
// get baseURI
function _baseURI() internal view virtual override returns (string memory) {
return _tokenBaseURI;
}
/**
* @notice Admin can set finalBadgeContractAddress
* @param _add as address of finalBadgeContractAddress
*/
function setFinalBadgeContractAddress(address _add)
external
onlyOwner
{
finalBadgeContractAddress = _add;
}
/**
* @notice Admin can update the estimated Gas for Mint
* @param _estimatedGasForMint Can Edit
*/
function setEstmatedGasForMint(uint256 _estimatedGasForMint)
external
onlyOwner
{
estimatedGasForMint = _estimatedGasForMint;
}
///--------------------------------------------------------
/// View functions
///--------------------------------------------------------
/**
* @notice Each token's URI
* @param tokenId Token ID
*/
function tokenURI(uint256 tokenId)
public
view
override(ERC721)
returns (string memory)
{
require(_exists(tokenId), 'Cannot query non-existent token');
if (tokenId <= jigsawTotal)
return
string(
abi.encodePacked(_baseURI(), tokenId.toString(), '.json')
);
else return 'ER: Not a valid token';
}
/**
* @notice Get list of owners and corresponding list of owner tokens
*/
function grabAllOwners()
public
view
returns (address[] memory, uint256[][] memory)
{
uint256 ts = totalSupply();
address[] memory owners = new address[](ts);
uint256[][] memory tokens = new uint256[][](ts);
//NOTE: current func might fail if used dynamic generated long tokenIds
// bool[] memory tempTokenIds = new bool[](jigsawTotal + MAX_FINAL_PUZZLE_PICTURE_NUMBER);
bool[] memory tempTokenIds = new bool[](jigsawTotal);
uint256 userCounterIndex = 0;
for (uint256 i = 0; i < totalSupply(); i++) {
uint256 tempTokenId = tokenByIndex(i);
address tempOwner = ownerOf(tempTokenId);
uint256 bal = balanceOf(tempOwner);
if (tempTokenIds[tempTokenId] != true) {
uint256[] memory tempIds = new uint256[](bal);
for (uint256 j = 0; j < bal; j++) {
uint256 tId = tokenOfOwnerByIndex(tempOwner, j);
tempIds[j] = tId;
tempTokenIds[tId] = true;
}
owners[userCounterIndex] = tempOwner;
tokens[userCounterIndex] = tempIds;
userCounterIndex += 1;
}
}
address[] memory owners1 = new address[](userCounterIndex);
uint256[][] memory tokens1 = new uint256[][](userCounterIndex);
for (uint256 i = 0; i < userCounterIndex; i++) {
owners1[i] = owners[i];
tokens1[i] = tokens[i];
}
return (owners1, tokens1);
}
//owner can withdraw the amount from the SC balance. pass 500 as args for 5%.
function withdraw(address _address, uint256 percentage) external onlyOwner {
// require(startedAt > 0, 'ER: Cant withdraw as game has not started yet');
uint256 amount = address(this).balance * percentage / 1e4;
(bool success, ) = payable(_address).call{value: amount}("");
require(success, "Withdraw amount failed");
}
receive() external payable {}
}
// 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 () {
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.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}. Empty by default, can be overriden
* in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// 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;
/**
* @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) {
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// 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) {
// 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)))
}
} else if (signature.length == 64) {
// 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 {
let vs := mload(add(signature, 0x40))
r := mload(add(signature, 0x20))
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
} else {
revert("ECDSA: invalid signature length");
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "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
* 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 These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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;`
*/
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;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// 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);
} | Admin can set the privateSaleBegin, fiatSaleBegin, publicSaleBegin timestamp _privateSaleBegin Timestamp to begin the private sale _fiatSaleBegin Timestamp to begin the fiat sale _publicSaleBegin Timestamp to begin the public sale/ | function setSalesBegin(
uint256 _privateSaleBegin,
uint256 _fiatSaleBegin,
uint256 _publicSaleBegin) external onlyOwner {
require(
_privateSaleBegin < _fiatSaleBegin &&
_fiatSaleBegin < _publicSaleBegin,
'ER: Invalid timestamp for sales'
);
privateSaleBegin = _privateSaleBegin;
fiatSaleBegin = _fiatSaleBegin;
publicSaleBegin = _publicSaleBegin;
}
| 6,256,838 |
// File: contracts/AnonymiceLibrary.sol
pragma solidity ^0.8.0;
library AnonymiceLibrary {
string internal constant TABLE =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return "";
// load the table into memory
string memory table = TABLE;
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((data.length + 2) / 3);
// add some extra buffer at the end required for the writing
string memory result = new string(encodedLen + 32);
assembly {
// set the actual output length
mstore(result, encodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 3 bytes at a time
for {
} lt(dataPtr, endPtr) {
} {
dataPtr := add(dataPtr, 3)
// read 3 bytes
let input := mload(dataPtr)
// write 4 characters
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(6, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(input, 0x3F))))
)
resultPtr := add(resultPtr, 1)
}
// padding with '='
switch mod(mload(data), 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
}
return result;
}
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
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);
}
function parseInt(string memory _a)
internal
pure
returns (uint8 _parsedInt)
{
bytes memory bresult = bytes(_a);
uint8 mint = 0;
for (uint8 i = 0; i < bresult.length; i++) {
if (
(uint8(uint8(bresult[i])) >= 48) &&
(uint8(uint8(bresult[i])) <= 57)
) {
mint *= 10;
mint += uint8(bresult[i]) - 48;
}
}
return mint;
}
function substring(
string memory str,
uint256 startIndex,
uint256 endIndex
) internal pure returns (string memory) {
bytes memory strBytes = bytes(str);
bytes memory result = new bytes(endIndex - startIndex);
for (uint256 i = startIndex; i < endIndex; i++) {
result[i - startIndex] = strBytes[i];
}
return string(result);
}
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;
}
}
// File: contracts/interfaces/IAxonsAuctionHouse.sol
/// @title Interface for Axons Auction Houses
pragma solidity ^0.8.6;
interface IAxonsAuctionHouse {
struct Auction {
// ID for the Axon (ERC721 token ID)
uint256 axonId;
// 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;
// The auction counter
uint256 counter;
}
event AuctionCreated(uint256 indexed axonId, uint256 startTime, uint256 endTime);
event AuctionBid(uint256 indexed axonId, address sender, uint256 value, bool extended);
event AuctionExtended(uint256 indexed axonId, uint256 endTime);
event AuctionSettled(uint256 indexed axonId, address winner, uint256 amount);
event AuctionTimeBufferUpdated(uint256 timeBuffer);
event AuctionReservePriceUpdated(uint256 reservePrice);
event AuctionMinBidIncrementPercentageUpdated(uint256 minBidIncrementPercentage);
function currentAuction() external view returns(IAxonsAuctionHouse.Auction memory);
function settleAuction() external;
function settleCurrentAndCreateNewAuction() external;
function createBid(uint256 axonId, uint256 amount) external;
function pause() external;
function unpause() external;
function setTimeBuffer(uint256 timeBuffer) external;
function setReservePrice(uint256 reservePrice) external;
function setMinBidIncrementPercentage(uint8 minBidIncrementPercentage) external;
}
// File: contracts/interfaces/IAxonsVoting.sol
/// @title Interface for Axons Auction Houses
pragma solidity ^0.8.6;
interface IAxonsVoting {
struct Auction {
// ID for the Axon (ERC721 token ID)
uint256 axonId;
// 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;
}
function currentWinnerForAuction(uint256 counter) external view returns (uint256);
function setupVoting(uint256 auctionCounter) external;
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/interfaces/IAxonsToken.sol
/// @title Interface for AxonsToken
pragma solidity ^0.8.6;
interface IAxonsToken is IERC20 {
event Claimed(address account, uint256 amount);
function generateReward(address recipient, uint256 amount) external;
function isGenesisAddress(address addressToCheck) external view returns(bool);
function burn(uint256 amount) external;
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: contracts/interfaces/IAxons.sol
/// @title Interface for Axons
pragma solidity ^0.8.6;
interface IAxons is IERC721Enumerable {
event AxonCreated(uint256 indexed tokenId);
event AxonBurned(uint256 indexed tokenId);
event MinterUpdated(address minter);
event MinterLocked();
function mint(uint256 axonId) external returns (uint256);
function burn(uint256 tokenId) external;
function dataURI(uint256 tokenId) external returns (string memory);
function setMinter(address minter) external;
function lockMinter() external;
}
// File: @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
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;
}
}
}
// File: @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.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 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;
}
// File: @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.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 OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// File: @openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// File: @openzeppelin/contracts/utils/math/SafeMath.sol
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: contracts/AxonsVoting.sol
/// @title The Axons auction house
// LICENSE
// AxonsAuctionHouse.sol is a modified version of NounsAuctionHouse.sol:
// https://raw.githubusercontent.com/nounsDAO/nouns-monorepo/master/packages/nouns-contracts/contracts/NounsAuctionHouse.sol
//
// AuctionHouse.sol source code Copyright Zora licensed under the GPL-3.0 license.
// With modifications by Axons.
pragma solidity ^0.8.6;
contract AxonsVoting is IAxonsVoting, ReentrancyGuardUpgradeable, OwnableUpgradeable {
using SafeMath for uint256;
// The Axons ERC721 token contract
IAxons public axons;
IAxonsAuctionHouse public auctionHouse;
// The address of the AxonToken contract
address public axonsToken;
// The address of the Filaments contract
address public filaments = 0x0a57e26e480355510028b5310FD251df96e2274b;
// The amount of time that must pass to re-register to vote with a specific Axon or Filament
uint256 public registrationCooldown = 86400;
// Voting
mapping(uint256 => uint256[]) public currentAxonsNumbersForVotes;
mapping(uint256 => uint256[]) public currentVotesForAxonNumbers;
mapping(uint256 => uint256) public currentNumberOfVotes;
mapping(uint256 => mapping(address => bool)) public votersForAuctionNumber;
mapping(address => uint256) public votesToClaim;
mapping(uint256 => bool) internal axonNumberToGenerated;
// Voter registration
mapping(uint256 => address) public registeredAxonToAddress;
mapping(uint256 => address) public registeredFilamentToAddress;
mapping(address => uint256) public registeredVoters;
mapping(uint256 => uint256) public registeredAxonToTimestamp;
mapping(uint256 => uint256) public registeredFilamentToTimestamp;
/**
* @notice Require that the sender is the auction house.
*/
modifier onlyAuctionHouse() {
require(msg.sender == address(auctionHouse), 'Sender is not the auction house');
_;
}
/**
* @notice Initialize the voting contracts,
* @dev This function can only be called once.
*/
function initialize(
IAxons _axons,
address _axonsToken,
IAxonsAuctionHouse _auctionHouse
) external initializer {
__ReentrancyGuard_init();
__Ownable_init();
axons = _axons;
axonsToken = _axonsToken;
auctionHouse = _auctionHouse;
}
/**
* @dev Generates a random axon number
* @param _a The address to be used within the hash.
*/
function randomAxonNumber(
address _a,
uint256 _c
) internal returns (uint256) {
uint256 _rand = uint256(
uint256(
keccak256(
abi.encodePacked(
block.timestamp,
block.difficulty,
_a,
_c
)
)
) % 900719925474000
);
if (axonNumberToGenerated[_rand]) return randomAxonNumber(_a, _c + 1);
axonNumberToGenerated[_rand] = true;
return _rand;
}
function registerVoterWithFilament(uint256 tokenId) public {
require(!AnonymiceLibrary.isContract(msg.sender)); // Prevent contracts because I don't know enough Solidity to comfortably allow them
require(IERC721Enumerable(filaments).ownerOf(tokenId) == msg.sender, "Can't register for a Filament you don't own");
address registeredAddress = registeredFilamentToAddress[tokenId]; // Get address that filament is currently registered to
require(registeredAddress != msg.sender, "Already registered to you! Don't waste your gas");
require(registeredFilamentToTimestamp[tokenId] == 0 || (block.timestamp > (registeredFilamentToTimestamp[tokenId] + registrationCooldown)), "Must wait a total of 24 hours to register to vote with this Filament");
registeredFilamentToTimestamp[tokenId] = block.timestamp;
registeredFilamentToAddress[tokenId] = msg.sender; // Register Filament to sender
registeredVoters[msg.sender]++; // Register to vote
if (registeredAddress == address(0)) {
// Never been registered, return
return;
}
// Remove registration from prior owner
if (registeredVoters[registeredAddress] > 0) {
registeredVoters[registeredAddress]--;
}
}
function registerVoterWithAxon(uint256 tokenId) public {
require(!AnonymiceLibrary.isContract(msg.sender)); // Prevent contracts because I don't know enough Solidity to comfortably allow them
require(IAxons(axons).ownerOf(tokenId) == msg.sender, "Can't register for an Axon you don't own");
address registeredAddress = registeredAxonToAddress[tokenId]; // Get address that axon is currently registered to
require(registeredAddress != msg.sender, "Already registered to you! Don't waste your gas");
require(registeredAxonToTimestamp[tokenId] == 0 || (block.timestamp > (registeredAxonToTimestamp[tokenId] + registrationCooldown)), "Must wait a total of 24 hours to register to vote with this Axon");
registeredAxonToTimestamp[tokenId] = block.timestamp;
registeredAxonToAddress[tokenId] = msg.sender; // Register Axon to sender
registeredVoters[msg.sender]++; // Register to vote
if (registeredAddress == address(0)) {
// Never been registered, return
return;
}
// Remove registration from prior owner
if (registeredVoters[registeredAddress] > 0) {
registeredVoters[registeredAddress]--;
}
}
function vote(bool[10] memory votes, uint256 auctionCounter) public {
require(votersForAuctionNumber[auctionCounter][msg.sender] == false, 'Can only vote once per day');
IAxonsAuctionHouse.Auction memory _auction = auctionHouse.currentAuction();
require(block.timestamp < _auction.endTime, 'Auction expired');
require(auctionCounter == _auction.counter, 'Can only vote for current auction');
require(!AnonymiceLibrary.isContract(msg.sender));
require(registeredVoters[msg.sender] > 0 || IAxonsToken(axonsToken).isGenesisAddress(msg.sender), 'Must own a Filament or Axon (and register it to vote) or be a genesis $AXON holder to vote');
// Record voting for today
votersForAuctionNumber[auctionCounter][msg.sender] = true;
// Add upvotes
for (uint i=0; i<10; i++) {
if (votes[i] == true) {
currentVotesForAxonNumbers[auctionCounter][i]++;
}
}
// Track total votes
currentNumberOfVotes[auctionCounter]++;
votesToClaim[msg.sender]++;
}
function claimAxonToken() public {
uint256 amount = votesToClaim[msg.sender];
require(amount > 0,'No votes to claim');
require(!AnonymiceLibrary.isContract(msg.sender));
votesToClaim[msg.sender] = 0;
// Distribute $AXON
IAxonsToken(axonsToken).generateReward(msg.sender, amount);
}
/**
* @dev Generates random axon numbers at the start of a day
*/
function newAxonNumbersForVotes() internal returns (uint256[10] memory) {
uint256[10] memory axonNumbers = [
randomAxonNumber(address(this),3),
randomAxonNumber(address(this),103),
randomAxonNumber(address(this),203),
randomAxonNumber(address(this),303),
randomAxonNumber(address(this),403),
randomAxonNumber(address(this),503),
randomAxonNumber(address(this),603),
randomAxonNumber(address(this),703),
randomAxonNumber(address(this),803),
randomAxonNumber(address(this),903)
];
return axonNumbers;
}
function currentWinnerForAuction(uint256 counter) external view override returns (uint256) {
return _determineWinner(counter);
}
/**
* @notice Determine winner by tallying votes
*/
function _determineWinner(uint256 counter) internal view returns (uint256) {
uint256 winner = currentAxonsNumbersForVotes[counter][0];
uint256 highestVoteCount = 0;
for (uint i=0; i<10; i++) {
uint256 currentAxonNumber = currentAxonsNumbersForVotes[counter][i];
uint256 currentVotesCount = currentVotesForAxonNumbers[counter][i];
if (currentVotesCount > highestVoteCount) {
winner = currentAxonNumber;
highestVoteCount = currentVotesCount;
}
}
return winner;
}
/**
* @notice Set up voting for next auction period
*/
function setupVoting(uint256 auctionCounter) external override onlyAuctionHouse {
currentVotesForAxonNumbers[auctionCounter] = [0,0,0,0,0,0,0,0,0,0];
currentAxonsNumbersForVotes[auctionCounter] = newAxonNumbersForVotes();
currentNumberOfVotes[auctionCounter] = 0;
}
} | Returns the total amount of tokens stored by the contract./ 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./ Returns a token ID at a given `index` of all the tokens stored by the contract. Use along with {totalSupply} to enumerate all tokens./ File: contracts/interfaces/IAxons.sol Interface for Axons | interface IAxons is IERC721Enumerable {
event AxonCreated(uint256 indexed tokenId);
event AxonBurned(uint256 indexed tokenId);
event MinterUpdated(address minter);
event MinterLocked();
function mint(uint256 axonId) external returns (uint256);
function burn(uint256 tokenId) external;
function dataURI(uint256 tokenId) external returns (string memory);
function setMinter(address minter) external;
function lockMinter() external;
}
| 1,432,893 |
./full_match/1/0x0000000000aec84F5BFc2af15EAfb943bf4e3522/sources/lib/solady/src/utils/LibZip.sol | Returns the decompressed `data`. | function flzDecompress(bytes memory data) internal pure returns (bytes memory result) {
for { let ip := add(2, a) } lt(ip, ipLimit) {} {
for {} 1 {} {
if iszero(lt(ip, ipLimit)) { break }
if iszero(gt(d, 0x1fff)) { if eq(s, u24(r)) { break } }
if iszero(lt(ip, ipLimit)) { break }
if gt(ip, a) { op := literals(sub(ip, a), a, op) }
let o := add(result, 0x20)
for { let i } lt(i, n) { i := add(i, 0x20) } { mstore(add(o, i), mload(add(t, i))) }
assembly {
let n := 0
let end := add(add(data, 0x20), mload(data))
result := mload(0x40)
let op := add(result, 0x20)
let w := mload(data)
let c := byte(0, w)
let t := shr(5, c)
if iszero(t) {
mstore(add(op, n), mload(add(data, 1)))
data := add(data, add(2, c))
n := add(n, add(1, c))
continue
}
let g := eq(t, 7)
let l := add(2, xor(t, mul(g, xor(t, add(7, byte(1, w))))))
for {
let s := add(add(shl(8, and(0x1f, c)), byte(add(1, g), w)), 1)
let r := add(op, sub(n, s))
let o := add(op, n)
let f := xor(s, mul(gt(s, 0x20), xor(s, 0x20)))
let j := 0
mstore(add(o, j), mload(add(r, j)))
j := add(j, f)
}
data := add(data, add(2, g))
n := add(n, l)
}
let o := add(add(result, 0x20), n)
for { data := add(data, 0x20) } lt(data, end) {} {
assembly {
let n := 0
let end := add(add(data, 0x20), mload(data))
result := mload(0x40)
let op := add(result, 0x20)
let w := mload(data)
let c := byte(0, w)
let t := shr(5, c)
if iszero(t) {
mstore(add(op, n), mload(add(data, 1)))
data := add(data, add(2, c))
n := add(n, add(1, c))
continue
}
let g := eq(t, 7)
let l := add(2, xor(t, mul(g, xor(t, add(7, byte(1, w))))))
for {
let s := add(add(shl(8, and(0x1f, c)), byte(add(1, g), w)), 1)
let r := add(op, sub(n, s))
let o := add(op, n)
let f := xor(s, mul(gt(s, 0x20), xor(s, 0x20)))
let j := 0
mstore(add(o, j), mload(add(r, j)))
j := add(j, f)
}
data := add(data, add(2, g))
n := add(n, l)
}
let o := add(add(result, 0x20), n)
assembly {
let n := 0
let end := add(add(data, 0x20), mload(data))
result := mload(0x40)
let op := add(result, 0x20)
let w := mload(data)
let c := byte(0, w)
let t := shr(5, c)
if iszero(t) {
mstore(add(op, n), mload(add(data, 1)))
data := add(data, add(2, c))
n := add(n, add(1, c))
continue
}
let g := eq(t, 7)
let l := add(2, xor(t, mul(g, xor(t, add(7, byte(1, w))))))
for {
let s := add(add(shl(8, and(0x1f, c)), byte(add(1, g), w)), 1)
let r := add(op, sub(n, s))
let o := add(op, n)
let f := xor(s, mul(gt(s, 0x20), xor(s, 0x20)))
let j := 0
mstore(add(o, j), mload(add(r, j)))
j := add(j, f)
}
data := add(data, add(2, g))
n := add(n, l)
}
let o := add(add(result, 0x20), n)
} 1 {} {
if iszero(lt(j, l)) { break }
}
| 4,875,489 |
pragma solidity >=0.5.0;
import "./VoteProxy.sol";
import "ds-chief/chief.sol";
/// @dev Deploys VoteProxy smart contracts and tracks the address of the proxies that have been deployed
contract VoteProxyFactory {
/// @dev Maps a hot key to the address of the VoteProxy contract that hot key controls
mapping(address => VoteProxy) public proxies;
/// @dev Creates a new vote proxy contract. The address calling this function is used as the "hot" key
/// for the vote proxy contract that is created. Note that a hot key can only be used to create
/// a single vote proxy contract with an instance of VoteProxyFactory. Subsequent calls to newProxy with
/// same hot key will fail.
/// @param _chief The address of a DSChief voting contract with which the proxy interacts
/// @param _cold The address of a "cold key"; funds are returned to this key only upon release().
/// used to interact with this contract. This key is stored in the proxies mapping.
/// @return the address of the vote proxy contract that was created. This is address is also
/// stored in the mapping.
function newProxy(DSChief _chief, address _cold) public returns (VoteProxy proxy) {
// Only one vote proxy is permitted per originating key
require(address(proxies[msg.sender]) == address(0), "Duplicate hot key not permitted");
// Create the proxy, store the mapping, and return the address of the new proxy
proxy = new VoteProxy(_chief, _cold, msg.sender);
proxies[msg.sender] = proxy;
return proxy;
}
} | Maps a hot key to the address of the VoteProxy contract that hot key controls Creates a new vote proxy contract. The address calling this function is used as the "hot" key for the vote proxy contract that is created. Note that a hot key can only be used to create a single vote proxy contract with an instance of VoteProxyFactory. Subsequent calls to newProxy with same hot key will fail. _chief The address of a DSChief voting contract with which the proxy interacts _cold The address of a "cold key"; funds are returned to this key only upon release(). used to interact with this contract. This key is stored in the proxies mapping. return the address of the vote proxy contract that was created. This is address is also stored in the mapping. Only one vote proxy is permitted per originating key Create the proxy, store the mapping, and return the address of the new proxy | function newProxy(DSChief _chief, address _cold) public returns (VoteProxy proxy) {
require(address(proxies[msg.sender]) == address(0), "Duplicate hot key not permitted");
proxy = new VoteProxy(_chief, _cold, msg.sender);
proxies[msg.sender] = proxy;
return proxy;
}
| 15,806,281 |
./partial_match/42/0x7DfD2ad5ef08E38A28Db6C19b20408193b98F6A8/sources/BatchBalanceReader.sol | Get a batch of ERC20 token total supplies. tokenAddresses Addresses of tokens where the balances need to be fetched. return Balances array./ | function totalSupplies(address[] calldata tokenAddresses)
external
view
returns (uint256[] memory)
{
uint256[] memory supplies = new uint256[](tokenAddresses.length);
for (uint256 i = 0; i < tokenAddresses.length; i++) {
supplies[i] = IERC20(tokenAddresses[i]).totalSupply();
}
return supplies;
}
| 3,359,056 |
// "SPDX-License-Identifier: Apache-2.0"
pragma solidity ^0.7.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "../IObserverOracleProxy.sol";
import "./IDataRegistryProxy.sol";
/**
* @title DataRegistryProxy
* @notice Registry for data which is published by an registered MarketObjectProvider
*/
contract DataRegistryProxy is IDataRegistryProxy, IObserverOracleProxy, Ownable {
event UpdatedDataProvider(bytes32 indexed setId, address provider);
event PublishedDataPoint(bytes32 indexed setId, int256 dataPoint, uint256 timestamp);
struct DataPoint {
int256 dataPoint;
bool isSet;
}
struct Set {
// timestamp => DataPoint
mapping(uint256 => DataPoint) dataPoints;
uint256 lastUpdatedTimestamp;
address provider;
bool isSet;
}
// SetId => Set
mapping(bytes32 => Set) internal sets;
/**
* @notice @notice Returns true if there is data registered for a given setId
* @param setId setId of the data set
* @return true if data set exists
*/
function isRegistered(bytes32 setId)
external
view
override
returns (bool)
{
return sets[setId].isSet;
}
/**
* @notice Returns a data point of a data set for a given timestamp.
* @param setId id of the data set
* @param timestamp timestamp of the data point
* @return data point, bool indicating whether data point exists
*/
function getDataPoint(
bytes32 setId,
uint256 timestamp
)
external
view
override(IDataRegistryProxy, IObserverOracleProxy)
returns (int256, bool)
{
return (
sets[setId].dataPoints[timestamp].dataPoint,
sets[setId].dataPoints[timestamp].isSet
);
}
/**
* @notice Returns most recent data point of a data set.
* @param setId id of the data set
* @return data point, bool indicating whether data point exists
*/
function getMostRecentDataPoint(bytes32 setId)
external
view
override(IDataRegistryProxy, IObserverOracleProxy)
returns (int256, bool)
{
uint256 lastUpdatedTimestamp = sets[setId].lastUpdatedTimestamp;
return (
sets[setId].dataPoints[lastUpdatedTimestamp].dataPoint,
sets[setId].dataPoints[lastUpdatedTimestamp].isSet
);
}
/**
* @notice Returns the timestamp on which the last data point for a data set
* was submitted.
* @param setId id of the data set
* @return last updated timestamp
*/
function getLastUpdatedTimestamp(bytes32 setId)
external
view
override
returns (uint256)
{
return sets[setId].lastUpdatedTimestamp;
}
/**
* @notice Returns the provider for a data set
* @param setId id of the data set
* @return address of provider
*/
function getDataProvider(bytes32 setId)
external
view
override
returns (address)
{
return sets[setId].provider;
}
/**
* @notice Registers / updates a data set provider.
* @dev Can only be called by the owner of the DataRegistryProxy.
* @param setId id of the data set
* @param provider address of the provider
*/
function setDataProvider(
bytes32 setId,
address provider
)
external
override
onlyOwner
{
sets[setId].provider = provider;
if (sets[setId].isSet == false) {
sets[setId].isSet = true;
}
emit UpdatedDataProvider(setId, provider);
}
/**
* @notice Stores a new data point of a data set for a given timestamp.
* @dev Can only be called by a whitelisted data provider.
* @param setId id of the data set
* @param timestamp timestamp of the data point
* @param dataPoint the data point of the data set
*/
function publishDataPoint(
bytes32 setId,
uint256 timestamp,
int256 dataPoint
)
external
override
{
require(
msg.sender == sets[setId].provider,
"DataRegistry.publishDataPoint: UNAUTHORIZED_SENDER"
);
sets[setId].dataPoints[timestamp] = DataPoint(dataPoint, true);
if (sets[setId].isSet == false) {
sets[setId].isSet = true;
}
if (sets[setId].lastUpdatedTimestamp < timestamp) {
sets[setId].lastUpdatedTimestamp = timestamp;
}
emit PublishedDataPoint(setId, dataPoint, timestamp);
}
}
| Returns a data point of a data set for a given timestamp. setId id of the data set timestamp timestamp of the data point return data point, bool indicating whether data point exists/ | function getDataPoint(
bytes32 setId,
uint256 timestamp
)
external
view
override(IDataRegistryProxy, IObserverOracleProxy)
returns (int256, bool)
{
return (
sets[setId].dataPoints[timestamp].dataPoint,
sets[setId].dataPoints[timestamp].isSet
);
}
| 14,052,065 |
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.6.12;
//
// _░▒███████
// ░██▓▒░░▒▓██
// ██▓▒░__░▒▓██___██████
// ██▓▒░____░▓███▓__░▒▓██
// ██▓▒░___░▓██▓_____░▒▓██
// ██▓▒░_______________░▒▓██
// _██▓▒░______________░▒▓██
// __██▓▒░____________░▒▓██
// ___██▓▒░__________░▒▓██
// ____██▓▒░________░▒▓██
// _____██▓▒░_____░▒▓██
// ██░▀██████████████▀░██_██▓▒░__░▒▓██
// █▌▒▒░████████████░▒▒▐█__█▓▒░░▒▓██
// █░▒▒▒░██████████░▒▒▒░█____░▒▓██
// ▌░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░▐__░▒▓██
// ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░▒▓██
// ███▀▀▀██▄▒▒▒▒▒▒▒▄██▀▀▀██
// ██░░░▐█░▀█▒▒▒▒▒█▀░█▌░░░█
// ▐▌░░░▐▄▌░▐▌▒▒▒▐▌░▐▄▌░░▐▌
// █░░░▐█▌░░▌▒▒▒▐░░▐█▌░░█
// ▒▀▄▄▄█▄▄▄▌░▄░▐▄▄▄█▄▄▀▒
// ░░░░░░░░░░└┴┘░░░░░░░░░
// ██▄▄░░░░░░░░░░░░░░▄▄██
// ████████▒▒▒▒▒▒████████
// █▀░░███▒▒░░▒░░▒▀██████
// █▒░███▒▒╖░░╥░░╓▒▐█████
// █▒░▀▀▀░░║░░║░░║░░█████
// ██▄▄▄▄▀▀┴┴╚╧╧╝╧╧╝┴┴███
// ██████████████████████
//
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
// ERC721
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
// ERC20
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
// For safe maths operations
import "@openzeppelin/contracts/math/SafeMath.sol";
// Utils only
import "./StringsUtil.sol";
interface IERC20Burnable {
function burn(uint256 amount) external;
function burnFrom(address account, uint256 amount) external;
function burnAmount() external view returns (uint256 _amount);
}
/**
* @title NotRealDigitalAsset - V2
*
* http://www.notreal.ai/
*
* ERC721 compliant digital assets for real-world artwork.
*
* Base NFT Issuance Contract
*
* AMPLIFY ART.
*
*/
contract NotRealDigitalAssetV2 is
AccessControl,
Ownable,
ERC721,
Pausable,
ReentrancyGuard
{
bytes32 public constant ROLE_NOT_REAL = keccak256('ROLE_NOT_REAL');
bytes32 public constant ROLE_MINTER = keccak256('ROLE_MINTER');
bytes32 public constant ROLE_MARKET = keccak256('ROLE_MARKET');
///////////////
// Modifiers //
///////////////
// Modifiers are wrapped around functions because it shaves off contract size
modifier onlyAvailableEdition(uint256 _editionNumber, uint256 _numTokens) {
_onlyAvailableEdition(_editionNumber, _numTokens);
_;
}
modifier onlyActiveEdition(uint256 _editionNumber) {
_onlyActiveEdition(_editionNumber);
_;
}
modifier onlyRealEdition(uint256 _editionNumber) {
_onlyRealEdition(_editionNumber);
_;
}
modifier onlyValidTokenId(uint256 _tokenId) {
_onlyValidTokenId(_tokenId);
_;
}
modifier onlyPurchaseDuringWindow(uint256 _editionNumber) {
_onlyPurchaseDuringWindow(_editionNumber);
_;
}
function _onlyAvailableEdition(uint256 _editionNumber, uint256 _numTokens) internal view {
require(editionNumberToEditionDetails[_editionNumber].totalSupply.add(_numTokens) <= editionNumberToEditionDetails[_editionNumber].totalAvailable);
}
function _onlyActiveEdition(uint256 _editionNumber) internal view {
require(editionNumberToEditionDetails[_editionNumber].active);
}
function _onlyRealEdition(uint256 _editionNumber) internal view {
require(editionNumberToEditionDetails[_editionNumber].editionNumber > 0);
}
function _onlyValidTokenId(uint256 _tokenId) internal view {
require(_exists(_tokenId));
}
function _onlyPurchaseDuringWindow(uint256 _editionNumber) internal view {
require(editionNumberToEditionDetails[_editionNumber].startDate <= block.timestamp);
require(editionNumberToEditionDetails[_editionNumber].endDate >= block.timestamp);
}
modifier onlyIfNotReal() {
_onlyIfNotReal();
_;
}
modifier onlyIfMinter() {
_onlyIfMinter();
_;
}
function _onlyIfNotReal() internal view {
require(_msgSender() == owner() || hasRole(ROLE_NOT_REAL, _msgSender()));
}
function _onlyIfMinter() internal view {
require(_msgSender() == owner() || hasRole(ROLE_NOT_REAL, _msgSender()) || hasRole(ROLE_MINTER, _msgSender()));
}
using SafeMath for uint256;
using SafeERC20 for IERC20;
////////////
// Events //
////////////
// Emitted on purchases from within this contract
event Purchase(
uint256 indexed _tokenId,
uint256 indexed _editionNumber,
address indexed _buyer,
uint256 _priceInWei,
uint256 _numTokens
);
// Emitted on every mint
event Minted(
uint256 indexed _tokenId,
uint256 indexed _editionNumber,
address indexed _buyer,
uint256 _numTokens
);
// Emitted on every edition created
event EditionCreated(
uint256 indexed _editionNumber,
bytes32 indexed _editionData,
uint256 indexed _editionType
);
event NameChange(uint256 indexed _tokenId, string _newName);
////////////////
// Properties //
////////////////
uint256 constant internal MAX_UINT32 = ~uint32(0);
string public tokenBaseURI = "https://ipfs.infura.io/ipfs/";
// simple counter to keep track of the highest edition number used
uint256 public highestEditionNumber;
// number of assets minted of any type
uint256 public totalNumberMinted;
// number of assets minted of any type
uint256 public totalPurchaseValueInWei;
// number of assets available of any type
uint256 public totalNumberAvailable;
// Max number of tokens that can be minted/purchased in a batch
uint256 public maxBatch = 100;
uint256 public maxGas = 100000000000;
// the NR account which can receive commission
address public nrCommissionAccount;
// Accepted ERC20 token
IERC20 public acceptedToken;
IERC20Burnable public nameToken;
// Optional commission split can be defined per edition
mapping(uint256 => CommissionSplit) internal editionNumberToOptionalCommissionSplit;
// Simple structure providing an optional commission split per edition purchase
struct CommissionSplit {
uint256 rate;
address recipient;
}
// Object for edition details
struct EditionDetails {
// Identifiers
uint256 editionNumber; // the range e.g. 10000
bytes32 editionData; // some data about the edition
uint256 editionType; // e.g. 1 = NRDA, 4 = Deactivated
// Config
uint256 startDate; // date when the edition goes on sale
uint256 endDate; // date when the edition is available until
address artistAccount; // artists account
uint256 artistCommission; // base artists commission, could be overridden by external contracts
uint256 priceInWei; // base price for edition, could be overridden by external contracts
string tokenURI; // IPFS hash - see base URI
bool active; // Root control - on/off for the edition
// Counters
uint256 totalSupply; // Total purchases or mints
uint256 totalAvailable; // Total number available to be purchased
}
// _editionNumber : EditionDetails
mapping(uint256 => EditionDetails) internal editionNumberToEditionDetails;
// _tokenId : _editionNumber
mapping(uint256 => uint256) internal tokenIdToEditionNumber;
// _editionNumber : [_tokenId, _tokenId]
mapping(uint256 => uint256[]) internal editionNumberToTokenIds;
mapping(uint256 => uint256[]) internal editionNumberToBurnedTokenIds;
// _artistAccount : [_editionNumber, _editionNumber]
mapping(address => uint256[]) internal artistToEditionNumbers;
mapping(uint256 => uint256) internal editionNumberToArtistIndex;
// _editionType : [_editionNumber, _editionNumber]
mapping(uint256 => uint256[]) internal editionTypeToEditionNumber;
mapping(uint256 => uint256) internal editionNumberToTypeIndex;
mapping (uint256 => string) public tokenName;
mapping (string => bool) internal reservedName;
/*
* Constructor
*/
constructor (IERC20 _acceptedToken) public payable ERC721("NotRealDigitalAsset", "NRDA") {
// set commission account to contract creator
nrCommissionAccount = _msgSender();
acceptedToken = _acceptedToken;
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setBaseURI(tokenBaseURI);
}
// Function wrapper for using native Ether or ERC20
function _acceptedTokenSafeTransferFrom(address _from, address _to, uint256 _msgValue) internal {
require(tx.gasprice <= maxGas, "Gas price too high");
if(address(acceptedToken) == address(0)) {
require(msg.value == _msgValue);
require(_from == _msgSender());
require(_to == address(this));
} else {
acceptedToken.safeTransferFrom(_from, _to, _msgValue);
}
}
function _acceptedTokenSafeTransfer(address _to, uint256 _msgValue) internal {
if(address(acceptedToken) == address(0)) {
payable(_to).transfer(_msgValue);
} else {
acceptedToken.safeTransfer(_to, _msgValue);
}
}
function pause() public onlyIfNotReal {
_pause();
}
function unpause() public onlyIfNotReal {
_unpause();
}
function setNameToken(address _nameToken) external onlyOwner {
nameToken = IERC20Burnable(_nameToken);
}
// Spend name tokens to give this ERC721 a unique name
function changeName(uint256 _tokenId, string memory _newName) public onlyValidTokenId(_tokenId) {
string memory _newNameLower = StringsUtil.toLower(_newName);
require(_msgSender() == ownerOf(_tokenId), "ERC721: caller is not the owner");
require(StringsUtil.validateName(_newName), "Not a valid new name");
require(!reservedName[_newNameLower], "Name already reserved");
reservedName[StringsUtil.toLower(tokenName[_tokenId])] = false;
reservedName[_newNameLower] = true;
nameToken.burnFrom(_msgSender(), nameToken.burnAmount());
tokenName[_tokenId] = _newName;
emit NameChange(_tokenId, _newName);
}
function mint(address _to, uint256 _editionNumber)
public
onlyIfMinter
returns (uint256) {
return mintMany(_to, _editionNumber, 1);
}
/**
* @dev Private (NR only) method for minting editions
* @dev Payment not needed for this method
*/
function mintMany(address _to, uint256 _editionNumber, uint256 _numTokens)
public
onlyIfMinter
onlyRealEdition(_editionNumber)
onlyAvailableEdition(_editionNumber, _numTokens)
returns (uint256) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
uint256 _tokenId = _editionDetails.editionNumber.add(_editionDetails.totalSupply).add(1);
for (uint256 i = 0; i < _numTokens; i++) {
// Construct next token ID e.g. 100000 + 1 = ID of 100001 (this first in the edition set)
// Create the token
_mintToken(_to, _tokenId.add(i), _editionNumber, _editionDetails.tokenURI);
}
totalNumberMinted = totalNumberMinted.add(_numTokens);
_editionDetails.totalSupply = _editionDetails.totalSupply.add(_numTokens);
// Emit minted event
emit Minted(_tokenId, _editionNumber, _to, _numTokens);
return _tokenId;
}
/**
* @dev Internal factory method for building editions
*/
function createEdition(
uint256 _editionNumber,
bytes32 _editionData,
uint256 _editionType,
uint256 _startDate,
uint256 _endDate,
address _artistAccount,
uint256 _artistCommission,
uint256 _priceInWei,
string memory _tokenURI,
uint256 _totalAvailable,
bool _active
)
public
onlyIfNotReal
returns (bool)
{
// Prevent missing edition number
require(_editionNumber != 0);
// Prevent edition number lower than last one used
require(_editionNumber > highestEditionNumber);
// Check previously edition plus total available is less than new edition number
require(highestEditionNumber.add(editionNumberToEditionDetails[highestEditionNumber].totalAvailable) < _editionNumber);
// Prevent missing types
require(_editionType != 0);
// Prevent missing token URI
require(bytes(_tokenURI).length != 0);
// Prevent empty artists address
require(_artistAccount != address(0));
// Prevent invalid commissions
require(_artistCommission <= 100 && _artistCommission >= 0);
// Prevent duplicate editions
require(editionNumberToEditionDetails[_editionNumber].editionNumber == 0);
// Default end date to max uint256
uint256 endDate = _endDate;
if (_endDate == 0) {
endDate = MAX_UINT32;
}
editionNumberToEditionDetails[_editionNumber] = EditionDetails({
editionNumber : _editionNumber,
editionData : _editionData,
editionType : _editionType,
startDate : _startDate,
endDate : endDate,
artistAccount : _artistAccount,
artistCommission : _artistCommission,
priceInWei : _priceInWei,
tokenURI : StringsUtil.strConcat(_tokenURI, "/"),
totalSupply : 0, // default to all available
totalAvailable : _totalAvailable,
active : _active
});
// Add to total available count
totalNumberAvailable = totalNumberAvailable.add(_totalAvailable);
// Update mappings
_updateArtistLookupData(_artistAccount, _editionNumber);
_updateEditionTypeLookupData(_editionType, _editionNumber);
emit EditionCreated(_editionNumber, _editionData, _editionType);
// Update the edition pointer if needs be
highestEditionNumber = _editionNumber;
return true;
}
function _updateEditionTypeLookupData(uint256 _editionType, uint256 _editionNumber) internal {
uint256 typeEditionIndex = editionTypeToEditionNumber[_editionType].length;
editionTypeToEditionNumber[_editionType].push(_editionNumber);
editionNumberToTypeIndex[_editionNumber] = typeEditionIndex;
}
function _updateArtistLookupData(address _artistAccount, uint256 _editionNumber) internal {
uint256 artistEditionIndex = artistToEditionNumbers[_artistAccount].length;
artistToEditionNumbers[_artistAccount].push(_editionNumber);
editionNumberToArtistIndex[_editionNumber] = artistEditionIndex;
}
///**
// * @dev Public entry point for purchasing an edition on behalf of someone else
// * @dev Reverts if edition is invalid
// * @dev Reverts if payment not provided in full
// * @dev Reverts if edition is sold out
// * @dev Reverts if edition is not active or available
// */
function purchaseMany(address _to, uint256 _editionNumber, uint256 _numTokens, uint256 _msgValue)
public
payable
whenNotPaused
nonReentrant
onlyRealEdition(_editionNumber)
onlyActiveEdition(_editionNumber)
onlyAvailableEdition(_editionNumber, _numTokens)
onlyPurchaseDuringWindow(_editionNumber)
returns (uint256) {
require(_numTokens <= maxBatch && _numTokens >= 1);
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
require(_msgValue >= _editionDetails.priceInWei.mul(_numTokens));
_acceptedTokenSafeTransferFrom(_msgSender(), address(this), _msgValue);
uint256 _tokenId = _editionDetails.editionNumber.add(_editionDetails.totalSupply).add(1);
for (uint256 i = 0; i < _numTokens; i++) {
// Transfer token to this contract
// Construct next token ID e.g. 100000 + 1 = ID of 100001 (this first in the edition set)
// Create the token
_mintToken(_to, _tokenId.add(i), _editionNumber, _editionDetails.tokenURI);
}
totalNumberMinted = totalNumberMinted.add(_numTokens);
_editionDetails.totalSupply = _editionDetails.totalSupply.add(_numTokens);
// Splice funds and handle commissions
_handleFunds(_editionNumber, _msgValue, _editionDetails.artistAccount, _editionDetails.artistCommission);
// Emit minted event
emit Minted(_tokenId, _editionNumber, _to, _numTokens);
// Broadcast purchase
emit Purchase(_tokenId, _editionNumber, _to, _editionDetails.priceInWei, _numTokens);
return _tokenId;
}
function _nextTokenId(uint256 _editionNumber) internal returns (uint256) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
// Bump number totalSupply
_editionDetails.totalSupply = _editionDetails.totalSupply.add(1);
// Construct next token ID e.g. 100000 + 1 = ID of 100001 (this first in the edition set)
return _editionDetails.editionNumber.add(_editionDetails.totalSupply);
}
function _mintToken(address _to, uint256 _tokenId, uint256 _editionNumber, string memory _tokenURI) internal {
// Mint new base token
super._mint(_to, _tokenId);
super._setTokenURI(_tokenId, StringsUtil.strConcat(_tokenURI, StringsUtil.uint2str(_tokenId)));
// Maintain mapping for tokenId to edition for lookup
tokenIdToEditionNumber[_tokenId] = _editionNumber;
// Maintain mapping of edition to token array for "edition minted tokens"
editionNumberToTokenIds[_editionNumber].push(_tokenId);
}
function _handleFunds(uint256 _editionNumber, uint256 _priceInWei, address _artistAccount, uint256 _artistCommission) internal {
// Extract the artists commission and send it
uint256 artistPayment = _priceInWei.div(100).mul(_artistCommission);
if (artistPayment > 0) {
_acceptedTokenSafeTransfer(_artistAccount, artistPayment);
}
// Load any commission overrides
CommissionSplit storage commission = editionNumberToOptionalCommissionSplit[_editionNumber];
// Apply optional commission structure
uint256 rateSplit = 0;
if (commission.rate > 0) {
rateSplit = _priceInWei.div(100).mul(commission.rate);
_acceptedTokenSafeTransfer(commission.recipient, rateSplit);
}
// Send remaining eth to NR
uint256 remainingCommission = _priceInWei.sub(artistPayment).sub(rateSplit);
_acceptedTokenSafeTransfer(nrCommissionAccount, remainingCommission);
// Record wei sale value
totalPurchaseValueInWei = totalPurchaseValueInWei.add(_priceInWei);
}
/**
* @dev Private (NR only) method for burning tokens which have been created incorrectly
*/
function burn(uint256 _tokenId) external onlyIfNotReal {
// Clear from parents
super._burn(_tokenId);
// Get hold of the edition for cleanup
uint256 _editionNumber = tokenIdToEditionNumber[_tokenId];
// Delete token ID mapping
delete tokenIdToEditionNumber[_tokenId];
editionNumberToBurnedTokenIds[_editionNumber].push(_tokenId);
}
//////////////////
// Base Updates //
//////////////////
//
function updateTokenBaseURI(string calldata _newBaseURI)
external
onlyIfNotReal {
require(bytes(_newBaseURI).length != 0);
tokenBaseURI = _newBaseURI;
}
function updateNrCommissionAccount(address _nrCommissionAccount)
external
onlyIfNotReal {
require(_nrCommissionAccount != address(0));
nrCommissionAccount = _nrCommissionAccount;
}
function updateMaxBatch(uint256 _maxBatch)
external
onlyIfNotReal {
maxBatch = _maxBatch;
}
function updateMaxGas(uint256 _maxGas)
external
onlyIfNotReal {
maxGas = _maxGas;
}
/////////////////////
// Edition Updates //
/////////////////////
function updateEditionTokenURI(uint256 _editionNumber, string calldata _uri)
external
onlyIfNotReal
onlyRealEdition(_editionNumber) {
editionNumberToEditionDetails[_editionNumber].tokenURI = StringsUtil.strConcat(_uri, "/");
}
function updatePriceInWei(uint256 _editionNumber, uint256 _priceInWei)
external
onlyIfNotReal
onlyRealEdition(_editionNumber) {
editionNumberToEditionDetails[_editionNumber].priceInWei = _priceInWei;
}
function updateArtistCommission(uint256 _editionNumber, uint256 _rate)
external
onlyIfNotReal
onlyRealEdition(_editionNumber) {
editionNumberToEditionDetails[_editionNumber].artistCommission = _rate;
}
function updateEditionType(uint256 _editionNumber, uint256 _editionType)
external
onlyIfNotReal
onlyRealEdition(_editionNumber) {
EditionDetails storage _originalEditionDetails = editionNumberToEditionDetails[_editionNumber];
// Get list of editions for old type
uint256[] storage editionNumbersForType = editionTypeToEditionNumber[_originalEditionDetails.editionType];
// Remove edition from old type list
uint256 editionTypeIndex = editionNumberToTypeIndex[_editionNumber];
delete editionNumbersForType[editionTypeIndex];
// Add new type to the list
uint256 newTypeEditionIndex = editionTypeToEditionNumber[_editionType].length;
editionTypeToEditionNumber[_editionType].push(_editionNumber);
editionNumberToTypeIndex[_editionNumber] = newTypeEditionIndex;
// Update the edition
_originalEditionDetails.editionType = _editionType;
}
function updateTotalSupply(uint256 _editionNumber, uint256 _totalSupply)
external
onlyIfNotReal
onlyRealEdition(_editionNumber) {
require(editionNumberToTokenIds[_editionNumber].length <= _totalSupply);
editionNumberToEditionDetails[_editionNumber].totalSupply = _totalSupply;
}
function updateTotalAvailable(uint256 _editionNumber, uint256 _totalAvailable)
external
onlyIfNotReal
onlyRealEdition(_editionNumber) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
require(_editionDetails.totalSupply <= _totalAvailable);
uint256 originalAvailability = _editionDetails.totalAvailable;
_editionDetails.totalAvailable = _totalAvailable;
totalNumberAvailable = totalNumberAvailable.sub(originalAvailability).add(_totalAvailable);
}
function updateActive(uint256 _editionNumber, bool _active)
external
onlyIfNotReal
onlyRealEdition(_editionNumber) {
editionNumberToEditionDetails[_editionNumber].active = _active;
}
function updateStartDate(uint256 _editionNumber, uint256 _startDate)
external
onlyIfNotReal
onlyRealEdition(_editionNumber) {
editionNumberToEditionDetails[_editionNumber].startDate = _startDate;
}
function updateEndDate(uint256 _editionNumber, uint256 _endDate)
external
onlyRealEdition(_editionNumber) {
require(_msgSender() == owner() || hasRole(ROLE_NOT_REAL, _msgSender()) || hasRole(ROLE_MARKET, _msgSender()));
editionNumberToEditionDetails[_editionNumber].endDate = _endDate;
}
function updateArtistsAccount(uint256 _editionNumber, address _artistAccount)
external
onlyIfNotReal
onlyRealEdition(_editionNumber) {
EditionDetails storage _originalEditionDetails = editionNumberToEditionDetails[_editionNumber];
uint256 editionArtistIndex = editionNumberToArtistIndex[_editionNumber];
// Get list of editions old artist works with
uint256[] storage editionNumbersForArtist = artistToEditionNumbers[_originalEditionDetails.artistAccount];
// Remove edition from artists lists
delete editionNumbersForArtist[editionArtistIndex];
// Add new artists to the list
uint256 newArtistsEditionIndex = artistToEditionNumbers[_artistAccount].length;
artistToEditionNumbers[_artistAccount].push(_editionNumber);
editionNumberToArtistIndex[_editionNumber] = newArtistsEditionIndex;
// Update the edition
_originalEditionDetails.artistAccount = _artistAccount;
}
function updateOptionalCommission(uint256 _editionNumber, uint256 _rate, address _recipient)
external
onlyIfNotReal
onlyRealEdition(_editionNumber) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
uint256 artistCommission = _editionDetails.artistCommission;
if (_rate > 0) {
require(_recipient != address(0));
}
require(artistCommission.add(_rate) <= 100);
editionNumberToOptionalCommissionSplit[_editionNumber] = CommissionSplit({rate : _rate, recipient : _recipient});
}
///////////////////
// Token Updates //
///////////////////
function setTokenURI(uint256 _tokenId, string calldata _uri)
external
onlyIfNotReal
onlyValidTokenId(_tokenId) {
_setTokenURI(_tokenId, _uri);
}
///////////////////
// Query Methods //
///////////////////
/**
* @dev Lookup the edition of the provided token ID
* @dev Returns 0 if not valid
*/
function editionOfTokenId(uint256 _tokenId) external view returns (uint256 _editionNumber) {
return tokenIdToEditionNumber[_tokenId];
}
/**
* @dev Lookup all editions added for the given edition type
* @dev Returns array of edition numbers, any zero edition ids can be ignore/stripped
*/
function editionsOfType(uint256 _type) external view returns (uint256[] memory _editionNumbers) {
return editionTypeToEditionNumber[_type];
}
/**
* @dev Lookup all editions for the given artist account
* @dev Returns empty list if not valid
*/
function artistsEditions(address _artistsAccount) external view returns (uint256[] memory _editionNumbers) {
return artistToEditionNumbers[_artistsAccount];
}
/**
* @dev Lookup all tokens minted for the given edition number
* @dev Returns array of token IDs, any zero edition ids can be ignore/stripped
*/
function tokensOfEdition(uint256 _editionNumber) external view returns (uint256[] memory _tokenIds) {
return editionNumberToTokenIds[_editionNumber];
}
/**
* @dev Lookup all owned tokens for the provided address
* @dev Returns array of token IDs
*/
function tokensOf(address _owner) external view returns (uint256[] memory _tokenIds) {
uint256[] memory results = new uint256[](balanceOf(_owner));
for (uint256 idx = 0; idx < results.length; idx++) {
results[idx] = tokenOfOwnerByIndex(_owner, idx);
}
return results;
}
/**
* @dev Checks to see if the edition exists, assumes edition of zero is invalid
*/
function editionExists(uint256 _editionNumber) external view returns (bool) {
if (_editionNumber == 0) {
return false;
}
EditionDetails storage editionNumber = editionNumberToEditionDetails[_editionNumber];
return editionNumber.editionNumber == _editionNumber;
}
/**
* @dev Checks to see if the token exists
*/
function exists(uint256 _tokenId) external view returns (bool) {
return _exists(_tokenId);
}
/**
* @dev Lookup any optional commission split set for the edition
* @dev Both values will be zero if not present
*/
function editionOptionalCommission(uint256 _editionNumber) external view returns (uint256 _rate, address _recipient) {
CommissionSplit storage commission = editionNumberToOptionalCommissionSplit[_editionNumber];
return (commission.rate, commission.recipient);
}
/**
* @dev Main entry point for looking up edition config/metadata
* @dev Reverts if invalid edition number provided
*/
function detailsOfEdition(uint256 editionNumber)
external view
onlyRealEdition(editionNumber)
returns (
bytes32 _editionData,
uint256 _editionType,
uint256 _startDate,
uint256 _endDate,
address _artistAccount,
uint256 _artistCommission,
uint256 _priceInWei,
string memory _tokenURI,
uint256 _totalSupply,
uint256 _totalAvailable,
bool _active
) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[editionNumber];
return (
_editionDetails.editionData,
_editionDetails.editionType,
_editionDetails.startDate,
_editionDetails.endDate,
_editionDetails.artistAccount,
_editionDetails.artistCommission,
_editionDetails.priceInWei,
StringsUtil.strConcat(tokenBaseURI, _editionDetails.tokenURI),
_editionDetails.totalSupply,
_editionDetails.totalAvailable,
_editionDetails.active
);
}
/**
* @dev Lookup a tokens common identifying characteristics
* @dev Reverts if invalid token ID provided
*/
function tokenData(uint256 _tokenId)
external view
onlyValidTokenId(_tokenId)
returns (
uint256 _editionNumber,
uint256 _editionType,
bytes32 _editionData,
string memory _tokenURI,
address _owner
) {
uint256 editionNumber = tokenIdToEditionNumber[_tokenId];
EditionDetails storage editionDetails = editionNumberToEditionDetails[editionNumber];
return (
editionNumber,
editionDetails.editionType,
editionDetails.editionData,
tokenURI(_tokenId),
ownerOf(_tokenId)
);
}
//////////////////////////
// Edition config query //
//////////////////////////
function purchaseDatesEdition(uint256 _editionNumber) public view returns (uint256 _startDate, uint256 _endDate) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
return (
_editionDetails.startDate,
_editionDetails.endDate
);
}
function artistCommission(uint256 _editionNumber) external view returns (address _artistAccount, uint256 _artistCommission) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
return (
_editionDetails.artistAccount,
_editionDetails.artistCommission
);
}
function priceInWeiEdition(uint256 _editionNumber) public view returns (uint256 _priceInWei) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
return _editionDetails.priceInWei;
}
function editionActive(uint256 _editionNumber) public view returns (bool) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
return _editionDetails.active;
}
function totalRemaining(uint256 _editionNumber) external view returns (uint256) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
return _editionDetails.totalAvailable.sub(_editionDetails.totalSupply);
}
function totalAvailableEdition(uint256 _editionNumber) public view returns (uint256) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
return _editionDetails.totalAvailable;
}
function totalSupplyEdition(uint256 _editionNumber) public view returns (uint256) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
return _editionDetails.totalSupply;
}
function reclaimEther() external onlyOwner {
payable(owner()).transfer(address(this).balance);
if (address(acceptedToken) != address(0)) {
acceptedToken.transfer(owner(), acceptedToken.balanceOf(address(this)));
}
}
}
pragma solidity ^0.6.12;
library StringsUtil {
// via https://github.com/provable-things/ethereum-api/blob/master/provableAPI_0.6.sol
function strConcat(string memory _a, string memory _b) internal pure returns (string memory _concatenatedString) {
return strConcat(_a, _b, "", "", "");
}
function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory _concatenatedString) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory _concatenatedString) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
uint i = 0;
for (i = 0; i < _ba.length; i++) {
babcde[k++] = _ba[i];
}
for (i = 0; i < _bb.length; i++) {
babcde[k++] = _bb[i];
}
for (i = 0; i < _bc.length; i++) {
babcde[k++] = _bc[i];
}
for (i = 0; i < _bd.length; i++) {
babcde[k++] = _bd[i];
}
for (i = 0; i < _be.length; i++) {
babcde[k++] = _be[i];
}
return string(babcde);
}
function equal(string memory a, string memory b) internal pure returns (bool) {
return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));
}
// NOTE! If you don't make library functions internal, then you have to do annoying linking steps during migration
/**
* @dev Check if the name string is valid (Alphanumeric and spaces without leading or trailing space)
*/
function validateName(string memory str) internal pure returns (bool){
bytes memory b = bytes(str);
if(b.length < 1 ||
b.length > 25 || // Cannot be longer than 25 characters
b[0] == 0x20 || // Leading space
// Trailing space
b[b.length - 1] == 0x20) {
return false;
}
bytes1 lastChar = b[0];
for(uint i; i<b.length; i++){
bytes1 char = b[i];
if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces
if(
!(char >= 0x30 && char <= 0x39) && //9-0
!(char >= 0x41 && char <= 0x5A) && //A-Z
!(char >= 0x61 && char <= 0x7A) && //a-z
!(char == 0x20) //space
)
return false;
lastChar = char;
}
return true;
}
function toLower(string memory str) internal pure returns (string memory){
bytes memory bStr = bytes(str);
bytes memory bLower = new bytes(bStr.length);
for (uint i = 0; i < bStr.length; i++) {
// Uppercase character
if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) {
bLower[i] = bytes1(uint8(bStr[i]) + 32);
} else {
bLower[i] = bStr[i];
}
}
return string(bLower);
}
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 - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @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.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC721.sol";
import "./IERC721Metadata.sol";
import "./IERC721Enumerable.sol";
import "./IERC721Receiver.sol";
import "../../introspection/ERC165.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
import "../../utils/EnumerableSet.sol";
import "../../utils/EnumerableMap.sol";
import "../../utils/Strings.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @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 _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721.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 _tokenOwners.contains(tokenId);
}
/**
* @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 || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @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"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @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 { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../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.6.2 <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.6.2 <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.6.0 <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.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
| Extract the artists commission and send it | function _handleFunds(uint256 _editionNumber, uint256 _priceInWei, address _artistAccount, uint256 _artistCommission) internal {
uint256 artistPayment = _priceInWei.div(100).mul(_artistCommission);
if (artistPayment > 0) {
_acceptedTokenSafeTransfer(_artistAccount, artistPayment);
}
if (commission.rate > 0) {
rateSplit = _priceInWei.div(100).mul(commission.rate);
_acceptedTokenSafeTransfer(commission.recipient, rateSplit);
}
_acceptedTokenSafeTransfer(nrCommissionAccount, remainingCommission);
}
| 6,043,729 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "./libs/IUpgradedStandardToken.sol";
import "./BlackList.sol";
contract SperaV3 is Initializable, OwnableUpgradeable, PausableUpgradeable, BlackList, ERC20Upgradeable {
// Called when new token are issued
event Issue(uint256 amount);
// Called when tokens are redeemed
event Redeem(uint256 amount);
// Called when contract is deprecated
event Deprecate(address newAddress);
address public upgradedAddress;
bool public deprecated;
function initialize() public initializer {
__ERC20_init("Spera", "SPRA");
_mint(msg.sender, 10000000000000000000);
__Ownable_init();
}
function destroyBlackFunds(address _blackListedUser) public override onlyOwner {
require(isBlackListed[_blackListedUser]);
uint256 dirtyFunds = balanceOf(_blackListedUser);
_burn(_blackListedUser, dirtyFunds);
emit DestroyedBlackFunds(_blackListedUser, dirtyFunds);
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transfer(address _to, uint256 _value) public override whenNotPaused returns (bool) {
require(!isBlackListed[msg.sender], "Blacklisted Member");
if (deprecated) {
IUpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value);
} else {
super.transfer(_to, _value);
}
return true;
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transferFrom(
address _from,
address _to,
uint256 _value
) public override whenNotPaused returns (bool) {
require(!isBlackListed[_from], "Blacklisted Member");
if (deprecated) {
IUpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value);
} else {
super.transferFrom(_from, _to, _value);
}
return true;
}
// deprecate current contract in favour of a new one
function deprecate(address _upgradedAddress) public onlyOwner {
deprecated = true;
upgradedAddress = _upgradedAddress;
emit Deprecate(_upgradedAddress);
}
// deprecate current contract if favour of a new one
function totalSupply() public view override returns (uint256) {
if (deprecated) {
return IERC20Upgradeable(upgradedAddress).totalSupply();
} else {
return super.totalSupply();
}
}
// Issue a new amount of tokens
// these tokens are deposited into the owner address
//
// @param _amount Number of tokens to be issued
function issue(uint256 amount) whenNotPaused external onlyOwner {
require(totalSupply() + amount > totalSupply(), "Invalide value");
uint256 addValue;
bool addBoolValue;
(addBoolValue, addValue) = SafeMathUpgradeable.tryAdd(balanceOf(owner()), amount);
require(addBoolValue &&(addValue > balanceOf(owner())), "Invalide value");
_mint(owner(), amount);
emit Issue(amount);
}
// Redeem tokens.
// These tokens are withdrawn from the owner address
// if the balance must be enough to cover the redeem
// or the call will fail.
// @param _amount Number of tokens to be issued
function redeem(uint256 amount) public onlyOwner {
require(balanceOf(owner()) >= amount);
_burn(owner(), amount);
emit Redeem(amount);
}
// Pause functions from Pausable.sol contract
function pause() public onlyOwner{
_pause();
}
// Unpause functions from Pausable.sol contract
function unpause() public onlyOwner{
_unpause();
}
// minting function to mint the coin
function mint(uint256 amount, address recipient) public onlyOwner whenNotPaused{
_mint(recipient, amount);
}
// burning function to burn the coin
function burn(address account, uint256 amount) public onlyOwner whenNotPaused{
_burn(account, amount);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
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 onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, _allowances[owner][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = _allowances[owner][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Spend `amount` form the allowance of `owner` toward `spender`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[45] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the UpgradedStandardToken standard as defined in the EIP.
*/
interface IUpgradedStandardToken {
// those methods are called by the legacy contract
// and they must ensure msg.sender to be the contract address
function transferByLegacy(
address from,
address to,
uint256 value
) external;
function transferFromByLegacy(
address sender,
address from,
address spender,
uint256 value
) external;
function approveByLegacy(
address from,
address spender,
uint256 value
) external;
function balanceOf(address _owner) external view returns (uint256 balance);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
contract BlackList is OwnableUpgradeable {
event DestroyedBlackFunds(address _blackListedUser, uint256 _balance);
event AddedBlackList(address _user);
event RemovedBlackList(address _user);
mapping(address => bool) public isBlackListed;
/////// Getters to allow the same blacklist to be used also by other contracts (including upgraded Tether) ///////
function getBlackListStatus(address _maker) external view returns (bool) {
return isBlackListed[_maker];
}
function getOwner() external view returns (address) {
return owner();
}
function addBlackList(address _evilUser) public onlyOwner {
isBlackListed[_evilUser] = true;
emit AddedBlackList(_evilUser);
}
function removeBlackList(address _clearedUser) public onlyOwner {
isBlackListed[_clearedUser] = false;
emit RemovedBlackList(_clearedUser);
}
function destroyBlackFunds(address _blackListedUser) public virtual onlyOwner {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library 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
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
} | deprecate current contract if favour of a new one | function totalSupply() public view override returns (uint256) {
if (deprecated) {
return IERC20Upgradeable(upgradedAddress).totalSupply();
return super.totalSupply();
}
}
| 6,231,911 |
./full_match/1/0x2ACDFE510384c08e62556dA121eD81242DaB7aAd/sources/contracts/CitizensOfOverworld.sol | Creates DNA object for Overworld's newest Citizen via pseudorandom trait generation./ | function generateSeed(uint256 tokenId) private view returns (uint256) {
return
uint256(
keccak256(
abi.encodePacked(
blockhash(block.number - 1),
tokenId,
msg.sender,
block.timestamp,
block.difficulty,
seed_nonce
)
)
);
}
| 9,682,647 |
./partial_match/1/0x4c5b67f6Cea97f3341E65C7ABa420c2b200bDe33/sources/DmmControllerV2.sol | Attempt to pull from the sender into this contract, then have the DMM token pull from here. | function adminDepositFunds(
uint dmmTokenId,
uint underlyingAmount
) public requireTokenExists(dmmTokenId) whenNotPaused requireIsFromAssetIntroducerOrGuardian {
IERC20 underlyingToken = IERC20(dmmTokenIdToUnderlyingTokenAddressMap[dmmTokenId]);
underlyingToken.safeTransferFrom(_msgSender(), address(this), underlyingAmount);
address dmmTokenAddress = dmmTokenIdToDmmTokenAddressMap[dmmTokenId];
underlyingToken.approve(dmmTokenAddress, underlyingAmount);
IDmmToken(dmmTokenAddress).depositUnderlying(underlyingAmount);
emit AdminDeposit(_msgSender(), underlyingAmount);
}
| 15,892,181 |
./partial_match/1/0x14BcEEfb9924f8DD6CF1462a51b4675Ddc2AcB99/sources/TAH.sol | get balance of liquidity pair calculate amount to burn pull tokens from pancakePair liquidity and move to dead address permanently | 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;
}
| 2,828,586 |
pragma solidity ^0.5.0;
import "../contracts/StructLib.sol";
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
/** @title Order Library
* @author Bryan Herbert
* @notice Functionality to make state changes when a new order is placed
*/
library OrderLib{
/** @dev Modifier that verifies ownership of the fund
* @param self Data struct that contains fund information
* @param _fundNum Fund number
* @param sender placeholder for msg.sender
*/
modifier verifyOwnership(StructLib.Data storage self,
uint _fundNum,
address sender) {
require(
self.list[_fundNum].fundOwner == sender,
"A non-owner is trying to submit an order to the fund"
);
_;
}
/** @dev Handlees error checking for order placement
* @dev Order is broadcast via the emission of the event in FundMarketplace.sol
* @param self Data struct that contains fund information
* @param _fundNum Fund number
* @param _action Order action: buy or sell
* @param _qty Number of shares
* @param _price price per share (in finney
* @dev uses verifyOwnership() modifier
*/
function placeOrder(StructLib.Data storage self,
uint _fundNum,
bytes32 _action,
uint _qty,
uint _price)
verifyOwnership(self, _fundNum, msg.sender)
public
{
bytes32 buy = "buy";
bytes32 sell = "sell";
if(compareStrings(_action, buy)){
require(
//Cost of trade is price * qty
self.list[_fundNum].totalCapital > SafeMath.mul(_price,_qty),
"Cost of trade is greater than balance of fund"
);
self.list[_fundNum].capitalDeployed += SafeMath.mul(_price, _qty);
}
else if(compareStrings(_action, sell)){
self.list[_fundNum].capitalDeployed -= SafeMath.mul(_price, _qty);
}
else{
revert("Not a valid action");
}
}
/** @dev Verifies two strings are the same using keccak256 hash of each string
* @param a string to compare
* @param b string to compare
* @return bool Equality test of string
*/
function compareStrings(bytes32 a, bytes32 b) public pure returns(bool){
return keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b));
}
/** @dev Calculates the quantity of shares for an investor's order based on their share of capital in the fund
* @param self Data struct with information about funds
* @param _fundNum Fund Number
* @param qty Total number of shares
* @return uint Number of shares for investor's order
*/
function calcQty(StructLib.Data storage self,
uint _fundNum,
uint qty
)
public view returns(uint) {
//Couldn't use local variables because of stack too deep error
//(Qty * Virtual Balance) / Total Capital
return(SafeMath.div(SafeMath.mul(qty, self.list[_fundNum].virtualBalances[msg.sender]), self.list[_fundNum].totalCapital));
}
} | Handlees error checking for order placement Order is broadcast via the emission of the event in FundMarketplace.sol self Data struct that contains fund information _fundNum Fund number _action Order action: buy or sell _qty Number of shares _price price per share (in finney uses verifyOwnership() modifier/Cost of trade is price qty | function placeOrder(StructLib.Data storage self,
uint _fundNum,
bytes32 _action,
uint _qty,
uint _price)
verifyOwnership(self, _fundNum, msg.sender)
public
{
bytes32 buy = "buy";
bytes32 sell = "sell";
if(compareStrings(_action, buy)){
require(
self.list[_fundNum].totalCapital > SafeMath.mul(_price,_qty),
"Cost of trade is greater than balance of fund"
);
self.list[_fundNum].capitalDeployed += SafeMath.mul(_price, _qty);
}
else if(compareStrings(_action, sell)){
self.list[_fundNum].capitalDeployed -= SafeMath.mul(_price, _qty);
}
else{
revert("Not a valid action");
}
}
| 955,583 |
./full_match/1/0x996eAcBd74D94C77bD6edA46dAbF99608dBb336E/sources/contracts/validations/RoleBasedAccessControl.sol | Adds a user to a role. roleId A unique id of role to connect. userId A unique id of user to connect./ | function addUserToRole(bytes32 roleId, bytes32 userId) public {
_setAccessOfCombination(roleId, userId, 1);
emit UserAddedToRole(msg.sender, roleId, userId);
}
| 17,037,362 |
./full_match/56/0xa65B23cA853CcEd962016B841BFF9D9C2699dF14/sources/project_/contracts/diamond/facets/TradingCheckerFacet.sol | notionalUsd = price qty openFeeUsd = notionalUsd openFeeP marginUsd = amountInUsd - openFeeUsd - executionFeeUsd leverage_10000 = notionalUsd 10000 / marginUsd | function checkLimitOrderTp(ILimitOrder.LimitOrder memory order) external view override {
IVault.MarginToken memory token = IVault(address(this)).getTokenForTrading(order.tokenIn);
uint notionalUsd = order.limitPrice * order.qty;
uint openFeeUsd = notionalUsd * IPairsManager(address(this)).getPairFeeConfig(order.pairBase).openFeeP / 1e4;
uint marginUsd = order.amountIn * token.price * 1e10 / (10 ** token.decimals) - openFeeUsd - ITradingConfig(address(this)).getTradingConfig().executionFeeUsd;
uint leverage_10000 = notionalUsd * 1e4 / marginUsd;
require(
checkTp(order.isLong, order.takeProfit, order.limitPrice, leverage_10000, ITradingConfig(address(this)).getTradingConfig().maxTakeProfitP),
"TradingCheckerFacet: takeProfit is not in the valid range"
);
}
| 3,239,605 |
// Contracts by dYdX Foundation. Individual files are released under different licenses.
//
// https://dydx.community
// https://github.com/dydxfoundation/governance-contracts
//
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { IERC20 } from '../../interfaces/IERC20.sol';
import { ILiquidityStakingV1 } from '../../interfaces/ILiquidityStakingV1.sol';
import { IMerkleDistributorV1 } from '../../interfaces/IMerkleDistributorV1.sol';
import { IStarkPerpetual } from '../../interfaces/IStarkPerpetual.sol';
import { SafeERC20 } from '../../dependencies/open-zeppelin/SafeERC20.sol';
import { SP2Withdrawals } from './impl/SP2Withdrawals.sol';
import { SP1Getters } from '../v1/impl/SP1Getters.sol';
import { SP2Guardian } from './impl/SP2Guardian.sol';
import { SP2Owner } from './impl/SP2Owner.sol';
/**
* @title StarkProxyV2
* @author dYdX
*
* @notice Proxy contract allowing a LiquidityStaking borrower to use borrowed funds (as well as
* their own funds, if desired) on the dYdX L2 exchange. Restrictions are put in place to
* prevent borrowed funds being used outside the exchange. Furthermore, a guardian address is
* specified which has the ability to restrict borrows and make repayments.
*
* Owner actions may be delegated to various roles as defined in SP1Roles. Other actions are
* available to guardian roles, to be nominated by dYdX governance.
*/
contract StarkProxyV2 is
SP2Guardian,
SP2Owner,
SP2Withdrawals,
SP1Getters
{
using SafeERC20 for IERC20;
// ============ Constructor ============
constructor(
ILiquidityStakingV1 liquidityStaking,
IStarkPerpetual starkPerpetual,
IERC20 token,
IMerkleDistributorV1 merkleDistributor
)
SP2Guardian(liquidityStaking, starkPerpetual, token)
SP2Withdrawals(merkleDistributor)
{}
// ============ External Functions ============
function initialize()
external
initializer
{}
// ============ Internal Functions ============
/**
* @dev Returns the revision of the implementation contract.
*
* @return The revision number.
*/
function getRevision()
internal
pure
override
returns (uint256)
{
return 2;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @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: Apache-2.0
pragma solidity 0.7.5;
pragma abicoder v2;
/**
* @title ILiquidityStakingV1
* @author dYdX
*
* @notice Partial interface for LiquidityStakingV1.
*/
interface ILiquidityStakingV1 {
function getToken() external view virtual returns (address);
function getBorrowedBalance(address borrower) external view virtual returns (uint256);
function getBorrowerDebtBalance(address borrower) external view virtual returns (uint256);
function isBorrowingRestrictedForBorrower(address borrower) external view virtual returns (bool);
function getTimeRemainingInEpoch() external view virtual returns (uint256);
function inBlackoutWindow() external view virtual returns (bool);
// LS1Borrowing
function borrow(uint256 amount) external virtual;
function repayBorrow(address borrower, uint256 amount) external virtual;
function getAllocatedBalanceCurrentEpoch(address borrower)
external
view
virtual
returns (uint256);
function getAllocatedBalanceNextEpoch(address borrower) external view virtual returns (uint256);
function getBorrowableAmount(address borrower) external view virtual returns (uint256);
// LS1DebtAccounting
function repayDebt(address borrower, uint256 amount) external virtual;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.5;
pragma abicoder v2;
/**
* @title IMerkleDistributorV1
* @author dYdX
*
* @notice Partial interface for the MerkleDistributorV1 contract.
*/
interface IMerkleDistributorV1 {
function getIpnsName()
external
virtual
view
returns (string memory);
function getRewardsParameters()
external
virtual
view
returns (uint256, uint256, uint256);
function getActiveRoot()
external
virtual
view
returns (bytes32 merkleRoot, uint256 epoch, bytes memory ipfsCid);
function getNextRootEpoch()
external
virtual
view
returns (uint256);
function claimRewards(
uint256 cumulativeAmount,
bytes32[] calldata merkleProof
)
external
returns (uint256);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.5;
pragma abicoder v2;
/**
* @title IStarkPerpetual
* @author dYdX
*
* @notice Partial interface for the StarkPerpetual contract, for accessing the dYdX L2 exchange.
* @dev See https://github.com/starkware-libs/starkex-contracts
*/
interface IStarkPerpetual {
function registerUser(
address ethKey,
uint256 starkKey,
bytes calldata signature
) external;
function deposit(
uint256 starkKey,
uint256 assetType,
uint256 vaultId,
uint256 quantizedAmount
) external;
function withdraw(uint256 starkKey, uint256 assetType) external;
function forcedWithdrawalRequest(
uint256 starkKey,
uint256 vaultId,
uint256 quantizedAmount,
bool premiumCost
) external;
function forcedTradeRequest(
uint256 starkKeyA,
uint256 starkKeyB,
uint256 vaultIdA,
uint256 vaultIdB,
uint256 collateralAssetId,
uint256 syntheticAssetId,
uint256 amountCollateral,
uint256 amountSynthetic,
bool aIsBuyingSynthetic,
uint256 submissionExpirationTime,
uint256 nonce,
bytes calldata signature,
bool premiumCost
) external;
function mainAcceptGovernance() external;
function proxyAcceptGovernance() external;
function mainRemoveGovernor(address governorForRemoval) external;
function proxyRemoveGovernor(address governorForRemoval) external;
function registerAssetConfigurationChange(uint256 assetId, bytes32 configHash) external;
function applyAssetConfigurationChange(uint256 assetId, bytes32 configHash) external;
function registerGlobalConfigurationChange(bytes32 configHash) external;
function applyGlobalConfigurationChange(bytes32 configHash) external;
function getEthKey(uint256 starkKey) external view returns (address);
function depositCancel(
uint256 starkKey,
uint256 assetType,
uint256 vaultId
) external;
function depositReclaim(
uint256 starkKey,
uint256 assetType,
uint256 vaultId
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import { IERC20 } from '../../interfaces/IERC20.sol';
import { SafeMath } from './SafeMath.sol';
import { Address } from './Address.sol';
/**
* @title SafeERC20
* @dev From https://github.com/OpenZeppelin/openzeppelin-contracts
* 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));
}
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
'SafeERC20: approve from non-zero to non-zero allowance'
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), 'SafeERC20: call to non-contract');
// 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
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol';
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { IMerkleDistributorV1 } from '../../../interfaces/IMerkleDistributorV1.sol';
import { IStarkPerpetual } from '../../../interfaces/IStarkPerpetual.sol';
import { SP2Exchange } from './SP2Exchange.sol';
/**
* @title SP2Withdrawals
* @author dYdX
*
* @dev Actions which may be called only by WITHDRAWAL_OPERATOR_ROLE. Allows for withdrawing
* funds from the contract to external addresses that were approved by OWNER_ROLE.
*/
abstract contract SP2Withdrawals is
SP2Exchange
{
using SafeERC20 for IERC20;
using SafeMath for uint256;
// ============ Constants ============
IMerkleDistributorV1 public immutable MERKLE_DISTRIBUTOR;
// ============ Events ============
event ExternalWithdrewToken(
address recipient,
uint256 amount
);
event ExternalWithdrewOtherToken(
address token,
address recipient,
uint256 amount
);
event ExternalWithdrewEther(
address recipient,
uint256 amount
);
// ============ Constructor ============
constructor(
IMerkleDistributorV1 merkleDistributor
) {
MERKLE_DISTRIBUTOR = merkleDistributor;
}
// ============ External Functions ============
/**
* @notice Claim rewards from the Merkle distributor. They will be held in this contract until
* withdrawn by the WITHDRAWAL_OPERATOR_ROLE.
*
* @param cumulativeAmount The total all-time rewards this contract has earned.
* @param merkleProof The Merkle proof for this contract address and cumulative amount.
*
* @return The amount of new reward received.
*/
function claimRewardsFromMerkleDistributor(
uint256 cumulativeAmount,
bytes32[] calldata merkleProof
)
external
nonReentrant
onlyRole(WITHDRAWAL_OPERATOR_ROLE)
returns (uint256)
{
return MERKLE_DISTRIBUTOR.claimRewards(cumulativeAmount, merkleProof);
}
/**
* @notice Withdraw a token amount in excess of the borrowed balance, or an amount approved by
* the GUARDIAN_ROLE.
*
* The contract may hold an excess balance if, for example, additional funds were added by the
* contract owner for use with the same exchange account, or if profits were earned from
* activity on the exchange.
*
* @param recipient The recipient to receive tokens. Must be authorized by OWNER_ROLE.
*/
function externalWithdrawToken(
address recipient,
uint256 amount
)
external
nonReentrant
onlyRole(WITHDRAWAL_OPERATOR_ROLE)
onlyAllowedRecipient(recipient)
{
// If we are approved for the full amount, then skip the borrowed balance check.
uint256 approvedAmount = _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_;
if (approvedAmount >= amount) {
_APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_ = approvedAmount.sub(amount);
} else {
uint256 owedBalance = getBorrowedAndDebtBalance();
uint256 tokenBalance = getTokenBalance();
require(tokenBalance > owedBalance, 'SP2Withdrawals: No withdrawable balance');
uint256 availableBalance = tokenBalance.sub(owedBalance);
require(amount <= availableBalance, 'SP2Withdrawals: Amount exceeds withdrawable balance');
// Always decrease the approval amount.
_APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_ = 0;
}
TOKEN.safeTransfer(recipient, amount);
emit ExternalWithdrewToken(recipient, amount);
}
/**
* @notice Withdraw any ERC20 token balance other than the token used for borrowing.
*
* @param recipient The recipient to receive tokens. Must be authorized by OWNER_ROLE.
*/
function externalWithdrawOtherToken(
address token,
address recipient,
uint256 amount
)
external
nonReentrant
onlyRole(WITHDRAWAL_OPERATOR_ROLE)
onlyAllowedRecipient(recipient)
{
require(
token != address(TOKEN),
'SP2Withdrawals: Cannot use this function to withdraw borrowed token'
);
IERC20(token).safeTransfer(recipient, amount);
emit ExternalWithdrewOtherToken(token, recipient, amount);
}
/**
* @notice Withdraw any ether.
*
* Note: The contract is not expected to hold Ether so this is not normally needed.
*
* @param recipient The recipient to receive Ether. Must be authorized by OWNER_ROLE.
*/
function externalWithdrawEther(
address recipient,
uint256 amount
)
external
nonReentrant
onlyRole(WITHDRAWAL_OPERATOR_ROLE)
onlyAllowedRecipient(recipient)
{
payable(recipient).transfer(amount);
emit ExternalWithdrewEther(recipient, amount);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { Math } from '../../../utils/Math.sol';
import { SP1Storage } from './SP1Storage.sol';
/**
* @title SP1Getters
* @author dYdX
*
* @dev Simple external getter functions.
*/
abstract contract SP1Getters is
SP1Storage
{
using SafeMath for uint256;
// ============ External Functions ============
/**
* @notice Check whether a STARK key is on the allowlist for exchange operations.
*
* @param starkKey The STARK key to check.
*
* @return Boolean `true` if the STARK key is allowed, otherwise `false`.
*/
function isStarkKeyAllowed(
uint256 starkKey
)
external
view
returns (bool)
{
return _ALLOWED_STARK_KEYS_[starkKey];
}
/**
* @notice Check whether a recipient is on the allowlist to receive withdrawals.
*
* @param recipient The recipient to check.
*
* @return Boolean `true` if the recipient is allowed, otherwise `false`.
*/
function isRecipientAllowed(
address recipient
)
external
view
returns (bool)
{
return _ALLOWED_RECIPIENTS_[recipient];
}
/**
* @notice Get the amount approved by the guardian for external withdrawals.
* Note that withdrawals are always permitted if the amount is in excess of the borrowed amount.
*
* @return The amount approved for external withdrawals.
*/
function getApprovedAmountForExternalWithdrawal()
external
view
returns (uint256)
{
return _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_;
}
/**
* @notice Check whether this borrower contract is restricted from new borrowing, as well as
* restricted from depositing borrowed funds to the exchange.
*
* @return Boolean `true` if the borrower is restricted, otherwise `false`.
*/
function isBorrowingRestricted()
external
view
returns (bool)
{
return _IS_BORROWING_RESTRICTED_;
}
/**
* @notice Get the timestamp at which a forced trade request was queued.
*
* @param argsHash The hash of the forced trade request args.
*
* @return Timestamp at which the forced trade was queued, or zero, if it was not queued or was
* vetoed by the VETO_GUARDIAN_ROLE.
*/
function getQueuedForcedTradeTimestamp(
bytes32 argsHash
)
external
view
returns (uint256)
{
return _QUEUED_FORCED_TRADE_TIMESTAMPS_[argsHash];
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { ILiquidityStakingV1 } from '../../../interfaces/ILiquidityStakingV1.sol';
import { IStarkPerpetual } from '../../../interfaces/IStarkPerpetual.sol';
import { SP1Borrowing } from '../../v1/impl/SP1Borrowing.sol';
import { SP2Exchange } from './SP2Exchange.sol';
/**
* @title SP2Guardian
* @author dYdX
*
* @dev Defines guardian powers, to be owned or delegated by dYdX governance.
*/
abstract contract SP2Guardian is
SP1Borrowing,
SP2Exchange
{
using SafeMath for uint256;
// ============ Events ============
event BorrowingRestrictionChanged(
bool isBorrowingRestricted
);
event GuardianVetoedForcedTradeRequest(
bytes32 argsHash
);
event GuardianUpdateApprovedAmountForExternalWithdrawal(
uint256 amount
);
// ============ Constructor ============
constructor(
ILiquidityStakingV1 liquidityStaking,
IStarkPerpetual starkPerpetual,
IERC20 token
)
SP1Borrowing(liquidityStaking, token)
SP2Exchange(starkPerpetual)
{}
// ============ External Functions ============
/**
* @notice Approve an additional amount for external withdrawal by WITHDRAWAL_OPERATOR_ROLE.
*
* @param amount The additional amount to approve for external withdrawal.
*
* @return The new amount approved for external withdrawal.
*/
function increaseApprovedAmountForExternalWithdrawal(
uint256 amount
)
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
returns (uint256)
{
uint256 newApprovedAmount = _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_.add(
amount
);
_APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_ = newApprovedAmount;
emit GuardianUpdateApprovedAmountForExternalWithdrawal(newApprovedAmount);
return newApprovedAmount;
}
/**
* @notice Set the approved amount for external withdrawal to zero.
*
* @return The amount that was previously approved for external withdrawal.
*/
function resetApprovedAmountForExternalWithdrawal()
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
returns (uint256)
{
uint256 previousApprovedAmount = _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_;
_APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_ = 0;
emit GuardianUpdateApprovedAmountForExternalWithdrawal(0);
return previousApprovedAmount;
}
/**
* @notice Guardian method to restrict borrowing or depositing borrowed funds to the exchange.
*/
function guardianSetBorrowingRestriction(
bool isBorrowingRestricted
)
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
{
_IS_BORROWING_RESTRICTED_ = isBorrowingRestricted;
emit BorrowingRestrictionChanged(isBorrowingRestricted);
}
/**
* @notice Guardian method to repay this contract's borrowed balance, using this contract's funds.
*
* @param amount Amount to repay.
*/
function guardianRepayBorrow(
uint256 amount
)
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
{
_repayBorrow(amount, true);
}
/**
* @notice Guardian method to repay a debt balance owed by the borrower.
*
* @param amount Amount to repay.
*/
function guardianRepayDebt(
uint256 amount
)
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
{
_repayDebt(amount, true);
}
/**
* @notice Guardian method to trigger a withdrawal. This will transfer funds from StarkPerpetual
* to this contract. This requires a (slow) withdrawal from L2 to have been previously processed.
*
* Note: This function is intentionally not protected by the onlyAllowedKey modifier.
*
* @return The ERC20 token amount received by this contract.
*/
function guardianWithdrawFromExchange(
uint256 starkKey,
uint256 assetType
)
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
returns (uint256)
{
return _withdrawFromExchange(starkKey, assetType, true);
}
/**
* @notice Guardian method to trigger a forced withdrawal request.
* Reverts if the borrower has no overdue debt.
*
* Note: This function is intentionally not protected by the onlyAllowedKey modifier.
*/
function guardianForcedWithdrawalRequest(
uint256 starkKey,
uint256 vaultId,
uint256 quantizedAmount,
bool premiumCost
)
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
{
require(
getDebtBalance() > 0,
'SP2Guardian: Cannot call forced action if borrower has no overdue debt'
);
_forcedWithdrawalRequest(
starkKey,
vaultId,
quantizedAmount,
premiumCost,
true // isGuardianAction
);
}
/**
* @notice Guardian method to trigger a forced trade request.
* Reverts if the borrower has no overdue debt.
*
* Note: This function is intentionally not protected by the onlyAllowedKey modifier.
*/
function guardianForcedTradeRequest(
uint256[12] calldata args,
bytes calldata signature
)
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
{
require(
getDebtBalance() > 0,
'SP2Guardian: Cannot call forced action if borrower has no overdue debt'
);
_forcedTradeRequest(args, signature, true);
}
/**
* @notice Guardian method to prevent queued forced trade requests from being executed.
*
* May only be called by VETO_GUARDIAN_ROLE.
*
* @param argsHashes An array of hashes for each forced trade request to veto.
*/
function guardianVetoForcedTradeRequests(
bytes32[] calldata argsHashes
)
external
nonReentrant
onlyRole(VETO_GUARDIAN_ROLE)
{
for (uint256 i = 0; i < argsHashes.length; i++) {
bytes32 argsHash = argsHashes[i];
_QUEUED_FORCED_TRADE_TIMESTAMPS_[argsHash] = 0;
emit GuardianVetoedForcedTradeRequest(argsHash);
}
}
/**
* @notice Guardian method to request to cancel a pending deposit to the exchange.
*
* @param starkKey The STARK key of the account.
* @param assetType The exchange asset ID for the deposit.
* @param vaultId The exchange position ID for the deposit.
*
* Note: This function is intentionally not protected by the onlyAllowedKey modifier.
*/
function guardianDepositCancel(
uint256 starkKey,
uint256 assetType,
uint256 vaultId
)
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
{
_depositCancel(starkKey, assetType, vaultId, true);
}
/**
* @notice Guardian method to reclaim a canceled pending deposit to the exchange. Requires
* that `depositCancel` was previously called.
*
* @param starkKey The STARK key of the account.
* @param assetType The exchange asset ID for the deposit.
* @param vaultId The exchange position ID for the deposit.
*
* Note: This function is intentionally not protected by the onlyAllowedKey modifier.
*/
function guardianDepositReclaim(
uint256 starkKey,
uint256 assetType,
uint256 vaultId
)
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
{
_depositReclaim(starkKey, assetType, vaultId, true);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol';
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { IStarkPerpetual } from '../../../interfaces/IStarkPerpetual.sol';
import { SP1Borrowing } from '../../v1/impl/SP1Borrowing.sol';
import { SP2Exchange } from './SP2Exchange.sol';
/**
* @title SP2Owner
* @author dYdX
*
* @dev Actions which may be called only by OWNER_ROLE. These include actions with a larger amount
* of control over the funds held by the contract.
*/
abstract contract SP2Owner is
SP1Borrowing,
SP2Exchange
{
using SafeERC20 for IERC20;
using SafeMath for uint256;
// ============ Constants ============
/// @notice Time that must elapse before a queued forced trade request can be submitted.
uint256 public constant FORCED_TRADE_WAITING_PERIOD = 7 days;
/// @notice Max time that may elapse after the waiting period before a queued forced trade
/// request expires.
uint256 public constant FORCED_TRADE_GRACE_PERIOD = 7 days;
// ============ Events ============
event UpdatedStarkKey(
uint256 starkKey,
bool isAllowed
);
event UpdatedExternalRecipient(
address recipient,
bool isAllowed
);
event QueuedForcedTradeRequest(
uint256[12] args,
bytes32 argsHash
);
// ============ External Functions ============
/**
* @notice Allow exchange functions to be called for a particular STARK key.
*
* Will revert if the STARK key is not registered to this contract's address on the
* StarkPerpetual contract.
*
* @param starkKey The STARK key to allow.
*/
function allowStarkKey(
uint256 starkKey
)
external
nonReentrant
onlyRole(OWNER_ROLE)
{
// This will revert with 'USER_UNREGISTERED' if the STARK key was not registered.
address ethKey = STARK_PERPETUAL.getEthKey(starkKey);
// Require the STARK key to be registered to this contract before we allow it to be used.
require(ethKey == address(this), 'SP2Owner: STARK key not registered to this contract');
require(!_ALLOWED_STARK_KEYS_[starkKey], 'SP2Owner: STARK key already allowed');
_ALLOWED_STARK_KEYS_[starkKey] = true;
emit UpdatedStarkKey(starkKey, true);
}
/**
* @notice Remove a STARK key from the allowed list.
*
* @param starkKey The STARK key to disallow.
*/
function disallowStarkKey(
uint256 starkKey
)
external
nonReentrant
onlyRole(OWNER_ROLE)
{
require(_ALLOWED_STARK_KEYS_[starkKey], 'SP2Owner: STARK key already disallowed');
_ALLOWED_STARK_KEYS_[starkKey] = false;
emit UpdatedStarkKey(starkKey, false);
}
/**
* @notice Allow withdrawals of excess funds to be made to a particular recipient.
*
* @param recipient The recipient to allow.
*/
function allowExternalRecipient(
address recipient
)
external
nonReentrant
onlyRole(OWNER_ROLE)
{
require(!_ALLOWED_RECIPIENTS_[recipient], 'SP2Owner: Recipient already allowed');
_ALLOWED_RECIPIENTS_[recipient] = true;
emit UpdatedExternalRecipient(recipient, true);
}
/**
* @notice Remove a recipient from the allowed list.
*
* @param recipient The recipient to disallow.
*/
function disallowExternalRecipient(
address recipient
)
external
nonReentrant
onlyRole(OWNER_ROLE)
{
require(_ALLOWED_RECIPIENTS_[recipient], 'SP2Owner: Recipient already disallowed');
_ALLOWED_RECIPIENTS_[recipient] = false;
emit UpdatedExternalRecipient(recipient, false);
}
/**
* @notice Set ERC20 token allowance for the exchange contract.
*
* @param token The ERC20 token to set the allowance for.
* @param amount The new allowance amount.
*/
function setExchangeContractAllowance(
address token,
uint256 amount
)
external
nonReentrant
onlyRole(OWNER_ROLE)
{
// SafeERC20 safeApprove requires setting to zero first.
IERC20(token).safeApprove(address(STARK_PERPETUAL), 0);
IERC20(token).safeApprove(address(STARK_PERPETUAL), amount);
}
/**
* @notice Set ERC20 token allowance for the staking contract.
*
* @param token The ERC20 token to set the allowance for.
* @param amount The new allowance amount.
*/
function setStakingContractAllowance(
address token,
uint256 amount
)
external
nonReentrant
onlyRole(OWNER_ROLE)
{
// SafeERC20 safeApprove requires setting to zero first.
IERC20(token).safeApprove(address(LIQUIDITY_STAKING), 0);
IERC20(token).safeApprove(address(LIQUIDITY_STAKING), amount);
}
/**
* @notice Request a forced withdrawal from the exchange.
*
* @param starkKey The STARK key of the account. Must be authorized by OWNER_ROLE.
* @param vaultId The exchange position ID for the account to deposit to.
* @param quantizedAmount The withdrawal amount denominated in the exchange base units.
* @param premiumCost Whether to pay a higher fee for faster inclusion in certain scenarios.
*/
function forcedWithdrawalRequest(
uint256 starkKey,
uint256 vaultId,
uint256 quantizedAmount,
bool premiumCost
)
external
nonReentrant
onlyRole(OWNER_ROLE)
onlyAllowedKey(starkKey)
{
_forcedWithdrawalRequest(starkKey, vaultId, quantizedAmount, premiumCost, false);
}
/**
* @notice Queue a forced trade request to be submitted after the waiting period.
*
* @param args Arguments for the forced trade request.
*/
function queueForcedTradeRequest(
uint256[12] calldata args
)
external
nonReentrant
onlyRole(OWNER_ROLE)
{
bytes32 argsHash = keccak256(abi.encodePacked(args));
_QUEUED_FORCED_TRADE_TIMESTAMPS_[argsHash] = block.timestamp;
emit QueuedForcedTradeRequest(args, argsHash);
}
/**
* @notice Submit a forced trade request that was previously queued.
*
* @param args Arguments for the forced trade request.
* @param signature The signature of the counterparty to the trade.
*/
function forcedTradeRequest(
uint256[12] calldata args,
bytes calldata signature
)
external
nonReentrant
onlyRole(OWNER_ROLE)
onlyAllowedKey(args[0]) // starkKeyA
{
bytes32 argsHash = keccak256(abi.encodePacked(args));
uint256 timestamp = _QUEUED_FORCED_TRADE_TIMESTAMPS_[argsHash];
require(
timestamp != 0,
'SP2Owner: Forced trade not queued or was vetoed'
);
uint256 elapsed = block.timestamp.sub(timestamp);
require(
elapsed >= FORCED_TRADE_WAITING_PERIOD,
'SP2Owner: Waiting period has not elapsed for forced trade'
);
require(
elapsed <= FORCED_TRADE_WAITING_PERIOD.add(FORCED_TRADE_GRACE_PERIOD),
'SP2Owner: Grace period has elapsed for forced trade'
);
_QUEUED_FORCED_TRADE_TIMESTAMPS_[argsHash] = 0;
_forcedTradeRequest(args, signature, false);
}
/**
* @notice Request to cancel a pending deposit to the exchange.
*
* @param starkKey The STARK key of the account. Must be authorized by OWNER_ROLE.
* @param assetType The exchange asset ID for the deposit.
* @param vaultId The exchange position ID for the deposit.
*/
function depositCancel(
uint256 starkKey,
uint256 assetType,
uint256 vaultId
)
external
nonReentrant
onlyRole(OWNER_ROLE)
onlyAllowedKey(starkKey)
{
_depositCancel(starkKey, assetType, vaultId, false);
}
/**
* @notice Reclaim a canceled pending deposit to the exchange. Requires that `depositCancel`
* was previously called.
*
* @param starkKey The STARK key of the account. Must be authorized by OWNER_ROLE.
* @param assetType The exchange asset ID for the deposit.
* @param vaultId The exchange position ID for the deposit.
*/
function depositReclaim(
uint256 starkKey,
uint256 assetType,
uint256 vaultId
)
external
nonReentrant
onlyRole(OWNER_ROLE)
onlyAllowedKey(starkKey)
{
_depositReclaim(starkKey, assetType, vaultId, false);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly {
codehash := extcodehash(account)
}
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev 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');
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { IStarkPerpetual } from '../../../interfaces/IStarkPerpetual.sol';
import { SP1Balances } from '../../v1/impl/SP1Balances.sol';
/**
* @title SP2Exchange
* @author dYdX
*
* @dev Handles calls to the StarkPerpetual contract, for interacting with the dYdX L2 exchange.
*
* Standard exchange operation is handled by EXCHANGE_OPERATOR_ROLE. The “forced” actions can only
* be called by the OWNER_ROLE or GUARDIAN_ROLE. Some other functions are also callable by
* the GUARDIAN_ROLE.
*
* See SP1Roles, SP2Guardian, SP2Owner, and SP2Withdrawals.
*/
abstract contract SP2Exchange is
SP1Balances
{
using SafeMath for uint256;
// ============ Constants ============
IStarkPerpetual public immutable STARK_PERPETUAL;
// ============ Events ============
event DepositedToExchange(
uint256 starkKey,
uint256 starkAssetType,
uint256 starkVaultId,
uint256 tokenAmount
);
event WithdrewFromExchange(
uint256 starkKey,
uint256 starkAssetType,
uint256 tokenAmount,
bool isGuardianAction
);
/// @dev Limited fields included. Details can be retrieved from Starkware logs if needed.
event RequestedForcedWithdrawal(
uint256 starkKey,
uint256 vaultId,
bool isGuardianAction
);
/// @dev Limited fields included. Details can be retrieved from Starkware logs if needed.
event RequestedForcedTrade(
uint256 starkKey,
uint256 vaultId,
bool isGuardianAction
);
event DepositCanceled(
uint256 starkKey,
uint256 starkAssetType,
uint256 vaultId,
bool isGuardianAction
);
event DepositReclaimed(
uint256 starkKey,
uint256 starkAssetType,
uint256 vaultId,
uint256 fundsReclaimed,
bool isGuardianAction
);
// ============ Constructor ============
constructor(
IStarkPerpetual starkPerpetual
) {
STARK_PERPETUAL = starkPerpetual;
}
// ============ External Functions ============
/**
* @notice Deposit funds to the exchange.
*
* IMPORTANT: The caller is responsible for providing `quantizedAmount` in the right units.
* Currently, the exchange collateral is USDC, denominated in ERC20 token units, but
* this could change.
*
* @param starkKey The STARK key of the account. Must be authorized by OWNER_ROLE.
* @param assetType The exchange asset ID for the asset to deposit.
* @param vaultId The exchange position ID for the account to deposit to.
* @param quantizedAmount The deposit amount denominated in the exchange base units.
*
* @return The ERC20 token amount spent.
*/
function depositToExchange(
uint256 starkKey,
uint256 assetType,
uint256 vaultId,
uint256 quantizedAmount
)
external
nonReentrant
onlyRole(EXCHANGE_OPERATOR_ROLE)
onlyAllowedKey(starkKey)
returns (uint256)
{
// Deposit and get the deposited token amount.
uint256 startingBalance = getTokenBalance();
STARK_PERPETUAL.deposit(starkKey, assetType, vaultId, quantizedAmount);
uint256 endingBalance = getTokenBalance();
uint256 tokenAmount = startingBalance.sub(endingBalance);
// Disallow depositing borrowed funds to the exchange if the guardian has restricted borrowing.
if (_IS_BORROWING_RESTRICTED_) {
require(
endingBalance >= getBorrowedAndDebtBalance(),
'SP2Exchange: Cannot deposit borrowed funds to the exchange while Restricted'
);
}
emit DepositedToExchange(starkKey, assetType, vaultId, tokenAmount);
return tokenAmount;
}
/**
* @notice Trigger a withdrawal of account funds held in the exchange contract. This can be
* called after a (slow) withdrawal has already been processed by the L2 exchange.
*
* @param starkKey The STARK key of the account. Must be authorized by OWNER_ROLE.
* @param assetType The exchange asset ID for the asset to withdraw.
*
* @return The ERC20 token amount received by this contract.
*/
function withdrawFromExchange(
uint256 starkKey,
uint256 assetType
)
external
nonReentrant
onlyRole(EXCHANGE_OPERATOR_ROLE)
onlyAllowedKey(starkKey)
returns (uint256)
{
return _withdrawFromExchange(starkKey, assetType, false);
}
// ============ Internal Functions ============
function _withdrawFromExchange(
uint256 starkKey,
uint256 assetType,
bool isGuardianAction
)
internal
returns (uint256)
{
uint256 startingBalance = getTokenBalance();
STARK_PERPETUAL.withdraw(starkKey, assetType);
uint256 endingBalance = getTokenBalance();
uint256 tokenAmount = endingBalance.sub(startingBalance);
emit WithdrewFromExchange(starkKey, assetType, tokenAmount, isGuardianAction);
return tokenAmount;
}
function _forcedWithdrawalRequest(
uint256 starkKey,
uint256 vaultId,
uint256 quantizedAmount,
bool premiumCost,
bool isGuardianAction
)
internal
{
STARK_PERPETUAL.forcedWithdrawalRequest(starkKey, vaultId, quantizedAmount, premiumCost);
emit RequestedForcedWithdrawal(starkKey, vaultId, isGuardianAction);
}
function _forcedTradeRequest(
uint256[12] calldata args,
bytes calldata signature,
bool isGuardianAction
)
internal
{
// Split into two functions to avoid error 'call stack too deep'.
if (args[11] != 0) {
_forcedTradeRequestPremiumCostTrue(args, signature);
} else {
_forcedTradeRequestPremiumCostFalse(args, signature);
}
emit RequestedForcedTrade(
args[0], // starkKeyA
args[2], // vaultIdA
isGuardianAction
);
}
function _depositCancel(
uint256 starkKey,
uint256 assetType,
uint256 vaultId,
bool isGuardianAction
)
internal
{
STARK_PERPETUAL.depositCancel(starkKey, assetType, vaultId);
emit DepositCanceled(starkKey, assetType, vaultId, isGuardianAction);
}
function _depositReclaim(
uint256 starkKey,
uint256 assetType,
uint256 vaultId,
bool isGuardianAction
)
internal
{
uint256 startingBalance = getTokenBalance();
STARK_PERPETUAL.depositReclaim(starkKey, assetType, vaultId);
uint256 endingBalance = getTokenBalance();
uint256 tokenAmount = endingBalance.sub(startingBalance);
emit DepositReclaimed(
starkKey,
assetType,
vaultId,
tokenAmount,
isGuardianAction
);
}
// ============ Private Functions ============
// Split into two functions to avoid error 'call stack too deep'.
function _forcedTradeRequestPremiumCostTrue(
uint256[12] calldata args,
bytes calldata signature
)
private
{
STARK_PERPETUAL.forcedTradeRequest(
args[0], // starkKeyA
args[1], // starkKeyB
args[2], // vaultIdA
args[3], // vaultIdB
args[4], // collateralAssetId
args[5], // syntheticAssetId
args[6], // amountCollateral
args[7], // amountSynthetic
args[8] != 0, // aIsBuyingSynthetic
args[9], // submissionExpirationTime
args[10], // nonce
signature,
true // premiumCost
);
}
// Split into two functions to avoid error 'call stack too deep'.
function _forcedTradeRequestPremiumCostFalse(
uint256[12] calldata args,
bytes calldata signature
)
private
{
STARK_PERPETUAL.forcedTradeRequest(
args[0], // starkKeyA
args[1], // starkKeyB
args[2], // vaultIdA
args[3], // vaultIdB
args[4], // collateralAssetId
args[5], // syntheticAssetId
args[6], // amountCollateral
args[7], // amountSynthetic
args[8] != 0, // aIsBuyingSynthetic
args[9], // submissionExpirationTime
args[10], // nonce
signature,
false // premiumCost
);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { ILiquidityStakingV1 } from '../../../interfaces/ILiquidityStakingV1.sol';
import { Math } from '../../../utils/Math.sol';
import { SP1Roles } from './SP1Roles.sol';
/**
* @title SP1Balances
* @author dYdX
*
* @dev Contains common constants and functions related to token balances.
*/
abstract contract SP1Balances is
SP1Roles
{
using SafeMath for uint256;
// ============ Constants ============
IERC20 public immutable TOKEN;
ILiquidityStakingV1 public immutable LIQUIDITY_STAKING;
// ============ Constructor ============
constructor(
ILiquidityStakingV1 liquidityStaking,
IERC20 token
) {
LIQUIDITY_STAKING = liquidityStaking;
TOKEN = token;
}
// ============ Public Functions ============
function getAllocatedBalanceCurrentEpoch()
public
view
returns (uint256)
{
return LIQUIDITY_STAKING.getAllocatedBalanceCurrentEpoch(address(this));
}
function getAllocatedBalanceNextEpoch()
public
view
returns (uint256)
{
return LIQUIDITY_STAKING.getAllocatedBalanceNextEpoch(address(this));
}
function getBorrowableAmount()
public
view
returns (uint256)
{
if (_IS_BORROWING_RESTRICTED_) {
return 0;
}
return LIQUIDITY_STAKING.getBorrowableAmount(address(this));
}
function getBorrowedBalance()
public
view
returns (uint256)
{
return LIQUIDITY_STAKING.getBorrowedBalance(address(this));
}
function getDebtBalance()
public
view
returns (uint256)
{
return LIQUIDITY_STAKING.getBorrowerDebtBalance(address(this));
}
function getBorrowedAndDebtBalance()
public
view
returns (uint256)
{
return getBorrowedBalance().add(getDebtBalance());
}
function getTokenBalance()
public
view
returns (uint256)
{
return TOKEN.balanceOf(address(this));
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../dependencies/open-zeppelin/SafeMath.sol';
/**
* @title Math
* @author dYdX
*
* @dev Library for non-standard Math functions.
*/
library Math {
using SafeMath for uint256;
// ============ Library Functions ============
/**
* @dev Return `ceil(numerator / denominator)`.
*/
function divRoundUp(
uint256 numerator,
uint256 denominator
)
internal
pure
returns (uint256)
{
if (numerator == 0) {
// SafeMath will check for zero denominator
return SafeMath.div(0, denominator);
}
return numerator.sub(1).div(denominator).add(1);
}
/**
* @dev Returns the minimum between a and b.
*/
function min(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
/**
* @dev Returns the maximum between a and b.
*/
function max(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
return a > b ? a : b;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SP1Storage } from './SP1Storage.sol';
/**
* @title SP1Roles
* @author dYdX
*
* @dev Defines roles used in the StarkProxyV1 contract. The hierarchy and powers of each role
* are described below. Not all roles need to be used.
*
* Overview:
*
* During operation of this contract, funds will flow between the following three
* contracts:
*
* LiquidityStaking <> StarkProxy <> StarkPerpetual
*
* Actions which move fund from left to right are called “open” actions, whereas actions which
* move funds from right to left are called “close” actions.
*
* Also note that the “forced” actions (forced trade and forced withdrawal) require special care
* since they directly impact the financial risk of positions held on the exchange.
*
* Roles:
*
* GUARDIAN_ROLE
* | -> May perform “close” actions as defined above, but “forced” actions can only be taken
* | if the borrower has an outstanding debt balance.
* | -> May restrict “open” actions as defined above, except w.r.t. funds in excess of the
* | borrowed balance.
* | -> May approve a token amount to be withdrawn externally by the WITHDRAWAL_OPERATOR_ROLE
* | to an allowed address.
* |
* +-- VETO_GUARDIAN_ROLE
* -> May veto forced trade requests initiated by the owner, during the waiting period.
*
* OWNER_ROLE
* | -> May add or remove allowed recipients who may receive excess funds.
* | -> May add or remove allowed STARK keys for use on the exchange.
* | -> May set ERC20 allowances on the LiquidityStakingV1 and StarkPerpetual contracts.
* | -> May call the “forced” actions: forcedWithdrawalRequest and forcedTradeRequest.
* |
* +-- DELEGATION_ADMIN_ROLE
* |
* +-- BORROWER_ROLE
* | -> May call functions on LiquidityStakingV1: autoPayOrBorrow, borrow, repay,
* | and repayDebt.
* |
* +-- EXCHANGE_OPERATOR_ROLE
* | -> May call functions on StarkPerpetual: depositToExchange and
* | withdrawFromExchange.
* |
* +-- WITHDRAWAL_OPERATOR_ROLE
* -> May withdraw funds in excess of the borrowed balance to an allowed recipient.
*/
abstract contract SP1Roles is
SP1Storage
{
bytes32 public constant GUARDIAN_ROLE = keccak256('GUARDIAN_ROLE');
bytes32 public constant VETO_GUARDIAN_ROLE = keccak256('VETO_GUARDIAN_ROLE');
bytes32 public constant OWNER_ROLE = keccak256('OWNER_ROLE');
bytes32 public constant DELEGATION_ADMIN_ROLE = keccak256('DELEGATION_ADMIN_ROLE');
bytes32 public constant BORROWER_ROLE = keccak256('BORROWER_ROLE');
bytes32 public constant EXCHANGE_OPERATOR_ROLE = keccak256('EXCHANGE_OPERATOR_ROLE');
bytes32 public constant WITHDRAWAL_OPERATOR_ROLE = keccak256('WITHDRAWAL_OPERATOR_ROLE');
function __SP1Roles_init(
address guardian
)
internal
{
// Assign GUARDIAN_ROLE.
_setupRole(GUARDIAN_ROLE, guardian);
// Assign OWNER_ROLE and DELEGATION_ADMIN_ROLE to the sender.
_setupRole(OWNER_ROLE, msg.sender);
_setupRole(DELEGATION_ADMIN_ROLE, msg.sender);
// Set admins for all roles. (Don't use the default admin role.)
_setRoleAdmin(GUARDIAN_ROLE, GUARDIAN_ROLE);
_setRoleAdmin(VETO_GUARDIAN_ROLE, GUARDIAN_ROLE);
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
_setRoleAdmin(DELEGATION_ADMIN_ROLE, OWNER_ROLE);
_setRoleAdmin(BORROWER_ROLE, DELEGATION_ADMIN_ROLE);
_setRoleAdmin(EXCHANGE_OPERATOR_ROLE, DELEGATION_ADMIN_ROLE);
_setRoleAdmin(WITHDRAWAL_OPERATOR_ROLE, DELEGATION_ADMIN_ROLE);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import {
AccessControlUpgradeable
} from '../../../dependencies/open-zeppelin/AccessControlUpgradeable.sol';
import { ReentrancyGuard } from '../../../utils/ReentrancyGuard.sol';
import { VersionedInitializable } from '../../../utils/VersionedInitializable.sol';
/**
* @title SP1Storage
* @author dYdX
*
* @dev Storage contract. Contains or inherits from all contracts with storage.
*/
abstract contract SP1Storage is
AccessControlUpgradeable,
ReentrancyGuard,
VersionedInitializable
{
// ============ Modifiers ============
/**
* @dev Modifier to ensure the STARK key is allowed.
*/
modifier onlyAllowedKey(
uint256 starkKey
) {
require(_ALLOWED_STARK_KEYS_[starkKey], 'SP1Storage: STARK key is not on the allowlist');
_;
}
/**
* @dev Modifier to ensure the recipient is allowed.
*/
modifier onlyAllowedRecipient(
address recipient
) {
require(_ALLOWED_RECIPIENTS_[recipient], 'SP1Storage: Recipient is not on the allowlist');
_;
}
// ============ Storage ============
mapping(uint256 => bool) internal _ALLOWED_STARK_KEYS_;
mapping(address => bool) internal _ALLOWED_RECIPIENTS_;
/// @dev Note that withdrawals are always permitted if the amount is in excess of the borrowed
/// amount. Also, this approval only applies to the primary ERC20 token, `TOKEN`.
uint256 internal _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_;
/// @dev Note that this is different from _IS_BORROWING_RESTRICTED_ in LiquidityStakingV1.
bool internal _IS_BORROWING_RESTRICTED_;
/// @dev Mapping from args hash to timestamp.
mapping(bytes32 => uint256) internal _QUEUED_FORCED_TRADE_TIMESTAMPS_;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import './Context.sol';
import './Strings.sol';
import './ERC165.sol';
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Context, IAccessControlUpgradeable, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(
bytes32 indexed role,
bytes32 indexed previousAdminRole,
bytes32 indexed newAdminRole
);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return
interfaceId == type(IAccessControlUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
'AccessControl: account ',
Strings.toHexString(uint160(account), 20),
' is missing role ',
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account)
public
virtual
override
onlyRole(getRoleAdmin(role))
{
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account)
public
virtual
override
onlyRole(getRoleAdmin(role))
{
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), 'AccessControl: can only renounce roles for self');
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.5;
pragma abicoder v2;
/**
* @title ReentrancyGuard
* @author dYdX
*
* @dev Updated ReentrancyGuard library designed to be used with Proxy Contracts.
*/
abstract contract ReentrancyGuard {
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = uint256(int256(-1));
uint256 private _STATUS_;
constructor()
internal
{
_STATUS_ = NOT_ENTERED;
}
modifier nonReentrant() {
require(_STATUS_ != ENTERED, 'ReentrancyGuard: reentrant call');
_STATUS_ = ENTERED;
_;
_STATUS_ = NOT_ENTERED;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
/**
* @title VersionedInitializable
* @author Aave, inspired by the OpenZeppelin Initializable contract
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*
*/
abstract contract VersionedInitializable {
/**
* @dev Indicates that the contract has been initialized.
*/
uint256 internal lastInitializedRevision = 0;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
uint256 revision = getRevision();
require(revision > lastInitializedRevision, "Contract instance has already been initialized");
lastInitializedRevision = revision;
_;
}
/// @dev returns the revision number of the contract.
/// Needs to be defined in the inherited class as a constant.
function getRevision() internal pure virtual returns(uint256);
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = '0123456789abcdef';
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return '0';
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return '0x00';
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = '0';
buffer[1] = 'x';
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, 'Strings: hex length insufficient');
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
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.7.5;
/**
* @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: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { ILiquidityStakingV1 } from '../../../interfaces/ILiquidityStakingV1.sol';
import { Math } from '../../../utils/Math.sol';
import { SP1Balances } from './SP1Balances.sol';
/**
* @title SP1Borrowing
* @author dYdX
*
* @dev Handles calls to the LiquidityStaking contract to borrow and repay funds.
*/
abstract contract SP1Borrowing is
SP1Balances
{
using SafeMath for uint256;
// ============ Events ============
event Borrowed(
uint256 amount,
uint256 newBorrowedBalance
);
event RepaidBorrow(
uint256 amount,
uint256 newBorrowedBalance,
bool isGuardianAction
);
event RepaidDebt(
uint256 amount,
uint256 newDebtBalance,
bool isGuardianAction
);
// ============ Constructor ============
constructor(
ILiquidityStakingV1 liquidityStaking,
IERC20 token
)
SP1Balances(liquidityStaking, token)
{}
// ============ External Functions ============
/**
* @notice Automatically repay or borrow to bring borrowed balance to the next allocated balance.
* Must be called during the blackout window, to ensure allocated balance will not change before
* the start of the next epoch. Reverts if there are insufficient funds to prevent a shortfall.
*
* Can be called with eth_call to view amounts that will be borrowed or repaid.
*
* @return The newly borrowed amount.
* @return The borrow amount repaid.
* @return The debt amount repaid.
*/
function autoPayOrBorrow()
external
nonReentrant
onlyRole(BORROWER_ROLE)
returns (
uint256,
uint256,
uint256
)
{
// Ensure we are in the blackout window.
require(
LIQUIDITY_STAKING.inBlackoutWindow(),
'SP1Borrowing: Auto-pay may only be used during the blackout window'
);
// Get the borrowed balance, next allocated balance, and token balance.
uint256 borrowedBalance = getBorrowedBalance();
uint256 nextAllocatedBalance = getAllocatedBalanceNextEpoch();
uint256 tokenBalance = getTokenBalance();
// Return values.
uint256 borrowAmount = 0;
uint256 repayBorrowAmount = 0;
uint256 repayDebtAmount = 0;
if (borrowedBalance > nextAllocatedBalance) {
// Make the necessary repayment due by the end of the current epoch.
repayBorrowAmount = borrowedBalance.sub(nextAllocatedBalance);
require(
tokenBalance >= repayBorrowAmount,
'SP1Borrowing: Insufficient funds to avoid falling short on repayment'
);
_repayBorrow(repayBorrowAmount, false);
} else {
// Borrow the max borrowable amount.
borrowAmount = getBorrowableAmount();
if (borrowAmount != 0) {
_borrow(borrowAmount);
}
}
// Finally, use remaining funds to pay any overdue debt.
uint256 debtBalance = getDebtBalance();
repayDebtAmount = Math.min(debtBalance, tokenBalance);
if (repayDebtAmount != 0) {
_repayDebt(repayDebtAmount, false);
}
return (borrowAmount, repayBorrowAmount, repayDebtAmount);
}
function borrow(
uint256 amount
)
external
nonReentrant
onlyRole(BORROWER_ROLE)
{
// Disallow if the guardian has restricted borrowing.
require(
!_IS_BORROWING_RESTRICTED_,
'SP1Borrowing: Cannot borrow while Restricted'
);
_borrow(amount);
}
function repayBorrow(
uint256 amount
)
external
nonReentrant
onlyRole(BORROWER_ROLE)
{
_repayBorrow(amount, false);
}
function repayDebt(
uint256 amount
)
external
nonReentrant
onlyRole(BORROWER_ROLE)
{
_repayDebt(amount, false);
}
// ============ Internal Functions ============
function _borrow(
uint256 amount
)
internal
{
LIQUIDITY_STAKING.borrow(amount);
emit Borrowed(amount, getBorrowedBalance());
}
function _repayBorrow(
uint256 amount,
bool isGovernanceAction
)
internal
{
LIQUIDITY_STAKING.repayBorrow(address(this), amount);
emit RepaidBorrow(amount, getBorrowedBalance(), isGovernanceAction);
}
function _repayDebt(
uint256 amount,
bool isGovernanceAction
)
internal
{
LIQUIDITY_STAKING.repayDebt(address(this), amount);
emit RepaidDebt(amount, getDebtBalance(), isGovernanceAction);
}
} | Reclaim a canceled pending deposit to the exchange. Requires that `depositCancel` was previously called. starkKey The STARK key of the account. Must be authorized by OWNER_ROLE. assetType The exchange asset ID for the deposit. vaultId The exchange position ID for the deposit./ | function depositReclaim(
uint256 starkKey,
uint256 assetType,
uint256 vaultId
)
external
nonReentrant
onlyRole(OWNER_ROLE)
onlyAllowedKey(starkKey)
{
_depositReclaim(starkKey, assetType, vaultId, false);
}
| 6,189,893 |
./full_match/62320/0xd04A54f983d55959F42F5370663AbbC1d85DE761/sources/lib/mento-core/contracts/Broker.sol | Transfer a specified Mento asset to the given address. If the specified asset is a stable asset it will be minted directly to the address. If the asset is a collateral asset it will be transferred from the reserve to the given address. to The address receiving the asset. token The asset to transfer. amount The amount of `token` to be transferred./ | function transferOut(
address payable to,
address token,
uint256 amount
) internal {
if (reserve.isStableAsset(token)) {
IStableToken(token).mint(to, amount);
reserve.transferExchangeCollateralAsset(token, to, amount);
revert("Token must be stable or collateral assert");
}
}
| 3,225,339 |
/**
*Submitted for verification at Etherscan.io on 2021-02-01
*/
// SPDX-License-Identifier: MIT
/*
____ __ __ __ _
/ __/__ __ ___ / /_ / / ___ / /_ (_)__ __
_\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ /
/___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\
/___/
* Synthetix: ISLARewards.sol
*
* Docs: https://docs.synthetix.io/
*
*
* MIT License
* ===========
*
* Copyright (c) 2020 Synthetix
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
pragma solidity ^0.7.6;
/**
* @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 Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/*
* @dev 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 () { }
// 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;
}
}
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 () {
_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;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing 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.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// 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 != 0x0 && codehash != accountHash);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call{value:amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
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));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
// 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");
}
}
}
abstract contract IRewardDistributionRecipient is Ownable {
address public rewardDistribution;
modifier onlyRewardDistribution() {
require(_msgSender() == rewardDistribution, "Caller is not reward distribution");
_;
}
function setRewardDistribution(address _rewardDistribution)
external
onlyOwner
{
rewardDistribution = _rewardDistribution;
}
}
contract LPTokenWrapper {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public lpt = IERC20(0x6B3595068778DD592e39A122f4f5a5cF09C90fE2); // SUSHI
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function stake(uint256 amount) public virtual {
_totalSupply = _totalSupply.add(amount);
_balances[msg.sender] = _balances[msg.sender].add(amount);
lpt.safeTransferFrom(msg.sender, address(this), amount);
}
function withdraw(uint256 amount) public virtual {
_totalSupply = _totalSupply.sub(amount);
_balances[msg.sender] = _balances[msg.sender].sub(amount);
lpt.safeTransfer(msg.sender, amount);
}
}
contract ISLASUSHILM is LPTokenWrapper, IRewardDistributionRecipient {
IERC20 public isla = IERC20(0x20a68F9e34076b2dc15ce726d7eEbB83b694702d);
uint256 public DURATION = 2592000; // 30 days in seconds (30 * 24 * 60 * 60)
uint256 public starttime = 1612202400; // start at 02/01/2021 18:00 UTC
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
using SafeMath for uint256;
using SafeERC20 for IERC20;
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);
modifier checkStart() {
require(block.timestamp >= starttime,"not start");
_;
}
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
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(totalSupply())
);
}
function earned(address account) public view returns (uint256) {
return
balanceOf(account)
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(1e18)
.add(rewards[account]);
}
// stake visibility is public as overriding LPTokenWrapper's stake() function
function stake(uint256 amount) public updateReward(msg.sender) checkStart override {
require(amount > 0, "Cannot stake 0");
super.stake(amount);
emit Staked(msg.sender, amount);
}
function withdraw(uint256 amount) public updateReward(msg.sender) checkStart override {
require(amount > 0, "Cannot withdraw 0");
super.withdraw(amount);
emit Withdrawn(msg.sender, amount);
}
function exit() external {
withdraw(balanceOf(msg.sender));
getReward();
}
function getReward() public updateReward(msg.sender) checkStart {
uint256 reward = earned(msg.sender);
if (reward > 0) {
rewards[msg.sender] = 0;
isla.safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
}
function notifyRewardAmount(uint256 reward)
external
onlyRewardDistribution
updateReward(address(0))
{
if (block.timestamp > starttime) {
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);
}
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(DURATION);
emit RewardAdded(reward);
} else {
rewardRate = reward.div(DURATION);
lastUpdateTime = starttime;
periodFinish = starttime.add(DURATION);
emit RewardAdded(reward);
}
}
} | stake visibility is public as overriding LPTokenWrapper's stake() function | function stake(uint256 amount) public updateReward(msg.sender) checkStart override {
require(amount > 0, "Cannot stake 0");
super.stake(amount);
emit Staked(msg.sender, amount);
}
| 10,973,678 |
./full_match/137/0x78f8Bd49670A4be3e1c6Bb18EeCa696d131015a6/sources/contracts/TierSystem.sol | /checkpoint for interest rewards and update timestamp update userInfo downgrade spontaneously | function unstake(uint _amount) external {
require(userInfo[_msgSender()].stake_amount>= _amount,"insufficient ammout");
calculateInterest(_msgSender());
userInfo[_msgSender()].stake_amount -= _amount;
userInfo[_msgSender()].frozen_amount += _amount;
userInfo[_msgSender()].countdown = block.timestamp;
if(uint8(userInfo[_msgSender()].tier) > uint8(0)){
if(userInfo[_msgSender()].stake_amount >= threshold[3]){
temp = Tier.Platinum;
}
else if(userInfo[_msgSender()].stake_amount >= threshold[2]){
temp = Tier.Gold;
}
else if(userInfo[_msgSender()].stake_amount >= threshold[1]){
temp = Tier.Silver;
}
else if(userInfo[_msgSender()].stake_amount >= threshold[0]){
temp = Tier.Bronze;
}
if(tier_user != temp){
userInfo[_msgSender()].tier = temp;
tierInfo[tier_user] --;
tierInfo[temp] ++;
}
}
totalStake -= _amount;
totalFrozen += _amount;
emit Unstake(_msgSender(), _amount, block.timestamp);
}
| 4,759,030 |
/**
*Submitted for verification at BscScan.com on 2021-05-05
*/
// File: @openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
//import "hardhat/console.sol";
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 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
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/ReentrancyGuard.sol
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
/**
* @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);
}
}
}
}
// File: "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.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");
}
}
}
// File: contracts/SmartChefInitializable.sol
contract SmartChefInitializable is Ownable, ReentrancyGuard {
using SafeERC20 for IERC20Metadata;
// The address of the smart chef factory
address public immutable SMART_CHEF_FACTORY;
// Whether a limit is set for users
bool public userLimit;
// Whether it is initialized
bool public isInitialized;
// Accrued token per share
uint256 public accTokenPerShare;
// The block number when CAKE mining ends.
uint256 public bonusEndBlock;
// The block number when CAKE mining starts.
uint256 public startBlock;
// The block number of the last pool update
uint256 public lastRewardBlock;
// The pool limit (0 if none)
uint256 public poolLimitPerUser;
// Block numbers available for user limit (after start block)
uint256 public numberBlocksForUserLimit;
// CAKE tokens created per block.
uint256 public rewardPerBlock;
// The precision factor
uint256 public PRECISION_FACTOR;
// The reward token
IERC20Metadata public rewardToken;
// The staked token
IERC20Metadata public stakedToken;
// Info of each user that stakes tokens (stakedToken)
mapping(address => UserInfo) public userInfo;
struct UserInfo {
uint256 amount; // How many staked tokens the user has provided
uint256 rewardDebt; // Reward debt
}
event Deposit(address indexed user, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 amount);
event NewStartAndEndBlocks(uint256 startBlock, uint256 endBlock);
event NewRewardPerBlock(uint256 rewardPerBlock);
event NewPoolLimit(uint256 poolLimitPerUser);
event RewardsStop(uint256 blockNumber);
event TokenRecovery(address indexed token, uint256 amount);
event Withdraw(address indexed user, uint256 amount);
/**
* @notice Constructor
*/
constructor(
) {
SMART_CHEF_FACTORY = msg.sender;
}
/*
* @notice Initialize the contract
* @param _stakedToken: staked token address
* @param _rewardToken: reward token address
* @param _rewardPerBlock: reward per block (in rewardToken)
* @param _startBlock: start block
* @param _bonusEndBlock: end block
* @param _poolLimitPerUser: pool limit per user in stakedToken (if any, else 0)
* @param _numberBlocksForUserLimit: block numbers available for user limit (after start block)
* @param _admin: admin address with ownership
*/
function initialize(
IERC20Metadata _stakedToken,
IERC20Metadata _rewardToken,
uint256 _rewardPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock,
uint256 _poolLimitPerUser,
uint256 _numberBlocksForUserLimit,
address _admin
) external {
require(!isInitialized, "Already initialized");
require(msg.sender == SMART_CHEF_FACTORY, "Not factory");
// Make this contract initialized
isInitialized = true;
stakedToken = _stakedToken;
rewardToken = _rewardToken;
rewardPerBlock = _rewardPerBlock;
startBlock = _startBlock;
bonusEndBlock = _bonusEndBlock;
if (_poolLimitPerUser > 0) {
userLimit = true;
poolLimitPerUser = _poolLimitPerUser;
numberBlocksForUserLimit = _numberBlocksForUserLimit;
}
uint256 decimalsRewardToken = uint256(rewardToken.decimals());
require(decimalsRewardToken < 30, "Must be less than 30");
PRECISION_FACTOR = uint256(10**(uint256(30) - decimalsRewardToken));
// Set the lastRewardBlock as the startBlock
lastRewardBlock = startBlock;
// Transfer ownership to the admin address who becomes owner of the contract
transferOwnership(_admin);
}
/*
* @notice Deposit staked tokens and collect reward tokens (if any)
* @param _amount: amount to withdraw (in rewardToken)
*/
function deposit(uint256 _amount) external nonReentrant {
UserInfo storage user = userInfo[msg.sender];
// Checks whether the user has an active profile
userLimit = hasUserLimit();
require(!userLimit || ((_amount + user.amount) <= poolLimitPerUser), "Deposit: Amount above limit");
_updatePool();
if (user.amount > 0) {
uint256 pending = (user.amount * accTokenPerShare) / PRECISION_FACTOR - user.rewardDebt;
if (pending > 0) {
rewardToken.safeTransfer(address(msg.sender), pending);
}
}
if (_amount > 0) {
user.amount = user.amount + _amount;
stakedToken.safeTransferFrom(address(msg.sender), address(this), _amount);
}
user.rewardDebt = (user.amount * accTokenPerShare) / PRECISION_FACTOR;
emit Deposit(msg.sender, _amount);
}
/*
* @notice Withdraw staked tokens and collect reward tokens
* @param _amount: amount to withdraw (in rewardToken)
*/
function withdraw(uint256 _amount) external nonReentrant {
UserInfo storage user = userInfo[msg.sender];
require(user.amount >= _amount, "Amount to withdraw too high");
_updatePool();
uint256 pending = (user.amount * accTokenPerShare) / PRECISION_FACTOR - user.rewardDebt;
if (_amount > 0) {
user.amount = user.amount - _amount;
stakedToken.safeTransfer(address(msg.sender), _amount);
}
if (pending > 0) {
rewardToken.safeTransfer(address(msg.sender), pending);
}
user.rewardDebt = (user.amount * accTokenPerShare) / PRECISION_FACTOR;
emit Withdraw(msg.sender, _amount);
}
/*
* @notice Withdraw staked tokens without caring about rewards rewards
* @dev Needs to be for emergency.
*/
function emergencyWithdraw() external nonReentrant {
UserInfo storage user = userInfo[msg.sender];
uint256 amountToTransfer = user.amount;
user.amount = 0;
user.rewardDebt = 0;
if (amountToTransfer > 0) {
stakedToken.safeTransfer(address(msg.sender), amountToTransfer);
}
emit EmergencyWithdraw(msg.sender, user.amount);
}
/*
* @notice Stop rewards
* @dev Only callable by owner. Needs to be for emergency.
*/
function emergencyRewardWithdraw(uint256 _amount) external onlyOwner {
rewardToken.safeTransfer(address(msg.sender), _amount);
}
/**
* @notice Allows the owner to recover tokens sent to the contract by mistake
* @param _token: token address
* @dev Callable by owner
*/
function recoverToken(address _token) external onlyOwner {
require(_token != address(stakedToken), "Operations: Cannot recover staked token");
require(_token != address(rewardToken), "Operations: Cannot recover reward token");
uint256 balance = IERC20Metadata(_token).balanceOf(address(this));
require(balance != 0, "Operations: Cannot recover zero balance");
IERC20Metadata(_token).safeTransfer(address(msg.sender), balance);
emit TokenRecovery(_token, balance);
}
/*
* @notice Stop rewards
* @dev Only callable by owner
*/
function stopReward() external onlyOwner {
bonusEndBlock = block.number;
}
/*
* @notice Update pool limit per user
* @dev Only callable by owner.
* @param _userLimit: whether the limit remains forced
* @param _poolLimitPerUser: new pool limit per user
*/
function updatePoolLimitPerUser(bool _userLimit, uint256 _poolLimitPerUser) external onlyOwner {
require(userLimit, "Must be set");
if (_userLimit) {
require(_poolLimitPerUser > poolLimitPerUser, "New limit must be higher");
poolLimitPerUser = _poolLimitPerUser;
} else {
userLimit = _userLimit;
poolLimitPerUser = 0;
}
emit NewPoolLimit(poolLimitPerUser);
}
/*
* @notice Update reward per block
* @dev Only callable by owner.
* @param _rewardPerBlock: the reward per block
*/
function updateRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner {
require(block.number < startBlock, "Pool has started");
rewardPerBlock = _rewardPerBlock;
emit NewRewardPerBlock(_rewardPerBlock);
}
/**
* @notice It allows the admin to update start and end blocks
* @dev This function is only callable by owner.
* @param _startBlock: the new start block
* @param _bonusEndBlock: the new end block
*/
function updateStartAndEndBlocks(uint256 _startBlock, uint256 _bonusEndBlock) external onlyOwner {
require(block.number < startBlock, "Pool has started");
require(_startBlock < _bonusEndBlock, "New startBlock must be lower than new endBlock");
require(block.number < _startBlock, "New startBlock must be higher than current block");
startBlock = _startBlock;
bonusEndBlock = _bonusEndBlock;
// Set the lastRewardBlock as the startBlock
lastRewardBlock = startBlock;
emit NewStartAndEndBlocks(_startBlock, _bonusEndBlock);
}
/*
* @notice View function to see pending reward on frontend.
* @param _user: user address
* @return Pending reward for a given user
*/
function pendingReward(address _user) external view returns (uint256) {
UserInfo storage user = userInfo[_user];
uint256 stakedTokenSupply = stakedToken.balanceOf(address(this));
if (block.number > lastRewardBlock && stakedTokenSupply != 0) {
uint256 multiplier = _getMultiplier(lastRewardBlock, block.number);
uint256 cakeReward = multiplier * rewardPerBlock;
uint256 adjustedTokenPerShare = accTokenPerShare + (cakeReward * PRECISION_FACTOR) / stakedTokenSupply;
return (user.amount * adjustedTokenPerShare) / PRECISION_FACTOR - user.rewardDebt;
} else {
return (user.amount * accTokenPerShare) / PRECISION_FACTOR - user.rewardDebt;
}
}
/*
* @notice Update reward variables of the given pool to be up-to-date.
*/
function _updatePool() internal {
if (block.number <= lastRewardBlock) {
return;
}
uint256 stakedTokenSupply = stakedToken.balanceOf(address(this));
if (stakedTokenSupply == 0) {
lastRewardBlock = block.number;
return;
}
uint256 multiplier = _getMultiplier(lastRewardBlock, block.number);
uint256 cakeReward = multiplier * rewardPerBlock;
accTokenPerShare = accTokenPerShare + (cakeReward * PRECISION_FACTOR) / stakedTokenSupply;
lastRewardBlock = block.number;
}
/*
* @notice Return reward multiplier over the given _from to _to block.
* @param _from: block to start
* @param _to: block to finish
*/
function _getMultiplier(uint256 _from, uint256 _to) internal view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to - _from;
} else if (_from >= bonusEndBlock) {
return 0;
} else {
return bonusEndBlock - _from;
}
}
/*
* @notice Return user limit is set or zero.
*/
function hasUserLimit() public view returns (bool) {
if (!userLimit || (block.number >= (startBlock + numberBlocksForUserLimit))) {
return false;
}
return true;
}
}
// File: contracts/SmartChefFactory.sol
contract SmartChefFactory is Ownable {
event NewSmartChefContract(address indexed smartChef);
constructor() {
//
}
/*
* @notice Deploy the pool
* @param _stakedToken: staked token address
* @param _rewardToken: reward token address
* @param _rewardPerBlock: reward per block (in rewardToken)
* @param _startBlock: start block
* @param _endBlock: end block
* @param _poolLimitPerUser: pool limit per user in stakedToken (if any, else 0)
* @param _numberBlocksForUserLimit: block numbers available for user limit (after start block)
* @param _admin: admin address with ownership
* @return address of new smart chef contract
*/
function deployPool(
IERC20Metadata _stakedToken,
IERC20Metadata _rewardToken,
uint256 _rewardPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock,
uint256 _poolLimitPerUser,
uint256 _numberBlocksForUserLimit,
address _admin
) external onlyOwner {
require(_stakedToken.totalSupply() >= 0);
require(_rewardToken.totalSupply() >= 0);
require(_stakedToken != _rewardToken, "Tokens must be be different");
bytes memory bytecode = type(SmartChefInitializable).creationCode;
// pass constructor argument
bytecode = abi.encodePacked(
bytecode,
abi.encode()
);
bytes32 salt = keccak256(abi.encodePacked(_stakedToken, _rewardToken, _startBlock));
address smartChefAddress;
assembly {
smartChefAddress := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
SmartChefInitializable(smartChefAddress).initialize(
_stakedToken,
_rewardToken,
_rewardPerBlock,
_startBlock,
_bonusEndBlock,
_poolLimitPerUser,
_numberBlocksForUserLimit,
_admin
);
emit NewSmartChefContract(smartChefAddress);
}
} | Update pool limit per user Only callable by owner. _userLimit: whether the limit remains forced _poolLimitPerUser: new pool limit per user/ | function updatePoolLimitPerUser(bool _userLimit, uint256 _poolLimitPerUser) external onlyOwner {
require(userLimit, "Must be set");
if (_userLimit) {
require(_poolLimitPerUser > poolLimitPerUser, "New limit must be higher");
poolLimitPerUser = _poolLimitPerUser;
userLimit = _userLimit;
poolLimitPerUser = 0;
}
emit NewPoolLimit(poolLimitPerUser);
}
| 1,017,832 |
./full_match/80001/0x6e92365c2B8610bDE6a45F70d351de9C1189bf61/sources/contracts/Farm.sol | Check the required material is setup | function createResource(address resourceAddress, address requires) public {
require(resourceAddress != address(token), "ROSE_TOKEN_IN_USE");
require(!materials[resourceAddress].exists, "RESOURCE_ALREADY_EXISTS");
require(materials[requires].exists, "MATERIAL_DOES_NOT_EXIST");
resources[resourceAddress] = Resource({
outputAddress: resourceAddress,
inputAddress: requires
});
materials[resourceAddress] = Material({
exists: true,
materialAddress: resourceAddress
});
}
| 5,651,256 |
pragma solidity ^0.4.19;
import "./BaseContent.sol";
contract MovieContent is BaseContent {
/* VARIABLES DECLARATION */
uint32 public movie_length; // duration of the movie in minutes
bytes32 public g = 0x4d6f766965000000000000000000000000000000000000000000000000000000; // string "Movie"
/* CONSTRUCTOR */
/* inheritates the contractor from Base Content */
constructor(Catalog _catalog, bytes32 _title, bytes32 _author, uint _price) BaseContent (_catalog, _title, _author, g, _price) public {
movie_length = 0;
}
/* FUNCTIONS */
/* utility function to understant contract class */
function ContentType() public view returns (bytes32) {
return g;
}
/* allows the owner to insert an additional information */
function SetMovieLength(uint32 _l) external byOwner {
movie_length = _l;
}
} | allows the owner to insert an additional information / | function SetMovieLength(uint32 _l) external byOwner {
movie_length = _l;
}
| 14,020,296 |
./partial_match/83/0xAA49141eEa36ce1A26Fc49DC2ff9983494FfA70B/sources/contracts/libraries/IncentiveId.sol | Calculate the key for a staking incentive key The components used to compute the incentive identifier return incentiveId The identifier for the incentive | function compute(IIncentiveKey.IncentiveKey memory key) internal pure returns (bytes32 incentiveId) {
return keccak256(abi.encode(key));
}
| 8,828,293 |
./full_match/4/0x087c1E153cb008471fAb7AA8AF2f8226D8b15093/sources/browser/Untitled.sol | Similar to EIP20 transfer, except it handles a False result from `transfer` and returns an explanatory error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified it is >= amount, this should not revert in normal conditions. Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value./ solium-disable-next-line security/no-inline-assembly | function doTransferOut(address payable to, uint amount) internal returns (Error) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
bool result;
token.transfer(to, amount);
assembly {
switch returndatasize()
}
returndatacopy(0, 0, 32)
}
| 793,289 |
// SPDX-License-Identifier: BUSL-1.1
// File: contracts/IPFSConvert.sol
// contracts/IPFSConvert.sol
pragma solidity ^0.8.0;
/// @title IPFSConvert
/// @author Teahouse Finance
library IPFSConvert {
bytes constant private CODE_STRING = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
bytes constant private CIDV0HEAD = "\x00\x04\x28\x0b\x12\x17\x09\x28\x31\x00\x12\x04\x28\x20\x25\x25\x22\x31\x1b\x1d\x39\x29\x09\x26\x1b\x29\x0b\x02\x0a\x18\x25\x22\x24\x1b\x39\x2c\x1d\x39\x07\x06\x29\x25\x13\x15\x2c\x17";
/**
* @dev This function converts an 256 bits hash value into IPFS CIDv0 hash string.
* @param _cidv0 256 bits hash value (not including the 0x12 0x20 signature)
* @return IPFS CIDv0 hash string (Qm...)
*/
function cidv0FromBytes32(bytes32 _cidv0) public pure returns (string memory) {
unchecked {
// convert to base58
bytes memory result = new bytes(46); // 46 is the longest possible base58 result from CIDv0
uint256 resultLen = 45;
uint256 number = uint256(_cidv0);
while(number > 0) {
uint256 rem = number % 58;
result[resultLen] = bytes1(uint8(rem));
resultLen--;
number = number / 58;
}
// add 0x1220 in front of _cidv0
uint256 i;
for (i = 0; i < 46; i++) {
uint8 r = uint8(result[45 - i]) + uint8(CIDV0HEAD[i]);
if (r >= 58) {
result[45 - i] = bytes1(r - 58);
result[45 - i - 1] = bytes1(uint8(result[45 - i - 1]) + 1);
}
else {
result[45 - i] = bytes1(r);
}
}
// convert to characters
for (i = 0; i < 46; i++) {
result[i] = CODE_STRING[uint8(result[i])];
}
return string(result);
}
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// 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 (last updated v4.6.0) (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`.
*
* 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 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 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 the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @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);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/utils/cryptography/MerkleProof.sol
// OpenZeppelin Contracts (last updated v4.6.0) (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*
* WARNING: You should avoid using leaf values that are 64 bytes long prior to
* hashing, or use a hash function other than keccak256 for hashing leaves.
* This is because the concatenation of a sorted pair of internal nodes in
* the merkle tree could be reinterpreted as a leaf value.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = _efficientHash(computedHash, proofElement);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = _efficientHash(proofElement, computedHash);
}
}
return computedHash;
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
// File: @chainlink/contracts/src/v0.8/VRFConsumerBaseV2.sol
pragma solidity ^0.8.0;
/** ****************************************************************************
* @notice Interface for contracts using VRF randomness
* *****************************************************************************
* @dev PURPOSE
*
* @dev Reggie the Random Oracle (not his real job) wants to provide randomness
* @dev to Vera the verifier in such a way that Vera can be sure he's not
* @dev making his output up to suit himself. Reggie provides Vera a public key
* @dev to which he knows the secret key. Each time Vera provides a seed to
* @dev Reggie, he gives back a value which is computed completely
* @dev deterministically from the seed and the secret key.
*
* @dev Reggie provides a proof by which Vera can verify that the output was
* @dev correctly computed once Reggie tells it to her, but without that proof,
* @dev the output is indistinguishable to her from a uniform random sample
* @dev from the output space.
*
* @dev The purpose of this contract is to make it easy for unrelated contracts
* @dev to talk to Vera the verifier about the work Reggie is doing, to provide
* @dev simple access to a verifiable source of randomness. It ensures 2 things:
* @dev 1. The fulfillment came from the VRFCoordinator
* @dev 2. The consumer contract implements fulfillRandomWords.
* *****************************************************************************
* @dev USAGE
*
* @dev Calling contracts must inherit from VRFConsumerBase, and can
* @dev initialize VRFConsumerBase's attributes in their constructor as
* @dev shown:
*
* @dev contract VRFConsumer {
* @dev constructor(<other arguments>, address _vrfCoordinator, address _link)
* @dev VRFConsumerBase(_vrfCoordinator) public {
* @dev <initialization with other arguments goes here>
* @dev }
* @dev }
*
* @dev The oracle will have given you an ID for the VRF keypair they have
* @dev committed to (let's call it keyHash). Create subscription, fund it
* @dev and your consumer contract as a consumer of it (see VRFCoordinatorInterface
* @dev subscription management functions).
* @dev Call requestRandomWords(keyHash, subId, minimumRequestConfirmations,
* @dev callbackGasLimit, numWords),
* @dev see (VRFCoordinatorInterface for a description of the arguments).
*
* @dev Once the VRFCoordinator has received and validated the oracle's response
* @dev to your request, it will call your contract's fulfillRandomWords method.
*
* @dev The randomness argument to fulfillRandomWords is a set of random words
* @dev generated from your requestId and the blockHash of the request.
*
* @dev If your contract could have concurrent requests open, you can use the
* @dev requestId returned from requestRandomWords to track which response is associated
* @dev with which randomness request.
* @dev See "SECURITY CONSIDERATIONS" for principles to keep in mind,
* @dev if your contract could have multiple requests in flight simultaneously.
*
* @dev Colliding `requestId`s are cryptographically impossible as long as seeds
* @dev differ.
*
* *****************************************************************************
* @dev SECURITY CONSIDERATIONS
*
* @dev A method with the ability to call your fulfillRandomness method directly
* @dev could spoof a VRF response with any random value, so it's critical that
* @dev it cannot be directly called by anything other than this base contract
* @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method).
*
* @dev For your users to trust that your contract's random behavior is free
* @dev from malicious interference, it's best if you can write it so that all
* @dev behaviors implied by a VRF response are executed *during* your
* @dev fulfillRandomness method. If your contract must store the response (or
* @dev anything derived from it) and use it later, you must ensure that any
* @dev user-significant behavior which depends on that stored value cannot be
* @dev manipulated by a subsequent VRF request.
*
* @dev Similarly, both miners and the VRF oracle itself have some influence
* @dev over the order in which VRF responses appear on the blockchain, so if
* @dev your contract could have multiple VRF requests in flight simultaneously,
* @dev you must ensure that the order in which the VRF responses arrive cannot
* @dev be used to manipulate your contract's user-significant behavior.
*
* @dev Since the block hash of the block which contains the requestRandomness
* @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
* @dev miner could, in principle, fork the blockchain to evict the block
* @dev containing the request, forcing the request to be included in a
* @dev different block with a different hash, and therefore a different input
* @dev to the VRF. However, such an attack would incur a substantial economic
* @dev cost. This cost scales with the number of blocks the VRF oracle waits
* @dev until it calls responds to a request. It is for this reason that
* @dev that you can signal to an oracle you'd like them to wait longer before
* @dev responding to the request (however this is not enforced in the contract
* @dev and so remains effective only in the case of unmodified oracle software).
*/
abstract contract VRFConsumerBaseV2 {
error OnlyCoordinatorCanFulfill(address have, address want);
address private immutable vrfCoordinator;
/**
* @param _vrfCoordinator address of VRFCoordinator contract
*/
constructor(address _vrfCoordinator) {
vrfCoordinator = _vrfCoordinator;
}
/**
* @notice fulfillRandomness handles the VRF response. Your contract must
* @notice implement it. See "SECURITY CONSIDERATIONS" above for important
* @notice principles to keep in mind when implementing your fulfillRandomness
* @notice method.
*
* @dev VRFConsumerBaseV2 expects its subcontracts to have a method with this
* @dev signature, and will call it once it has verified the proof
* @dev associated with the randomness. (It is triggered via a call to
* @dev rawFulfillRandomness, below.)
*
* @param requestId The Id initially returned by requestRandomness
* @param randomWords the VRF output expanded to the requested number of words
*/
function fulfillRandomWords(uint256 requestId, uint256[] memory randomWords) internal virtual;
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
// proof. rawFulfillRandomness then calls fulfillRandomness, after validating
// the origin of the call
function rawFulfillRandomWords(uint256 requestId, uint256[] memory randomWords) external {
if (msg.sender != vrfCoordinator) {
revert OnlyCoordinatorCanFulfill(msg.sender, vrfCoordinator);
}
fulfillRandomWords(requestId, randomWords);
}
}
// File: @chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol
pragma solidity ^0.8.0;
interface VRFCoordinatorV2Interface {
/**
* @notice Get configuration relevant for making requests
* @return minimumRequestConfirmations global min for request confirmations
* @return maxGasLimit global max for request gas limit
* @return s_provingKeyHashes list of registered key hashes
*/
function getRequestConfig()
external
view
returns (
uint16,
uint32,
bytes32[] memory
);
/**
* @notice Request a set of random words.
* @param keyHash - Corresponds to a particular oracle job which uses
* that key for generating the VRF proof. Different keyHash's have different gas price
* ceilings, so you can select a specific one to bound your maximum per request cost.
* @param subId - The ID of the VRF subscription. Must be funded
* with the minimum subscription balance required for the selected keyHash.
* @param minimumRequestConfirmations - How many blocks you'd like the
* oracle to wait before responding to the request. See SECURITY CONSIDERATIONS
* for why you may want to request more. The acceptable range is
* [minimumRequestBlockConfirmations, 200].
* @param callbackGasLimit - How much gas you'd like to receive in your
* fulfillRandomWords callback. Note that gasleft() inside fulfillRandomWords
* may be slightly less than this amount because of gas used calling the function
* (argument decoding etc.), so you may need to request slightly more than you expect
* to have inside fulfillRandomWords. The acceptable range is
* [0, maxGasLimit]
* @param numWords - The number of uint256 random values you'd like to receive
* in your fulfillRandomWords callback. Note these numbers are expanded in a
* secure way by the VRFCoordinator from a single random value supplied by the oracle.
* @return requestId - A unique identifier of the request. Can be used to match
* a request to a response in fulfillRandomWords.
*/
function requestRandomWords(
bytes32 keyHash,
uint64 subId,
uint16 minimumRequestConfirmations,
uint32 callbackGasLimit,
uint32 numWords
) external returns (uint256 requestId);
/**
* @notice Create a VRF subscription.
* @return subId - A unique subscription id.
* @dev You can manage the consumer set dynamically with addConsumer/removeConsumer.
* @dev Note to fund the subscription, use transferAndCall. For example
* @dev LINKTOKEN.transferAndCall(
* @dev address(COORDINATOR),
* @dev amount,
* @dev abi.encode(subId));
*/
function createSubscription() external returns (uint64 subId);
/**
* @notice Get a VRF subscription.
* @param subId - ID of the subscription
* @return balance - LINK balance of the subscription in juels.
* @return reqCount - number of requests for this subscription, determines fee tier.
* @return owner - owner of the subscription.
* @return consumers - list of consumer address which are able to use this subscription.
*/
function getSubscription(uint64 subId)
external
view
returns (
uint96 balance,
uint64 reqCount,
address owner,
address[] memory consumers
);
/**
* @notice Request subscription owner transfer.
* @param subId - ID of the subscription
* @param newOwner - proposed new owner of the subscription
*/
function requestSubscriptionOwnerTransfer(uint64 subId, address newOwner) external;
/**
* @notice Request subscription owner transfer.
* @param subId - ID of the subscription
* @dev will revert if original owner of subId has
* not requested that msg.sender become the new owner.
*/
function acceptSubscriptionOwnerTransfer(uint64 subId) external;
/**
* @notice Add a consumer to a VRF subscription.
* @param subId - ID of the subscription
* @param consumer - New consumer which can use the subscription
*/
function addConsumer(uint64 subId, address consumer) external;
/**
* @notice Remove a consumer from a VRF subscription.
* @param subId - ID of the subscription
* @param consumer - Consumer to remove from the subscription
*/
function removeConsumer(uint64 subId, address consumer) external;
/**
* @notice Cancel a subscription
* @param subId - ID of the subscription
* @param to - Where to send the remaining LINK to
*/
function cancelSubscription(uint64 subId, address to) external;
}
// File: @openzeppelin/contracts/security/ReentrancyGuard.sol
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/cryptography/ECDSA.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)
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 = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// 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: contracts/ERC721A.sol
// Creator: Chiru Labs
pragma solidity ^0.8.4;
error ApprovalCallerNotOwnerNorApproved();
error ApprovalQueryForNonexistentToken();
error ApproveToCaller();
error ApprovalToCurrentOwner();
error BalanceQueryForZeroAddress();
error MintedQueryForZeroAddress();
error BurnedQueryForZeroAddress();
error AuxQueryForZeroAddress();
error MintToZeroAddress();
error MintZeroQuantity();
error OwnerIndexOutOfBounds();
error OwnerQueryForNonexistentToken();
error TokenIndexOutOfBounds();
error TransferCallerNotOwnerNorApproved();
error TransferFromIncorrectOwner();
error TransferToNonERC721ReceiverImplementer();
error TransferToZeroAddress();
error URIQueryForNonexistentToken();
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..).
*
* Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
*
* Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256).
*/
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Compiler will pack this into a single 256bit word.
struct TokenOwnership {
// The address of the owner.
address addr;
// Keeps track of the start time of ownership with minimal overhead for tokenomics.
uint64 startTimestamp;
// Whether the token has been burned.
bool burned;
}
// Compiler will pack this into a single 256bit word.
struct AddressData {
// Realistically, 2**64-1 is more than enough.
uint64 balance;
// Keeps track of mint count with minimal overhead for tokenomics.
uint64 numberMinted;
// Keeps track of burn count with minimal overhead for tokenomics.
uint64 numberBurned;
// For miscellaneous variable(s) pertaining to the address
// (e.g. number of whitelist mint slots used).
// If there are multiple variables, please pack them into a uint64.
uint64 aux;
}
// The tokenId of the next token to be minted.
uint256 internal _currentIndex;
// The number of tokens burned.
uint256 internal _burnCounter;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) internal _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_currentIndex = _startTokenId();
}
/**
* To change the starting tokenId, please override this function.
*/
function _startTokenId() internal view virtual returns (uint256) {
return 0;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
* @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens.
*/
function totalSupply() public view returns (uint256) {
// Counter underflow is impossible as _burnCounter cannot be incremented
// more than _currentIndex - _startTokenId() times
unchecked {
return _currentIndex - _burnCounter - _startTokenId();
}
}
/**
* Returns the total amount of tokens minted in the contract.
*/
function _totalMinted() internal view returns (uint256) {
// Counter underflow is impossible as _currentIndex does not decrement,
// and it is initialized to _startTokenId()
unchecked {
return _currentIndex - _startTokenId();
}
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
if (owner == address(0)) revert BalanceQueryForZeroAddress();
return uint256(_addressData[owner].balance);
}
/**
* Returns the number of tokens minted by `owner`.
*/
function _numberMinted(address owner) internal view returns (uint256) {
if (owner == address(0)) revert MintedQueryForZeroAddress();
return uint256(_addressData[owner].numberMinted);
}
/**
* Returns the number of tokens burned by or on behalf of `owner`.
*/
function _numberBurned(address owner) internal view returns (uint256) {
if (owner == address(0)) revert BurnedQueryForZeroAddress();
return uint256(_addressData[owner].numberBurned);
}
/**
* Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
*/
function _getAux(address owner) internal view returns (uint64) {
if (owner == address(0)) revert AuxQueryForZeroAddress();
return _addressData[owner].aux;
}
/**
* Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
* If there are multiple variables, please pack them into a uint64.
*/
function _setAux(address owner, uint64 aux) internal {
if (owner == address(0)) revert AuxQueryForZeroAddress();
_addressData[owner].aux = aux;
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/
function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
// Invariant:
// There will always be an ownership that has an address and is not burned
// before an ownership that does not have an address and is not burned.
// Hence, curr will not underflow.
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
string memory baseURI = _baseURI();
return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : '';
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return '';
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
if (to == owner) revert ApprovalToCurrentOwner();
if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
if (operator == _msgSender()) revert ApproveToCaller();
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, '');
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
_transfer(from, to, tokenId);
if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _startTokenId() <= tokenId && tokenId < _currentIndex &&
!_ownerships[tokenId].burned;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, '');
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1
// updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
// Reentrancy protection
if (_currentIndex != startTokenId) revert();
} else {
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
isApprovedForAll(prevOwnership.addr, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
_beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[prevOwnership.addr].balance -= 1;
_addressData[prevOwnership.addr].numberBurned += 1;
// Keep track of who burned the token, and the timestamp of burning.
_ownerships[tokenId].addr = prevOwnership.addr;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
_ownerships[tokenId].burned = true;
// If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(prevOwnership.addr, address(0), tokenId);
_afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
// Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
unchecked {
_burnCounter++;
}
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
* And also called before burning one token.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, `tokenId` will be burned by `from`.
* - `from` and `to` are never both zero.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
* And also called after one token has been burned.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` has been
* transferred to `to`.
* - When `from` is zero, `tokenId` has been minted for `to`.
* - When `to` is zero, `tokenId` has been burned by `from`.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// File: @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: contracts/ZombieClubToken.sol
pragma solidity ^0.8.0;
error InvalidTotalMysteryBoxes();
error ReachedMaxSupply();
error TransactionExpired();
error SignatureAlreadyUsed();
error ExceedMaxAllowedMintAmount();
error IncorrectSignature();
error InsufficientPayments();
error RevealNotAllowed();
error MerkleTreeRootNotSet();
error InvalidMerkleTreeProof();
error RequestRevealNotOwner();
error RevealAlreadyRequested();
error IncorrectRevealIndex();
error TokenAlreadyRevealed();
error MerkleTreeProofFailed();
error IncorrectRevealManyLength();
error TokenRevealQueryForNonexistentToken();
/// @title ZombieClubToken
/// @author Teahouse Finance
contract ZombieClubToken is ERC721A, Ownable, ReentrancyGuard, VRFConsumerBaseV2 {
using Strings for uint256;
using ECDSA for bytes32;
struct ChainlinkParams {
bytes32 keyHash;
uint64 subId;
uint32 gasLimit;
uint16 requestConfirms;
}
struct TokenReveal {
bool requested; // token reveal requested
uint64 revealId;
}
struct TokenInternalInfo {
bool requested; // token reveal requested
uint64 revealId;
uint64 lastTransferTime;
uint64 stateChangePeriod;
}
// Chainlink info
VRFCoordinatorV2Interface immutable public COORDINATOR;
ChainlinkParams public chainlinkParams;
address private signer;
uint256 public price = 0.666 ether;
uint256 public maxCollection;
uint64 public presaleEndTime;
string public unrevealURI;
bool public allowReveal = false;
bytes32 public hashMerkleRoot;
uint256 public revealedTokens;
uint256 public totalMysteryBoxes;
// state change period (second)
uint256 constant stateChangePeriod = 2397600;
uint256 constant stateChangeVariation = 237600;
uint256 constant numOfStates = 4;
mapping(uint256 => uint256) private tokenIdMap;
mapping(uint256 => bytes32[numOfStates]) private tokenBaseURIHashes;
mapping(uint256 => uint256) public chainlinkTokenId;
mapping(uint256 => TokenInternalInfo) private tokenInternalInfo;
mapping(bytes32 => bool) public signatureUsed;
event RevealRequested(uint256 indexed tokenId, uint256 requestId);
event RevealReceived(uint256 indexed tokenId, uint256 revealId);
event Revealed(uint256 indexed tokenId);
constructor(
string memory _name,
string memory _symbol,
address _initSigner, // whitelist signer address
uint256 _maxCollection, // total supply
uint256 _totalMysteryBoxes, // number of all mystery boxes available
address _vrfCoordinator, // Chainlink VRF coordinator address
ChainlinkParams memory _chainlinkParams
) ERC721A(_name, _symbol) VRFConsumerBaseV2(_vrfCoordinator) {
if (_totalMysteryBoxes < _maxCollection) revert InvalidTotalMysteryBoxes();
COORDINATOR = VRFCoordinatorV2Interface(_vrfCoordinator);
signer = _initSigner;
maxCollection = _maxCollection;
totalMysteryBoxes = _totalMysteryBoxes;
chainlinkParams = _chainlinkParams;
}
function setPresaleEndTime(uint64 _newTime) external onlyOwner {
presaleEndTime = _newTime;
}
function setPrice(uint256 _newPrice) external onlyOwner {
price = _newPrice;
}
function setSigner(address _newSigner) external onlyOwner {
signer = _newSigner;
}
function setChainlinkParams(ChainlinkParams memory _chainlinkParams) external onlyOwner {
chainlinkParams = _chainlinkParams;
}
function setUnrevealURI(string calldata _newURI) external onlyOwner {
unrevealURI = _newURI;
}
function setMerkleRoot(bytes32 _hashMerkleRoot) public onlyOwner {
require(revealedTokens == 0); // can't be changed after someone requested reveal
hashMerkleRoot = _hashMerkleRoot;
}
function setAllowReveal(bool _allowReveal) external onlyOwner {
allowReveal = _allowReveal;
}
function withdraw(address payable _to) external payable onlyOwner {
(bool success, ) = _to.call{value: address(this).balance}("");
require(success);
}
function isAuthorized(
address _sender,
uint32 _allowAmount,
uint64 _expireTime,
bytes memory _signature
) private view returns (bool) {
bytes32 hashMsg = keccak256(abi.encodePacked(_sender, _allowAmount, _expireTime));
bytes32 ethHashMessage = hashMsg.toEthSignedMessageHash();
return ethHashMessage.recover(_signature) == signer;
}
function mint(uint32 _amount, uint32 _allowAmount, uint64 _expireTime, bytes calldata _signature) external payable {
if (totalSupply() + _amount > maxCollection) revert ReachedMaxSupply();
if (block.timestamp > _expireTime) revert TransactionExpired();
if (block.timestamp > presaleEndTime) {
// PUBLIC SALE mode
// does not limit how many tokens one can mint in total,
// only limit how many tokens one can mint in one go
// also, make sure one signature can only be used once
if (_amount > _allowAmount) revert ExceedMaxAllowedMintAmount();
bytes32 sigHash = keccak256(abi.encodePacked(_signature));
if (signatureUsed[sigHash]) revert SignatureAlreadyUsed();
signatureUsed[sigHash] = true;
}
else {
// WHITELIST SALE mode
// limit how many tokens one can mint in total
if (_numberMinted(msg.sender) + _amount > _allowAmount) revert ExceedMaxAllowedMintAmount();
}
if (!isAuthorized(msg.sender, _allowAmount, _expireTime, _signature)) revert IncorrectSignature();
uint256 finalPrice = price * _amount;
if (msg.value < finalPrice) revert InsufficientPayments();
_safeMint(msg.sender, _amount);
}
function devMint(uint256 _amount, address _to) external onlyOwner {
if (totalSupply() + _amount > maxCollection) revert ReachedMaxSupply();
_safeMint(_to, _amount);
}
function requestReveal(uint256 _tokenId) external nonReentrant {
if (!allowReveal) revert RevealNotAllowed();
if (ownerOf(_tokenId) != msg.sender) revert RequestRevealNotOwner();
if (tokenInternalInfo[_tokenId].requested) revert RevealAlreadyRequested();
if (hashMerkleRoot == bytes32(0)) revert MerkleTreeRootNotSet();
uint256 requestId = COORDINATOR.requestRandomWords(
chainlinkParams.keyHash,
chainlinkParams.subId,
chainlinkParams.requestConfirms,
chainlinkParams.gasLimit,
1
);
tokenInternalInfo[_tokenId].requested = true;
chainlinkTokenId[requestId] = _tokenId;
emit RevealRequested(_tokenId, requestId);
}
function fulfillRandomWords(uint256 requestId, uint256[] memory randomWords) internal override {
uint256 tokenId = chainlinkTokenId[requestId];
if (tokenInternalInfo[tokenId].requested && tokenInternalInfo[tokenId].revealId == 0) {
uint256 randomIndex = randomWords[0] % (totalMysteryBoxes - revealedTokens) + revealedTokens;
uint256 revealId = _tokenIdMap(randomIndex);
uint256 currentId = _tokenIdMap(revealedTokens);
tokenIdMap[randomIndex] = currentId;
tokenInternalInfo[tokenId].revealId = uint64(revealId);
revealedTokens ++;
emit RevealReceived(tokenId, revealId);
}
}
function reveal(uint256 _tokenId, bytes32[numOfStates] memory _tokenBaseURIHashes, uint256 _index, bytes32 _salt, bytes32[] memory _proof) public {
if (hashMerkleRoot == bytes32(0)) revert MerkleTreeRootNotSet();
if (_index == 0 || tokenInternalInfo[_tokenId].revealId != _index) revert IncorrectRevealIndex();
if (tokenBaseURIHashes[_tokenId][0] != 0) revert TokenAlreadyRevealed();
// perform merkle root proof verification
bytes32 hash = keccak256(abi.encodePacked(_tokenBaseURIHashes, _index, _salt));
if (!MerkleProof.verify(_proof, hashMerkleRoot, hash)) revert MerkleTreeProofFailed();
tokenBaseURIHashes[_tokenId] = _tokenBaseURIHashes;
_setTokenTimeInfo(_tokenId);
emit Revealed(_tokenId);
}
function revealMany(uint256[] memory _tokenIds, bytes32[numOfStates][] memory _tokenBaseURIHashes, uint256[] memory _indexes, bytes32[] memory _salts, bytes32[][] memory _prooves) public {
if (hashMerkleRoot == bytes32(0)) revert MerkleTreeRootNotSet();
if (_tokenIds.length != _tokenBaseURIHashes.length) revert IncorrectRevealManyLength();
if (_tokenIds.length != _indexes.length) revert IncorrectRevealManyLength();
if (_tokenIds.length != _salts.length) revert IncorrectRevealManyLength();
if (_tokenIds.length != _prooves.length) revert IncorrectRevealManyLength();
uint256 i;
uint256 length = _tokenIds.length;
for (i = 0; i < length; i++) {
if (tokenBaseURIHashes[_tokenIds[i]][0] == 0) {
// only calls reveal for those not revealed yet
// this is to revent the case where one revealed token will cause the entire batch to revert
// we only check for "revealed" but not for other situation as the entire batch is supposed to have
// correct parameters
reveal(_tokenIds[i], _tokenBaseURIHashes[i], _indexes[i], _salts[i], _prooves[i]);
}
}
}
function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) {
if (!_exists(_tokenId)) revert URIQueryForNonexistentToken();
if (tokenBaseURIHashes[_tokenId][0] == 0) {
return unrevealURI;
}
else {
bytes32 hash = tokenBaseURIHashes[_tokenId][_getZombieState(_tokenId)];
return string(abi.encodePacked("ipfs://", IPFSConvert.cidv0FromBytes32(hash)));
}
}
function totalMinted() external view returns (uint256) {
return _totalMinted();
}
function numberMinted(address _minter) external view returns (uint256) {
return _numberMinted(_minter);
}
function tokenReveal(uint256 _tokenId) external view returns (TokenReveal memory) {
if (!_exists(_tokenId)) revert TokenRevealQueryForNonexistentToken();
return TokenReveal({
requested: tokenInternalInfo[_tokenId].requested,
revealId: tokenInternalInfo[_tokenId].revealId
});
}
function ownedTokens(address _addr, uint256 _startId, uint256 _endId) external view returns (uint256[] memory, uint256) {
if (_endId == 0) {
_endId = _currentIndex - 1;
}
if (_startId < _startTokenId() || _endId >= _currentIndex) revert TokenIndexOutOfBounds();
uint256 i;
uint256 balance = balanceOf(_addr);
if (balance == 0) {
return (new uint256[](0), _endId + 1);
}
if (balance > 256) {
balance = 256;
}
uint256[] memory results = new uint256[](balance);
uint256 idx = 0;
address owner = ownerOf(_startId);
for (i = _startId; i <= _endId; i++) {
if (_ownerships[i].addr != address(0)) {
owner = _ownerships[i].addr;
}
if (!_ownerships[i].burned && owner == _addr) {
results[idx] = i;
idx++;
if (idx == balance) {
if (balance == balanceOf(_addr)) {
return (results, _endId + 1);
}
else {
return (results, i + 1);
}
}
}
}
uint256[] memory partialResults = new uint256[](idx);
for (i = 0; i < idx; i++) {
partialResults[i] = results[i];
}
return (partialResults, _endId + 1);
}
function unrevealedTokens(uint256 _startId, uint256 _endId) external view returns (uint256[] memory, uint256) {
if (_endId == 0) {
_endId = _currentIndex - 1;
}
if (_startId < _startTokenId() || _endId >= _currentIndex) revert TokenIndexOutOfBounds();
uint256 i;
uint256[] memory results = new uint256[](256);
uint256 idx = 0;
for (i = _startId; i <= _endId; i++) {
if (tokenInternalInfo[i].revealId != 0 && tokenBaseURIHashes[i][0] == 0) {
// reveal received but not revealed
results[idx] = i;
idx++;
if (idx == 256) {
return (results, i + 1);
}
}
}
uint256[] memory partialResults = new uint256[](idx);
for (i = 0; i < idx; i++) {
partialResults[i] = results[i];
}
return (partialResults, _endId + 1);
}
function _startTokenId() override internal view virtual returns (uint256) {
return 1;
}
function _tokenIdMap(uint256 _index) private view returns (uint256) {
if (tokenIdMap[_index] == 0) {
return _index + 1;
}
else {
return tokenIdMap[_index];
}
}
function _getZombieState(uint256 _tokenId) internal view returns (uint256) {
uint256 duration = block.timestamp - tokenInternalInfo[_tokenId].lastTransferTime;
uint256 state = duration / tokenInternalInfo[_tokenId].stateChangePeriod;
if (state >= numOfStates) {
state = numOfStates - 1;
}
while(tokenBaseURIHashes[_tokenId][state] == 0) {
state--;
}
return state;
}
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 /*quantity*/) internal override {
// only reset token time info when actually transfering the token
// not when minting
// so "quantity" should always be 1
if (from != address(0) && to != address(0)) {
_setTokenTimeInfo(startTokenId);
}
}
function _setTokenTimeInfo(uint256 _tokenId) private {
tokenInternalInfo[_tokenId].lastTransferTime = uint64(block.timestamp);
tokenInternalInfo[_tokenId].stateChangePeriod = uint64(stateChangePeriod + _randomNumber() % stateChangeVariation);
}
function _randomNumber() internal view returns (uint256) {
return uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), block.timestamp)));
}
} | only calls reveal for those not revealed yet this is to revent the case where one revealed token will cause the entire batch to revert we only check for "revealed" but not for other situation as the entire batch is supposed to have correct parameters | function revealMany(uint256[] memory _tokenIds, bytes32[numOfStates][] memory _tokenBaseURIHashes, uint256[] memory _indexes, bytes32[] memory _salts, bytes32[][] memory _prooves) public {
if (hashMerkleRoot == bytes32(0)) revert MerkleTreeRootNotSet();
if (_tokenIds.length != _tokenBaseURIHashes.length) revert IncorrectRevealManyLength();
if (_tokenIds.length != _indexes.length) revert IncorrectRevealManyLength();
if (_tokenIds.length != _salts.length) revert IncorrectRevealManyLength();
if (_tokenIds.length != _prooves.length) revert IncorrectRevealManyLength();
uint256 i;
uint256 length = _tokenIds.length;
for (i = 0; i < length; i++) {
if (tokenBaseURIHashes[_tokenIds[i]][0] == 0) {
reveal(_tokenIds[i], _tokenBaseURIHashes[i], _indexes[i], _salts[i], _prooves[i]);
}
}
}
| 11,804,053 |
Subsets and Splits