file_name
stringlengths 71
779k
| comments
stringlengths 20
182k
| code_string
stringlengths 20
36.9M
| __index_level_0__
int64 0
17.2M
| input_ids
list | attention_mask
list | labels
list |
---|---|---|---|---|---|---|
./partial_match/1/0x11b2164DDf1C3c0a420cEaD050d422B26530d11C/sources/contracts/facets/ERC721A/ERC721AUpgradeableFacet.sol | * @dev Returns the token collection symbol./ | function symbol() public view virtual returns (string memory) {
return ERC721AStorage.layout()._symbol;
}
| 9,188,648 | [
1,
1356,
326,
1147,
1849,
3273,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
3273,
1435,
1071,
1476,
5024,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
4232,
39,
27,
5340,
37,
3245,
18,
6741,
1435,
6315,
7175,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/43114/0xd31Fdc40323AedDd07c631Fc42576Be9A63791F3/sources/contracts/MasterChef.sol | 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.lpSupply;
if (lpSupply == 0 || pool.allocPoint == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 AvacoReward = multiplier.mul(AvacoPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
Avaco.mint(devAddress, AvacoReward.mul(15).div(100));
Avaco.mint(treasuryAddress, AvacoReward.mul(10).div(100));
Avaco.mint(address(this), AvacoReward);
pool.accAvacoPerShare = pool.accAvacoPerShare.add(AvacoReward.mul(1e18).div(lpSupply));
pool.lastRewardBlock = block.number;
}
| 4,519,438 | [
1,
1891,
19890,
3152,
434,
326,
864,
2845,
358,
506,
731,
17,
869,
17,
712,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1089,
2864,
12,
11890,
5034,
389,
6610,
13,
1071,
288,
203,
3639,
8828,
966,
2502,
2845,
273,
2845,
966,
63,
67,
6610,
15533,
203,
3639,
309,
261,
2629,
18,
2696,
1648,
2845,
18,
2722,
17631,
1060,
1768,
13,
288,
203,
5411,
327,
31,
203,
3639,
289,
203,
3639,
2254,
5034,
12423,
3088,
1283,
273,
2845,
18,
9953,
3088,
1283,
31,
203,
3639,
309,
261,
9953,
3088,
1283,
422,
374,
747,
2845,
18,
9853,
2148,
422,
374,
13,
288,
203,
5411,
2845,
18,
2722,
17631,
1060,
1768,
273,
1203,
18,
2696,
31,
203,
5411,
327,
31,
203,
3639,
289,
203,
3639,
2254,
5034,
15027,
273,
31863,
5742,
12,
6011,
18,
2722,
17631,
1060,
1768,
16,
1203,
18,
2696,
1769,
203,
3639,
2254,
5034,
8789,
24363,
17631,
1060,
273,
15027,
18,
16411,
12,
3769,
24363,
2173,
1768,
2934,
16411,
12,
6011,
18,
9853,
2148,
2934,
2892,
12,
4963,
8763,
2148,
1769,
203,
3639,
8789,
24363,
18,
81,
474,
12,
5206,
1887,
16,
8789,
24363,
17631,
1060,
18,
16411,
12,
3600,
2934,
2892,
12,
6625,
10019,
203,
202,
202,
3769,
24363,
18,
81,
474,
12,
27427,
345,
22498,
1887,
16,
8789,
24363,
17631,
1060,
18,
16411,
12,
2163,
2934,
2892,
12,
6625,
10019,
203,
3639,
8789,
24363,
18,
81,
474,
12,
2867,
12,
2211,
3631,
8789,
24363,
17631,
1060,
1769,
203,
3639,
2845,
18,
8981,
3769,
24363,
2173,
9535,
273,
2845,
18,
8981,
3769,
24363,
2173,
9535,
18,
1289,
12,
3769,
24363,
17631,
1060,
18,
16411,
12,
21,
73,
2643,
2934,
2892,
12,
9953,
3088,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import { Guild } from "./Guild.sol";
/// @title Staking contract for farming generic rewards in return for staking a whitelisted token(s)
/// @author BlockRocket.tech
/// @notice Fork of MasterChef.sol from SushiSwap
/// @dev Only the owner can add new pools
contract LaunchPoolStakingWithGuild is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/// @dev Details about each user in a pool
struct UserInfo {
uint256 amount; // How many tokens the user has provided to a pool
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of reward tokens
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accRewardPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws ERC20 tokens to a pool. Here's what happens:
// 1. The pool's `accRewardPerShare` (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.
}
/// @dev Info of each pool.
struct PoolInfo {
IERC20 erc20Token; // Address of token contract.
uint256 allocPoint; // How many allocation points assigned to this pool; this is a weighting for rewards.
uint256 lastRewardBlock; // Last block number that reward token distribution has occurred up to endBlock.
uint256 accRewardPerShare; // Per LP token staked, how much reward token earned in pool that users will get
uint256 maxStakingAmountPerUser; // Max. amount of tokens that can be staked per account/user
}
/// @notice Container for holding all rewards
Guild public rewardGuildBank;
/// @notice Number of reward tokens distributed per block, across all pools.
uint256 public rewardPerBlock;
/// @notice The total amount of reward token available for farming across all pools between start and end block.
uint256 public maxRewardTokenAvailableForFarming;
/// @notice List of pools that users can stake into
PoolInfo[] public poolInfo;
/// @notice Per pool, info of each user that stakes ERC20 tokens.
/// @notice Pool ID => User Address => User Info
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
/// @notice Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
/// @notice The block number when rewards starts across all pools.
uint256 public startBlock;
/// @notice The block number when rewards ends.
uint256 public endBlock;
/// @notice Tracks ERC20 tokens added by owner
mapping(address => bool) isErc20TokenWhitelisted;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
/// @param _rewardToken Address of the reward token
/// @param _maxRewardTokenAvailableForFarming Maximum number of reward token that will be distributed between the start and end of farming
/// @param _startBlock Block number when farming will begin for all pools
/// @param _endBlock Block number when farming will end for all pools
constructor(
IERC20 _rewardToken,
uint256 _maxRewardTokenAvailableForFarming,
uint256 _startBlock,
uint256 _endBlock
) public {
require(address(_rewardToken) != address(0), "constructor: _rewardToken must not be zero address");
require(_maxRewardTokenAvailableForFarming > 0, "constructor: _maxRewardTokenAvailableForFarming must be greater than zero");
maxRewardTokenAvailableForFarming = _maxRewardTokenAvailableForFarming;
startBlock = _startBlock;
endBlock = _endBlock;
uint256 numberOfBlocksForFarming = endBlock.sub(startBlock);
rewardPerBlock = maxRewardTokenAvailableForFarming.div(numberOfBlocksForFarming);
rewardGuildBank = new Guild(IERC20(address(_rewardToken)), address(this));
}
/// @notice Returns the number of pools that have been added by the owner
/// @return Number of pools
function numberOfPools() external view returns (uint256) {
return poolInfo.length;
}
/// @notice Create a new reward pool by whitelisting a new ERC20 token.
/// @dev Can only be called by the contract owner
/// @param _allocPoint Governs what percentage of the total rewards this pool and other pools will get
/// @param _erc20Token Address of the staking token being whitelisted
/// @param _maxStakingAmountPerUser For this pool, maximum amount per user that can be staked
/// @param _withUpdate Set to true for updating all pools before adding this one
function add(uint256 _allocPoint, IERC20 _erc20Token, uint256 _maxStakingAmountPerUser, bool _withUpdate) public onlyOwner {
require(block.number < endBlock, "add: must be before end");
address erc20TokenAddress = address(_erc20Token);
require(erc20TokenAddress != address(0), "add: _erc20Token must not be zero address");
require(isErc20TokenWhitelisted[erc20TokenAddress] == false, "add: already whitelisted");
require(_maxStakingAmountPerUser > 0, "add: _maxStakingAmountPerUser must be greater than zero");
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
erc20Token : _erc20Token,
allocPoint : _allocPoint,
lastRewardBlock : lastRewardBlock,
accRewardPerShare : 0,
maxStakingAmountPerUser: _maxStakingAmountPerUser
}));
isErc20TokenWhitelisted[erc20TokenAddress] = true;
}
/// @notice Update a pool's allocation point to increase or decrease its share of contract-level rewards
/// @notice Can also update the max amount that can be staked per user
/// @dev Can only be called by the owner
/// @param _pid ID of the pool being updated
/// @param _allocPoint New allocation point
/// @param _maxStakingAmountPerUser Maximum amount that a user can deposit into the far
/// @param _withUpdate Set to true if you want to update all pools before making this change - it will checkpoint those rewards
function set(uint256 _pid, uint256 _allocPoint, uint256 _maxStakingAmountPerUser, bool _withUpdate) public onlyOwner {
require(block.number < endBlock, "set: must be before end");
require(_pid < poolInfo.length, "set: invalid _pid");
require(_maxStakingAmountPerUser > 0, "set: _maxStakingAmountPerUser must be greater than zero");
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
poolInfo[_pid].maxStakingAmountPerUser = _maxStakingAmountPerUser;
}
/// @notice View function to see pending and unclaimed reward tokens for a given user
/// @param _pid ID of the pool where a user has a stake
/// @param _user Account being queried
/// @return Amount of reward tokens due to a user
function pendingRewards(uint256 _pid, address _user) external view returns (uint256) {
require(_pid < poolInfo.length, "pendingRewards: invalid _pid");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accRewardPerShare = pool.accRewardPerShare;
uint256 lpSupply = pool.erc20Token.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 maxEndBlock = block.number <= endBlock ? block.number : endBlock;
uint256 multiplier = getMultiplier(pool.lastRewardBlock, maxEndBlock);
uint256 reward = multiplier.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accRewardPerShare = accRewardPerShare.add(reward.mul(1e18).div(lpSupply));
}
return user.amount.mul(accRewardPerShare).div(1e18).sub(user.rewardDebt);
}
/// @notice Cycles through the pools to update all of the rewards accrued
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
/// @notice Updates a specific pool to track all of the rewards accrued up to the TX block
/// @param _pid ID of the pool
function updatePool(uint256 _pid) public {
require(_pid < poolInfo.length, "updatePool: invalid _pid");
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 erc20Supply = pool.erc20Token.balanceOf(address(this));
if (erc20Supply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 maxEndBlock = block.number <= endBlock ? block.number : endBlock;
uint256 multiplier = getMultiplier(pool.lastRewardBlock, maxEndBlock);
// No point in doing any more logic as the rewards have ended
if (multiplier == 0) {
return;
}
uint256 reward = multiplier.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
pool.accRewardPerShare = pool.accRewardPerShare.add(reward.mul(1e18).div(erc20Supply));
pool.lastRewardBlock = maxEndBlock;
}
/// @notice Where any user can stake their ERC20 tokens into a pool in order to farm rewards
/// @param _pid ID of the pool
/// @param _amount Amount of ERC20 being staked
function deposit(uint256 _pid, uint256 _amount) external {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount.add(_amount) <= pool.maxStakingAmountPerUser, "deposit: can not exceed max staking amount per user");
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accRewardPerShare).div(1e18).sub(user.rewardDebt);
if (pending > 0) {
safeRewardTransfer(msg.sender, pending);
}
}
if (_amount > 0) {
pool.erc20Token.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accRewardPerShare).div(1e18);
emit Deposit(msg.sender, _pid, _amount);
}
/// @notice Allows a user to withdraw any ERC20 tokens staked in a pool
/// @dev Partial withdrawals permitted
/// @param _pid Pool ID
/// @param _amount Being withdrawn
function withdraw(uint256 _pid, uint256 _amount) external {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: _amount not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accRewardPerShare).div(1e18).sub(user.rewardDebt);
if (pending > 0) {
safeRewardTransfer(msg.sender, pending);
}
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.erc20Token.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accRewardPerShare).div(1e18);
emit Withdraw(msg.sender, _pid, _amount);
}
/// @notice Emergency only. Should the rewards issuance mechanism fail, people can still withdraw their stake
/// @param _pid Pool ID
function emergencyWithdraw(uint256 _pid) external {
require(_pid < poolInfo.length, "updatePool: invalid _pid");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.erc20Token.safeTransfer(address(msg.sender), amount);
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
////////////
// Private /
////////////
/// @dev Safe reward transfer function, just in case if rounding error causes pool to not have enough rewards.
/// @param _to Whom to send reward into
/// @param _amount of reward to send
function safeRewardTransfer(address _to, uint256 _amount) private {
uint256 bal = rewardGuildBank.tokenBalance();
if (_amount > bal) {
rewardGuildBank.withdrawTo(_to, bal);
} else {
rewardGuildBank.withdrawTo(_to, _amount);
}
}
/// @notice Return reward multiplier over the given _from to _to block.
/// @param _from Block number
/// @param _to Block number
/// @return Number of blocks that have passed
function getMultiplier(uint256 _from, uint256 _to) private view returns (uint256) {
return _to.sub(_from);
}
}
// 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;
/**
* @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 Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
contract Guild {
using SafeERC20 for IERC20;
IERC20 public token;
address public stakingContract;
constructor(IERC20 _token, address _stakingContract) public {
token = _token;
stakingContract = _stakingContract;
}
function withdrawTo(address _recipient, uint256 _amount) external {
require(msg.sender == stakingContract, "Guild.withdrawTo: Only staking contract");
token.safeTransfer(_recipient, _amount);
}
function tokenBalance() external returns (uint256) {
return token.balanceOf(address(this));
}
}
// 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;
}
}
| @notice Emergency only. Should the rewards issuance mechanism fail, people can still withdraw their stake @param _pid Pool ID | function emergencyWithdraw(uint256 _pid) external {
require(_pid < poolInfo.length, "updatePool: invalid _pid");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.erc20Token.safeTransfer(address(msg.sender), amount);
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
| 1,641,783 | [
1,
1514,
24530,
1338,
18,
9363,
326,
283,
6397,
3385,
89,
1359,
12860,
2321,
16,
16951,
848,
4859,
598,
9446,
3675,
384,
911,
225,
389,
6610,
8828,
1599,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
801,
24530,
1190,
9446,
12,
11890,
5034,
389,
6610,
13,
3903,
288,
203,
3639,
2583,
24899,
6610,
411,
2845,
966,
18,
2469,
16,
315,
2725,
2864,
30,
2057,
389,
6610,
8863,
203,
203,
3639,
8828,
966,
2502,
2845,
273,
2845,
966,
63,
67,
6610,
15533,
203,
3639,
25003,
2502,
729,
273,
16753,
63,
67,
6610,
6362,
3576,
18,
15330,
15533,
203,
203,
3639,
2254,
5034,
3844,
273,
729,
18,
8949,
31,
203,
3639,
729,
18,
8949,
273,
374,
31,
203,
3639,
729,
18,
266,
2913,
758,
23602,
273,
374,
31,
203,
203,
3639,
2845,
18,
12610,
3462,
1345,
18,
4626,
5912,
12,
2867,
12,
3576,
18,
15330,
3631,
3844,
1769,
203,
3639,
3626,
512,
6592,
75,
2075,
1190,
9446,
12,
3576,
18,
15330,
16,
389,
6610,
16,
3844,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.23;
import './bancor/LimitedTransferBancorSmartToken.sol';
/**
A Token which is 'Bancor' compatible and can mint new tokens and pause token-transfer functionality
*/
contract IPSSmartToken is LimitedTransferBancorSmartToken {
// =================================================================================================================
// Members
// =================================================================================================================
string public name = "IPS.FinTech";
string public symbol = "IPS";
uint8 public decimals = 2;
// =================================================================================================================
// Constructor
// =================================================================================================================
function IPSSmartToken() public {
//Apart of 'Bancor' computability - triggered when a smart token is deployed
NewSmartToken(address(this));
}
}
| Apart of 'Bancor' computability - triggered when a smart token is deployed | A Token which is 'Bancor' compatible and can mint new tokens and pause token-transfer functionality
function IPSSmartToken() public {
NewSmartToken(address(this));
}
| 1,002,597 | [
1,
1294,
485,
434,
296,
38,
304,
3850,
11,
5305,
2967,
300,
10861,
1347,
279,
13706,
1147,
353,
19357,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
432,
3155,
1492,
353,
296,
38,
304,
3850,
11,
7318,
471,
848,
312,
474,
394,
2430,
471,
11722,
1147,
17,
13866,
14176,
203,
565,
445,
2971,
1260,
81,
485,
1345,
1435,
1071,
288,
203,
3639,
1166,
23824,
1345,
12,
2867,
12,
2211,
10019,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./TradingAction.sol";
import "./ActionGuards.sol";
import "./nTokenMintAction.sol";
import "./nTokenRedeemAction.sol";
import "../SettleAssetsExternal.sol";
import "../FreeCollateralExternal.sol";
import "../../math/SafeInt256.sol";
import "../../global/StorageLayoutV1.sol";
import "../../internal/balances/BalanceHandler.sol";
import "../../internal/portfolio/PortfolioHandler.sol";
import "../../internal/AccountContextHandler.sol";
import "../../../interfaces/notional/NotionalCallback.sol";
contract BatchAction is StorageLayoutV1, ActionGuards {
using BalanceHandler for BalanceState;
using PortfolioHandler for PortfolioState;
using AccountContextHandler for AccountContext;
using SafeInt256 for int256;
/// @notice Executes a batch of balance transfers including minting and redeeming nTokens.
/// @param account the account for the action
/// @param actions array of balance actions to take, must be sorted by currency id
/// @dev emit:CashBalanceChange, emit:nTokenSupplyChange
/// @dev auth:msg.sender auth:ERC1155
function batchBalanceAction(address account, BalanceAction[] calldata actions)
external
payable
nonReentrant
{
require(account == msg.sender || msg.sender == address(this), "Unauthorized");
requireValidAccount(account);
// Return any settle amounts here to reduce the number of storage writes to balances
AccountContext memory accountContext = _settleAccountIfRequired(account);
BalanceState memory balanceState;
for (uint256 i = 0; i < actions.length; i++) {
BalanceAction calldata action = actions[i];
// msg.value will only be used when currency id == 1, referencing ETH. The requirement
// to sort actions by increasing id enforces that msg.value will only be used once.
if (i > 0) {
require(action.currencyId > actions[i - 1].currencyId, "Unsorted actions");
}
// Loads the currencyId into balance state
balanceState.loadBalanceState(account, action.currencyId, accountContext);
_executeDepositAction(
account,
balanceState,
action.actionType,
action.depositActionAmount
);
_calculateWithdrawActionAndFinalize(
account,
accountContext,
balanceState,
action.withdrawAmountInternalPrecision,
action.withdrawEntireCashBalance,
action.redeemToUnderlying
);
}
_finalizeAccountContext(account, accountContext);
}
/// @notice Executes a batch of balance transfers and trading actions
/// @param account the account for the action
/// @param actions array of balance actions with trades to take, must be sorted by currency id
/// @dev emit:CashBalanceChange, emit:nTokenSupplyChange, emit:LendBorrowTrade, emit:AddRemoveLiquidity,
/// @dev emit:SettledCashDebt, emit:nTokenResidualPurchase, emit:ReserveFeeAccrued
/// @dev auth:msg.sender auth:ERC1155
function batchBalanceAndTradeAction(address account, BalanceActionWithTrades[] calldata actions)
external
payable
nonReentrant
{
require(account == msg.sender || msg.sender == address(this), "Unauthorized");
requireValidAccount(account);
AccountContext memory accountContext = _batchBalanceAndTradeAction(account, actions);
_finalizeAccountContext(account, accountContext);
}
/// @notice Executes a batch of balance transfers and trading actions via an authorized callback contract. This
/// can be used as a "flash loan" facility for special contracts that migrate assets between protocols or perform
/// other actions on behalf of the user.
/// Contracts can borrow from Notional and receive a callback prior to an FC check, this can be useful if the contract
/// needs to perform a trade or repay a debt on a different protocol before depositing collateral. Since Notional's AMM
/// will never be as capital efficient or gas efficient as other flash loan facilities, this method requires whitelisting
/// and will mainly be used for contracts that make migrating assets a better user experience.
/// @param account the account that will take all the actions
/// @param actions array of balance actions with trades to take, must be sorted by currency id
/// @param callbackData arbitrary bytes to be passed backed to the caller in the callback
/// @dev emit:CashBalanceChange, emit:nTokenSupplyChange, emit:LendBorrowTrade, emit:AddRemoveLiquidity,
/// @dev emit:SettledCashDebt, emit:nTokenResidualPurchase, emit:ReserveFeeAccrued
/// @dev auth:authorizedCallbackContract
function batchBalanceAndTradeActionWithCallback(
address account,
BalanceActionWithTrades[] calldata actions,
bytes calldata callbackData
) external payable {
// NOTE: Re-entrancy is allowed for authorized callback functions.
require(authorizedCallbackContract[msg.sender], "Unauthorized");
requireValidAccount(account);
AccountContext memory accountContext = _batchBalanceAndTradeAction(account, actions);
accountContext.setAccountContext(account);
// Be sure to set the account context before initiating the callback, all stateful updates
// have been finalized at this point so we are safe to issue a callback. This callback may
// re-enter Notional safely to deposit or take other actions.
NotionalCallback(msg.sender).notionalCallback(msg.sender, account, callbackData);
if (accountContext.hasDebt != 0x00) {
// NOTE: this method may update the account context to turn off the hasDebt flag, this
// is ok because the worst case would be causing an extra free collateral check when it
// is not required. This check will be entered if the account hasDebt prior to the callback
// being triggered above, so it will happen regardless of what the callback function does.
FreeCollateralExternal.checkFreeCollateralAndRevert(account);
}
}
function _batchBalanceAndTradeAction(
address account,
BalanceActionWithTrades[] calldata actions
) internal returns (AccountContext memory) {
AccountContext memory accountContext = _settleAccountIfRequired(account);
BalanceState memory balanceState;
// NOTE: loading the portfolio state must happen after settle account to get the
// correct portfolio, it will have changed if the account is settled.
PortfolioState memory portfolioState = PortfolioHandler.buildPortfolioState(
account,
accountContext.assetArrayLength,
0
);
for (uint256 i = 0; i < actions.length; i++) {
BalanceActionWithTrades calldata action = actions[i];
// msg.value will only be used when currency id == 1, referencing ETH. The requirement
// to sort actions by increasing id enforces that msg.value will only be used once.
if (i > 0) {
require(action.currencyId > actions[i - 1].currencyId, "Unsorted actions");
}
// Loads the currencyId into balance state
balanceState.loadBalanceState(account, action.currencyId, accountContext);
// Does not revert on invalid action types here, they also have no effect.
_executeDepositAction(
account,
balanceState,
action.actionType,
action.depositActionAmount
);
if (action.trades.length > 0) {
int256 netCash;
if (accountContext.isBitmapEnabled()) {
require(
accountContext.bitmapCurrencyId == action.currencyId,
"Invalid trades for account"
);
bool didIncurDebt;
(netCash, didIncurDebt) = TradingAction.executeTradesBitmapBatch(
account,
accountContext.bitmapCurrencyId,
accountContext.nextSettleTime,
action.trades
);
if (didIncurDebt) {
accountContext.hasDebt = Constants.HAS_ASSET_DEBT | accountContext.hasDebt;
}
} else {
// NOTE: we return portfolio state here instead of setting it inside executeTradesArrayBatch
// because we want to only write to storage once after all trades are completed
(portfolioState, netCash) = TradingAction.executeTradesArrayBatch(
account,
action.currencyId,
portfolioState,
action.trades
);
}
// If the account owes cash after trading, ensure that it has enough
if (netCash < 0) _checkSufficientCash(balanceState, netCash.neg());
balanceState.netCashChange = balanceState.netCashChange.add(netCash);
}
_calculateWithdrawActionAndFinalize(
account,
accountContext,
balanceState,
action.withdrawAmountInternalPrecision,
action.withdrawEntireCashBalance,
action.redeemToUnderlying
);
}
// Update the portfolio state if bitmap is not enabled. If bitmap is already enabled
// then all the assets have already been updated in in storage.
if (!accountContext.isBitmapEnabled()) {
// NOTE: account context is updated in memory inside this method call.
accountContext.storeAssetsAndUpdateContext(account, portfolioState, false);
}
// NOTE: free collateral and account context will be set outside of this method call.
return accountContext;
}
/// @dev Executes deposits
function _executeDepositAction(
address account,
BalanceState memory balanceState,
DepositActionType depositType,
uint256 depositActionAmount_
) private {
int256 depositActionAmount = SafeInt256.toInt(depositActionAmount_);
int256 assetInternalAmount;
require(depositActionAmount >= 0);
if (depositType == DepositActionType.None) {
return;
} else if (
depositType == DepositActionType.DepositAsset ||
depositType == DepositActionType.DepositAssetAndMintNToken
) {
// NOTE: this deposit will NOT revert on a failed transfer unless there is a
// transfer fee. The actual transfer will take effect later in balanceState.finalize
assetInternalAmount = balanceState.depositAssetToken(
account,
depositActionAmount,
false // no force transfer
);
} else if (
depositType == DepositActionType.DepositUnderlying ||
depositType == DepositActionType.DepositUnderlyingAndMintNToken
) {
// NOTE: this deposit will revert on a failed transfer immediately
assetInternalAmount = balanceState.depositUnderlyingToken(account, depositActionAmount);
} else if (depositType == DepositActionType.ConvertCashToNToken) {
// _executeNTokenAction will check if the account has sufficient cash
assetInternalAmount = depositActionAmount;
}
_executeNTokenAction(
balanceState,
depositType,
depositActionAmount,
assetInternalAmount
);
}
/// @dev Executes nToken actions
function _executeNTokenAction(
BalanceState memory balanceState,
DepositActionType depositType,
int256 depositActionAmount,
int256 assetInternalAmount
) private {
// After deposits have occurred, check if we are minting nTokens
if (
depositType == DepositActionType.DepositAssetAndMintNToken ||
depositType == DepositActionType.DepositUnderlyingAndMintNToken ||
depositType == DepositActionType.ConvertCashToNToken
) {
// Will revert if trying to mint ntokens and results in a negative cash balance
_checkSufficientCash(balanceState, assetInternalAmount);
balanceState.netCashChange = balanceState.netCashChange.sub(assetInternalAmount);
// Converts a given amount of cash (denominated in internal precision) into nTokens
int256 tokensMinted = nTokenMintAction.nTokenMint(
balanceState.currencyId,
assetInternalAmount
);
balanceState.netNTokenSupplyChange = balanceState.netNTokenSupplyChange.add(
tokensMinted
);
} else if (depositType == DepositActionType.RedeemNToken) {
require(
// prettier-ignore
balanceState
.storedNTokenBalance
.add(balanceState.netNTokenTransfer) // transfers would not occur at this point
.add(balanceState.netNTokenSupplyChange) >= depositActionAmount,
"Insufficient token balance"
);
balanceState.netNTokenSupplyChange = balanceState.netNTokenSupplyChange.sub(
depositActionAmount
);
int256 assetCash = nTokenRedeemAction.nTokenRedeemViaBatch(
balanceState.currencyId,
depositActionAmount
);
balanceState.netCashChange = balanceState.netCashChange.add(assetCash);
}
}
/// @dev Calculations any withdraws and finalizes balances
function _calculateWithdrawActionAndFinalize(
address account,
AccountContext memory accountContext,
BalanceState memory balanceState,
uint256 withdrawAmountInternalPrecision,
bool withdrawEntireCashBalance,
bool redeemToUnderlying
) private {
int256 withdrawAmount = SafeInt256.toInt(withdrawAmountInternalPrecision);
require(withdrawAmount >= 0); // dev: withdraw action overflow
// NOTE: if withdrawEntireCashBalance is set it will override the withdrawAmountInternalPrecision input
if (withdrawEntireCashBalance) {
// This option is here so that accounts do not end up with dust after lending since we generally
// cannot calculate exact cash amounts from the liquidity curve.
withdrawAmount = balanceState.storedCashBalance
.add(balanceState.netCashChange)
.add(balanceState.netAssetTransferInternalPrecision);
// If the account has a negative cash balance then cannot withdraw
if (withdrawAmount < 0) withdrawAmount = 0;
}
// prettier-ignore
balanceState.netAssetTransferInternalPrecision = balanceState
.netAssetTransferInternalPrecision
.sub(withdrawAmount);
balanceState.finalize(account, accountContext, redeemToUnderlying);
}
function _finalizeAccountContext(address account, AccountContext memory accountContext)
private
{
// At this point all balances, market states and portfolio states should be finalized. Just need to check free
// collateral if required.
accountContext.setAccountContext(account);
if (accountContext.hasDebt != 0x00) {
FreeCollateralExternal.checkFreeCollateralAndRevert(account);
}
}
/// @notice When lending, adding liquidity or minting nTokens the account must have a sufficient cash balance
/// to do so.
function _checkSufficientCash(BalanceState memory balanceState, int256 amountInternalPrecision)
private
pure
{
// The total cash position at this point is: storedCashBalance + netCashChange + netAssetTransferInternalPrecision
require(
amountInternalPrecision >= 0 &&
balanceState.storedCashBalance
.add(balanceState.netCashChange)
.add(balanceState.netAssetTransferInternalPrecision) >= amountInternalPrecision,
"Insufficient cash"
);
}
function _settleAccountIfRequired(address account)
private
returns (AccountContext memory)
{
AccountContext memory accountContext = AccountContextHandler.getAccountContext(account);
if (accountContext.mustSettleAssets()) {
// Returns a new memory reference to account context
return SettleAssetsExternal.settleAccount(account, accountContext);
} else {
return accountContext;
}
}
/// @notice Get a list of deployed library addresses (sorted by library name)
function getLibInfo() external view returns (address, address, address, address, address, address) {
return (
address(FreeCollateralExternal),
address(MigrateIncentives),
address(SettleAssetsExternal),
address(TradingAction),
address(nTokenMintAction),
address(nTokenRedeemAction)
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../FreeCollateralExternal.sol";
import "../SettleAssetsExternal.sol";
import "../../internal/markets/Market.sol";
import "../../internal/markets/CashGroup.sol";
import "../../internal/markets/AssetRate.sol";
import "../../internal/balances/BalanceHandler.sol";
import "../../internal/portfolio/PortfolioHandler.sol";
import "../../internal/portfolio/TransferAssets.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library TradingAction {
using PortfolioHandler for PortfolioState;
using AccountContextHandler for AccountContext;
using Market for MarketParameters;
using CashGroup for CashGroupParameters;
using AssetRate for AssetRateParameters;
using SafeInt256 for int256;
using SafeMath for uint256;
event LendBorrowTrade(
address indexed account,
uint16 indexed currencyId,
uint40 maturity,
int256 netAssetCash,
int256 netfCash
);
event AddRemoveLiquidity(
address indexed account,
uint16 indexed currencyId,
uint40 maturity,
int256 netAssetCash,
int256 netfCash,
int256 netLiquidityTokens
);
event SettledCashDebt(
address indexed settledAccount,
uint16 indexed currencyId,
address indexed settler,
int256 amountToSettleAsset,
int256 fCashAmount
);
event nTokenResidualPurchase(
uint16 indexed currencyId,
uint40 indexed maturity,
address indexed purchaser,
int256 fCashAmountToPurchase,
int256 netAssetCashNToken
);
/// @dev Used internally to manage stack issues
struct TradeContext {
int256 cash;
int256 fCashAmount;
int256 fee;
int256 netCash;
int256 totalFee;
uint256 blockTime;
}
/// @notice Executes trades for a bitmapped portfolio, cannot be called directly
/// @param account account to put fCash assets in
/// @param bitmapCurrencyId currency id of the bitmap
/// @param nextSettleTime used to calculate the relative positions in the bitmap
/// @param trades tightly packed array of trades, schema is defined in global/Types.sol
/// @return netCash generated by trading
/// @return didIncurDebt if the bitmap had an fCash position go negative
function executeTradesBitmapBatch(
address account,
uint16 bitmapCurrencyId,
uint40 nextSettleTime,
bytes32[] calldata trades
) external returns (int256, bool) {
CashGroupParameters memory cashGroup = CashGroup.buildCashGroupStateful(bitmapCurrencyId);
MarketParameters memory market;
bool didIncurDebt;
TradeContext memory c;
c.blockTime = block.timestamp;
for (uint256 i = 0; i < trades.length; i++) {
uint256 maturity;
(maturity, c.cash, c.fCashAmount) = _executeTrade(
account,
cashGroup,
market,
trades[i],
c.blockTime
);
c.fCashAmount = BitmapAssetsHandler.addifCashAsset(
account,
bitmapCurrencyId,
maturity,
nextSettleTime,
c.fCashAmount
);
didIncurDebt = didIncurDebt || (c.fCashAmount < 0);
c.netCash = c.netCash.add(c.cash);
}
return (c.netCash, didIncurDebt);
}
/// @notice Executes trades for a bitmapped portfolio, cannot be called directly
/// @param account account to put fCash assets in
/// @param currencyId currency id to trade
/// @param portfolioState used to update the positions in the portfolio
/// @param trades tightly packed array of trades, schema is defined in global/Types.sol
/// @return resulting portfolio state
/// @return netCash generated by trading
function executeTradesArrayBatch(
address account,
uint16 currencyId,
PortfolioState memory portfolioState,
bytes32[] calldata trades
) external returns (PortfolioState memory, int256) {
CashGroupParameters memory cashGroup = CashGroup.buildCashGroupStateful(currencyId);
MarketParameters memory market;
TradeContext memory c;
c.blockTime = block.timestamp;
for (uint256 i = 0; i < trades.length; i++) {
TradeActionType tradeType = TradeActionType(uint256(uint8(bytes1(trades[i]))));
if (
tradeType == TradeActionType.AddLiquidity ||
tradeType == TradeActionType.RemoveLiquidity
) {
revert("Disabled");
/**
* Manual adding and removing of liquidity is currently disabled.
*
* // Liquidity tokens can only be added by array portfolio
* c.cash = _executeLiquidityTrade(
* account,
* cashGroup,
* market,
* tradeType,
* trades[i],
* portfolioState,
* c.netCash
* );
*/
} else {
uint256 maturity;
(maturity, c.cash, c.fCashAmount) = _executeTrade(
account,
cashGroup,
market,
trades[i],
c.blockTime
);
portfolioState.addAsset(
currencyId,
maturity,
Constants.FCASH_ASSET_TYPE,
c.fCashAmount
);
}
c.netCash = c.netCash.add(c.cash);
}
return (portfolioState, c.netCash);
}
/// @notice Executes a non-liquidity token trade
/// @param account the initiator of the trade
/// @param cashGroup parameters for the trade
/// @param market market memory location to use
/// @param trade bytes32 encoding of the particular trade
/// @param blockTime the current block time
/// @return maturity of the asset that was traded
/// @return cashAmount - a positive or negative cash amount accrued to the account
/// @return fCashAmount - a positive or negative fCash amount accrued to the account
function _executeTrade(
address account,
CashGroupParameters memory cashGroup,
MarketParameters memory market,
bytes32 trade,
uint256 blockTime
)
private
returns (
uint256 maturity,
int256 cashAmount,
int256 fCashAmount
)
{
TradeActionType tradeType = TradeActionType(uint256(uint8(bytes1(trade))));
if (tradeType == TradeActionType.PurchaseNTokenResidual) {
(maturity, cashAmount, fCashAmount) = _purchaseNTokenResidual(
account,
cashGroup,
blockTime,
trade
);
} else if (tradeType == TradeActionType.SettleCashDebt) {
(maturity, cashAmount, fCashAmount) = _settleCashDebt(account, cashGroup, blockTime, trade);
} else if (tradeType == TradeActionType.Lend || tradeType == TradeActionType.Borrow) {
(cashAmount, fCashAmount) = _executeLendBorrowTrade(
cashGroup,
market,
tradeType,
blockTime,
trade
);
// This is a little ugly but required to deal with stack issues. We know the market is loaded
// with the proper maturity inside _executeLendBorrowTrade
maturity = market.maturity;
emit LendBorrowTrade(
account,
uint16(cashGroup.currencyId),
uint40(maturity),
cashAmount,
fCashAmount
);
} else {
revert("Invalid trade type");
}
}
/// @notice Executes a liquidity token trade, no fees incurred and only array portfolios may hold
/// liquidity tokens.
/// @param account the initiator of the trade
/// @param cashGroup parameters for the trade
/// @param market market memory location to use
/// @param tradeType whether this is add or remove liquidity
/// @param trade bytes32 encoding of the particular trade
/// @param portfolioState the current account's portfolio state
/// @param netCash the current net cash accrued in this batch of trades, can be
// used for adding liquidity
/// @return cashAmount: a positive or negative cash amount accrued to the account
function _executeLiquidityTrade(
address account,
CashGroupParameters memory cashGroup,
MarketParameters memory market,
TradeActionType tradeType,
bytes32 trade,
PortfolioState memory portfolioState,
int256 netCash
) private returns (int256) {
uint256 marketIndex = uint8(bytes1(trade << 8));
// NOTE: this loads the market in memory
cashGroup.loadMarket(market, marketIndex, true, block.timestamp);
int256 cashAmount;
int256 fCashAmount;
int256 tokens;
if (tradeType == TradeActionType.AddLiquidity) {
cashAmount = int256((uint256(trade) >> 152) & type(uint88).max);
// Setting cash amount to zero will deposit all net cash accumulated in this trade into
// liquidity. This feature allows accounts to borrow in one maturity to provide liquidity
// in another in a single transaction without dust. It also allows liquidity providers to
// sell off the net cash residuals and use the cash amount in the new market without dust
if (cashAmount == 0) cashAmount = netCash;
// Add liquidity will check cash amount is positive
(tokens, fCashAmount) = market.addLiquidity(cashAmount);
cashAmount = cashAmount.neg(); // Report a negative cash amount in the event
} else {
tokens = int256((uint256(trade) >> 152) & type(uint88).max);
(cashAmount, fCashAmount) = market.removeLiquidity(tokens);
tokens = tokens.neg(); // Report a negative amount tokens in the event
}
{
uint256 minImpliedRate = uint32(uint256(trade) >> 120);
uint256 maxImpliedRate = uint32(uint256(trade) >> 88);
// If minImpliedRate is not set then it will be zero
require(market.lastImpliedRate >= minImpliedRate, "Trade failed, slippage");
if (maxImpliedRate != 0)
require(market.lastImpliedRate <= maxImpliedRate, "Trade failed, slippage");
}
// Add the assets in this order so they are sorted
portfolioState.addAsset(
cashGroup.currencyId,
market.maturity,
Constants.FCASH_ASSET_TYPE,
fCashAmount
);
// Adds the liquidity token asset
portfolioState.addAsset(
cashGroup.currencyId,
market.maturity,
marketIndex + 1,
tokens
);
emit AddRemoveLiquidity(
account,
cashGroup.currencyId,
// This will not overflow for a long time
uint40(market.maturity),
cashAmount,
fCashAmount,
tokens
);
return cashAmount;
}
/// @notice Executes a lend or borrow trade
/// @param cashGroup parameters for the trade
/// @param market market memory location to use
/// @param tradeType whether this is add or remove liquidity
/// @param blockTime the current block time
/// @param trade bytes32 encoding of the particular trade
/// @return cashAmount - a positive or negative cash amount accrued to the account
/// @return fCashAmount - a positive or negative fCash amount accrued to the account
function _executeLendBorrowTrade(
CashGroupParameters memory cashGroup,
MarketParameters memory market,
TradeActionType tradeType,
uint256 blockTime,
bytes32 trade
)
private
returns (
int256 cashAmount,
int256 fCashAmount
)
{
uint256 marketIndex = uint256(uint8(bytes1(trade << 8)));
// NOTE: this updates the market in memory
cashGroup.loadMarket(market, marketIndex, false, blockTime);
fCashAmount = int256(uint88(bytes11(trade << 16)));
// fCash to account will be negative here
if (tradeType == TradeActionType.Borrow) fCashAmount = fCashAmount.neg();
cashAmount = market.executeTrade(
cashGroup,
fCashAmount,
market.maturity.sub(blockTime),
marketIndex
);
require(cashAmount != 0, "Trade failed, liquidity");
uint256 rateLimit = uint256(uint32(bytes4(trade << 104)));
if (rateLimit != 0) {
if (tradeType == TradeActionType.Borrow) {
// Do not allow borrows over the rate limit
require(market.lastImpliedRate <= rateLimit, "Trade failed, slippage");
} else {
// Do not allow lends under the rate limit
require(market.lastImpliedRate >= rateLimit, "Trade failed, slippage");
}
}
}
/// @notice If an account has a negative cash balance we allow anyone to lend to to that account at a penalty
/// rate to the 3 month market.
/// @param account the account initiating the trade, used to check that self settlement is not possible
/// @param cashGroup parameters for the trade
/// @param blockTime the current block time
/// @param trade bytes32 encoding of the particular trade
/// @return maturity: the date of the three month maturity where fCash will be exchanged
/// @return cashAmount: a negative cash amount that the account must pay to the settled account
/// @return fCashAmount: a positive fCash amount that the account will receive
function _settleCashDebt(
address account,
CashGroupParameters memory cashGroup,
uint256 blockTime,
bytes32 trade
)
internal
returns (
uint256,
int256,
int256
)
{
address counterparty = address(uint256(trade) >> 88);
// Allowing an account to settle itself would result in strange outcomes
require(account != counterparty, "Cannot settle self");
int256 amountToSettleAsset = int256(uint88(uint256(trade)));
AccountContext memory counterpartyContext =
AccountContextHandler.getAccountContext(counterparty);
if (counterpartyContext.mustSettleAssets()) {
counterpartyContext = SettleAssetsExternal.settleAccount(counterparty, counterpartyContext);
}
// This will check if the amountToSettleAsset is valid and revert if it is not. Amount to settle is a positive
// number denominated in asset terms. If amountToSettleAsset is set equal to zero on the input, will return the
// max amount to settle. This will update the balance storage on the counterparty.
amountToSettleAsset = BalanceHandler.setBalanceStorageForSettleCashDebt(
counterparty,
cashGroup,
amountToSettleAsset,
counterpartyContext
);
// Settled account must borrow from the 3 month market at a penalty rate. This will fail if the market
// is not initialized.
uint256 threeMonthMaturity = DateTime.getReferenceTime(blockTime) + Constants.QUARTER;
int256 fCashAmount =
_getfCashSettleAmount(cashGroup, threeMonthMaturity, blockTime, amountToSettleAsset);
// Defensive check to ensure that we can't inadvertently cause the settler to lose fCash.
require(fCashAmount >= 0);
// It's possible that this action will put an account into negative free collateral. In this case they
// will immediately become eligible for liquidation and the account settling the debt can also liquidate
// them in the same transaction. Do not run a free collateral check here to allow this to happen.
{
PortfolioAsset[] memory assets = new PortfolioAsset[](1);
assets[0].currencyId = cashGroup.currencyId;
assets[0].maturity = threeMonthMaturity;
assets[0].notional = fCashAmount.neg(); // This is the debt the settled account will incur
assets[0].assetType = Constants.FCASH_ASSET_TYPE;
// Can transfer assets, we have settled above
counterpartyContext = TransferAssets.placeAssetsInAccount(
counterparty,
counterpartyContext,
assets
);
}
counterpartyContext.setAccountContext(counterparty);
emit SettledCashDebt(
counterparty,
uint16(cashGroup.currencyId),
account,
amountToSettleAsset,
fCashAmount.neg()
);
return (threeMonthMaturity, amountToSettleAsset.neg(), fCashAmount);
}
/// @dev Helper method to calculate the fCashAmount from the penalty settlement rate
function _getfCashSettleAmount(
CashGroupParameters memory cashGroup,
uint256 threeMonthMaturity,
uint256 blockTime,
int256 amountToSettleAsset
) private view returns (int256) {
uint256 oracleRate = cashGroup.calculateOracleRate(threeMonthMaturity, blockTime);
int256 exchangeRate =
Market.getExchangeRateFromImpliedRate(
oracleRate.add(cashGroup.getSettlementPenalty()),
threeMonthMaturity.sub(blockTime)
);
// Amount to settle is positive, this returns the fCashAmount that the settler will
// receive as a positive number
return
cashGroup.assetRate
.convertToUnderlying(amountToSettleAsset)
// Exchange rate converts from cash to fCash when multiplying
.mulInRatePrecision(exchangeRate);
}
/// @notice Allows an account to purchase ntoken residuals
/// @param purchaser account that is purchasing the residuals
/// @param cashGroup parameters for the trade
/// @param blockTime the current block time
/// @param trade bytes32 encoding of the particular trade
/// @return maturity: the date of the idiosyncratic maturity where fCash will be exchanged
/// @return cashAmount: a positive or negative cash amount that the account will receive or pay
/// @return fCashAmount: a positive or negative fCash amount that the account will receive
function _purchaseNTokenResidual(
address purchaser,
CashGroupParameters memory cashGroup,
uint256 blockTime,
bytes32 trade
)
internal
returns (
uint256,
int256,
int256
)
{
uint256 maturity = uint256(uint32(uint256(trade) >> 216));
int256 fCashAmountToPurchase = int88(uint88(uint256(trade) >> 128));
require(maturity > blockTime, "Invalid maturity");
// Require that the residual to purchase does not fall on an existing maturity (i.e.
// it is an idiosyncratic maturity)
require(
!DateTime.isValidMarketMaturity(cashGroup.maxMarketIndex, maturity, blockTime),
"Non idiosyncratic maturity"
);
address nTokenAddress = nTokenHandler.nTokenAddress(cashGroup.currencyId);
// prettier-ignore
(
/* currencyId */,
/* incentiveRate */,
uint256 lastInitializedTime,
/* assetArrayLength */,
bytes5 parameters
) = nTokenHandler.getNTokenContext(nTokenAddress);
// Restrict purchasing until some amount of time after the last initialized time to ensure that arbitrage
// opportunities are not available (by generating residuals and then immediately purchasing them at a discount)
// This is always relative to the last initialized time which is set at utc0 when initialized, not the
// reference time. Therefore we will always restrict residual purchase relative to initialization, not reference.
// This is safer, prevents an attack if someone forces residuals and then somehow prevents market initialization
// until the residual time buffer passes.
require(
blockTime >
lastInitializedTime.add(
uint256(uint8(parameters[Constants.RESIDUAL_PURCHASE_TIME_BUFFER])) * 1 hours
),
"Insufficient block time"
);
int256 notional =
BitmapAssetsHandler.getifCashNotional(nTokenAddress, cashGroup.currencyId, maturity);
// Check if amounts are valid and set them to the max available if necessary
if (notional < 0 && fCashAmountToPurchase < 0) {
// Does not allow purchasing more negative notional than available
if (fCashAmountToPurchase < notional) fCashAmountToPurchase = notional;
} else if (notional > 0 && fCashAmountToPurchase > 0) {
// Does not allow purchasing more positive notional than available
if (fCashAmountToPurchase > notional) fCashAmountToPurchase = notional;
} else {
// Does not allow moving notional in the opposite direction
revert("Invalid amount");
}
// If fCashAmount > 0 then this will return netAssetCash > 0, if fCashAmount < 0 this will return
// netAssetCash < 0. fCashAmount will go to the purchaser and netAssetCash will go to the nToken.
int256 netAssetCashNToken =
_getResidualPriceAssetCash(
cashGroup,
maturity,
blockTime,
fCashAmountToPurchase,
parameters
);
_updateNTokenPortfolio(
nTokenAddress,
cashGroup.currencyId,
maturity,
lastInitializedTime,
fCashAmountToPurchase,
netAssetCashNToken
);
emit nTokenResidualPurchase(
uint16(cashGroup.currencyId),
uint40(maturity),
purchaser,
fCashAmountToPurchase,
netAssetCashNToken
);
return (maturity, netAssetCashNToken.neg(), fCashAmountToPurchase);
}
/// @notice Returns the amount of asset cash required to purchase the nToken residual
function _getResidualPriceAssetCash(
CashGroupParameters memory cashGroup,
uint256 maturity,
uint256 blockTime,
int256 fCashAmount,
bytes6 parameters
) internal view returns (int256) {
uint256 oracleRate = cashGroup.calculateOracleRate(maturity, blockTime);
// Residual purchase incentive is specified in ten basis point increments
uint256 purchaseIncentive =
uint256(uint8(parameters[Constants.RESIDUAL_PURCHASE_INCENTIVE])) *
Constants.TEN_BASIS_POINTS;
if (fCashAmount > 0) {
// When fCash is positive then we add the purchase incentive, the purchaser
// can pay less cash for the fCash relative to the oracle rate
oracleRate = oracleRate.add(purchaseIncentive);
} else if (oracleRate > purchaseIncentive) {
// When fCash is negative, we reduce the interest rate that the purchaser will
// borrow at, we do this check to ensure that we floor the oracle rate at zero.
oracleRate = oracleRate.sub(purchaseIncentive);
} else {
// If the oracle rate is less than the purchase incentive floor the interest rate at zero
oracleRate = 0;
}
int256 exchangeRate =
Market.getExchangeRateFromImpliedRate(oracleRate, maturity.sub(blockTime));
// Returns the net asset cash from the nToken perspective, which is the same sign as the fCash amount
return
cashGroup.assetRate.convertFromUnderlying(fCashAmount.divInRatePrecision(exchangeRate));
}
function _updateNTokenPortfolio(
address nTokenAddress,
uint256 currencyId,
uint256 maturity,
uint256 lastInitializedTime,
int256 fCashAmountToPurchase,
int256 netAssetCashNToken
) private {
int256 finalNotional = BitmapAssetsHandler.addifCashAsset(
nTokenAddress,
currencyId,
maturity,
lastInitializedTime,
fCashAmountToPurchase.neg() // the nToken takes on the negative position
);
// Defensive check to ensure that fCash amounts do not flip signs
require(
(fCashAmountToPurchase > 0 && finalNotional >= 0) ||
(fCashAmountToPurchase < 0 && finalNotional <= 0)
);
// prettier-ignore
(
int256 nTokenCashBalance,
/* storedNTokenBalance */,
/* lastClaimTime */,
/* accountIncentiveDebt */
) = BalanceHandler.getBalanceStorage(nTokenAddress, currencyId);
nTokenCashBalance = nTokenCashBalance.add(netAssetCashNToken);
// This will ensure that the cash balance is not negative
BalanceHandler.setBalanceStorageForNToken(nTokenAddress, currencyId, nTokenCashBalance);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/StorageLayoutV1.sol";
import "../../internal/nToken/nTokenHandler.sol";
abstract contract ActionGuards is StorageLayoutV1 {
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
function initializeReentrancyGuard() internal {
require(reentrancyStatus == 0);
// Initialize the guard to a non-zero value, see the OZ reentrancy guard
// description for why this is more gas efficient:
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol
reentrancyStatus = _NOT_ENTERED;
}
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(reentrancyStatus != _ENTERED, "Reentrant call");
// Any calls to nonReentrant after this point will fail
reentrancyStatus = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
reentrancyStatus = _NOT_ENTERED;
}
// These accounts cannot receive deposits, transfers, fCash or any other
// types of value transfers.
function requireValidAccount(address account) internal view {
require(account != Constants.RESERVE); // Reserve address is address(0)
require(account != address(this));
(
uint256 isNToken,
/* incentiveAnnualEmissionRate */,
/* lastInitializedTime */,
/* assetArrayLength */,
/* parameters */
) = nTokenHandler.getNTokenContext(account);
require(isNToken == 0);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/Constants.sol";
import "../../internal/nToken/nTokenHandler.sol";
import "../../internal/nToken/nTokenCalculations.sol";
import "../../internal/markets/Market.sol";
import "../../internal/markets/CashGroup.sol";
import "../../internal/markets/AssetRate.sol";
import "../../internal/balances/BalanceHandler.sol";
import "../../internal/portfolio/PortfolioHandler.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library nTokenMintAction {
using SafeInt256 for int256;
using BalanceHandler for BalanceState;
using CashGroup for CashGroupParameters;
using Market for MarketParameters;
using nTokenHandler for nTokenPortfolio;
using PortfolioHandler for PortfolioState;
using AssetRate for AssetRateParameters;
using SafeMath for uint256;
using nTokenHandler for nTokenPortfolio;
/// @notice Converts the given amount of cash to nTokens in the same currency.
/// @param currencyId the currency associated the nToken
/// @param amountToDepositInternal the amount of asset tokens to deposit denominated in internal decimals
/// @return nTokens minted by this action
function nTokenMint(uint16 currencyId, int256 amountToDepositInternal)
external
returns (int256)
{
uint256 blockTime = block.timestamp;
nTokenPortfolio memory nToken;
nToken.loadNTokenPortfolioStateful(currencyId);
int256 tokensToMint = calculateTokensToMint(nToken, amountToDepositInternal, blockTime);
require(tokensToMint >= 0, "Invalid token amount");
if (nToken.portfolioState.storedAssets.length == 0) {
// If the token does not have any assets, then the markets must be initialized first.
nToken.cashBalance = nToken.cashBalance.add(amountToDepositInternal);
BalanceHandler.setBalanceStorageForNToken(
nToken.tokenAddress,
currencyId,
nToken.cashBalance
);
} else {
_depositIntoPortfolio(nToken, amountToDepositInternal, blockTime);
}
// NOTE: token supply does not change here, it will change after incentives have been claimed
// during BalanceHandler.finalize
return tokensToMint;
}
/// @notice Calculates the tokens to mint to the account as a ratio of the nToken
/// present value denominated in asset cash terms.
/// @return the amount of tokens to mint, the ifCash bitmap
function calculateTokensToMint(
nTokenPortfolio memory nToken,
int256 amountToDepositInternal,
uint256 blockTime
) internal view returns (int256) {
require(amountToDepositInternal >= 0); // dev: deposit amount negative
if (amountToDepositInternal == 0) return 0;
if (nToken.lastInitializedTime != 0) {
// For the sake of simplicity, nTokens cannot be minted if they have assets
// that need to be settled. This is only done during market initialization.
uint256 nextSettleTime = nToken.getNextSettleTime();
// If next settle time <= blockTime then the token can be settled
require(nextSettleTime > blockTime, "Requires settlement");
}
int256 assetCashPV = nTokenCalculations.getNTokenAssetPV(nToken, blockTime);
// Defensive check to ensure PV remains positive
require(assetCashPV >= 0);
// Allow for the first deposit
if (nToken.totalSupply == 0) {
return amountToDepositInternal;
} else {
// assetCashPVPost = assetCashPV + amountToDeposit
// (tokenSupply + tokensToMint) / tokenSupply == (assetCashPV + amountToDeposit) / assetCashPV
// (tokenSupply + tokensToMint) == (assetCashPV + amountToDeposit) * tokenSupply / assetCashPV
// (tokenSupply + tokensToMint) == tokenSupply + (amountToDeposit * tokenSupply) / assetCashPV
// tokensToMint == (amountToDeposit * tokenSupply) / assetCashPV
return amountToDepositInternal.mul(nToken.totalSupply).div(assetCashPV);
}
}
/// @notice Portions out assetCashDeposit into amounts to deposit into individual markets. When
/// entering this method we know that assetCashDeposit is positive and the nToken has been
/// initialized to have liquidity tokens.
function _depositIntoPortfolio(
nTokenPortfolio memory nToken,
int256 assetCashDeposit,
uint256 blockTime
) private {
(int256[] memory depositShares, int256[] memory leverageThresholds) =
nTokenHandler.getDepositParameters(
nToken.cashGroup.currencyId,
nToken.cashGroup.maxMarketIndex
);
// Loop backwards from the last market to the first market, the reasoning is a little complicated:
// If we have to deleverage the markets (i.e. lend instead of provide liquidity) it's quite gas inefficient
// to calculate the cash amount to lend. We do know that longer term maturities will have more
// slippage and therefore the residual from the perMarketDeposit will be lower as the maturities get
// closer to the current block time. Any residual cash from lending will be rolled into shorter
// markets as this loop progresses.
int256 residualCash;
MarketParameters memory market;
for (uint256 marketIndex = nToken.cashGroup.maxMarketIndex; marketIndex > 0; marketIndex--) {
int256 fCashAmount;
// Loads values into the market memory slot
nToken.cashGroup.loadMarket(
market,
marketIndex,
true, // Needs liquidity to true
blockTime
);
// If market has not been initialized, continue. This can occur when cash groups extend maxMarketIndex
// before initializing
if (market.totalLiquidity == 0) continue;
// Checked that assetCashDeposit must be positive before entering
int256 perMarketDeposit =
assetCashDeposit
.mul(depositShares[marketIndex - 1])
.div(Constants.DEPOSIT_PERCENT_BASIS)
.add(residualCash);
(fCashAmount, residualCash) = _lendOrAddLiquidity(
nToken,
market,
perMarketDeposit,
leverageThresholds[marketIndex - 1],
marketIndex,
blockTime
);
if (fCashAmount != 0) {
BitmapAssetsHandler.addifCashAsset(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
market.maturity,
nToken.lastInitializedTime,
fCashAmount
);
}
}
// nToken is allowed to store assets directly without updating account context.
nToken.portfolioState.storeAssets(nToken.tokenAddress);
// Defensive check to ensure that we do not somehow accrue negative residual cash.
require(residualCash >= 0, "Negative residual cash");
// This will occur if the three month market is over levered and we cannot lend into it
if (residualCash > 0) {
// Any remaining residual cash will be put into the nToken balance and added as liquidity on the
// next market initialization
nToken.cashBalance = nToken.cashBalance.add(residualCash);
BalanceHandler.setBalanceStorageForNToken(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.cashBalance
);
}
}
/// @notice For a given amount of cash to deposit, decides how much to lend or provide
/// given the market conditions.
function _lendOrAddLiquidity(
nTokenPortfolio memory nToken,
MarketParameters memory market,
int256 perMarketDeposit,
int256 leverageThreshold,
uint256 marketIndex,
uint256 blockTime
) private returns (int256 fCashAmount, int256 residualCash) {
// We start off with the entire per market deposit as residuals
residualCash = perMarketDeposit;
// If the market is over leveraged then we will lend to it instead of providing liquidity
if (_isMarketOverLeveraged(nToken.cashGroup, market, leverageThreshold)) {
(residualCash, fCashAmount) = _deleverageMarket(
nToken.cashGroup,
market,
perMarketDeposit,
blockTime,
marketIndex
);
// Recalculate this after lending into the market, if it is still over leveraged then
// we will not add liquidity and just exit.
if (_isMarketOverLeveraged(nToken.cashGroup, market, leverageThreshold)) {
// Returns the residual cash amount
return (fCashAmount, residualCash);
}
}
// Add liquidity to the market only if we have successfully delevered.
// (marketIndex - 1) is the index of the nToken portfolio array where the asset is stored
// If deleveraged, residualCash is what remains
// If not deleveraged, residual cash is per market deposit
fCashAmount = fCashAmount.add(
_addLiquidityToMarket(nToken, market, marketIndex - 1, residualCash)
);
// No residual cash if we're adding liquidity
return (fCashAmount, 0);
}
/// @notice Markets are over levered when their proportion is greater than a governance set
/// threshold. At this point, providing liquidity will incur too much negative fCash on the nToken
/// account for the given amount of cash deposited, putting the nToken account at risk of liquidation.
/// If the market is over leveraged, we call `deleverageMarket` to lend to the market instead.
function _isMarketOverLeveraged(
CashGroupParameters memory cashGroup,
MarketParameters memory market,
int256 leverageThreshold
) private pure returns (bool) {
int256 totalCashUnderlying = cashGroup.assetRate.convertToUnderlying(market.totalAssetCash);
// Comparison we want to do:
// (totalfCash) / (totalfCash + totalCashUnderlying) > leverageThreshold
// However, the division will introduce rounding errors so we change this to:
// totalfCash * RATE_PRECISION > leverageThreshold * (totalfCash + totalCashUnderlying)
// Leverage threshold is denominated in rate precision.
return (
market.totalfCash.mul(Constants.RATE_PRECISION) >
leverageThreshold.mul(market.totalfCash.add(totalCashUnderlying))
);
}
function _addLiquidityToMarket(
nTokenPortfolio memory nToken,
MarketParameters memory market,
uint256 index,
int256 perMarketDeposit
) private returns (int256) {
// Add liquidity to the market
PortfolioAsset memory asset = nToken.portfolioState.storedAssets[index];
// We expect that all the liquidity tokens are in the portfolio in order.
require(
asset.maturity == market.maturity &&
// Ensures that the asset type references the proper liquidity token
asset.assetType == index + Constants.MIN_LIQUIDITY_TOKEN_INDEX &&
// Ensures that the storage state will not be overwritten
asset.storageState == AssetStorageState.NoChange,
"PT: invalid liquidity token"
);
// This will update the market state as well, fCashAmount returned here is negative
(int256 liquidityTokens, int256 fCashAmount) = market.addLiquidity(perMarketDeposit);
asset.notional = asset.notional.add(liquidityTokens);
asset.storageState = AssetStorageState.Update;
return fCashAmount;
}
/// @notice Lends into the market to reduce the leverage that the nToken will add liquidity at. May fail due
/// to slippage or result in some amount of residual cash.
function _deleverageMarket(
CashGroupParameters memory cashGroup,
MarketParameters memory market,
int256 perMarketDeposit,
uint256 blockTime,
uint256 marketIndex
) private returns (int256, int256) {
uint256 timeToMaturity = market.maturity.sub(blockTime);
// Shift the last implied rate by some buffer and calculate the exchange rate to fCash. Hope that this
// is sufficient to cover all potential slippage. We don't use the `getfCashGivenCashAmount` method here
// because it is very gas inefficient.
int256 assumedExchangeRate;
if (market.lastImpliedRate < Constants.DELEVERAGE_BUFFER) {
// Floor the exchange rate at zero interest rate
assumedExchangeRate = Constants.RATE_PRECISION;
} else {
assumedExchangeRate = Market.getExchangeRateFromImpliedRate(
market.lastImpliedRate.sub(Constants.DELEVERAGE_BUFFER),
timeToMaturity
);
}
int256 fCashAmount;
{
int256 perMarketDepositUnderlying =
cashGroup.assetRate.convertToUnderlying(perMarketDeposit);
// NOTE: cash * exchangeRate = fCash
fCashAmount = perMarketDepositUnderlying.mulInRatePrecision(assumedExchangeRate);
}
int256 netAssetCash = market.executeTrade(cashGroup, fCashAmount, timeToMaturity, marketIndex);
// This means that the trade failed
if (netAssetCash == 0) {
return (perMarketDeposit, 0);
} else {
// Ensure that net the per market deposit figure does not drop below zero, this should not be possible
// given how we've calculated the exchange rate but extra caution here
int256 residual = perMarketDeposit.add(netAssetCash);
require(residual >= 0); // dev: insufficient cash
return (residual, fCashAmount);
}
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../internal/markets/Market.sol";
import "../../internal/nToken/nTokenHandler.sol";
import "../../internal/nToken/nTokenCalculations.sol";
import "../../internal/portfolio/PortfolioHandler.sol";
import "../../internal/portfolio/TransferAssets.sol";
import "../../internal/balances/BalanceHandler.sol";
import "../../math/SafeInt256.sol";
import "../../math/Bitmap.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library nTokenRedeemAction {
using SafeInt256 for int256;
using SafeMath for uint256;
using Bitmap for bytes32;
using BalanceHandler for BalanceState;
using Market for MarketParameters;
using CashGroup for CashGroupParameters;
using PortfolioHandler for PortfolioState;
using nTokenHandler for nTokenPortfolio;
/// @notice When redeeming nTokens via the batch they must all be sold to cash and this
/// method will return the amount of asset cash sold.
/// @param currencyId the currency associated the nToken
/// @param tokensToRedeem the amount of nTokens to convert to cash
/// @return amount of asset cash to return to the account, denominated in internal token decimals
function nTokenRedeemViaBatch(uint16 currencyId, int256 tokensToRedeem)
external
returns (int256)
{
uint256 blockTime = block.timestamp;
// prettier-ignore
(
int256 totalAssetCash,
bool hasResidual,
/* PortfolioAssets[] memory newfCashAssets */
) = _redeem(currencyId, tokensToRedeem, true, false, blockTime);
require(!hasResidual, "Cannot redeem via batch, residual");
return totalAssetCash;
}
/// @notice Redeems nTokens for asset cash and fCash
/// @param currencyId the currency associated the nToken
/// @param tokensToRedeem the amount of nTokens to convert to cash
/// @param sellTokenAssets attempt to sell residual fCash and convert to cash, if unsuccessful then place
/// back into the account's portfolio
/// @param acceptResidualAssets if true, then ifCash residuals will be placed into the account and there will
/// be no penalty assessed
/// @return assetCash positive amount of asset cash to the account
/// @return hasResidual true if there are fCash residuals left
/// @return assets an array of fCash asset residuals to place into the account
function redeem(
uint16 currencyId,
int256 tokensToRedeem,
bool sellTokenAssets,
bool acceptResidualAssets
) external returns (int256, bool, PortfolioAsset[] memory) {
return _redeem(
currencyId,
tokensToRedeem,
sellTokenAssets,
acceptResidualAssets,
block.timestamp
);
}
function _redeem(
uint16 currencyId,
int256 tokensToRedeem,
bool sellTokenAssets,
bool acceptResidualAssets,
uint256 blockTime
) internal returns (int256, bool, PortfolioAsset[] memory) {
require(tokensToRedeem > 0);
nTokenPortfolio memory nToken;
nToken.loadNTokenPortfolioStateful(currencyId);
// nTokens cannot be redeemed during the period of time where they require settlement.
require(nToken.getNextSettleTime() > blockTime, "Requires settlement");
require(tokensToRedeem < nToken.totalSupply, "Cannot redeem");
PortfolioAsset[] memory newifCashAssets;
// Get the ifCash bits that are idiosyncratic
bytes32 ifCashBits = nTokenCalculations.getNTokenifCashBits(
nToken.tokenAddress,
currencyId,
nToken.lastInitializedTime,
blockTime,
nToken.cashGroup.maxMarketIndex
);
if (ifCashBits != 0 && acceptResidualAssets) {
// This will remove all the ifCash assets proportionally from the account
newifCashAssets = _reduceifCashAssetsProportional(
nToken.tokenAddress,
currencyId,
nToken.lastInitializedTime,
tokensToRedeem,
nToken.totalSupply,
ifCashBits
);
// Once the ifCash bits have been withdrawn, set this to zero so that getLiquidityTokenWithdraw
// simply gets the proportional amount of liquidity tokens to remove
ifCashBits = 0;
}
// Returns the liquidity tokens to withdraw per market and the netfCash amounts. Net fCash amounts are only
// set when ifCashBits != 0. Otherwise they must be calculated in _withdrawLiquidityTokens
(int256[] memory tokensToWithdraw, int256[] memory netfCash) = nTokenCalculations.getLiquidityTokenWithdraw(
nToken,
tokensToRedeem,
blockTime,
ifCashBits
);
// Returns the totalAssetCash as a result of withdrawing liquidity tokens and cash. netfCash will be updated
// in memory if required and will contain the fCash to be sold or returned to the portfolio
int256 totalAssetCash = _reduceLiquidAssets(
nToken,
tokensToRedeem,
tokensToWithdraw,
netfCash,
ifCashBits == 0, // If there are no residuals then we need to populate netfCash amounts
blockTime
);
bool netfCashRemaining = true;
if (sellTokenAssets) {
int256 assetCash;
// NOTE: netfCash is modified in place and set to zero if the fCash is sold
(assetCash, netfCashRemaining) = _sellfCashAssets(nToken, netfCash, blockTime);
totalAssetCash = totalAssetCash.add(assetCash);
}
if (netfCashRemaining) {
// If the account is unwilling to accept residuals then will fail here.
require(acceptResidualAssets, "Residuals");
newifCashAssets = _addResidualsToAssets(nToken.portfolioState.storedAssets, newifCashAssets, netfCash);
}
return (totalAssetCash, netfCashRemaining, newifCashAssets);
}
/// @notice Removes liquidity tokens and cash from the nToken
/// @param nToken portfolio object
/// @param nTokensToRedeem tokens to redeem
/// @param tokensToWithdraw array of liquidity tokens to withdraw
/// @param netfCash array of netfCash figures
/// @param mustCalculatefCash true if netfCash must be calculated in the removeLiquidityTokens step
/// @param blockTime current block time
/// @return assetCashShare amount of cash the redeemer will receive from withdrawing cash assets from the nToken
function _reduceLiquidAssets(
nTokenPortfolio memory nToken,
int256 nTokensToRedeem,
int256[] memory tokensToWithdraw,
int256[] memory netfCash,
bool mustCalculatefCash,
uint256 blockTime
) private returns (int256 assetCashShare) {
// Get asset cash share for the nToken, if it exists. It is required in balance handler that the
// nToken can never have a negative cash asset cash balance so what we get here is always positive
// or zero.
assetCashShare = nToken.cashBalance.mul(nTokensToRedeem).div(nToken.totalSupply);
if (assetCashShare > 0) {
nToken.cashBalance = nToken.cashBalance.subNoNeg(assetCashShare);
BalanceHandler.setBalanceStorageForNToken(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.cashBalance
);
}
// Get share of liquidity tokens to remove, netfCash is modified in memory during this method if mustCalculatefcash
// is set to true
assetCashShare = assetCashShare.add(
_removeLiquidityTokens(nToken, nTokensToRedeem, tokensToWithdraw, netfCash, blockTime, mustCalculatefCash)
);
nToken.portfolioState.storeAssets(nToken.tokenAddress);
// NOTE: Token supply change will happen when we finalize balances and after minting of incentives
return assetCashShare;
}
/// @notice Removes nToken liquidity tokens and updates the netfCash figures.
/// @param nToken portfolio object
/// @param nTokensToRedeem tokens to redeem
/// @param tokensToWithdraw array of liquidity tokens to withdraw
/// @param netfCash array of netfCash figures
/// @param blockTime current block time
/// @param mustCalculatefCash true if netfCash must be calculated in the removeLiquidityTokens step
/// @return totalAssetCashClaims is the amount of asset cash raised from liquidity token cash claims
function _removeLiquidityTokens(
nTokenPortfolio memory nToken,
int256 nTokensToRedeem,
int256[] memory tokensToWithdraw,
int256[] memory netfCash,
uint256 blockTime,
bool mustCalculatefCash
) private returns (int256 totalAssetCashClaims) {
MarketParameters memory market;
for (uint256 i = 0; i < nToken.portfolioState.storedAssets.length; i++) {
PortfolioAsset memory asset = nToken.portfolioState.storedAssets[i];
asset.notional = asset.notional.sub(tokensToWithdraw[i]);
// Cannot redeem liquidity tokens down to zero or this will cause many issues with
// market initialization.
require(asset.notional > 0, "Cannot redeem to zero");
require(asset.storageState == AssetStorageState.NoChange);
asset.storageState = AssetStorageState.Update;
// This will load a market object in memory
nToken.cashGroup.loadMarket(market, i + 1, true, blockTime);
int256 fCashClaim;
{
int256 assetCash;
// Remove liquidity from the market
(assetCash, fCashClaim) = market.removeLiquidity(tokensToWithdraw[i]);
totalAssetCashClaims = totalAssetCashClaims.add(assetCash);
}
int256 fCashToNToken;
if (mustCalculatefCash) {
// Do this calculation if net ifCash is not set, will happen if there are no residuals
int256 fCashShare = BitmapAssetsHandler.getifCashNotional(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
asset.maturity
);
fCashShare = fCashShare.mul(nTokensToRedeem).div(nToken.totalSupply);
// netfCash = fCashClaim + fCashShare
netfCash[i] = fCashClaim.add(fCashShare);
fCashToNToken = fCashShare.neg();
} else {
// Account will receive netfCash amount. Deduct that from the fCash claim and add the
// remaining back to the nToken to net off the nToken's position
// fCashToNToken = -fCashShare
// netfCash = fCashClaim + fCashShare
// fCashToNToken = -(netfCash - fCashClaim)
// fCashToNToken = fCashClaim - netfCash
fCashToNToken = fCashClaim.sub(netfCash[i]);
}
// Removes the account's fCash position from the nToken
BitmapAssetsHandler.addifCashAsset(
nToken.tokenAddress,
asset.currencyId,
asset.maturity,
nToken.lastInitializedTime,
fCashToNToken
);
}
return totalAssetCashClaims;
}
/// @notice Sells fCash assets back into the market for cash. Negative fCash assets will decrease netAssetCash
/// as a result. The aim here is to ensure that accounts can redeem nTokens without having to take on
/// fCash assets.
function _sellfCashAssets(
nTokenPortfolio memory nToken,
int256[] memory netfCash,
uint256 blockTime
) private returns (int256 totalAssetCash, bool hasResidual) {
MarketParameters memory market;
hasResidual = false;
for (uint256 i = 0; i < netfCash.length; i++) {
if (netfCash[i] == 0) continue;
nToken.cashGroup.loadMarket(market, i + 1, false, blockTime);
int256 netAssetCash = market.executeTrade(
nToken.cashGroup,
// Use the negative of fCash notional here since we want to net it out
netfCash[i].neg(),
nToken.portfolioState.storedAssets[i].maturity.sub(blockTime),
i + 1
);
if (netAssetCash == 0) {
// This means that the trade failed
hasResidual = true;
} else {
totalAssetCash = totalAssetCash.add(netAssetCash);
netfCash[i] = 0;
}
}
}
/// @notice Combines newifCashAssets array with netfCash assets into a single finalfCashAssets array
function _addResidualsToAssets(
PortfolioAsset[] memory liquidityTokens,
PortfolioAsset[] memory newifCashAssets,
int256[] memory netfCash
) internal pure returns (PortfolioAsset[] memory finalfCashAssets) {
uint256 numAssetsToExtend;
for (uint256 i = 0; i < netfCash.length; i++) {
if (netfCash[i] != 0) numAssetsToExtend++;
}
uint256 newLength = newifCashAssets.length + numAssetsToExtend;
finalfCashAssets = new PortfolioAsset[](newLength);
uint index = 0;
for (; index < newifCashAssets.length; index++) {
finalfCashAssets[index] = newifCashAssets[index];
}
uint netfCashIndex = 0;
for (; index < finalfCashAssets.length; ) {
if (netfCash[netfCashIndex] != 0) {
PortfolioAsset memory asset = finalfCashAssets[index];
asset.currencyId = liquidityTokens[netfCashIndex].currencyId;
asset.maturity = liquidityTokens[netfCashIndex].maturity;
asset.assetType = Constants.FCASH_ASSET_TYPE;
asset.notional = netfCash[netfCashIndex];
index++;
}
netfCashIndex++;
}
return finalfCashAssets;
}
/// @notice Used to reduce an nToken ifCash assets portfolio proportionately when redeeming
/// nTokens to its underlying assets.
function _reduceifCashAssetsProportional(
address account,
uint256 currencyId,
uint256 lastInitializedTime,
int256 tokensToRedeem,
int256 totalSupply,
bytes32 assetsBitmap
) internal returns (PortfolioAsset[] memory) {
uint256 index = assetsBitmap.totalBitsSet();
mapping(address => mapping(uint256 =>
mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage();
PortfolioAsset[] memory assets = new PortfolioAsset[](index);
index = 0;
uint256 bitNum = assetsBitmap.getNextBitNum();
while (bitNum != 0) {
uint256 maturity = DateTime.getMaturityFromBitNum(lastInitializedTime, bitNum);
ifCashStorage storage fCashSlot = store[account][currencyId][maturity];
int256 notional = fCashSlot.notional;
int256 notionalToTransfer = notional.mul(tokensToRedeem).div(totalSupply);
int256 finalNotional = notional.sub(notionalToTransfer);
require(type(int128).min <= finalNotional && finalNotional <= type(int128).max); // dev: bitmap notional overflow
fCashSlot.notional = int128(finalNotional);
PortfolioAsset memory asset = assets[index];
asset.currencyId = currencyId;
asset.maturity = maturity;
asset.assetType = Constants.FCASH_ASSET_TYPE;
asset.notional = notionalToTransfer;
index += 1;
// Turn off the bit and look for the next one
assetsBitmap = assetsBitmap.setBit(bitNum, false);
bitNum = assetsBitmap.getNextBitNum();
}
return assets;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../internal/portfolio/PortfolioHandler.sol";
import "../internal/balances/BalanceHandler.sol";
import "../internal/settlement/SettlePortfolioAssets.sol";
import "../internal/settlement/SettleBitmapAssets.sol";
import "../internal/AccountContextHandler.sol";
/// @notice External library for settling assets
library SettleAssetsExternal {
using PortfolioHandler for PortfolioState;
using AccountContextHandler for AccountContext;
event AccountSettled(address indexed account);
/// @notice Settles an account, returns the new account context object after settlement.
/// @dev The memory location of the account context object is not the same as the one returned.
function settleAccount(
address account,
AccountContext memory accountContext
) external returns (AccountContext memory) {
// Defensive check to ensure that this is a valid settlement
require(accountContext.mustSettleAssets());
SettleAmount[] memory settleAmounts;
PortfolioState memory portfolioState;
if (accountContext.isBitmapEnabled()) {
(int256 settledCash, uint256 blockTimeUTC0) =
SettleBitmapAssets.settleBitmappedCashGroup(
account,
accountContext.bitmapCurrencyId,
accountContext.nextSettleTime,
block.timestamp
);
require(blockTimeUTC0 < type(uint40).max); // dev: block time utc0 overflow
accountContext.nextSettleTime = uint40(blockTimeUTC0);
settleAmounts = new SettleAmount[](1);
settleAmounts[0] = SettleAmount(accountContext.bitmapCurrencyId, settledCash);
} else {
portfolioState = PortfolioHandler.buildPortfolioState(
account,
accountContext.assetArrayLength,
0
);
settleAmounts = SettlePortfolioAssets.settlePortfolio(portfolioState, block.timestamp);
accountContext.storeAssetsAndUpdateContext(account, portfolioState, false);
}
BalanceHandler.finalizeSettleAmounts(account, accountContext, settleAmounts);
emit AccountSettled(account);
return accountContext;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../external/SettleAssetsExternal.sol";
import "../internal/AccountContextHandler.sol";
import "../internal/valuation/FreeCollateral.sol";
/// @title Externally deployed library for free collateral calculations
library FreeCollateralExternal {
using AccountContextHandler for AccountContext;
/// @notice Returns the ETH denominated free collateral of an account, represents the amount of
/// debt that the account can incur before liquidation. If an account's assets need to be settled this
/// will revert, either settle the account or use the off chain SDK to calculate free collateral.
/// @dev Called via the Views.sol method to return an account's free collateral. Does not work
/// for the nToken, the nToken does not have an account context.
/// @param account account to calculate free collateral for
/// @return total free collateral in ETH w/ 8 decimal places
/// @return array of net local values in asset values ordered by currency id
function getFreeCollateralView(address account)
external
view
returns (int256, int256[] memory)
{
AccountContext memory accountContext = AccountContextHandler.getAccountContext(account);
// The internal free collateral function does not account for settled assets. The Notional SDK
// can calculate the free collateral off chain if required at this point.
require(!accountContext.mustSettleAssets(), "Assets not settled");
return FreeCollateral.getFreeCollateralView(account, accountContext, block.timestamp);
}
/// @notice Calculates free collateral and will revert if it falls below zero. If the account context
/// must be updated due to changes in debt settings, will update. Cannot check free collateral if assets
/// need to be settled first.
/// @dev Cannot be called directly by users, used during various actions that require an FC check. Must be
/// called before the end of any transaction for accounts where FC can decrease.
/// @param account account to calculate free collateral for
function checkFreeCollateralAndRevert(address account) external {
AccountContext memory accountContext = AccountContextHandler.getAccountContext(account);
require(!accountContext.mustSettleAssets(), "Assets not settled");
(int256 ethDenominatedFC, bool updateContext) =
FreeCollateral.getFreeCollateralStateful(account, accountContext, block.timestamp);
if (updateContext) {
accountContext.setAccountContext(account);
}
require(ethDenominatedFC >= 0, "Insufficient free collateral");
}
/// @notice Calculates liquidation factors for an account
/// @dev Only called internally by liquidation actions, does some initial validation of currencies. If a currency is
/// specified that the account does not have, a asset available figure of zero will be returned. If this is the case then
/// liquidation actions will revert.
/// @dev an ntoken account will return 0 FC and revert if called
/// @param account account to liquidate
/// @param localCurrencyId currency that the debts are denominated in
/// @param collateralCurrencyId collateral currency to liquidate against, set to zero in the case of local currency liquidation
/// @return accountContext the accountContext of the liquidated account
/// @return factors struct of relevant factors for liquidation
/// @return portfolio the portfolio array of the account (bitmap accounts will return an empty array)
function getLiquidationFactors(
address account,
uint256 localCurrencyId,
uint256 collateralCurrencyId
)
external
returns (
AccountContext memory accountContext,
LiquidationFactors memory factors,
PortfolioAsset[] memory portfolio
)
{
accountContext = AccountContextHandler.getAccountContext(account);
if (accountContext.mustSettleAssets()) {
accountContext = SettleAssetsExternal.settleAccount(account, accountContext);
}
if (accountContext.isBitmapEnabled()) {
// A bitmap currency can only ever hold debt in this currency
require(localCurrencyId == accountContext.bitmapCurrencyId);
}
(factors, portfolio) = FreeCollateral.getLiquidationFactors(
account,
accountContext,
block.timestamp,
localCurrencyId,
collateralCurrencyId
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
import "../global/Constants.sol";
library SafeInt256 {
int256 private constant _INT256_MIN = type(int256).min;
/// @dev Returns the multiplication of two signed integers, reverting on
/// overflow.
/// Counterpart to Solidity's `*` operator.
/// Requirements:
/// - Multiplication cannot overflow.
function mul(int256 a, int256 b) internal pure returns (int256 c) {
c = a * b;
if (a == -1) require (b == 0 || c / b == a);
else require (a == 0 || c / a == b);
}
/// @dev Returns the integer division of two signed integers. Reverts on
/// division by zero. The result is rounded towards zero.
/// Counterpart to Solidity's `/` operator. Note: this function uses a
/// `revert` opcode (which leaves remaining gas untouched) while Solidity
/// uses an invalid opcode to revert (consuming all remaining gas).
/// Requirements:
/// - The divisor cannot be zero.
function div(int256 a, int256 b) internal pure returns (int256 c) {
require(!(b == -1 && a == _INT256_MIN)); // dev: int256 div overflow
// NOTE: solidity will automatically revert on divide by zero
c = a / b;
}
function sub(int256 x, int256 y) internal pure returns (int256 z) {
// taken from uniswap v3
require((z = x - y) <= x == (y >= 0));
}
function add(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x + y) >= x == (y >= 0));
}
function neg(int256 x) internal pure returns (int256 y) {
return mul(-1, x);
}
function abs(int256 x) internal pure returns (int256) {
if (x < 0) return neg(x);
else return x;
}
function subNoNeg(int256 x, int256 y) internal pure returns (int256 z) {
z = sub(x, y);
require(z >= 0); // dev: int256 sub to negative
return z;
}
/// @dev Calculates x * RATE_PRECISION / y while checking overflows
function divInRatePrecision(int256 x, int256 y) internal pure returns (int256) {
return div(mul(x, Constants.RATE_PRECISION), y);
}
/// @dev Calculates x * y / RATE_PRECISION while checking overflows
function mulInRatePrecision(int256 x, int256 y) internal pure returns (int256) {
return div(mul(x, y), Constants.RATE_PRECISION);
}
function toUint(int256 x) internal pure returns (uint256) {
require(x >= 0);
return uint256(x);
}
function toInt(uint256 x) internal pure returns (int256) {
require (x <= uint256(type(int256).max)); // dev: toInt overflow
return int256(x);
}
function max(int256 x, int256 y) internal pure returns (int256) {
return x > y ? x : y;
}
function min(int256 x, int256 y) internal pure returns (int256) {
return x < y ? x : y;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./Types.sol";
/**
* @notice Storage layout for the system. Do not change this file once deployed, future storage
* layouts must inherit this and increment the version number.
*/
contract StorageLayoutV1 {
// The current maximum currency id
uint16 internal maxCurrencyId;
// Sets the state of liquidations being enabled during a paused state. Each of the four lower
// bits can be turned on to represent one of the liquidation types being enabled.
bytes1 internal liquidationEnabledState;
// Set to true once the system has been initialized
bool internal hasInitialized;
/* Authentication Mappings */
// This is set to the timelock contract to execute governance functions
address public owner;
// This is set to an address of a router that can only call governance actions
address public pauseRouter;
// This is set to an address of a router that can only call governance actions
address public pauseGuardian;
// On upgrades this is set in the case that the pause router is used to pass the rollback check
address internal rollbackRouterImplementation;
// A blanket allowance for a spender to transfer any of an account's nTokens. This would allow a user
// to set an allowance on all nTokens for a particular integrating contract system.
// owner => spender => transferAllowance
mapping(address => mapping(address => uint256)) internal nTokenWhitelist;
// Individual transfer allowances for nTokens used for ERC20
// owner => spender => currencyId => transferAllowance
mapping(address => mapping(address => mapping(uint16 => uint256))) internal nTokenAllowance;
// Transfer operators
// Mapping from a global ERC1155 transfer operator contract to an approval value for it
mapping(address => bool) internal globalTransferOperator;
// Mapping from an account => operator => approval status for that operator. This is a specific
// approval between two addresses for ERC1155 transfers.
mapping(address => mapping(address => bool)) internal accountAuthorizedTransferOperator;
// Approval for a specific contract to use the `batchBalanceAndTradeActionWithCallback` method in
// BatchAction.sol, can only be set by governance
mapping(address => bool) internal authorizedCallbackContract;
// Reverse mapping from token addresses to currency ids, only used for referencing in views
// and checking for duplicate token listings.
mapping(address => uint16) internal tokenAddressToCurrencyId;
// Reentrancy guard
uint256 internal reentrancyStatus;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./Incentives.sol";
import "./TokenHandler.sol";
import "../AccountContextHandler.sol";
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../../math/SafeInt256.sol";
import "../../math/FloatingPoint56.sol";
library BalanceHandler {
using SafeInt256 for int256;
using TokenHandler for Token;
using AssetRate for AssetRateParameters;
using AccountContextHandler for AccountContext;
/// @notice Emitted when a cash balance changes
event CashBalanceChange(address indexed account, uint16 indexed currencyId, int256 netCashChange);
/// @notice Emitted when nToken supply changes (not the same as transfers)
event nTokenSupplyChange(address indexed account, uint16 indexed currencyId, int256 tokenSupplyChange);
/// @notice Emitted when reserve fees are accrued
event ReserveFeeAccrued(uint16 indexed currencyId, int256 fee);
/// @notice Emitted when reserve balance is updated
event ReserveBalanceUpdated(uint16 indexed currencyId, int256 newBalance);
/// @notice Emitted when reserve balance is harvested
event ExcessReserveBalanceHarvested(uint16 indexed currencyId, int256 harvestAmount);
/// @notice Deposits asset tokens into an account
/// @dev Handles two special cases when depositing tokens into an account.
/// - If a token has transfer fees then the amount specified does not equal the amount that the contract
/// will receive. Complete the deposit here rather than in finalize so that the contract has the correct
/// balance to work with.
/// - Force a transfer before finalize to allow a different account to deposit into an account
/// @return assetAmountInternal which is the converted asset amount accounting for transfer fees
function depositAssetToken(
BalanceState memory balanceState,
address account,
int256 assetAmountExternal,
bool forceTransfer
) internal returns (int256 assetAmountInternal) {
if (assetAmountExternal == 0) return 0;
require(assetAmountExternal > 0); // dev: deposit asset token amount negative
Token memory token = TokenHandler.getAssetToken(balanceState.currencyId);
if (token.tokenType == TokenType.aToken) {
// Handles special accounting requirements for aTokens
assetAmountExternal = AaveHandler.convertToScaledBalanceExternal(
balanceState.currencyId,
assetAmountExternal
);
}
// Force transfer is used to complete the transfer before going to finalize
if (token.hasTransferFee || forceTransfer) {
// If the token has a transfer fee the deposit amount may not equal the actual amount
// that the contract will receive. We handle the deposit here and then update the netCashChange
// accordingly which is denominated in internal precision.
int256 assetAmountExternalPrecisionFinal = token.transfer(account, balanceState.currencyId, assetAmountExternal);
// Convert the external precision to internal, it's possible that we lose dust amounts here but
// this is unavoidable because we do not know how transfer fees are calculated.
assetAmountInternal = token.convertToInternal(assetAmountExternalPrecisionFinal);
// Transfer has been called
balanceState.netCashChange = balanceState.netCashChange.add(assetAmountInternal);
return assetAmountInternal;
} else {
assetAmountInternal = token.convertToInternal(assetAmountExternal);
// Otherwise add the asset amount here. It may be net off later and we want to only do
// a single transfer during the finalize method. Use internal precision to ensure that internal accounting
// and external account remain in sync.
// Transfer will be deferred
balanceState.netAssetTransferInternalPrecision = balanceState
.netAssetTransferInternalPrecision
.add(assetAmountInternal);
// Returns the converted assetAmountExternal to the internal amount
return assetAmountInternal;
}
}
/// @notice Handle deposits of the underlying token
/// @dev In this case we must wrap the underlying token into an asset token, ensuring that we do not end up
/// with any underlying tokens left as dust on the contract.
function depositUnderlyingToken(
BalanceState memory balanceState,
address account,
int256 underlyingAmountExternal
) internal returns (int256) {
if (underlyingAmountExternal == 0) return 0;
require(underlyingAmountExternal > 0); // dev: deposit underlying token negative
Token memory underlyingToken = TokenHandler.getUnderlyingToken(balanceState.currencyId);
// This is the exact amount of underlying tokens the account has in external precision.
if (underlyingToken.tokenType == TokenType.Ether) {
// Underflow checked above
require(uint256(underlyingAmountExternal) == msg.value, "ETH Balance");
} else {
underlyingAmountExternal = underlyingToken.transfer(account, balanceState.currencyId, underlyingAmountExternal);
}
Token memory assetToken = TokenHandler.getAssetToken(balanceState.currencyId);
int256 assetTokensReceivedExternalPrecision =
assetToken.mint(balanceState.currencyId, SafeInt256.toUint(underlyingAmountExternal));
// cTokens match INTERNAL_TOKEN_PRECISION so this will short circuit but we leave this here in case a different
// type of asset token is listed in the future. It's possible if those tokens have a different precision dust may
// accrue but that is not relevant now.
int256 assetTokensReceivedInternal =
assetToken.convertToInternal(assetTokensReceivedExternalPrecision);
// Transfer / mint has taken effect
balanceState.netCashChange = balanceState.netCashChange.add(assetTokensReceivedInternal);
return assetTokensReceivedInternal;
}
/// @notice Finalizes an account's balances, handling any transfer logic required
/// @dev This method SHOULD NOT be used for nToken accounts, for that use setBalanceStorageForNToken
/// as the nToken is limited in what types of balances it can hold.
function finalize(
BalanceState memory balanceState,
address account,
AccountContext memory accountContext,
bool redeemToUnderlying
) internal returns (int256 transferAmountExternal) {
bool mustUpdate;
if (balanceState.netNTokenTransfer < 0) {
require(
balanceState.storedNTokenBalance
.add(balanceState.netNTokenSupplyChange)
.add(balanceState.netNTokenTransfer) >= 0,
"Neg nToken"
);
}
if (balanceState.netAssetTransferInternalPrecision < 0) {
require(
balanceState.storedCashBalance
.add(balanceState.netCashChange)
.add(balanceState.netAssetTransferInternalPrecision) >= 0,
"Neg Cash"
);
}
// Transfer amount is checked inside finalize transfers in case when converting to external we
// round down to zero. This returns the actual net transfer in internal precision as well.
(
transferAmountExternal,
balanceState.netAssetTransferInternalPrecision
) = _finalizeTransfers(balanceState, account, redeemToUnderlying);
// No changes to total cash after this point
int256 totalCashChange = balanceState.netCashChange.add(balanceState.netAssetTransferInternalPrecision);
if (totalCashChange != 0) {
balanceState.storedCashBalance = balanceState.storedCashBalance.add(totalCashChange);
mustUpdate = true;
emit CashBalanceChange(
account,
uint16(balanceState.currencyId),
totalCashChange
);
}
if (balanceState.netNTokenTransfer != 0 || balanceState.netNTokenSupplyChange != 0) {
// Final nToken balance is used to calculate the account incentive debt
int256 finalNTokenBalance = balanceState.storedNTokenBalance
.add(balanceState.netNTokenTransfer)
.add(balanceState.netNTokenSupplyChange);
// The toUint() call here will ensure that nToken balances never become negative
Incentives.claimIncentives(balanceState, account, finalNTokenBalance.toUint());
balanceState.storedNTokenBalance = finalNTokenBalance;
if (balanceState.netNTokenSupplyChange != 0) {
emit nTokenSupplyChange(
account,
uint16(balanceState.currencyId),
balanceState.netNTokenSupplyChange
);
}
mustUpdate = true;
}
if (mustUpdate) {
_setBalanceStorage(
account,
balanceState.currencyId,
balanceState.storedCashBalance,
balanceState.storedNTokenBalance,
balanceState.lastClaimTime,
balanceState.accountIncentiveDebt
);
}
accountContext.setActiveCurrency(
balanceState.currencyId,
// Set active currency to true if either balance is non-zero
balanceState.storedCashBalance != 0 || balanceState.storedNTokenBalance != 0,
Constants.ACTIVE_IN_BALANCES
);
if (balanceState.storedCashBalance < 0) {
// NOTE: HAS_CASH_DEBT cannot be extinguished except by a free collateral check where all balances
// are examined
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT;
}
}
/// @dev Returns the amount transferred in underlying or asset terms depending on how redeem to underlying
/// is specified.
function _finalizeTransfers(
BalanceState memory balanceState,
address account,
bool redeemToUnderlying
) private returns (int256 actualTransferAmountExternal, int256 assetTransferAmountInternal) {
Token memory assetToken = TokenHandler.getAssetToken(balanceState.currencyId);
// Dust accrual to the protocol is possible if the token decimals is less than internal token precision.
// See the comments in TokenHandler.convertToExternal and TokenHandler.convertToInternal
int256 assetTransferAmountExternal =
assetToken.convertToExternal(balanceState.netAssetTransferInternalPrecision);
if (assetTransferAmountExternal == 0) {
return (0, 0);
} else if (redeemToUnderlying && assetTransferAmountExternal < 0) {
// We only do the redeem to underlying if the asset transfer amount is less than zero. If it is greater than
// zero then we will do a normal transfer instead.
// We use the internal amount here and then scale it to the external amount so that there is
// no loss of precision between our internal accounting and the external account. In this case
// there will be no dust accrual in underlying tokens since we will transfer the exact amount
// of underlying that was received.
actualTransferAmountExternal = assetToken.redeem(
balanceState.currencyId,
account,
// No overflow, checked above
uint256(assetTransferAmountExternal.neg())
);
// In this case we're transferring underlying tokens, we want to convert the internal
// asset transfer amount to store in cash balances
assetTransferAmountInternal = assetToken.convertToInternal(assetTransferAmountExternal);
} else {
// NOTE: in the case of aTokens assetTransferAmountExternal is the scaledBalanceOf in external precision, it
// will be converted to balanceOf denomination inside transfer
actualTransferAmountExternal = assetToken.transfer(account, balanceState.currencyId, assetTransferAmountExternal);
// Convert the actual transferred amount
assetTransferAmountInternal = assetToken.convertToInternal(actualTransferAmountExternal);
}
}
/// @notice Special method for settling negative current cash debts. This occurs when an account
/// has a negative fCash balance settle to cash. A settler may come and force the account to borrow
/// at the prevailing 3 month rate
/// @dev Use this method to avoid any nToken and transfer logic in finalize which is unnecessary.
function setBalanceStorageForSettleCashDebt(
address account,
CashGroupParameters memory cashGroup,
int256 amountToSettleAsset,
AccountContext memory accountContext
) internal returns (int256) {
require(amountToSettleAsset >= 0); // dev: amount to settle negative
(int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt) =
getBalanceStorage(account, cashGroup.currencyId);
// Prevents settlement of positive balances
require(cashBalance < 0, "Invalid settle balance");
if (amountToSettleAsset == 0) {
// Symbolizes that the entire debt should be settled
amountToSettleAsset = cashBalance.neg();
cashBalance = 0;
} else {
// A partial settlement of the debt
require(amountToSettleAsset <= cashBalance.neg(), "Invalid amount to settle");
cashBalance = cashBalance.add(amountToSettleAsset);
}
// NOTE: we do not update HAS_CASH_DEBT here because it is possible that the other balances
// also have cash debts
if (cashBalance == 0 && nTokenBalance == 0) {
accountContext.setActiveCurrency(
cashGroup.currencyId,
false,
Constants.ACTIVE_IN_BALANCES
);
}
_setBalanceStorage(
account,
cashGroup.currencyId,
cashBalance,
nTokenBalance,
lastClaimTime,
accountIncentiveDebt
);
// Emit the event here, we do not call finalize
emit CashBalanceChange(account, cashGroup.currencyId, amountToSettleAsset);
return amountToSettleAsset;
}
/**
* @notice A special balance storage method for fCash liquidation to reduce the bytecode size.
*/
function setBalanceStorageForfCashLiquidation(
address account,
AccountContext memory accountContext,
uint16 currencyId,
int256 netCashChange
) internal {
(int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt) =
getBalanceStorage(account, currencyId);
int256 newCashBalance = cashBalance.add(netCashChange);
// If a cash balance is negative already we cannot put an account further into debt. In this case
// the netCashChange must be positive so that it is coming out of debt.
if (newCashBalance < 0) {
require(netCashChange > 0, "Neg Cash");
// NOTE: HAS_CASH_DEBT cannot be extinguished except by a free collateral check
// where all balances are examined. In this case the has cash debt flag should
// already be set (cash balances cannot get more negative) but we do it again
// here just to be safe.
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT;
}
bool isActive = newCashBalance != 0 || nTokenBalance != 0;
accountContext.setActiveCurrency(currencyId, isActive, Constants.ACTIVE_IN_BALANCES);
// Emit the event here, we do not call finalize
emit CashBalanceChange(account, currencyId, netCashChange);
_setBalanceStorage(
account,
currencyId,
newCashBalance,
nTokenBalance,
lastClaimTime,
accountIncentiveDebt
);
}
/// @notice Helper method for settling the output of the SettleAssets method
function finalizeSettleAmounts(
address account,
AccountContext memory accountContext,
SettleAmount[] memory settleAmounts
) internal {
for (uint256 i = 0; i < settleAmounts.length; i++) {
SettleAmount memory amt = settleAmounts[i];
if (amt.netCashChange == 0) continue;
(
int256 cashBalance,
int256 nTokenBalance,
uint256 lastClaimTime,
uint256 accountIncentiveDebt
) = getBalanceStorage(account, amt.currencyId);
cashBalance = cashBalance.add(amt.netCashChange);
accountContext.setActiveCurrency(
amt.currencyId,
cashBalance != 0 || nTokenBalance != 0,
Constants.ACTIVE_IN_BALANCES
);
if (cashBalance < 0) {
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT;
}
emit CashBalanceChange(
account,
uint16(amt.currencyId),
amt.netCashChange
);
_setBalanceStorage(
account,
amt.currencyId,
cashBalance,
nTokenBalance,
lastClaimTime,
accountIncentiveDebt
);
}
}
/// @notice Special method for setting balance storage for nToken
function setBalanceStorageForNToken(
address nTokenAddress,
uint256 currencyId,
int256 cashBalance
) internal {
require(cashBalance >= 0); // dev: invalid nToken cash balance
_setBalanceStorage(nTokenAddress, currencyId, cashBalance, 0, 0, 0);
}
/// @notice increments fees to the reserve
function incrementFeeToReserve(uint256 currencyId, int256 fee) internal {
require(fee >= 0); // dev: invalid fee
// prettier-ignore
(int256 totalReserve, /* */, /* */, /* */) = getBalanceStorage(Constants.RESERVE, currencyId);
totalReserve = totalReserve.add(fee);
_setBalanceStorage(Constants.RESERVE, currencyId, totalReserve, 0, 0, 0);
emit ReserveFeeAccrued(uint16(currencyId), fee);
}
/// @notice harvests excess reserve balance
function harvestExcessReserveBalance(uint16 currencyId, int256 reserve, int256 assetInternalRedeemAmount) internal {
// parameters are validated by the caller
reserve = reserve.subNoNeg(assetInternalRedeemAmount);
_setBalanceStorage(Constants.RESERVE, currencyId, reserve, 0, 0, 0);
emit ExcessReserveBalanceHarvested(currencyId, assetInternalRedeemAmount);
}
/// @notice sets the reserve balance, see TreasuryAction.setReserveCashBalance
function setReserveCashBalance(uint16 currencyId, int256 newBalance) internal {
require(newBalance >= 0); // dev: invalid balance
_setBalanceStorage(Constants.RESERVE, currencyId, newBalance, 0, 0, 0);
emit ReserveBalanceUpdated(currencyId, newBalance);
}
/// @notice Sets internal balance storage.
function _setBalanceStorage(
address account,
uint256 currencyId,
int256 cashBalance,
int256 nTokenBalance,
uint256 lastClaimTime,
uint256 accountIncentiveDebt
) private {
mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage();
BalanceStorage storage balanceStorage = store[account][currencyId];
require(cashBalance >= type(int88).min && cashBalance <= type(int88).max); // dev: stored cash balance overflow
// Allows for 12 quadrillion nToken balance in 1e8 decimals before overflow
require(nTokenBalance >= 0 && nTokenBalance <= type(uint80).max); // dev: stored nToken balance overflow
if (lastClaimTime == 0) {
// In this case the account has migrated and we set the accountIncentiveDebt
// The maximum NOTE supply is 100_000_000e8 (1e16) which is less than 2^56 (7.2e16) so we should never
// encounter an overflow for accountIncentiveDebt
require(accountIncentiveDebt <= type(uint56).max); // dev: account incentive debt overflow
balanceStorage.accountIncentiveDebt = uint56(accountIncentiveDebt);
} else {
// In this case the last claim time has not changed and we do not update the last integral supply
// (stored in the accountIncentiveDebt position)
require(lastClaimTime == balanceStorage.lastClaimTime);
}
balanceStorage.lastClaimTime = uint32(lastClaimTime);
balanceStorage.nTokenBalance = uint80(nTokenBalance);
balanceStorage.cashBalance = int88(cashBalance);
}
/// @notice Gets internal balance storage, nTokens are stored alongside cash balances
function getBalanceStorage(address account, uint256 currencyId)
internal
view
returns (
int256 cashBalance,
int256 nTokenBalance,
uint256 lastClaimTime,
uint256 accountIncentiveDebt
)
{
mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage();
BalanceStorage storage balanceStorage = store[account][currencyId];
nTokenBalance = balanceStorage.nTokenBalance;
lastClaimTime = balanceStorage.lastClaimTime;
if (lastClaimTime > 0) {
// NOTE: this is only necessary to support the deprecated integral supply values, which are stored
// in the accountIncentiveDebt slot
accountIncentiveDebt = FloatingPoint56.unpackFrom56Bits(balanceStorage.accountIncentiveDebt);
} else {
accountIncentiveDebt = balanceStorage.accountIncentiveDebt;
}
cashBalance = balanceStorage.cashBalance;
}
/// @notice Loads a balance state memory object
/// @dev Balance state objects occupy a lot of memory slots, so this method allows
/// us to reuse them if possible
function loadBalanceState(
BalanceState memory balanceState,
address account,
uint16 currencyId,
AccountContext memory accountContext
) internal view {
require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id
balanceState.currencyId = currencyId;
if (accountContext.isActiveInBalances(currencyId)) {
(
balanceState.storedCashBalance,
balanceState.storedNTokenBalance,
balanceState.lastClaimTime,
balanceState.accountIncentiveDebt
) = getBalanceStorage(account, currencyId);
} else {
balanceState.storedCashBalance = 0;
balanceState.storedNTokenBalance = 0;
balanceState.lastClaimTime = 0;
balanceState.accountIncentiveDebt = 0;
}
balanceState.netCashChange = 0;
balanceState.netAssetTransferInternalPrecision = 0;
balanceState.netNTokenTransfer = 0;
balanceState.netNTokenSupplyChange = 0;
}
/// @notice Used when manually claiming incentives in nTokenAction. Also sets the balance state
/// to storage to update the accountIncentiveDebt. lastClaimTime will be set to zero as accounts
/// are migrated to the new incentive calculation
function claimIncentivesManual(BalanceState memory balanceState, address account)
internal
returns (uint256 incentivesClaimed)
{
incentivesClaimed = Incentives.claimIncentives(
balanceState,
account,
balanceState.storedNTokenBalance.toUint()
);
_setBalanceStorage(
account,
balanceState.currencyId,
balanceState.storedCashBalance,
balanceState.storedNTokenBalance,
balanceState.lastClaimTime,
balanceState.accountIncentiveDebt
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./TransferAssets.sol";
import "../valuation/AssetHandler.sol";
import "../../math/SafeInt256.sol";
import "../../global/LibStorage.sol";
/// @notice Handles the management of an array of assets including reading from storage, inserting
/// updating, deleting and writing back to storage.
library PortfolioHandler {
using SafeInt256 for int256;
using AssetHandler for PortfolioAsset;
// Mirror of LibStorage.MAX_PORTFOLIO_ASSETS
uint256 private constant MAX_PORTFOLIO_ASSETS = 16;
/// @notice Primarily used by the TransferAssets library
function addMultipleAssets(PortfolioState memory portfolioState, PortfolioAsset[] memory assets)
internal
pure
{
for (uint256 i = 0; i < assets.length; i++) {
PortfolioAsset memory asset = assets[i];
if (asset.notional == 0) continue;
addAsset(
portfolioState,
asset.currencyId,
asset.maturity,
asset.assetType,
asset.notional
);
}
}
function _mergeAssetIntoArray(
PortfolioAsset[] memory assetArray,
uint256 currencyId,
uint256 maturity,
uint256 assetType,
int256 notional
) private pure returns (bool) {
for (uint256 i = 0; i < assetArray.length; i++) {
PortfolioAsset memory asset = assetArray[i];
if (
asset.assetType != assetType ||
asset.currencyId != currencyId ||
asset.maturity != maturity
) continue;
// Either of these storage states mean that some error in logic has occurred, we cannot
// store this portfolio
require(
asset.storageState != AssetStorageState.Delete &&
asset.storageState != AssetStorageState.RevertIfStored
); // dev: portfolio handler deleted storage
int256 newNotional = asset.notional.add(notional);
// Liquidity tokens cannot be reduced below zero.
if (AssetHandler.isLiquidityToken(assetType)) {
require(newNotional >= 0); // dev: portfolio handler negative liquidity token balance
}
require(newNotional >= type(int88).min && newNotional <= type(int88).max); // dev: portfolio handler notional overflow
asset.notional = newNotional;
asset.storageState = AssetStorageState.Update;
return true;
}
return false;
}
/// @notice Adds an asset to a portfolio state in memory (does not write to storage)
/// @dev Ensures that only one version of an asset exists in a portfolio (i.e. does not allow two fCash assets of the same maturity
/// to exist in a single portfolio). Also ensures that liquidity tokens do not have a negative notional.
function addAsset(
PortfolioState memory portfolioState,
uint256 currencyId,
uint256 maturity,
uint256 assetType,
int256 notional
) internal pure {
if (
// Will return true if merged
_mergeAssetIntoArray(
portfolioState.storedAssets,
currencyId,
maturity,
assetType,
notional
)
) return;
if (portfolioState.lastNewAssetIndex > 0) {
bool merged = _mergeAssetIntoArray(
portfolioState.newAssets,
currencyId,
maturity,
assetType,
notional
);
if (merged) return;
}
// At this point if we have not merged the asset then append to the array
// Cannot remove liquidity that the portfolio does not have
if (AssetHandler.isLiquidityToken(assetType)) {
require(notional >= 0); // dev: portfolio handler negative liquidity token balance
}
require(notional >= type(int88).min && notional <= type(int88).max); // dev: portfolio handler notional overflow
// Need to provision a new array at this point
if (portfolioState.lastNewAssetIndex == portfolioState.newAssets.length) {
portfolioState.newAssets = _extendNewAssetArray(portfolioState.newAssets);
}
// Otherwise add to the new assets array. It should not be possible to add matching assets in a single transaction, we will
// check this again when we write to storage. Assigning to memory directly here, do not allocate new memory via struct.
PortfolioAsset memory newAsset = portfolioState.newAssets[portfolioState.lastNewAssetIndex];
newAsset.currencyId = currencyId;
newAsset.maturity = maturity;
newAsset.assetType = assetType;
newAsset.notional = notional;
newAsset.storageState = AssetStorageState.NoChange;
portfolioState.lastNewAssetIndex += 1;
}
/// @dev Extends the new asset array if it is not large enough, this is likely to get a bit expensive if we do
/// it too much
function _extendNewAssetArray(PortfolioAsset[] memory newAssets)
private
pure
returns (PortfolioAsset[] memory)
{
// Double the size of the new asset array every time we have to extend to reduce the number of times
// that we have to extend it. This will go: 0, 1, 2, 4, 8 (probably stops there).
uint256 newLength = newAssets.length == 0 ? 1 : newAssets.length * 2;
PortfolioAsset[] memory extendedArray = new PortfolioAsset[](newLength);
for (uint256 i = 0; i < newAssets.length; i++) {
extendedArray[i] = newAssets[i];
}
return extendedArray;
}
/// @notice Takes a portfolio state and writes it to storage.
/// @dev This method should only be called directly by the nToken. Account updates to portfolios should happen via
/// the storeAssetsAndUpdateContext call in the AccountContextHandler.sol library.
/// @return updated variables to update the account context with
/// hasDebt: whether or not the portfolio has negative fCash assets
/// portfolioActiveCurrencies: a byte32 word with all the currencies in the portfolio
/// uint8: the length of the storage array
/// uint40: the new nextSettleTime for the portfolio
function storeAssets(PortfolioState memory portfolioState, address account)
internal
returns (
bool,
bytes32,
uint8,
uint40
)
{
bool hasDebt;
// NOTE: cannot have more than 16 assets or this byte object will overflow. Max assets is
// set to 7 and the worst case during liquidation would be 7 liquidity tokens that generate
// 7 additional fCash assets for a total of 14 assets. Although even in this case all assets
// would be of the same currency so it would not change the end result of the active currency
// calculation.
bytes32 portfolioActiveCurrencies;
uint256 nextSettleTime;
for (uint256 i = 0; i < portfolioState.storedAssets.length; i++) {
PortfolioAsset memory asset = portfolioState.storedAssets[i];
// NOTE: this is to prevent the storage of assets that have been modified in the AssetHandler
// during valuation.
require(asset.storageState != AssetStorageState.RevertIfStored);
// Mark any zero notional assets as deleted
if (asset.storageState != AssetStorageState.Delete && asset.notional == 0) {
deleteAsset(portfolioState, i);
}
}
// First delete assets from asset storage to maintain asset storage indexes
for (uint256 i = 0; i < portfolioState.storedAssets.length; i++) {
PortfolioAsset memory asset = portfolioState.storedAssets[i];
if (asset.storageState == AssetStorageState.Delete) {
// Delete asset from storage
uint256 currentSlot = asset.storageSlot;
assembly {
sstore(currentSlot, 0x00)
}
} else {
if (asset.storageState == AssetStorageState.Update) {
PortfolioAssetStorage storage assetStorage;
uint256 currentSlot = asset.storageSlot;
assembly {
assetStorage.slot := currentSlot
}
_storeAsset(asset, assetStorage);
}
// Update portfolio context for every asset that is in storage, whether it is
// updated in storage or not.
(hasDebt, portfolioActiveCurrencies, nextSettleTime) = _updatePortfolioContext(
asset,
hasDebt,
portfolioActiveCurrencies,
nextSettleTime
);
}
}
// Add new assets
uint256 assetStorageLength = portfolioState.storedAssetLength;
mapping(address =>
PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store = LibStorage.getPortfolioArrayStorage();
PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS] storage storageArray = store[account];
for (uint256 i = 0; i < portfolioState.newAssets.length; i++) {
PortfolioAsset memory asset = portfolioState.newAssets[i];
if (asset.notional == 0) continue;
require(
asset.storageState != AssetStorageState.Delete &&
asset.storageState != AssetStorageState.RevertIfStored
); // dev: store assets deleted storage
(hasDebt, portfolioActiveCurrencies, nextSettleTime) = _updatePortfolioContext(
asset,
hasDebt,
portfolioActiveCurrencies,
nextSettleTime
);
_storeAsset(asset, storageArray[assetStorageLength]);
assetStorageLength += 1;
}
// 16 is the maximum number of assets or portfolio active currencies will overflow at 32 bytes with
// 2 bytes per currency
require(assetStorageLength <= 16 && nextSettleTime <= type(uint40).max); // dev: portfolio return value overflow
return (
hasDebt,
portfolioActiveCurrencies,
uint8(assetStorageLength),
uint40(nextSettleTime)
);
}
/// @notice Updates context information during the store assets method
function _updatePortfolioContext(
PortfolioAsset memory asset,
bool hasDebt,
bytes32 portfolioActiveCurrencies,
uint256 nextSettleTime
)
private
pure
returns (
bool,
bytes32,
uint256
)
{
uint256 settlementDate = asset.getSettlementDate();
// Tis will set it to the minimum settlement date
if (nextSettleTime == 0 || nextSettleTime > settlementDate) {
nextSettleTime = settlementDate;
}
hasDebt = hasDebt || asset.notional < 0;
require(uint16(uint256(portfolioActiveCurrencies)) == 0); // dev: portfolio active currencies overflow
portfolioActiveCurrencies = (portfolioActiveCurrencies >> 16) | (bytes32(asset.currencyId) << 240);
return (hasDebt, portfolioActiveCurrencies, nextSettleTime);
}
/// @dev Encodes assets for storage
function _storeAsset(
PortfolioAsset memory asset,
PortfolioAssetStorage storage assetStorage
) internal {
require(0 < asset.currencyId && asset.currencyId <= Constants.MAX_CURRENCIES); // dev: encode asset currency id overflow
require(0 < asset.maturity && asset.maturity <= type(uint40).max); // dev: encode asset maturity overflow
require(0 < asset.assetType && asset.assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); // dev: encode asset type invalid
require(type(int88).min <= asset.notional && asset.notional <= type(int88).max); // dev: encode asset notional overflow
assetStorage.currencyId = uint16(asset.currencyId);
assetStorage.maturity = uint40(asset.maturity);
assetStorage.assetType = uint8(asset.assetType);
assetStorage.notional = int88(asset.notional);
}
/// @notice Deletes an asset from a portfolio
/// @dev This method should only be called during settlement, assets can only be removed from a portfolio before settlement
/// by adding the offsetting negative position
function deleteAsset(PortfolioState memory portfolioState, uint256 index) internal pure {
require(index < portfolioState.storedAssets.length); // dev: stored assets bounds
require(portfolioState.storedAssetLength > 0); // dev: stored assets length is zero
PortfolioAsset memory assetToDelete = portfolioState.storedAssets[index];
require(
assetToDelete.storageState != AssetStorageState.Delete &&
assetToDelete.storageState != AssetStorageState.RevertIfStored
); // dev: cannot delete asset
portfolioState.storedAssetLength -= 1;
uint256 maxActiveSlotIndex;
uint256 maxActiveSlot;
// The max active slot is the last storage slot where an asset exists, it's not clear where this will be in the
// array so we search for it here.
for (uint256 i; i < portfolioState.storedAssets.length; i++) {
PortfolioAsset memory a = portfolioState.storedAssets[i];
if (a.storageSlot > maxActiveSlot && a.storageState != AssetStorageState.Delete) {
maxActiveSlot = a.storageSlot;
maxActiveSlotIndex = i;
}
}
if (index == maxActiveSlotIndex) {
// In this case we are deleting the asset with the max storage slot so no swap is necessary.
assetToDelete.storageState = AssetStorageState.Delete;
return;
}
// Swap the storage slots of the deleted asset with the last non-deleted asset in the array. Mark them accordingly
// so that when we call store assets they will be updated appropriately
PortfolioAsset memory assetToSwap = portfolioState.storedAssets[maxActiveSlotIndex];
(
assetToSwap.storageSlot,
assetToDelete.storageSlot
) = (
assetToDelete.storageSlot,
assetToSwap.storageSlot
);
assetToSwap.storageState = AssetStorageState.Update;
assetToDelete.storageState = AssetStorageState.Delete;
}
/// @notice Returns a portfolio array, will be sorted
function getSortedPortfolio(address account, uint8 assetArrayLength)
internal
view
returns (PortfolioAsset[] memory)
{
PortfolioAsset[] memory assets = _loadAssetArray(account, assetArrayLength);
// No sorting required for length of 1
if (assets.length <= 1) return assets;
_sortInPlace(assets);
return assets;
}
/// @notice Builds a portfolio array from storage. The new assets hint parameter will
/// be used to provision a new array for the new assets. This will increase gas efficiency
/// so that we don't have to make copies when we extend the array.
function buildPortfolioState(
address account,
uint8 assetArrayLength,
uint256 newAssetsHint
) internal view returns (PortfolioState memory) {
PortfolioState memory state;
if (assetArrayLength == 0) return state;
state.storedAssets = getSortedPortfolio(account, assetArrayLength);
state.storedAssetLength = assetArrayLength;
state.newAssets = new PortfolioAsset[](newAssetsHint);
return state;
}
function _sortInPlace(PortfolioAsset[] memory assets) private pure {
uint256 length = assets.length;
uint256[] memory ids = new uint256[](length);
for (uint256 k; k < length; k++) {
PortfolioAsset memory asset = assets[k];
// Prepopulate the ids to calculate just once
ids[k] = TransferAssets.encodeAssetId(asset.currencyId, asset.maturity, asset.assetType);
}
// Uses insertion sort
uint256 i = 1;
while (i < length) {
uint256 j = i;
while (j > 0 && ids[j - 1] > ids[j]) {
// Swap j - 1 and j
(ids[j - 1], ids[j]) = (ids[j], ids[j - 1]);
(assets[j - 1], assets[j]) = (assets[j], assets[j - 1]);
j--;
}
i++;
}
}
function _loadAssetArray(address account, uint8 length)
private
view
returns (PortfolioAsset[] memory)
{
// This will overflow the storage pointer
require(length <= MAX_PORTFOLIO_ASSETS);
mapping(address =>
PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store = LibStorage.getPortfolioArrayStorage();
PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS] storage storageArray = store[account];
PortfolioAsset[] memory assets = new PortfolioAsset[](length);
for (uint256 i = 0; i < length; i++) {
PortfolioAssetStorage storage assetStorage = storageArray[i];
PortfolioAsset memory asset = assets[i];
uint256 slot;
assembly {
slot := assetStorage.slot
}
asset.currencyId = assetStorage.currencyId;
asset.maturity = assetStorage.maturity;
asset.assetType = assetStorage.assetType;
asset.notional = assetStorage.notional;
asset.storageSlot = slot;
}
return assets;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../global/LibStorage.sol";
import "./balances/BalanceHandler.sol";
import "./portfolio/BitmapAssetsHandler.sol";
import "./portfolio/PortfolioHandler.sol";
library AccountContextHandler {
using PortfolioHandler for PortfolioState;
bytes18 private constant TURN_OFF_PORTFOLIO_FLAGS = 0x7FFF7FFF7FFF7FFF7FFF7FFF7FFF7FFF7FFF;
event AccountContextUpdate(address indexed account);
/// @notice Returns the account context of a given account
function getAccountContext(address account) internal view returns (AccountContext memory) {
mapping(address => AccountContext) storage store = LibStorage.getAccountStorage();
return store[account];
}
/// @notice Sets the account context of a given account
function setAccountContext(AccountContext memory accountContext, address account) internal {
mapping(address => AccountContext) storage store = LibStorage.getAccountStorage();
store[account] = accountContext;
emit AccountContextUpdate(account);
}
function isBitmapEnabled(AccountContext memory accountContext) internal pure returns (bool) {
return accountContext.bitmapCurrencyId != 0;
}
/// @notice Enables a bitmap type portfolio for an account. A bitmap type portfolio allows
/// an account to hold more fCash than a normal portfolio, except only in a single currency.
/// Once enabled, it cannot be disabled or changed. An account can only enable a bitmap if
/// it has no assets or debt so that we ensure no assets are left stranded.
/// @param accountContext refers to the account where the bitmap will be enabled
/// @param currencyId the id of the currency to enable
/// @param blockTime the current block time to set the next settle time
function enableBitmapForAccount(
AccountContext memory accountContext,
uint16 currencyId,
uint256 blockTime
) internal view {
require(!isBitmapEnabled(accountContext), "Cannot change bitmap");
require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES, "Invalid currency id");
// Account cannot have assets or debts
require(accountContext.assetArrayLength == 0, "Cannot have assets");
require(accountContext.hasDebt == 0x00, "Cannot have debt");
// Ensure that the active currency is set to false in the array so that there is no double
// counting during FreeCollateral
setActiveCurrency(accountContext, currencyId, false, Constants.ACTIVE_IN_BALANCES);
accountContext.bitmapCurrencyId = currencyId;
// Setting this is required to initialize the assets bitmap
uint256 nextSettleTime = DateTime.getTimeUTC0(blockTime);
require(nextSettleTime < type(uint40).max); // dev: blockTime overflow
accountContext.nextSettleTime = uint40(nextSettleTime);
}
/// @notice Returns true if the context needs to settle
function mustSettleAssets(AccountContext memory accountContext) internal view returns (bool) {
uint256 blockTime = block.timestamp;
if (isBitmapEnabled(accountContext)) {
// nextSettleTime will be set to utc0 after settlement so we
// settle if this is strictly less than utc0
return accountContext.nextSettleTime < DateTime.getTimeUTC0(blockTime);
} else {
// 0 value occurs on an uninitialized account
// Assets mature exactly on the blockTime (not one second past) so in this
// case we settle on the block timestamp
return 0 < accountContext.nextSettleTime && accountContext.nextSettleTime <= blockTime;
}
}
/// @notice Checks if a currency id (uint16 max) is in the 9 slots in the account
/// context active currencies list.
/// @dev NOTE: this may be more efficient as a binary search since we know that the array
/// is sorted
function isActiveInBalances(AccountContext memory accountContext, uint256 currencyId)
internal
pure
returns (bool)
{
require(currencyId != 0 && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id
bytes18 currencies = accountContext.activeCurrencies;
if (accountContext.bitmapCurrencyId == currencyId) return true;
while (currencies != 0x00) {
uint256 cid = uint16(bytes2(currencies) & Constants.UNMASK_FLAGS);
if (cid == currencyId) {
// Currency found, return if it is active in balances or not
return bytes2(currencies) & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES;
}
currencies = currencies << 16;
}
return false;
}
/// @notice Iterates through the active currency list and removes, inserts or does nothing
/// to ensure that the active currency list is an ordered byte array of uint16 currency ids
/// that refer to the currencies that an account is active in.
///
/// This is called to ensure that currencies are active when the account has a non zero cash balance,
/// a non zero nToken balance or a portfolio asset.
function setActiveCurrency(
AccountContext memory accountContext,
uint256 currencyId,
bool isActive,
bytes2 flags
) internal pure {
require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id
// If the bitmapped currency is already set then return here. Turning off the bitmap currency
// id requires other logical handling so we will do it elsewhere.
if (isActive && accountContext.bitmapCurrencyId == currencyId) return;
bytes18 prefix;
bytes18 suffix = accountContext.activeCurrencies;
uint256 shifts;
/// There are six possible outcomes from this search:
/// 1. The currency id is in the list
/// - it must be set to active, do nothing
/// - it must be set to inactive, shift suffix and concatenate
/// 2. The current id is greater than the one in the search:
/// - it must be set to active, append to prefix and then concatenate the suffix,
/// ensure that we do not lose the last 2 bytes if set.
/// - it must be set to inactive, it is not in the list, do nothing
/// 3. Reached the end of the list:
/// - it must be set to active, check that the last two bytes are not set and then
/// append to the prefix
/// - it must be set to inactive, do nothing
while (suffix != 0x00) {
uint256 cid = uint256(uint16(bytes2(suffix) & Constants.UNMASK_FLAGS));
// if matches and isActive then return, already in list
if (cid == currencyId && isActive) {
// set flag and return
accountContext.activeCurrencies =
accountContext.activeCurrencies |
(bytes18(flags) >> (shifts * 16));
return;
}
// if matches and not active then shift suffix to remove
if (cid == currencyId && !isActive) {
// turn off flag, if both flags are off then remove
suffix = suffix & ~bytes18(flags);
if (bytes2(suffix) & ~Constants.UNMASK_FLAGS == 0x0000) suffix = suffix << 16;
accountContext.activeCurrencies = prefix | (suffix >> (shifts * 16));
return;
}
// if greater than and isActive then insert into prefix
if (cid > currencyId && isActive) {
prefix = prefix | (bytes18(bytes2(uint16(currencyId)) | flags) >> (shifts * 16));
// check that the total length is not greater than 9, meaning that the last
// two bytes of the active currencies array should be zero
require((accountContext.activeCurrencies << 128) == 0x00); // dev: AC: too many currencies
// append the suffix
accountContext.activeCurrencies = prefix | (suffix >> ((shifts + 1) * 16));
return;
}
// if past the point of the currency id and not active, not in list
if (cid > currencyId && !isActive) return;
prefix = prefix | (bytes18(bytes2(suffix)) >> (shifts * 16));
suffix = suffix << 16;
shifts += 1;
}
// If reached this point and not active then return
if (!isActive) return;
// if end and isActive then insert into suffix, check max length
require(shifts < 9); // dev: AC: too many currencies
accountContext.activeCurrencies =
prefix |
(bytes18(bytes2(uint16(currencyId)) | flags) >> (shifts * 16));
}
function _clearPortfolioActiveFlags(bytes18 activeCurrencies) internal pure returns (bytes18) {
bytes18 result;
// This is required to clear the suffix as we append below
bytes18 suffix = activeCurrencies & TURN_OFF_PORTFOLIO_FLAGS;
uint256 shifts;
// This loop will append all currencies that are active in balances into the result.
while (suffix != 0x00) {
if (bytes2(suffix) & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES) {
// If any flags are active, then append.
result = result | (bytes18(bytes2(suffix)) >> shifts);
shifts += 16;
}
suffix = suffix << 16;
}
return result;
}
/// @notice Stores a portfolio array and updates the account context information, this method should
/// be used whenever updating a portfolio array except in the case of nTokens
function storeAssetsAndUpdateContext(
AccountContext memory accountContext,
address account,
PortfolioState memory portfolioState,
bool isLiquidation
) internal {
// Each of these parameters is recalculated based on the entire array of assets in store assets,
// regardless of whether or not they have been updated.
(bool hasDebt, bytes32 portfolioCurrencies, uint8 assetArrayLength, uint40 nextSettleTime) =
portfolioState.storeAssets(account);
accountContext.nextSettleTime = nextSettleTime;
require(mustSettleAssets(accountContext) == false); // dev: cannot store matured assets
accountContext.assetArrayLength = assetArrayLength;
// During liquidation it is possible for an array to go over the max amount of assets allowed due to
// liquidity tokens being withdrawn into fCash.
if (!isLiquidation) {
require(assetArrayLength <= uint8(Constants.MAX_TRADED_MARKET_INDEX)); // dev: max assets allowed
}
// Sets the hasDebt flag properly based on whether or not portfolio has asset debt, meaning
// a negative fCash balance.
if (hasDebt) {
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT;
} else {
// Turns off the ASSET_DEBT flag
accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_ASSET_DEBT;
}
// Clear the active portfolio active flags and they will be recalculated in the next step
accountContext.activeCurrencies = _clearPortfolioActiveFlags(accountContext.activeCurrencies);
uint256 lastCurrency;
while (portfolioCurrencies != 0) {
// Portfolio currencies will not have flags, it is just an byte array of all the currencies found
// in a portfolio. They are appended in a sorted order so we can compare to the previous currency
// and only set it if they are different.
uint256 currencyId = uint16(bytes2(portfolioCurrencies));
if (currencyId != lastCurrency) {
setActiveCurrency(accountContext, currencyId, true, Constants.ACTIVE_IN_PORTFOLIO);
}
lastCurrency = currencyId;
portfolioCurrencies = portfolioCurrencies << 16;
}
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
interface NotionalCallback {
function notionalCallback(address sender, address account, bytes calldata callbackdata) external;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./AssetRate.sol";
import "./CashGroup.sol";
import "./DateTime.sol";
import "../balances/BalanceHandler.sol";
import "../../global/LibStorage.sol";
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../../math/SafeInt256.sol";
import "../../math/ABDKMath64x64.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library Market {
using SafeMath for uint256;
using SafeInt256 for int256;
using CashGroup for CashGroupParameters;
using AssetRate for AssetRateParameters;
// Max positive value for a ABDK64x64 integer
int256 private constant MAX64 = 0x7FFFFFFFFFFFFFFF;
/// @notice Add liquidity to a market, assuming that it is initialized. If not then
/// this method will revert and the market must be initialized first.
/// Return liquidityTokens and negative fCash to the portfolio
function addLiquidity(MarketParameters memory market, int256 assetCash)
internal
returns (int256 liquidityTokens, int256 fCash)
{
require(market.totalLiquidity > 0, "M: zero liquidity");
if (assetCash == 0) return (0, 0);
require(assetCash > 0); // dev: negative asset cash
liquidityTokens = market.totalLiquidity.mul(assetCash).div(market.totalAssetCash);
// No need to convert this to underlying, assetCash / totalAssetCash is a unitless proportion.
fCash = market.totalfCash.mul(assetCash).div(market.totalAssetCash);
market.totalLiquidity = market.totalLiquidity.add(liquidityTokens);
market.totalfCash = market.totalfCash.add(fCash);
market.totalAssetCash = market.totalAssetCash.add(assetCash);
_setMarketStorageForLiquidity(market);
// Flip the sign to represent the LP's net position
fCash = fCash.neg();
}
/// @notice Remove liquidity from a market, assuming that it is initialized.
/// Return assetCash and positive fCash to the portfolio
function removeLiquidity(MarketParameters memory market, int256 tokensToRemove)
internal
returns (int256 assetCash, int256 fCash)
{
if (tokensToRemove == 0) return (0, 0);
require(tokensToRemove > 0); // dev: negative tokens to remove
assetCash = market.totalAssetCash.mul(tokensToRemove).div(market.totalLiquidity);
fCash = market.totalfCash.mul(tokensToRemove).div(market.totalLiquidity);
market.totalLiquidity = market.totalLiquidity.subNoNeg(tokensToRemove);
market.totalfCash = market.totalfCash.subNoNeg(fCash);
market.totalAssetCash = market.totalAssetCash.subNoNeg(assetCash);
_setMarketStorageForLiquidity(market);
}
function executeTrade(
MarketParameters memory market,
CashGroupParameters memory cashGroup,
int256 fCashToAccount,
uint256 timeToMaturity,
uint256 marketIndex
) internal returns (int256 netAssetCash) {
int256 netAssetCashToReserve;
(netAssetCash, netAssetCashToReserve) = calculateTrade(
market,
cashGroup,
fCashToAccount,
timeToMaturity,
marketIndex
);
MarketStorage storage marketStorage = _getMarketStoragePointer(market);
_setMarketStorage(
marketStorage,
market.totalfCash,
market.totalAssetCash,
market.lastImpliedRate,
market.oracleRate,
market.previousTradeTime
);
BalanceHandler.incrementFeeToReserve(cashGroup.currencyId, netAssetCashToReserve);
}
/// @notice Calculates the asset cash amount the results from trading fCashToAccount with the market. A positive
/// fCashToAccount is equivalent of lending, a negative is borrowing. Updates the market state in memory.
/// @param market the current market state
/// @param cashGroup cash group configuration parameters
/// @param fCashToAccount the fCash amount that will be deposited into the user's portfolio. The net change
/// to the market is in the opposite direction.
/// @param timeToMaturity number of seconds until maturity
/// @return netAssetCash, netAssetCashToReserve
function calculateTrade(
MarketParameters memory market,
CashGroupParameters memory cashGroup,
int256 fCashToAccount,
uint256 timeToMaturity,
uint256 marketIndex
) internal view returns (int256, int256) {
// We return false if there is not enough fCash to support this trade.
// if fCashToAccount > 0 and totalfCash - fCashToAccount <= 0 then the trade will fail
// if fCashToAccount < 0 and totalfCash > 0 then this will always pass
if (market.totalfCash <= fCashToAccount) return (0, 0);
// Calculates initial rate factors for the trade
(int256 rateScalar, int256 totalCashUnderlying, int256 rateAnchor) =
getExchangeRateFactors(market, cashGroup, timeToMaturity, marketIndex);
// Calculates the exchange rate from cash to fCash before any liquidity fees
// are applied
int256 preFeeExchangeRate;
{
bool success;
(preFeeExchangeRate, success) = _getExchangeRate(
market.totalfCash,
totalCashUnderlying,
rateScalar,
rateAnchor,
fCashToAccount
);
if (!success) return (0, 0);
}
// Given the exchange rate, returns the net cash amounts to apply to each of the
// three relevant balances.
(int256 netCashToAccount, int256 netCashToMarket, int256 netCashToReserve) =
_getNetCashAmountsUnderlying(
cashGroup,
preFeeExchangeRate,
fCashToAccount,
timeToMaturity
);
// Signifies a failed net cash amount calculation
if (netCashToAccount == 0) return (0, 0);
{
// Set the new implied interest rate after the trade has taken effect, this
// will be used to calculate the next trader's interest rate.
market.totalfCash = market.totalfCash.subNoNeg(fCashToAccount);
market.lastImpliedRate = getImpliedRate(
market.totalfCash,
totalCashUnderlying.add(netCashToMarket),
rateScalar,
rateAnchor,
timeToMaturity
);
// It's technically possible that the implied rate is actually exactly zero (or
// more accurately the natural log rounds down to zero) but we will still fail
// in this case. If this does happen we may assume that markets are not initialized.
if (market.lastImpliedRate == 0) return (0, 0);
}
return
_setNewMarketState(
market,
cashGroup.assetRate,
netCashToAccount,
netCashToMarket,
netCashToReserve
);
}
/// @notice Returns factors for calculating exchange rates
/// @return
/// rateScalar: a scalar value in rate precision that defines the slope of the line
/// totalCashUnderlying: the converted asset cash to underlying cash for calculating
/// the exchange rates for the trade
/// rateAnchor: an offset from the x axis to maintain interest rate continuity over time
function getExchangeRateFactors(
MarketParameters memory market,
CashGroupParameters memory cashGroup,
uint256 timeToMaturity,
uint256 marketIndex
)
internal
pure
returns (
int256,
int256,
int256
)
{
int256 rateScalar = cashGroup.getRateScalar(marketIndex, timeToMaturity);
int256 totalCashUnderlying = cashGroup.assetRate.convertToUnderlying(market.totalAssetCash);
// This would result in a divide by zero
if (market.totalfCash == 0 || totalCashUnderlying == 0) return (0, 0, 0);
// Get the rate anchor given the market state, this will establish the baseline for where
// the exchange rate is set.
int256 rateAnchor;
{
bool success;
(rateAnchor, success) = _getRateAnchor(
market.totalfCash,
market.lastImpliedRate,
totalCashUnderlying,
rateScalar,
timeToMaturity
);
if (!success) return (0, 0, 0);
}
return (rateScalar, totalCashUnderlying, rateAnchor);
}
/// @dev Returns net asset cash amounts to the account, the market and the reserve
/// @return
/// netCashToAccount: this is a positive or negative amount of cash change to the account
/// netCashToMarket: this is a positive or negative amount of cash change in the market
// netCashToReserve: this is always a positive amount of cash accrued to the reserve
function _getNetCashAmountsUnderlying(
CashGroupParameters memory cashGroup,
int256 preFeeExchangeRate,
int256 fCashToAccount,
uint256 timeToMaturity
)
private
pure
returns (
int256,
int256,
int256
)
{
// Fees are specified in basis points which is an rate precision denomination. We convert this to
// an exchange rate denomination for the given time to maturity. (i.e. get e^(fee * t) and multiply
// or divide depending on the side of the trade).
// tradeExchangeRate = exp((tradeInterestRateNoFee +/- fee) * timeToMaturity)
// tradeExchangeRate = tradeExchangeRateNoFee (* or /) exp(fee * timeToMaturity)
// cash = fCash / exchangeRate, exchangeRate > 1
int256 preFeeCashToAccount =
fCashToAccount.divInRatePrecision(preFeeExchangeRate).neg();
int256 fee = getExchangeRateFromImpliedRate(cashGroup.getTotalFee(), timeToMaturity);
if (fCashToAccount > 0) {
// Lending
// Dividing reduces exchange rate, lending should receive less fCash for cash
int256 postFeeExchangeRate = preFeeExchangeRate.divInRatePrecision(fee);
// It's possible that the fee pushes exchange rates into negative territory. This is not possible
// when borrowing. If this happens then the trade has failed.
if (postFeeExchangeRate < Constants.RATE_PRECISION) return (0, 0, 0);
// cashToAccount = -(fCashToAccount / exchangeRate)
// postFeeExchangeRate = preFeeExchangeRate / feeExchangeRate
// preFeeCashToAccount = -(fCashToAccount / preFeeExchangeRate)
// postFeeCashToAccount = -(fCashToAccount / postFeeExchangeRate)
// netFee = preFeeCashToAccount - postFeeCashToAccount
// netFee = (fCashToAccount / postFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate)
// netFee = ((fCashToAccount * feeExchangeRate) / preFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate)
// netFee = (fCashToAccount / preFeeExchangeRate) * (feeExchangeRate - 1)
// netFee = -(preFeeCashToAccount) * (feeExchangeRate - 1)
// netFee = preFeeCashToAccount * (1 - feeExchangeRate)
// RATE_PRECISION - fee will be negative here, preFeeCashToAccount < 0, fee > 0
fee = preFeeCashToAccount.mulInRatePrecision(Constants.RATE_PRECISION.sub(fee));
} else {
// Borrowing
// cashToAccount = -(fCashToAccount / exchangeRate)
// postFeeExchangeRate = preFeeExchangeRate * feeExchangeRate
// netFee = preFeeCashToAccount - postFeeCashToAccount
// netFee = (fCashToAccount / postFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate)
// netFee = ((fCashToAccount / (feeExchangeRate * preFeeExchangeRate)) - (fCashToAccount / preFeeExchangeRate)
// netFee = (fCashToAccount / preFeeExchangeRate) * (1 / feeExchangeRate - 1)
// netFee = preFeeCashToAccount * ((1 - feeExchangeRate) / feeExchangeRate)
// NOTE: preFeeCashToAccount is negative in this branch so we negate it to ensure that fee is a positive number
// preFee * (1 - fee) / fee will be negative, use neg() to flip to positive
// RATE_PRECISION - fee will be negative
fee = preFeeCashToAccount.mul(Constants.RATE_PRECISION.sub(fee)).div(fee).neg();
}
int256 cashToReserve =
fee.mul(cashGroup.getReserveFeeShare()).div(Constants.PERCENTAGE_DECIMALS);
return (
// postFeeCashToAccount = preFeeCashToAccount - fee
preFeeCashToAccount.sub(fee),
// netCashToMarket = -(preFeeCashToAccount - fee + cashToReserve)
(preFeeCashToAccount.sub(fee).add(cashToReserve)).neg(),
cashToReserve
);
}
/// @notice Sets the new market state
/// @return
/// netAssetCashToAccount: the positive or negative change in asset cash to the account
/// assetCashToReserve: the positive amount of cash that accrues to the reserve
function _setNewMarketState(
MarketParameters memory market,
AssetRateParameters memory assetRate,
int256 netCashToAccount,
int256 netCashToMarket,
int256 netCashToReserve
) private view returns (int256, int256) {
int256 netAssetCashToMarket = assetRate.convertFromUnderlying(netCashToMarket);
// Set storage checks that total asset cash is above zero
market.totalAssetCash = market.totalAssetCash.add(netAssetCashToMarket);
// Sets the trade time for the next oracle update
market.previousTradeTime = block.timestamp;
int256 assetCashToReserve = assetRate.convertFromUnderlying(netCashToReserve);
int256 netAssetCashToAccount = assetRate.convertFromUnderlying(netCashToAccount);
return (netAssetCashToAccount, assetCashToReserve);
}
/// @notice Rate anchors update as the market gets closer to maturity. Rate anchors are not comparable
/// across time or markets but implied rates are. The goal here is to ensure that the implied rate
/// before and after the rate anchor update is the same. Therefore, the market will trade at the same implied
/// rate that it last traded at. If these anchors do not update then it opens up the opportunity for arbitrage
/// which will hurt the liquidity providers.
///
/// The rate anchor will update as the market rolls down to maturity. The calculation is:
/// newExchangeRate = e^(lastImpliedRate * timeToMaturity / Constants.IMPLIED_RATE_TIME)
/// newAnchor = newExchangeRate - ln((proportion / (1 - proportion)) / rateScalar
///
/// where:
/// lastImpliedRate = ln(exchangeRate') * (Constants.IMPLIED_RATE_TIME / timeToMaturity')
/// (calculated when the last trade in the market was made)
/// @return the new rate anchor and a boolean that signifies success
function _getRateAnchor(
int256 totalfCash,
uint256 lastImpliedRate,
int256 totalCashUnderlying,
int256 rateScalar,
uint256 timeToMaturity
) internal pure returns (int256, bool) {
// This is the exchange rate at the new time to maturity
int256 newExchangeRate = getExchangeRateFromImpliedRate(lastImpliedRate, timeToMaturity);
if (newExchangeRate < Constants.RATE_PRECISION) return (0, false);
int256 rateAnchor;
{
// totalfCash / (totalfCash + totalCashUnderlying)
int256 proportion =
totalfCash.divInRatePrecision(totalfCash.add(totalCashUnderlying));
(int256 lnProportion, bool success) = _logProportion(proportion);
if (!success) return (0, false);
// newExchangeRate - ln(proportion / (1 - proportion)) / rateScalar
rateAnchor = newExchangeRate.sub(lnProportion.divInRatePrecision(rateScalar));
}
return (rateAnchor, true);
}
/// @notice Calculates the current market implied rate.
/// @return the implied rate and a bool that is true on success
function getImpliedRate(
int256 totalfCash,
int256 totalCashUnderlying,
int256 rateScalar,
int256 rateAnchor,
uint256 timeToMaturity
) internal pure returns (uint256) {
// This will check for exchange rates < Constants.RATE_PRECISION
(int256 exchangeRate, bool success) =
_getExchangeRate(totalfCash, totalCashUnderlying, rateScalar, rateAnchor, 0);
if (!success) return 0;
// Uses continuous compounding to calculate the implied rate:
// ln(exchangeRate) * Constants.IMPLIED_RATE_TIME / timeToMaturity
int128 rate = ABDKMath64x64.fromInt(exchangeRate);
// Scales down to a floating point for LN
int128 rateScaled = ABDKMath64x64.div(rate, Constants.RATE_PRECISION_64x64);
// We will not have a negative log here because we check that exchangeRate > Constants.RATE_PRECISION
// inside getExchangeRate
int128 lnRateScaled = ABDKMath64x64.ln(rateScaled);
// Scales up to a fixed point
uint256 lnRate =
ABDKMath64x64.toUInt(ABDKMath64x64.mul(lnRateScaled, Constants.RATE_PRECISION_64x64));
// lnRate * IMPLIED_RATE_TIME / ttm
uint256 impliedRate = lnRate.mul(Constants.IMPLIED_RATE_TIME).div(timeToMaturity);
// Implied rates over 429% will overflow, this seems like a safe assumption
if (impliedRate > type(uint32).max) return 0;
return impliedRate;
}
/// @notice Converts an implied rate to an exchange rate given a time to maturity. The
/// formula is E = e^rt
function getExchangeRateFromImpliedRate(uint256 impliedRate, uint256 timeToMaturity)
internal
pure
returns (int256)
{
int128 expValue =
ABDKMath64x64.fromUInt(
impliedRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME)
);
int128 expValueScaled = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64);
int128 expResult = ABDKMath64x64.exp(expValueScaled);
int128 expResultScaled = ABDKMath64x64.mul(expResult, Constants.RATE_PRECISION_64x64);
return ABDKMath64x64.toInt(expResultScaled);
}
/// @notice Returns the exchange rate between fCash and cash for the given market
/// Calculates the following exchange rate:
/// (1 / rateScalar) * ln(proportion / (1 - proportion)) + rateAnchor
/// where:
/// proportion = totalfCash / (totalfCash + totalUnderlyingCash)
/// @dev has an underscore to denote as private but is marked internal for the mock
function _getExchangeRate(
int256 totalfCash,
int256 totalCashUnderlying,
int256 rateScalar,
int256 rateAnchor,
int256 fCashToAccount
) internal pure returns (int256, bool) {
int256 numerator = totalfCash.subNoNeg(fCashToAccount);
// This is the proportion scaled by Constants.RATE_PRECISION
// (totalfCash + fCash) / (totalfCash + totalCashUnderlying)
int256 proportion =
numerator.divInRatePrecision(totalfCash.add(totalCashUnderlying));
// This limit is here to prevent the market from reaching extremely high interest rates via an
// excessively large proportion (high amounts of fCash relative to cash).
// Market proportion can only increase via borrowing (fCash is added to the market and cash is
// removed). Over time, the returns from asset cash will slightly decrease the proportion (the
// value of cash underlying in the market must be monotonically increasing). Therefore it is not
// possible for the proportion to go over max market proportion unless borrowing occurs.
if (proportion > Constants.MAX_MARKET_PROPORTION) return (0, false);
(int256 lnProportion, bool success) = _logProportion(proportion);
if (!success) return (0, false);
// lnProportion / rateScalar + rateAnchor
int256 rate = lnProportion.divInRatePrecision(rateScalar).add(rateAnchor);
// Do not succeed if interest rates fall below 1
if (rate < Constants.RATE_PRECISION) {
return (0, false);
} else {
return (rate, true);
}
}
/// @dev This method calculates the log of the proportion inside the logit function which is
/// defined as ln(proportion / (1 - proportion)). Special handling here is required to deal with
/// fixed point precision and the ABDK library.
function _logProportion(int256 proportion) internal pure returns (int256, bool) {
// This will result in divide by zero, short circuit
if (proportion == Constants.RATE_PRECISION) return (0, false);
// Convert proportion to what is used inside the logit function (p / (1-p))
int256 logitP = proportion.divInRatePrecision(Constants.RATE_PRECISION.sub(proportion));
// ABDK does not handle log of numbers that are less than 1, in order to get the right value
// scaled by RATE_PRECISION we use the log identity:
// (ln(logitP / RATE_PRECISION)) * RATE_PRECISION = (ln(logitP) - ln(RATE_PRECISION)) * RATE_PRECISION
int128 abdkProportion = ABDKMath64x64.fromInt(logitP);
// Here, abdk will revert due to negative log so abort
if (abdkProportion <= 0) return (0, false);
int256 result =
ABDKMath64x64.toInt(
ABDKMath64x64.mul(
ABDKMath64x64.sub(
ABDKMath64x64.ln(abdkProportion),
Constants.LOG_RATE_PRECISION_64x64
),
Constants.RATE_PRECISION_64x64
)
);
return (result, true);
}
/// @notice Oracle rate protects against short term price manipulation. Time window will be set to a value
/// on the order of minutes to hours. This is to protect fCash valuations from market manipulation. For example,
/// a trader could use a flash loan to dump a large amount of cash into the market and depress interest rates.
/// Since we value fCash in portfolios based on these rates, portfolio values will decrease and they may then
/// be liquidated.
///
/// Oracle rates are calculated when the market is loaded from storage.
///
/// The oracle rate is a lagged weighted average over a short term price window. If we are past
/// the short term window then we just set the rate to the lastImpliedRate, otherwise we take the
/// weighted average:
/// lastImpliedRatePreTrade * (currentTs - previousTs) / timeWindow +
/// oracleRatePrevious * (1 - (currentTs - previousTs) / timeWindow)
function _updateRateOracle(
uint256 previousTradeTime,
uint256 lastImpliedRate,
uint256 oracleRate,
uint256 rateOracleTimeWindow,
uint256 blockTime
) private pure returns (uint256) {
require(rateOracleTimeWindow > 0); // dev: update rate oracle, time window zero
// This can occur when using a view function get to a market state in the past
if (previousTradeTime > blockTime) return lastImpliedRate;
uint256 timeDiff = blockTime.sub(previousTradeTime);
if (timeDiff > rateOracleTimeWindow) {
// If past the time window just return the lastImpliedRate
return lastImpliedRate;
}
// (currentTs - previousTs) / timeWindow
uint256 lastTradeWeight =
timeDiff.mul(uint256(Constants.RATE_PRECISION)).div(rateOracleTimeWindow);
// 1 - (currentTs - previousTs) / timeWindow
uint256 oracleWeight = uint256(Constants.RATE_PRECISION).sub(lastTradeWeight);
uint256 newOracleRate =
(lastImpliedRate.mul(lastTradeWeight).add(oracleRate.mul(oracleWeight))).div(
uint256(Constants.RATE_PRECISION)
);
return newOracleRate;
}
function getOracleRate(
uint256 currencyId,
uint256 maturity,
uint256 rateOracleTimeWindow,
uint256 blockTime
) internal view returns (uint256) {
mapping(uint256 => mapping(uint256 =>
mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage();
uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER;
MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate];
uint256 lastImpliedRate = marketStorage.lastImpliedRate;
uint256 oracleRate = marketStorage.oracleRate;
uint256 previousTradeTime = marketStorage.previousTradeTime;
// If the oracle rate is set to zero this can only be because the markets have past their settlement
// date but the new set of markets has not yet been initialized. This means that accounts cannot be liquidated
// during this time, but market initialization can be called by anyone so the actual time that this condition
// exists for should be quite short.
require(oracleRate > 0, "Market not initialized");
return
_updateRateOracle(
previousTradeTime,
lastImpliedRate,
oracleRate,
rateOracleTimeWindow,
blockTime
);
}
/// @notice Reads a market object directly from storage. `loadMarket` should be called instead of this method
/// which ensures that the rate oracle is set properly.
function _loadMarketStorage(
MarketParameters memory market,
uint256 currencyId,
uint256 maturity,
bool needsLiquidity,
uint256 settlementDate
) private view {
// Market object always uses the most current reference time as the settlement date
mapping(uint256 => mapping(uint256 =>
mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage();
MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate];
bytes32 slot;
assembly {
slot := marketStorage.slot
}
market.storageSlot = slot;
market.maturity = maturity;
market.totalfCash = marketStorage.totalfCash;
market.totalAssetCash = marketStorage.totalAssetCash;
market.lastImpliedRate = marketStorage.lastImpliedRate;
market.oracleRate = marketStorage.oracleRate;
market.previousTradeTime = marketStorage.previousTradeTime;
if (needsLiquidity) {
market.totalLiquidity = marketStorage.totalLiquidity;
} else {
market.totalLiquidity = 0;
}
}
function _getMarketStoragePointer(
MarketParameters memory market
) private pure returns (MarketStorage storage marketStorage) {
bytes32 slot = market.storageSlot;
assembly {
marketStorage.slot := slot
}
}
function _setMarketStorageForLiquidity(MarketParameters memory market) internal {
MarketStorage storage marketStorage = _getMarketStoragePointer(market);
// Oracle rate does not change on liquidity
uint32 storedOracleRate = marketStorage.oracleRate;
_setMarketStorage(
marketStorage,
market.totalfCash,
market.totalAssetCash,
market.lastImpliedRate,
storedOracleRate,
market.previousTradeTime
);
_setTotalLiquidity(marketStorage, market.totalLiquidity);
}
function setMarketStorageForInitialize(
MarketParameters memory market,
uint256 currencyId,
uint256 settlementDate
) internal {
// On initialization we have not yet calculated the storage slot so we get it here.
mapping(uint256 => mapping(uint256 =>
mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage();
MarketStorage storage marketStorage = store[currencyId][market.maturity][settlementDate];
_setMarketStorage(
marketStorage,
market.totalfCash,
market.totalAssetCash,
market.lastImpliedRate,
market.oracleRate,
market.previousTradeTime
);
_setTotalLiquidity(marketStorage, market.totalLiquidity);
}
function _setTotalLiquidity(
MarketStorage storage marketStorage,
int256 totalLiquidity
) internal {
require(totalLiquidity >= 0 && totalLiquidity <= type(uint80).max); // dev: market storage totalLiquidity overflow
marketStorage.totalLiquidity = uint80(totalLiquidity);
}
function _setMarketStorage(
MarketStorage storage marketStorage,
int256 totalfCash,
int256 totalAssetCash,
uint256 lastImpliedRate,
uint256 oracleRate,
uint256 previousTradeTime
) private {
require(totalfCash >= 0 && totalfCash <= type(uint80).max); // dev: storage totalfCash overflow
require(totalAssetCash >= 0 && totalAssetCash <= type(uint80).max); // dev: storage totalAssetCash overflow
require(0 < lastImpliedRate && lastImpliedRate <= type(uint32).max); // dev: storage lastImpliedRate overflow
require(0 < oracleRate && oracleRate <= type(uint32).max); // dev: storage oracleRate overflow
require(0 <= previousTradeTime && previousTradeTime <= type(uint32).max); // dev: storage previous trade time overflow
marketStorage.totalfCash = uint80(totalfCash);
marketStorage.totalAssetCash = uint80(totalAssetCash);
marketStorage.lastImpliedRate = uint32(lastImpliedRate);
marketStorage.oracleRate = uint32(oracleRate);
marketStorage.previousTradeTime = uint32(previousTradeTime);
}
/// @notice Creates a market object and ensures that the rate oracle time window is updated appropriately.
function loadMarket(
MarketParameters memory market,
uint256 currencyId,
uint256 maturity,
uint256 blockTime,
bool needsLiquidity,
uint256 rateOracleTimeWindow
) internal view {
// Always reference the current settlement date
uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER;
loadMarketWithSettlementDate(
market,
currencyId,
maturity,
blockTime,
needsLiquidity,
rateOracleTimeWindow,
settlementDate
);
}
/// @notice Creates a market object and ensures that the rate oracle time window is updated appropriately, this
/// is mainly used in the InitializeMarketAction contract.
function loadMarketWithSettlementDate(
MarketParameters memory market,
uint256 currencyId,
uint256 maturity,
uint256 blockTime,
bool needsLiquidity,
uint256 rateOracleTimeWindow,
uint256 settlementDate
) internal view {
_loadMarketStorage(market, currencyId, maturity, needsLiquidity, settlementDate);
market.oracleRate = _updateRateOracle(
market.previousTradeTime,
market.lastImpliedRate,
market.oracleRate,
rateOracleTimeWindow,
blockTime
);
}
function loadSettlementMarket(
MarketParameters memory market,
uint256 currencyId,
uint256 maturity,
uint256 settlementDate
) internal view {
_loadMarketStorage(market, currencyId, maturity, true, settlementDate);
}
/// Uses Newton's method to converge on an fCash amount given the amount of
/// cash. The relation between cash and fcash is:
/// cashAmount * exchangeRate * fee + fCash = 0
/// where exchangeRate(fCash) = (rateScalar ^ -1) * ln(p / (1 - p)) + rateAnchor
/// p = (totalfCash - fCash) / (totalfCash + totalCash)
/// if cashAmount < 0: fee = feeRate ^ -1
/// if cashAmount > 0: fee = feeRate
///
/// Newton's method is:
/// fCash_(n+1) = fCash_n - f(fCash) / f'(fCash)
///
/// f(fCash) = cashAmount * exchangeRate(fCash) * fee + fCash
///
/// (totalfCash + totalCash)
/// exchangeRate'(fCash) = - ------------------------------------------
/// (totalfCash - fCash) * (totalCash + fCash)
///
/// https://www.wolframalpha.com/input/?i=ln%28%28%28a-x%29%2F%28a%2Bb%29%29%2F%281-%28a-x%29%2F%28a%2Bb%29%29%29
///
/// (cashAmount * fee) * (totalfCash + totalCash)
/// f'(fCash) = 1 - ------------------------------------------------------
/// rateScalar * (totalfCash - fCash) * (totalCash + fCash)
///
/// NOTE: each iteration costs about 11.3k so this is only done via a view function.
function getfCashGivenCashAmount(
int256 totalfCash,
int256 netCashToAccount,
int256 totalCashUnderlying,
int256 rateScalar,
int256 rateAnchor,
int256 feeRate,
int256 maxDelta
) internal pure returns (int256) {
require(maxDelta >= 0);
int256 fCashChangeToAccountGuess = netCashToAccount.mulInRatePrecision(rateAnchor).neg();
for (uint8 i = 0; i < 250; i++) {
(int256 exchangeRate, bool success) =
_getExchangeRate(
totalfCash,
totalCashUnderlying,
rateScalar,
rateAnchor,
fCashChangeToAccountGuess
);
require(success); // dev: invalid exchange rate
int256 delta =
_calculateDelta(
netCashToAccount,
totalfCash,
totalCashUnderlying,
rateScalar,
fCashChangeToAccountGuess,
exchangeRate,
feeRate
);
if (delta.abs() <= maxDelta) return fCashChangeToAccountGuess;
fCashChangeToAccountGuess = fCashChangeToAccountGuess.sub(delta);
}
revert("No convergence");
}
/// @dev Calculates: f(fCash) / f'(fCash)
/// f(fCash) = cashAmount * exchangeRate * fee + fCash
/// (cashAmount * fee) * (totalfCash + totalCash)
/// f'(fCash) = 1 - ------------------------------------------------------
/// rateScalar * (totalfCash - fCash) * (totalCash + fCash)
function _calculateDelta(
int256 cashAmount,
int256 totalfCash,
int256 totalCashUnderlying,
int256 rateScalar,
int256 fCashGuess,
int256 exchangeRate,
int256 feeRate
) private pure returns (int256) {
int256 derivative;
// rateScalar * (totalfCash - fCash) * (totalCash + fCash)
// Precision: TOKEN_PRECISION ^ 2
int256 denominator =
rateScalar.mulInRatePrecision(
(totalfCash.sub(fCashGuess)).mul(totalCashUnderlying.add(fCashGuess))
);
if (fCashGuess > 0) {
// Lending
exchangeRate = exchangeRate.divInRatePrecision(feeRate);
require(exchangeRate >= Constants.RATE_PRECISION); // dev: rate underflow
// (cashAmount / fee) * (totalfCash + totalCash)
// Precision: TOKEN_PRECISION ^ 2
derivative = cashAmount
.mul(totalfCash.add(totalCashUnderlying))
.divInRatePrecision(feeRate);
} else {
// Borrowing
exchangeRate = exchangeRate.mulInRatePrecision(feeRate);
require(exchangeRate >= Constants.RATE_PRECISION); // dev: rate underflow
// (cashAmount * fee) * (totalfCash + totalCash)
// Precision: TOKEN_PRECISION ^ 2
derivative = cashAmount.mulInRatePrecision(
feeRate.mul(totalfCash.add(totalCashUnderlying))
);
}
// 1 - numerator / denominator
// Precision: TOKEN_PRECISION
derivative = Constants.INTERNAL_TOKEN_PRECISION.sub(derivative.div(denominator));
// f(fCash) = cashAmount * exchangeRate * fee + fCash
// NOTE: exchangeRate at this point already has the fee taken into account
int256 numerator = cashAmount.mulInRatePrecision(exchangeRate);
numerator = numerator.add(fCashGuess);
// f(fCash) / f'(fCash), note that they are both denominated as cashAmount so use TOKEN_PRECISION
// here instead of RATE_PRECISION
return numerator.mul(Constants.INTERNAL_TOKEN_PRECISION).div(derivative);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./Market.sol";
import "./AssetRate.sol";
import "./DateTime.sol";
import "../../global/LibStorage.sol";
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library CashGroup {
using SafeMath for uint256;
using SafeInt256 for int256;
using AssetRate for AssetRateParameters;
using Market for MarketParameters;
// Bit number references for each parameter in the 32 byte word (0-indexed)
uint256 private constant MARKET_INDEX_BIT = 31;
uint256 private constant RATE_ORACLE_TIME_WINDOW_BIT = 30;
uint256 private constant TOTAL_FEE_BIT = 29;
uint256 private constant RESERVE_FEE_SHARE_BIT = 28;
uint256 private constant DEBT_BUFFER_BIT = 27;
uint256 private constant FCASH_HAIRCUT_BIT = 26;
uint256 private constant SETTLEMENT_PENALTY_BIT = 25;
uint256 private constant LIQUIDATION_FCASH_HAIRCUT_BIT = 24;
uint256 private constant LIQUIDATION_DEBT_BUFFER_BIT = 23;
// 7 bytes allocated, one byte per market for the liquidity token haircut
uint256 private constant LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT = 22;
// 7 bytes allocated, one byte per market for the rate scalar
uint256 private constant RATE_SCALAR_FIRST_BIT = 15;
// Offsets for the bytes of the different parameters
uint256 private constant MARKET_INDEX = (31 - MARKET_INDEX_BIT) * 8;
uint256 private constant RATE_ORACLE_TIME_WINDOW = (31 - RATE_ORACLE_TIME_WINDOW_BIT) * 8;
uint256 private constant TOTAL_FEE = (31 - TOTAL_FEE_BIT) * 8;
uint256 private constant RESERVE_FEE_SHARE = (31 - RESERVE_FEE_SHARE_BIT) * 8;
uint256 private constant DEBT_BUFFER = (31 - DEBT_BUFFER_BIT) * 8;
uint256 private constant FCASH_HAIRCUT = (31 - FCASH_HAIRCUT_BIT) * 8;
uint256 private constant SETTLEMENT_PENALTY = (31 - SETTLEMENT_PENALTY_BIT) * 8;
uint256 private constant LIQUIDATION_FCASH_HAIRCUT = (31 - LIQUIDATION_FCASH_HAIRCUT_BIT) * 8;
uint256 private constant LIQUIDATION_DEBT_BUFFER = (31 - LIQUIDATION_DEBT_BUFFER_BIT) * 8;
uint256 private constant LIQUIDITY_TOKEN_HAIRCUT = (31 - LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT) * 8;
uint256 private constant RATE_SCALAR = (31 - RATE_SCALAR_FIRST_BIT) * 8;
/// @notice Returns the rate scalar scaled by time to maturity. The rate scalar multiplies
/// the ln() portion of the liquidity curve as an inverse so it increases with time to
/// maturity. The effect of the rate scalar on slippage must decrease with time to maturity.
function getRateScalar(
CashGroupParameters memory cashGroup,
uint256 marketIndex,
uint256 timeToMaturity
) internal pure returns (int256) {
require(1 <= marketIndex && marketIndex <= cashGroup.maxMarketIndex); // dev: invalid market index
uint256 offset = RATE_SCALAR + 8 * (marketIndex - 1);
int256 scalar = int256(uint8(uint256(cashGroup.data >> offset))) * Constants.RATE_PRECISION;
int256 rateScalar =
scalar.mul(int256(Constants.IMPLIED_RATE_TIME)).div(SafeInt256.toInt(timeToMaturity));
// Rate scalar is denominated in RATE_PRECISION, it is unlikely to underflow in the
// division above.
require(rateScalar > 0); // dev: rate scalar underflow
return rateScalar;
}
/// @notice Haircut on liquidity tokens to account for the risk associated with changes in the
/// proportion of cash to fCash within the pool. This is set as a percentage less than or equal to 100.
function getLiquidityHaircut(CashGroupParameters memory cashGroup, uint256 assetType)
internal
pure
returns (uint8)
{
require(
Constants.MIN_LIQUIDITY_TOKEN_INDEX <= assetType &&
assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX
); // dev: liquidity haircut invalid asset type
uint256 offset =
LIQUIDITY_TOKEN_HAIRCUT + 8 * (assetType - Constants.MIN_LIQUIDITY_TOKEN_INDEX);
return uint8(uint256(cashGroup.data >> offset));
}
/// @notice Total trading fee denominated in RATE_PRECISION with basis point increments
function getTotalFee(CashGroupParameters memory cashGroup) internal pure returns (uint256) {
return uint256(uint8(uint256(cashGroup.data >> TOTAL_FEE))) * Constants.BASIS_POINT;
}
/// @notice Percentage of the total trading fee that goes to the reserve
function getReserveFeeShare(CashGroupParameters memory cashGroup)
internal
pure
returns (int256)
{
return uint8(uint256(cashGroup.data >> RESERVE_FEE_SHARE));
}
/// @notice fCash haircut for valuation denominated in rate precision with five basis point increments
function getfCashHaircut(CashGroupParameters memory cashGroup) internal pure returns (uint256) {
return
uint256(uint8(uint256(cashGroup.data >> FCASH_HAIRCUT))) * Constants.FIVE_BASIS_POINTS;
}
/// @notice fCash debt buffer for valuation denominated in rate precision with five basis point increments
function getDebtBuffer(CashGroupParameters memory cashGroup) internal pure returns (uint256) {
return uint256(uint8(uint256(cashGroup.data >> DEBT_BUFFER))) * Constants.FIVE_BASIS_POINTS;
}
/// @notice Time window factor for the rate oracle denominated in seconds with five minute increments.
function getRateOracleTimeWindow(CashGroupParameters memory cashGroup)
internal
pure
returns (uint256)
{
// This is denominated in 5 minute increments in storage
return uint256(uint8(uint256(cashGroup.data >> RATE_ORACLE_TIME_WINDOW))) * Constants.FIVE_MINUTES;
}
/// @notice Penalty rate for settling cash debts denominated in basis points
function getSettlementPenalty(CashGroupParameters memory cashGroup)
internal
pure
returns (uint256)
{
return
uint256(uint8(uint256(cashGroup.data >> SETTLEMENT_PENALTY))) * Constants.FIVE_BASIS_POINTS;
}
/// @notice Haircut for positive fCash during liquidation denominated rate precision
/// with five basis point increments
function getLiquidationfCashHaircut(CashGroupParameters memory cashGroup)
internal
pure
returns (uint256)
{
return
uint256(uint8(uint256(cashGroup.data >> LIQUIDATION_FCASH_HAIRCUT))) * Constants.FIVE_BASIS_POINTS;
}
/// @notice Haircut for negative fCash during liquidation denominated rate precision
/// with five basis point increments
function getLiquidationDebtBuffer(CashGroupParameters memory cashGroup)
internal
pure
returns (uint256)
{
return
uint256(uint8(uint256(cashGroup.data >> LIQUIDATION_DEBT_BUFFER))) * Constants.FIVE_BASIS_POINTS;
}
function loadMarket(
CashGroupParameters memory cashGroup,
MarketParameters memory market,
uint256 marketIndex,
bool needsLiquidity,
uint256 blockTime
) internal view {
require(1 <= marketIndex && marketIndex <= cashGroup.maxMarketIndex, "Invalid market");
uint256 maturity =
DateTime.getReferenceTime(blockTime).add(DateTime.getTradedMarket(marketIndex));
market.loadMarket(
cashGroup.currencyId,
maturity,
blockTime,
needsLiquidity,
getRateOracleTimeWindow(cashGroup)
);
}
/// @notice Returns the linear interpolation between two market rates. The formula is
/// slope = (longMarket.oracleRate - shortMarket.oracleRate) / (longMarket.maturity - shortMarket.maturity)
/// interpolatedRate = slope * (assetMaturity - shortMarket.maturity) + shortMarket.oracleRate
function interpolateOracleRate(
uint256 shortMaturity,
uint256 longMaturity,
uint256 shortRate,
uint256 longRate,
uint256 assetMaturity
) internal pure returns (uint256) {
require(shortMaturity < assetMaturity); // dev: cash group interpolation error, short maturity
require(assetMaturity < longMaturity); // dev: cash group interpolation error, long maturity
// It's possible that the rates are inverted where the short market rate > long market rate and
// we will get an underflow here so we check for that
if (longRate >= shortRate) {
return
(longRate - shortRate)
.mul(assetMaturity - shortMaturity)
// No underflow here, checked above
.div(longMaturity - shortMaturity)
.add(shortRate);
} else {
// In this case the slope is negative so:
// interpolatedRate = shortMarket.oracleRate - slope * (assetMaturity - shortMarket.maturity)
// NOTE: this subtraction should never overflow, the linear interpolation between two points above zero
// cannot go below zero
return
shortRate.sub(
// This is reversed to keep it it positive
(shortRate - longRate)
.mul(assetMaturity - shortMaturity)
// No underflow here, checked above
.div(longMaturity - shortMaturity)
);
}
}
/// @dev Gets an oracle rate given any valid maturity.
function calculateOracleRate(
CashGroupParameters memory cashGroup,
uint256 maturity,
uint256 blockTime
) internal view returns (uint256) {
(uint256 marketIndex, bool idiosyncratic) =
DateTime.getMarketIndex(cashGroup.maxMarketIndex, maturity, blockTime);
uint256 timeWindow = getRateOracleTimeWindow(cashGroup);
if (!idiosyncratic) {
return Market.getOracleRate(cashGroup.currencyId, maturity, timeWindow, blockTime);
} else {
uint256 referenceTime = DateTime.getReferenceTime(blockTime);
// DateTime.getMarketIndex returns the market that is past the maturity if idiosyncratic
uint256 longMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex));
uint256 longRate =
Market.getOracleRate(cashGroup.currencyId, longMaturity, timeWindow, blockTime);
uint256 shortMaturity;
uint256 shortRate;
if (marketIndex == 1) {
// In this case the short market is the annualized asset supply rate
shortMaturity = blockTime;
shortRate = cashGroup.assetRate.getSupplyRate();
} else {
// Minimum value for marketIndex here is 2
shortMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex - 1));
shortRate = Market.getOracleRate(
cashGroup.currencyId,
shortMaturity,
timeWindow,
blockTime
);
}
return interpolateOracleRate(shortMaturity, longMaturity, shortRate, longRate, maturity);
}
}
function _getCashGroupStorageBytes(uint256 currencyId) private view returns (bytes32 data) {
mapping(uint256 => bytes32) storage store = LibStorage.getCashGroupStorage();
return store[currencyId];
}
/// @dev Helper method for validating maturities in ERC1155Action
function getMaxMarketIndex(uint256 currencyId) internal view returns (uint8) {
bytes32 data = _getCashGroupStorageBytes(currencyId);
return uint8(data[MARKET_INDEX_BIT]);
}
/// @notice Checks all cash group settings for invalid values and sets them into storage
function setCashGroupStorage(uint256 currencyId, CashGroupSettings calldata cashGroup)
internal
{
// Due to the requirements of the yield curve we do not allow a cash group to have solely a 3 month market.
// The reason is that borrowers will not have a further maturity to roll from their 3 month fixed to a 6 month
// fixed. It also complicates the logic in the nToken initialization method. Additionally, we cannot have cash
// groups with 0 market index, it has no effect.
require(2 <= cashGroup.maxMarketIndex && cashGroup.maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX,
"CG: invalid market index"
);
require(
cashGroup.reserveFeeShare <= Constants.PERCENTAGE_DECIMALS,
"CG: invalid reserve share"
);
require(cashGroup.liquidityTokenHaircuts.length == cashGroup.maxMarketIndex);
require(cashGroup.rateScalars.length == cashGroup.maxMarketIndex);
// This is required so that fCash liquidation can proceed correctly
require(cashGroup.liquidationfCashHaircut5BPS < cashGroup.fCashHaircut5BPS);
require(cashGroup.liquidationDebtBuffer5BPS < cashGroup.debtBuffer5BPS);
// Market indexes cannot decrease or they will leave fCash assets stranded in the future with no valuation curve
uint8 previousMaxMarketIndex = getMaxMarketIndex(currencyId);
require(
previousMaxMarketIndex <= cashGroup.maxMarketIndex,
"CG: market index cannot decrease"
);
// Per cash group settings
bytes32 data =
(bytes32(uint256(cashGroup.maxMarketIndex)) |
(bytes32(uint256(cashGroup.rateOracleTimeWindow5Min)) << RATE_ORACLE_TIME_WINDOW) |
(bytes32(uint256(cashGroup.totalFeeBPS)) << TOTAL_FEE) |
(bytes32(uint256(cashGroup.reserveFeeShare)) << RESERVE_FEE_SHARE) |
(bytes32(uint256(cashGroup.debtBuffer5BPS)) << DEBT_BUFFER) |
(bytes32(uint256(cashGroup.fCashHaircut5BPS)) << FCASH_HAIRCUT) |
(bytes32(uint256(cashGroup.settlementPenaltyRate5BPS)) << SETTLEMENT_PENALTY) |
(bytes32(uint256(cashGroup.liquidationfCashHaircut5BPS)) <<
LIQUIDATION_FCASH_HAIRCUT) |
(bytes32(uint256(cashGroup.liquidationDebtBuffer5BPS)) << LIQUIDATION_DEBT_BUFFER));
// Per market group settings
for (uint256 i = 0; i < cashGroup.liquidityTokenHaircuts.length; i++) {
require(
cashGroup.liquidityTokenHaircuts[i] <= Constants.PERCENTAGE_DECIMALS,
"CG: invalid token haircut"
);
data =
data |
(bytes32(uint256(cashGroup.liquidityTokenHaircuts[i])) <<
(LIQUIDITY_TOKEN_HAIRCUT + i * 8));
}
for (uint256 i = 0; i < cashGroup.rateScalars.length; i++) {
// Causes a divide by zero error
require(cashGroup.rateScalars[i] != 0, "CG: invalid rate scalar");
data = data | (bytes32(uint256(cashGroup.rateScalars[i])) << (RATE_SCALAR + i * 8));
}
mapping(uint256 => bytes32) storage store = LibStorage.getCashGroupStorage();
store[currencyId] = data;
}
/// @notice Deserialize the cash group storage bytes into a user friendly object
function deserializeCashGroupStorage(uint256 currencyId)
internal
view
returns (CashGroupSettings memory)
{
bytes32 data = _getCashGroupStorageBytes(currencyId);
uint8 maxMarketIndex = uint8(data[MARKET_INDEX_BIT]);
uint8[] memory tokenHaircuts = new uint8[](uint256(maxMarketIndex));
uint8[] memory rateScalars = new uint8[](uint256(maxMarketIndex));
for (uint8 i = 0; i < maxMarketIndex; i++) {
tokenHaircuts[i] = uint8(data[LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT - i]);
rateScalars[i] = uint8(data[RATE_SCALAR_FIRST_BIT - i]);
}
return
CashGroupSettings({
maxMarketIndex: maxMarketIndex,
rateOracleTimeWindow5Min: uint8(data[RATE_ORACLE_TIME_WINDOW_BIT]),
totalFeeBPS: uint8(data[TOTAL_FEE_BIT]),
reserveFeeShare: uint8(data[RESERVE_FEE_SHARE_BIT]),
debtBuffer5BPS: uint8(data[DEBT_BUFFER_BIT]),
fCashHaircut5BPS: uint8(data[FCASH_HAIRCUT_BIT]),
settlementPenaltyRate5BPS: uint8(data[SETTLEMENT_PENALTY_BIT]),
liquidationfCashHaircut5BPS: uint8(data[LIQUIDATION_FCASH_HAIRCUT_BIT]),
liquidationDebtBuffer5BPS: uint8(data[LIQUIDATION_DEBT_BUFFER_BIT]),
liquidityTokenHaircuts: tokenHaircuts,
rateScalars: rateScalars
});
}
function _buildCashGroup(uint16 currencyId, AssetRateParameters memory assetRate)
private
view
returns (CashGroupParameters memory)
{
bytes32 data = _getCashGroupStorageBytes(currencyId);
uint256 maxMarketIndex = uint8(data[MARKET_INDEX_BIT]);
return
CashGroupParameters({
currencyId: currencyId,
maxMarketIndex: maxMarketIndex,
assetRate: assetRate,
data: data
});
}
/// @notice Builds a cash group using a view version of the asset rate
function buildCashGroupView(uint16 currencyId)
internal
view
returns (CashGroupParameters memory)
{
AssetRateParameters memory assetRate = AssetRate.buildAssetRateView(currencyId);
return _buildCashGroup(currencyId, assetRate);
}
/// @notice Builds a cash group using a stateful version of the asset rate
function buildCashGroupStateful(uint16 currencyId)
internal
returns (CashGroupParameters memory)
{
AssetRateParameters memory assetRate = AssetRate.buildAssetRateStateful(currencyId);
return _buildCashGroup(currencyId, assetRate);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/Types.sol";
import "../../global/LibStorage.sol";
import "../../global/Constants.sol";
import "../../math/SafeInt256.sol";
import "../../../interfaces/notional/AssetRateAdapter.sol";
library AssetRate {
using SafeInt256 for int256;
event SetSettlementRate(uint256 indexed currencyId, uint256 indexed maturity, uint128 rate);
// Asset rates are in 1e18 decimals (cToken exchange rates), internal balances
// are in 1e8 decimals. Therefore we leave this as 1e18 / 1e8 = 1e10
int256 private constant ASSET_RATE_DECIMAL_DIFFERENCE = 1e10;
/// @notice Converts an internal asset cash value to its underlying token value.
/// @param ar exchange rate object between asset and underlying
/// @param assetBalance amount to convert to underlying
function convertToUnderlying(AssetRateParameters memory ar, int256 assetBalance)
internal
pure
returns (int256)
{
// Calculation here represents:
// rate * balance * internalPrecision / rateDecimals * underlyingPrecision
int256 underlyingBalance = ar.rate
.mul(assetBalance)
.div(ASSET_RATE_DECIMAL_DIFFERENCE)
.div(ar.underlyingDecimals);
return underlyingBalance;
}
/// @notice Converts an internal underlying cash value to its asset cash value
/// @param ar exchange rate object between asset and underlying
/// @param underlyingBalance amount to convert to asset cash, denominated in internal token precision
function convertFromUnderlying(AssetRateParameters memory ar, int256 underlyingBalance)
internal
pure
returns (int256)
{
// Calculation here represents:
// rateDecimals * balance * underlyingPrecision / rate * internalPrecision
int256 assetBalance = underlyingBalance
.mul(ASSET_RATE_DECIMAL_DIFFERENCE)
.mul(ar.underlyingDecimals)
.div(ar.rate);
return assetBalance;
}
/// @notice Returns the current per block supply rate, is used when calculating oracle rates
/// for idiosyncratic fCash with a shorter duration than the 3 month maturity.
function getSupplyRate(AssetRateParameters memory ar) internal view returns (uint256) {
// If the rate oracle is not set, the asset is not interest bearing and has an oracle rate of zero.
if (address(ar.rateOracle) == address(0)) return 0;
uint256 rate = ar.rateOracle.getAnnualizedSupplyRate();
// Zero supply rate is valid since this is an interest rate, we do not divide by
// the supply rate so we do not get div by zero errors.
require(rate >= 0); // dev: invalid supply rate
return rate;
}
function _getAssetRateStorage(uint256 currencyId)
private
view
returns (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces)
{
mapping(uint256 => AssetRateStorage) storage store = LibStorage.getAssetRateStorage();
AssetRateStorage storage ar = store[currencyId];
rateOracle = AssetRateAdapter(ar.rateOracle);
underlyingDecimalPlaces = ar.underlyingDecimalPlaces;
}
/// @notice Gets an asset rate using a view function, does not accrue interest so the
/// exchange rate will not be up to date. Should only be used for non-stateful methods
function _getAssetRateView(uint256 currencyId)
private
view
returns (
int256,
AssetRateAdapter,
uint8
)
{
(AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStorage(currencyId);
int256 rate;
if (address(rateOracle) == address(0)) {
// If no rate oracle is set, then set this to the identity
rate = ASSET_RATE_DECIMAL_DIFFERENCE;
// This will get raised to 10^x and return 1, will not end up with div by zero
underlyingDecimalPlaces = 0;
} else {
rate = rateOracle.getExchangeRateView();
require(rate > 0); // dev: invalid exchange rate
}
return (rate, rateOracle, underlyingDecimalPlaces);
}
/// @notice Gets an asset rate using a stateful function, accrues interest so the
/// exchange rate will be up to date for the current block.
function _getAssetRateStateful(uint256 currencyId)
private
returns (
int256,
AssetRateAdapter,
uint8
)
{
(AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStorage(currencyId);
int256 rate;
if (address(rateOracle) == address(0)) {
// If no rate oracle is set, then set this to the identity
rate = ASSET_RATE_DECIMAL_DIFFERENCE;
// This will get raised to 10^x and return 1, will not end up with div by zero
underlyingDecimalPlaces = 0;
} else {
rate = rateOracle.getExchangeRateStateful();
require(rate > 0); // dev: invalid exchange rate
}
return (rate, rateOracle, underlyingDecimalPlaces);
}
/// @notice Returns an asset rate object using the view method
function buildAssetRateView(uint256 currencyId)
internal
view
returns (AssetRateParameters memory)
{
(int256 rate, AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) =
_getAssetRateView(currencyId);
return
AssetRateParameters({
rateOracle: rateOracle,
rate: rate,
// No overflow, restricted on storage
underlyingDecimals: int256(10**underlyingDecimalPlaces)
});
}
/// @notice Returns an asset rate object using the stateful method
function buildAssetRateStateful(uint256 currencyId)
internal
returns (AssetRateParameters memory)
{
(int256 rate, AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) =
_getAssetRateStateful(currencyId);
return
AssetRateParameters({
rateOracle: rateOracle,
rate: rate,
// No overflow, restricted on storage
underlyingDecimals: int256(10**underlyingDecimalPlaces)
});
}
/// @dev Gets a settlement rate object
function _getSettlementRateStorage(uint256 currencyId, uint256 maturity)
private
view
returns (
int256 settlementRate,
uint8 underlyingDecimalPlaces
)
{
mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store = LibStorage.getSettlementRateStorage();
SettlementRateStorage storage rateStorage = store[currencyId][maturity];
settlementRate = rateStorage.settlementRate;
underlyingDecimalPlaces = rateStorage.underlyingDecimalPlaces;
}
/// @notice Returns a settlement rate object using the view method
function buildSettlementRateView(uint256 currencyId, uint256 maturity)
internal
view
returns (AssetRateParameters memory)
{
// prettier-ignore
(
int256 settlementRate,
uint8 underlyingDecimalPlaces
) = _getSettlementRateStorage(currencyId, maturity);
// Asset exchange rates cannot be zero
if (settlementRate == 0) {
// If settlement rate has not been set then we need to fetch it
// prettier-ignore
(
settlementRate,
/* address */,
underlyingDecimalPlaces
) = _getAssetRateView(currencyId);
}
return AssetRateParameters(
AssetRateAdapter(address(0)),
settlementRate,
// No overflow, restricted on storage
int256(10**underlyingDecimalPlaces)
);
}
/// @notice Returns a settlement rate object and sets the rate if it has not been set yet
function buildSettlementRateStateful(
uint256 currencyId,
uint256 maturity,
uint256 blockTime
) internal returns (AssetRateParameters memory) {
(int256 settlementRate, uint8 underlyingDecimalPlaces) =
_getSettlementRateStorage(currencyId, maturity);
if (settlementRate == 0) {
// Settlement rate has not yet been set, set it in this branch
AssetRateAdapter rateOracle;
// If rate oracle == 0 then this will return the identity settlement rate
// prettier-ignore
(
settlementRate,
rateOracle,
underlyingDecimalPlaces
) = _getAssetRateStateful(currencyId);
if (address(rateOracle) != address(0)) {
mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store = LibStorage.getSettlementRateStorage();
// Only need to set settlement rates when the rate oracle is set (meaning the asset token has
// a conversion rate to an underlying). If not set then the asset cash always settles to underlying at a 1-1
// rate since they are the same.
require(0 < blockTime && maturity <= blockTime && blockTime <= type(uint40).max); // dev: settlement rate timestamp overflow
require(0 < settlementRate && settlementRate <= type(uint128).max); // dev: settlement rate overflow
SettlementRateStorage storage rateStorage = store[currencyId][maturity];
rateStorage.blockTime = uint40(blockTime);
rateStorage.settlementRate = uint128(settlementRate);
rateStorage.underlyingDecimalPlaces = underlyingDecimalPlaces;
emit SetSettlementRate(currencyId, maturity, uint128(settlementRate));
}
}
return AssetRateParameters(
AssetRateAdapter(address(0)),
settlementRate,
// No overflow, restricted on storage
int256(10**underlyingDecimalPlaces)
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./PortfolioHandler.sol";
import "./BitmapAssetsHandler.sol";
import "../AccountContextHandler.sol";
import "../../global/Types.sol";
import "../../math/SafeInt256.sol";
/// @notice Helper library for transferring assets from one portfolio to another
library TransferAssets {
using AccountContextHandler for AccountContext;
using PortfolioHandler for PortfolioState;
using SafeInt256 for int256;
/// @notice Decodes asset ids
function decodeAssetId(uint256 id)
internal
pure
returns (
uint256 currencyId,
uint256 maturity,
uint256 assetType
)
{
assetType = uint8(id);
maturity = uint40(id >> 8);
currencyId = uint16(id >> 48);
}
/// @notice Encodes asset ids
function encodeAssetId(
uint256 currencyId,
uint256 maturity,
uint256 assetType
) internal pure returns (uint256) {
require(currencyId <= Constants.MAX_CURRENCIES);
require(maturity <= type(uint40).max);
require(assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX);
return
uint256(
(bytes32(uint256(uint16(currencyId))) << 48) |
(bytes32(uint256(uint40(maturity))) << 8) |
bytes32(uint256(uint8(assetType)))
);
}
/// @dev Used to flip the sign of assets to decrement the `from` account that is sending assets
function invertNotionalAmountsInPlace(PortfolioAsset[] memory assets) internal pure {
for (uint256 i; i < assets.length; i++) {
assets[i].notional = assets[i].notional.neg();
}
}
/// @dev Useful method for hiding the logic of updating an account. WARNING: the account
/// context returned from this method may not be the same memory location as the account
/// context provided if the account is settled.
function placeAssetsInAccount(
address account,
AccountContext memory accountContext,
PortfolioAsset[] memory assets
) internal returns (AccountContext memory) {
// If an account has assets that require settlement then placing assets inside it
// may cause issues.
require(!accountContext.mustSettleAssets(), "Account must settle");
if (accountContext.isBitmapEnabled()) {
// Adds fCash assets into the account and finalized storage
BitmapAssetsHandler.addMultipleifCashAssets(account, accountContext, assets);
} else {
PortfolioState memory portfolioState = PortfolioHandler.buildPortfolioState(
account,
accountContext.assetArrayLength,
assets.length
);
// This will add assets in memory
portfolioState.addMultipleAssets(assets);
// This will store assets and update the account context in memory
accountContext.storeAssetsAndUpdateContext(account, portfolioState, false);
}
return accountContext;
}
}
// 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: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./AssetHandler.sol";
import "./ExchangeRate.sol";
import "../markets/CashGroup.sol";
import "../AccountContextHandler.sol";
import "../balances/BalanceHandler.sol";
import "../portfolio/PortfolioHandler.sol";
import "../nToken/nTokenHandler.sol";
import "../nToken/nTokenCalculations.sol";
import "../../math/SafeInt256.sol";
library FreeCollateral {
using SafeInt256 for int256;
using Bitmap for bytes;
using ExchangeRate for ETHRate;
using AssetRate for AssetRateParameters;
using AccountContextHandler for AccountContext;
using nTokenHandler for nTokenPortfolio;
/// @dev This is only used within the library to clean up the stack
struct FreeCollateralFactors {
int256 netETHValue;
bool updateContext;
uint256 portfolioIndex;
CashGroupParameters cashGroup;
MarketParameters market;
PortfolioAsset[] portfolio;
AssetRateParameters assetRate;
nTokenPortfolio nToken;
}
/// @notice Checks if an asset is active in the portfolio
function _isActiveInPortfolio(bytes2 currencyBytes) private pure returns (bool) {
return currencyBytes & Constants.ACTIVE_IN_PORTFOLIO == Constants.ACTIVE_IN_PORTFOLIO;
}
/// @notice Checks if currency balances are active in the account returns them if true
/// @return cash balance, nTokenBalance
function _getCurrencyBalances(address account, bytes2 currencyBytes)
private
view
returns (int256, int256)
{
if (currencyBytes & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES) {
uint256 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS);
// prettier-ignore
(
int256 cashBalance,
int256 nTokenBalance,
/* lastClaimTime */,
/* accountIncentiveDebt */
) = BalanceHandler.getBalanceStorage(account, currencyId);
return (cashBalance, nTokenBalance);
}
return (0, 0);
}
/// @notice Calculates the nToken asset value with a haircut set by governance
/// @return the value of the account's nTokens after haircut, the nToken parameters
function _getNTokenHaircutAssetPV(
CashGroupParameters memory cashGroup,
nTokenPortfolio memory nToken,
int256 tokenBalance,
uint256 blockTime
) internal view returns (int256, bytes6) {
nToken.loadNTokenPortfolioNoCashGroup(cashGroup.currencyId);
nToken.cashGroup = cashGroup;
int256 nTokenAssetPV = nTokenCalculations.getNTokenAssetPV(nToken, blockTime);
// (tokenBalance * nTokenValue * haircut) / totalSupply
int256 nTokenHaircutAssetPV =
tokenBalance
.mul(nTokenAssetPV)
.mul(uint8(nToken.parameters[Constants.PV_HAIRCUT_PERCENTAGE]))
.div(Constants.PERCENTAGE_DECIMALS)
.div(nToken.totalSupply);
// nToken.parameters is returned for use in liquidation
return (nTokenHaircutAssetPV, nToken.parameters);
}
/// @notice Calculates portfolio and/or nToken values while using the supplied cash groups and
/// markets. The reason these are grouped together is because they both require storage reads of the same
/// values.
function _getPortfolioAndNTokenAssetValue(
FreeCollateralFactors memory factors,
int256 nTokenBalance,
uint256 blockTime
)
private
view
returns (
int256 netPortfolioValue,
int256 nTokenHaircutAssetValue,
bytes6 nTokenParameters
)
{
// If the next asset matches the currency id then we need to calculate the cash group value
if (
factors.portfolioIndex < factors.portfolio.length &&
factors.portfolio[factors.portfolioIndex].currencyId == factors.cashGroup.currencyId
) {
// netPortfolioValue is in asset cash
(netPortfolioValue, factors.portfolioIndex) = AssetHandler.getNetCashGroupValue(
factors.portfolio,
factors.cashGroup,
factors.market,
blockTime,
factors.portfolioIndex
);
} else {
netPortfolioValue = 0;
}
if (nTokenBalance > 0) {
(nTokenHaircutAssetValue, nTokenParameters) = _getNTokenHaircutAssetPV(
factors.cashGroup,
factors.nToken,
nTokenBalance,
blockTime
);
} else {
nTokenHaircutAssetValue = 0;
nTokenParameters = 0;
}
}
/// @notice Returns balance values for the bitmapped currency
function _getBitmapBalanceValue(
address account,
uint256 blockTime,
AccountContext memory accountContext,
FreeCollateralFactors memory factors
)
private
view
returns (
int256 cashBalance,
int256 nTokenHaircutAssetValue,
bytes6 nTokenParameters
)
{
int256 nTokenBalance;
// prettier-ignore
(
cashBalance,
nTokenBalance,
/* lastClaimTime */,
/* accountIncentiveDebt */
) = BalanceHandler.getBalanceStorage(account, accountContext.bitmapCurrencyId);
if (nTokenBalance > 0) {
(nTokenHaircutAssetValue, nTokenParameters) = _getNTokenHaircutAssetPV(
factors.cashGroup,
factors.nToken,
nTokenBalance,
blockTime
);
} else {
nTokenHaircutAssetValue = 0;
}
}
/// @notice Returns portfolio value for the bitmapped currency
function _getBitmapPortfolioValue(
address account,
uint256 blockTime,
AccountContext memory accountContext,
FreeCollateralFactors memory factors
) private view returns (int256) {
(int256 netPortfolioValueUnderlying, bool bitmapHasDebt) =
BitmapAssetsHandler.getifCashNetPresentValue(
account,
accountContext.bitmapCurrencyId,
accountContext.nextSettleTime,
blockTime,
factors.cashGroup,
true // risk adjusted
);
// Turns off has debt flag if it has changed
bool contextHasAssetDebt =
accountContext.hasDebt & Constants.HAS_ASSET_DEBT == Constants.HAS_ASSET_DEBT;
if (bitmapHasDebt && !contextHasAssetDebt) {
// Turn on has debt
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT;
factors.updateContext = true;
} else if (!bitmapHasDebt && contextHasAssetDebt) {
// Turn off has debt
accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_ASSET_DEBT;
factors.updateContext = true;
}
// Return asset cash value
return factors.cashGroup.assetRate.convertFromUnderlying(netPortfolioValueUnderlying);
}
function _updateNetETHValue(
uint256 currencyId,
int256 netLocalAssetValue,
FreeCollateralFactors memory factors
) private view returns (ETHRate memory) {
ETHRate memory ethRate = ExchangeRate.buildExchangeRate(currencyId);
// Converts to underlying first, ETH exchange rates are in underlying
factors.netETHValue = factors.netETHValue.add(
ethRate.convertToETH(factors.assetRate.convertToUnderlying(netLocalAssetValue))
);
return ethRate;
}
/// @notice Stateful version of get free collateral, returns the total net ETH value and true or false if the account
/// context needs to be updated.
function getFreeCollateralStateful(
address account,
AccountContext memory accountContext,
uint256 blockTime
) internal returns (int256, bool) {
FreeCollateralFactors memory factors;
bool hasCashDebt;
if (accountContext.isBitmapEnabled()) {
factors.cashGroup = CashGroup.buildCashGroupStateful(accountContext.bitmapCurrencyId);
// prettier-ignore
(
int256 netCashBalance,
int256 nTokenHaircutAssetValue,
/* nTokenParameters */
) = _getBitmapBalanceValue(account, blockTime, accountContext, factors);
if (netCashBalance < 0) hasCashDebt = true;
int256 portfolioAssetValue =
_getBitmapPortfolioValue(account, blockTime, accountContext, factors);
int256 netLocalAssetValue =
netCashBalance.add(nTokenHaircutAssetValue).add(portfolioAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
_updateNetETHValue(accountContext.bitmapCurrencyId, netLocalAssetValue, factors);
} else {
factors.portfolio = PortfolioHandler.getSortedPortfolio(
account,
accountContext.assetArrayLength
);
}
bytes18 currencies = accountContext.activeCurrencies;
while (currencies != 0) {
bytes2 currencyBytes = bytes2(currencies);
uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS);
// Explicitly ensures that bitmap currency cannot be double counted
require(currencyId != accountContext.bitmapCurrencyId);
(int256 netLocalAssetValue, int256 nTokenBalance) =
_getCurrencyBalances(account, currencyBytes);
if (netLocalAssetValue < 0) hasCashDebt = true;
if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) {
factors.cashGroup = CashGroup.buildCashGroupStateful(currencyId);
// prettier-ignore
(
int256 netPortfolioAssetValue,
int256 nTokenHaircutAssetValue,
/* nTokenParameters */
) = _getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime);
netLocalAssetValue = netLocalAssetValue
.add(netPortfolioAssetValue)
.add(nTokenHaircutAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
} else {
// NOTE: we must set the proper assetRate when we updateNetETHValue
factors.assetRate = AssetRate.buildAssetRateStateful(currencyId);
}
_updateNetETHValue(currencyId, netLocalAssetValue, factors);
currencies = currencies << 16;
}
// Free collateral is the only method that examines all cash balances for an account at once. If there is no cash debt (i.e.
// they have been repaid or settled via more debt) then this will turn off the flag. It's possible that this flag is out of
// sync temporarily after a cash settlement and before the next free collateral check. The only downside for that is forcing
// an account to do an extra free collateral check to turn off this setting.
if (
accountContext.hasDebt & Constants.HAS_CASH_DEBT == Constants.HAS_CASH_DEBT &&
!hasCashDebt
) {
accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_CASH_DEBT;
factors.updateContext = true;
}
return (factors.netETHValue, factors.updateContext);
}
/// @notice View version of getFreeCollateral, does not use the stateful version of build cash group and skips
/// all the update context logic.
function getFreeCollateralView(
address account,
AccountContext memory accountContext,
uint256 blockTime
) internal view returns (int256, int256[] memory) {
FreeCollateralFactors memory factors;
uint256 netLocalIndex;
int256[] memory netLocalAssetValues = new int256[](10);
if (accountContext.isBitmapEnabled()) {
factors.cashGroup = CashGroup.buildCashGroupView(accountContext.bitmapCurrencyId);
// prettier-ignore
(
int256 netCashBalance,
int256 nTokenHaircutAssetValue,
/* nTokenParameters */
) = _getBitmapBalanceValue(account, blockTime, accountContext, factors);
int256 portfolioAssetValue =
_getBitmapPortfolioValue(account, blockTime, accountContext, factors);
netLocalAssetValues[netLocalIndex] = netCashBalance
.add(nTokenHaircutAssetValue)
.add(portfolioAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
_updateNetETHValue(
accountContext.bitmapCurrencyId,
netLocalAssetValues[netLocalIndex],
factors
);
netLocalIndex++;
} else {
factors.portfolio = PortfolioHandler.getSortedPortfolio(
account,
accountContext.assetArrayLength
);
}
bytes18 currencies = accountContext.activeCurrencies;
while (currencies != 0) {
bytes2 currencyBytes = bytes2(currencies);
uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS);
// Explicitly ensures that bitmap currency cannot be double counted
require(currencyId != accountContext.bitmapCurrencyId);
int256 nTokenBalance;
(netLocalAssetValues[netLocalIndex], nTokenBalance) = _getCurrencyBalances(
account,
currencyBytes
);
if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) {
factors.cashGroup = CashGroup.buildCashGroupView(currencyId);
// prettier-ignore
(
int256 netPortfolioValue,
int256 nTokenHaircutAssetValue,
/* nTokenParameters */
) = _getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime);
netLocalAssetValues[netLocalIndex] = netLocalAssetValues[netLocalIndex]
.add(netPortfolioValue)
.add(nTokenHaircutAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
} else {
factors.assetRate = AssetRate.buildAssetRateView(currencyId);
}
_updateNetETHValue(currencyId, netLocalAssetValues[netLocalIndex], factors);
netLocalIndex++;
currencies = currencies << 16;
}
return (factors.netETHValue, netLocalAssetValues);
}
/// @notice Calculates the net value of a currency within a portfolio, this is a bit
/// convoluted to fit into the stack frame
function _calculateLiquidationAssetValue(
FreeCollateralFactors memory factors,
LiquidationFactors memory liquidationFactors,
bytes2 currencyBytes,
bool setLiquidationFactors,
uint256 blockTime
) private returns (int256) {
uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS);
(int256 netLocalAssetValue, int256 nTokenBalance) =
_getCurrencyBalances(liquidationFactors.account, currencyBytes);
if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) {
factors.cashGroup = CashGroup.buildCashGroupStateful(currencyId);
(int256 netPortfolioValue, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters) =
_getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime);
netLocalAssetValue = netLocalAssetValue
.add(netPortfolioValue)
.add(nTokenHaircutAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
// If collateralCurrencyId is set to zero then this is a local currency liquidation
if (setLiquidationFactors) {
liquidationFactors.collateralCashGroup = factors.cashGroup;
liquidationFactors.nTokenParameters = nTokenParameters;
liquidationFactors.nTokenHaircutAssetValue = nTokenHaircutAssetValue;
}
} else {
factors.assetRate = AssetRate.buildAssetRateStateful(currencyId);
}
return netLocalAssetValue;
}
/// @notice A version of getFreeCollateral used during liquidation to save off necessary additional information.
function getLiquidationFactors(
address account,
AccountContext memory accountContext,
uint256 blockTime,
uint256 localCurrencyId,
uint256 collateralCurrencyId
) internal returns (LiquidationFactors memory, PortfolioAsset[] memory) {
FreeCollateralFactors memory factors;
LiquidationFactors memory liquidationFactors;
// This is only set to reduce the stack size
liquidationFactors.account = account;
if (accountContext.isBitmapEnabled()) {
factors.cashGroup = CashGroup.buildCashGroupStateful(accountContext.bitmapCurrencyId);
(int256 netCashBalance, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters) =
_getBitmapBalanceValue(account, blockTime, accountContext, factors);
int256 portfolioBalance =
_getBitmapPortfolioValue(account, blockTime, accountContext, factors);
int256 netLocalAssetValue =
netCashBalance.add(nTokenHaircutAssetValue).add(portfolioBalance);
factors.assetRate = factors.cashGroup.assetRate;
ETHRate memory ethRate =
_updateNetETHValue(accountContext.bitmapCurrencyId, netLocalAssetValue, factors);
// If the bitmap currency id can only ever be the local currency where debt is held.
// During enable bitmap we check that the account has no assets in their portfolio and
// no cash debts.
if (accountContext.bitmapCurrencyId == localCurrencyId) {
liquidationFactors.localAssetAvailable = netLocalAssetValue;
liquidationFactors.localETHRate = ethRate;
liquidationFactors.localAssetRate = factors.assetRate;
// This will be the case during local currency or local fCash liquidation
if (collateralCurrencyId == 0) {
// If this is local fCash liquidation, the cash group information is required
// to calculate fCash haircuts and buffers.
liquidationFactors.collateralCashGroup = factors.cashGroup;
liquidationFactors.nTokenHaircutAssetValue = nTokenHaircutAssetValue;
liquidationFactors.nTokenParameters = nTokenParameters;
}
}
} else {
factors.portfolio = PortfolioHandler.getSortedPortfolio(
account,
accountContext.assetArrayLength
);
}
bytes18 currencies = accountContext.activeCurrencies;
while (currencies != 0) {
bytes2 currencyBytes = bytes2(currencies);
// This next bit of code here is annoyingly structured to get around stack size issues
bool setLiquidationFactors;
{
uint256 tempId = uint256(uint16(currencyBytes & Constants.UNMASK_FLAGS));
// Explicitly ensures that bitmap currency cannot be double counted
require(tempId != accountContext.bitmapCurrencyId);
setLiquidationFactors =
(tempId == localCurrencyId && collateralCurrencyId == 0) ||
tempId == collateralCurrencyId;
}
int256 netLocalAssetValue =
_calculateLiquidationAssetValue(
factors,
liquidationFactors,
currencyBytes,
setLiquidationFactors,
blockTime
);
uint256 currencyId = uint256(uint16(currencyBytes & Constants.UNMASK_FLAGS));
ETHRate memory ethRate = _updateNetETHValue(currencyId, netLocalAssetValue, factors);
if (currencyId == collateralCurrencyId) {
// Ensure that this is set even if the cash group is not loaded, it will not be
// loaded if the account only has a cash balance and no nTokens or assets
liquidationFactors.collateralCashGroup.assetRate = factors.assetRate;
liquidationFactors.collateralAssetAvailable = netLocalAssetValue;
liquidationFactors.collateralETHRate = ethRate;
} else if (currencyId == localCurrencyId) {
// This branch will not be entered if bitmap is enabled
liquidationFactors.localAssetAvailable = netLocalAssetValue;
liquidationFactors.localETHRate = ethRate;
liquidationFactors.localAssetRate = factors.assetRate;
// If this is local fCash liquidation, the cash group information is required
// to calculate fCash haircuts and buffers and it will have been set in
// _calculateLiquidationAssetValue above because the account must have fCash assets,
// there is no need to set cash group in this branch.
}
currencies = currencies << 16;
}
liquidationFactors.netETHValue = factors.netETHValue;
require(liquidationFactors.netETHValue < 0, "Sufficient collateral");
// Refetch the portfolio if it exists, AssetHandler.getNetCashValue updates values in memory to do fCash
// netting which will make further calculations incorrect.
if (accountContext.assetArrayLength > 0) {
factors.portfolio = PortfolioHandler.getSortedPortfolio(
account,
accountContext.assetArrayLength
);
}
return (liquidationFactors, factors.portfolio);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../valuation/AssetHandler.sol";
import "../markets/Market.sol";
import "../markets/AssetRate.sol";
import "../portfolio/PortfolioHandler.sol";
import "../../math/SafeInt256.sol";
import "../../global/Constants.sol";
import "../../global/Types.sol";
library SettlePortfolioAssets {
using SafeInt256 for int256;
using AssetRate for AssetRateParameters;
using Market for MarketParameters;
using PortfolioHandler for PortfolioState;
using AssetHandler for PortfolioAsset;
/// @dev Returns a SettleAmount array for the assets that will be settled
function _getSettleAmountArray(PortfolioState memory portfolioState, uint256 blockTime)
private
pure
returns (SettleAmount[] memory)
{
uint256 currenciesSettled;
uint256 lastCurrencyId = 0;
if (portfolioState.storedAssets.length == 0) return new SettleAmount[](0);
// Loop backwards so "lastCurrencyId" will be set to the first currency in the portfolio
// NOTE: if this contract is ever upgraded to Solidity 0.8+ then this i-- will underflow and cause
// a revert, must wrap in an unchecked.
for (uint256 i = portfolioState.storedAssets.length; (i--) > 0;) {
PortfolioAsset memory asset = portfolioState.storedAssets[i];
// Assets settle on exactly blockTime
if (asset.getSettlementDate() > blockTime) continue;
// Assume that this is sorted by cash group and maturity, currencyId = 0 is unused so this
// will work for the first asset
if (lastCurrencyId != asset.currencyId) {
lastCurrencyId = asset.currencyId;
currenciesSettled++;
}
}
// Actual currency ids will be set as we loop through the portfolio and settle assets
SettleAmount[] memory settleAmounts = new SettleAmount[](currenciesSettled);
if (currenciesSettled > 0) settleAmounts[0].currencyId = lastCurrencyId;
return settleAmounts;
}
/// @notice Settles a portfolio array
function settlePortfolio(PortfolioState memory portfolioState, uint256 blockTime)
internal
returns (SettleAmount[] memory)
{
AssetRateParameters memory settlementRate;
SettleAmount[] memory settleAmounts = _getSettleAmountArray(portfolioState, blockTime);
MarketParameters memory market;
if (settleAmounts.length == 0) return settleAmounts;
uint256 settleAmountIndex;
for (uint256 i; i < portfolioState.storedAssets.length; i++) {
PortfolioAsset memory asset = portfolioState.storedAssets[i];
uint256 settleDate = asset.getSettlementDate();
// Settlement date is on block time exactly
if (settleDate > blockTime) continue;
// On the first loop the lastCurrencyId is already set.
if (settleAmounts[settleAmountIndex].currencyId != asset.currencyId) {
// New currency in the portfolio
settleAmountIndex += 1;
settleAmounts[settleAmountIndex].currencyId = asset.currencyId;
}
int256 assetCash;
if (asset.assetType == Constants.FCASH_ASSET_TYPE) {
// Gets or sets the settlement rate, only do this before settling fCash
settlementRate = AssetRate.buildSettlementRateStateful(
asset.currencyId,
asset.maturity,
blockTime
);
assetCash = settlementRate.convertFromUnderlying(asset.notional);
portfolioState.deleteAsset(i);
} else if (AssetHandler.isLiquidityToken(asset.assetType)) {
Market.loadSettlementMarket(market, asset.currencyId, asset.maturity, settleDate);
int256 fCash;
(assetCash, fCash) = market.removeLiquidity(asset.notional);
// Assets mature exactly on block time
if (asset.maturity > blockTime) {
// If fCash has not yet matured then add it to the portfolio
_settleLiquidityTokenTofCash(portfolioState, i, fCash);
} else {
// Gets or sets the settlement rate, only do this before settling fCash
settlementRate = AssetRate.buildSettlementRateStateful(
asset.currencyId,
asset.maturity,
blockTime
);
// If asset has matured then settle fCash to asset cash
assetCash = assetCash.add(settlementRate.convertFromUnderlying(fCash));
portfolioState.deleteAsset(i);
}
}
settleAmounts[settleAmountIndex].netCashChange = settleAmounts[settleAmountIndex]
.netCashChange
.add(assetCash);
}
return settleAmounts;
}
/// @notice Settles a liquidity token to idiosyncratic fCash, this occurs when the maturity is still in the future
function _settleLiquidityTokenTofCash(
PortfolioState memory portfolioState,
uint256 index,
int256 fCash
) private pure {
PortfolioAsset memory liquidityToken = portfolioState.storedAssets[index];
// If the liquidity token's maturity is still in the future then we change the entry to be
// an idiosyncratic fCash entry with the net fCash amount.
if (index != 0) {
// Check to see if the previous index is the matching fCash asset, this will be the case when the
// portfolio is sorted
PortfolioAsset memory fCashAsset = portfolioState.storedAssets[index - 1];
if (
fCashAsset.currencyId == liquidityToken.currencyId &&
fCashAsset.maturity == liquidityToken.maturity &&
fCashAsset.assetType == Constants.FCASH_ASSET_TYPE
) {
// This fCash asset has not matured if we are settling to fCash
fCashAsset.notional = fCashAsset.notional.add(fCash);
fCashAsset.storageState = AssetStorageState.Update;
portfolioState.deleteAsset(index);
}
}
// We are going to delete this asset anyway, convert to an fCash position
liquidityToken.assetType = Constants.FCASH_ASSET_TYPE;
liquidityToken.notional = fCash;
liquidityToken.storageState = AssetStorageState.Update;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../markets/AssetRate.sol";
import "../../global/LibStorage.sol";
import "../portfolio/BitmapAssetsHandler.sol";
import "../../math/SafeInt256.sol";
import "../../math/Bitmap.sol";
import "../../global/Constants.sol";
import "../../global/Types.sol";
/**
* Settles a bitmap portfolio by checking for all matured fCash assets and turning them into cash
* at the prevailing settlement rate. It will also update the asset bitmap to ensure that it continues
* to correctly reference all actual maturities. fCash asset notional values are stored in *absolute*
* time terms and bitmap bits are *relative* time terms based on the bitNumber and the stored oldSettleTime.
* Remapping bits requires converting the old relative bit numbers to new relative bit numbers based on
* newSettleTime and the absolute times (maturities) that the previous bitmap references.
*/
library SettleBitmapAssets {
using SafeInt256 for int256;
using AssetRate for AssetRateParameters;
using Bitmap for bytes32;
/// @notice Given a bitmap for a cash group and timestamps, will settle all assets
/// that have matured and remap the bitmap to correspond to the current time.
function settleBitmappedCashGroup(
address account,
uint256 currencyId,
uint256 oldSettleTime,
uint256 blockTime
) internal returns (int256 totalAssetCash, uint256 newSettleTime) {
bytes32 bitmap = BitmapAssetsHandler.getAssetsBitmap(account, currencyId);
// This newSettleTime will be set to the new `oldSettleTime`. The bits between 1 and
// `lastSettleBit` (inclusive) will be shifted out of the bitmap and settled. The reason
// that lastSettleBit is inclusive is that it refers to newSettleTime which always less
// than the current block time.
newSettleTime = DateTime.getTimeUTC0(blockTime);
// If newSettleTime == oldSettleTime lastSettleBit will be zero
require(newSettleTime >= oldSettleTime); // dev: new settle time before previous
// Do not need to worry about validity, if newSettleTime is not on an exact bit we will settle up until
// the closest maturity that is less than newSettleTime.
(uint256 lastSettleBit, /* isValid */) = DateTime.getBitNumFromMaturity(oldSettleTime, newSettleTime);
if (lastSettleBit == 0) return (totalAssetCash, newSettleTime);
// Returns the next bit that is set in the bitmap
uint256 nextBitNum = bitmap.getNextBitNum();
while (nextBitNum != 0 && nextBitNum <= lastSettleBit) {
uint256 maturity = DateTime.getMaturityFromBitNum(oldSettleTime, nextBitNum);
totalAssetCash = totalAssetCash.add(
_settlefCashAsset(account, currencyId, maturity, blockTime)
);
// Turn the bit off now that it is settled
bitmap = bitmap.setBit(nextBitNum, false);
nextBitNum = bitmap.getNextBitNum();
}
bytes32 newBitmap;
while (nextBitNum != 0) {
uint256 maturity = DateTime.getMaturityFromBitNum(oldSettleTime, nextBitNum);
(uint256 newBitNum, bool isValid) = DateTime.getBitNumFromMaturity(newSettleTime, maturity);
require(isValid); // dev: invalid new bit num
newBitmap = newBitmap.setBit(newBitNum, true);
// Turn the bit off now that it is remapped
bitmap = bitmap.setBit(nextBitNum, false);
nextBitNum = bitmap.getNextBitNum();
}
BitmapAssetsHandler.setAssetsBitmap(account, currencyId, newBitmap);
}
/// @dev Stateful settlement function to settle a bitmapped asset. Deletes the
/// asset from storage after calculating it.
function _settlefCashAsset(
address account,
uint256 currencyId,
uint256 maturity,
uint256 blockTime
) private returns (int256 assetCash) {
mapping(address => mapping(uint256 =>
mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage();
int256 notional = store[account][currencyId][maturity].notional;
// Gets the current settlement rate or will store a new settlement rate if it does not
// yet exist.
AssetRateParameters memory rate =
AssetRate.buildSettlementRateStateful(currencyId, maturity, blockTime);
assetCash = rate.convertFromUnderlying(notional);
delete store[account][currencyId][maturity];
return assetCash;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../markets/CashGroup.sol";
import "../markets/AssetRate.sol";
import "../markets/DateTime.sol";
import "../portfolio/PortfolioHandler.sol";
import "../../math/SafeInt256.sol";
import "../../math/ABDKMath64x64.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library AssetHandler {
using SafeMath for uint256;
using SafeInt256 for int256;
using CashGroup for CashGroupParameters;
using AssetRate for AssetRateParameters;
function isLiquidityToken(uint256 assetType) internal pure returns (bool) {
return
assetType >= Constants.MIN_LIQUIDITY_TOKEN_INDEX &&
assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX;
}
/// @notice Liquidity tokens settle every 90 days (not at the designated maturity). This method
/// calculates the settlement date for any PortfolioAsset.
function getSettlementDate(PortfolioAsset memory asset) internal pure returns (uint256) {
require(asset.assetType > 0 && asset.assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); // dev: settlement date invalid asset type
// 3 month tokens and fCash tokens settle at maturity
if (asset.assetType <= Constants.MIN_LIQUIDITY_TOKEN_INDEX) return asset.maturity;
uint256 marketLength = DateTime.getTradedMarket(asset.assetType - 1);
// Liquidity tokens settle at tRef + 90 days. The formula to get a maturity is:
// maturity = tRef + marketLength
// Here we calculate:
// tRef = (maturity - marketLength) + 90 days
return asset.maturity.sub(marketLength).add(Constants.QUARTER);
}
/// @notice Returns the continuously compounded discount rate given an oracle rate and a time to maturity.
/// The formula is: e^(-rate * timeToMaturity).
function getDiscountFactor(uint256 timeToMaturity, uint256 oracleRate)
internal
pure
returns (int256)
{
int128 expValue =
ABDKMath64x64.fromUInt(oracleRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME));
expValue = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64);
expValue = ABDKMath64x64.exp(ABDKMath64x64.neg(expValue));
expValue = ABDKMath64x64.mul(expValue, Constants.RATE_PRECISION_64x64);
int256 discountFactor = ABDKMath64x64.toInt(expValue);
return discountFactor;
}
/// @notice Present value of an fCash asset without any risk adjustments.
function getPresentfCashValue(
int256 notional,
uint256 maturity,
uint256 blockTime,
uint256 oracleRate
) internal pure returns (int256) {
if (notional == 0) return 0;
// NOTE: this will revert if maturity < blockTime. That is the correct behavior because we cannot
// discount matured assets.
uint256 timeToMaturity = maturity.sub(blockTime);
int256 discountFactor = getDiscountFactor(timeToMaturity, oracleRate);
require(discountFactor <= Constants.RATE_PRECISION); // dev: get present value invalid discount factor
return notional.mulInRatePrecision(discountFactor);
}
/// @notice Present value of an fCash asset with risk adjustments. Positive fCash value will be discounted more
/// heavily than the oracle rate given and vice versa for negative fCash.
function getRiskAdjustedPresentfCashValue(
CashGroupParameters memory cashGroup,
int256 notional,
uint256 maturity,
uint256 blockTime,
uint256 oracleRate
) internal pure returns (int256) {
if (notional == 0) return 0;
// NOTE: this will revert if maturity < blockTime. That is the correct behavior because we cannot
// discount matured assets.
uint256 timeToMaturity = maturity.sub(blockTime);
int256 discountFactor;
if (notional > 0) {
// If fCash is positive then discounting by a higher rate will result in a smaller
// discount factor (e ^ -x), meaning a lower positive fCash value.
discountFactor = getDiscountFactor(
timeToMaturity,
oracleRate.add(cashGroup.getfCashHaircut())
);
} else {
uint256 debtBuffer = cashGroup.getDebtBuffer();
// If the adjustment exceeds the oracle rate we floor the value of the fCash
// at the notional value. We don't want to require the account to hold more than
// absolutely required.
if (debtBuffer >= oracleRate) return notional;
discountFactor = getDiscountFactor(timeToMaturity, oracleRate - debtBuffer);
}
require(discountFactor <= Constants.RATE_PRECISION); // dev: get risk adjusted pv, invalid discount factor
return notional.mulInRatePrecision(discountFactor);
}
/// @notice Returns the non haircut claims on cash and fCash by the liquidity token.
function getCashClaims(PortfolioAsset memory token, MarketParameters memory market)
internal
pure
returns (int256 assetCash, int256 fCash)
{
require(isLiquidityToken(token.assetType) && token.notional >= 0); // dev: invalid asset, get cash claims
assetCash = market.totalAssetCash.mul(token.notional).div(market.totalLiquidity);
fCash = market.totalfCash.mul(token.notional).div(market.totalLiquidity);
}
/// @notice Returns the haircut claims on cash and fCash
function getHaircutCashClaims(
PortfolioAsset memory token,
MarketParameters memory market,
CashGroupParameters memory cashGroup
) internal pure returns (int256 assetCash, int256 fCash) {
require(isLiquidityToken(token.assetType) && token.notional >= 0); // dev: invalid asset get haircut cash claims
require(token.currencyId == cashGroup.currencyId); // dev: haircut cash claims, currency id mismatch
// This won't overflow, the liquidity token haircut is stored as an uint8
int256 haircut = int256(cashGroup.getLiquidityHaircut(token.assetType));
assetCash =
_calcToken(market.totalAssetCash, token.notional, haircut, market.totalLiquidity);
fCash =
_calcToken(market.totalfCash, token.notional, haircut, market.totalLiquidity);
return (assetCash, fCash);
}
/// @dev This is here to clean up the stack in getHaircutCashClaims
function _calcToken(
int256 numerator,
int256 tokens,
int256 haircut,
int256 liquidity
) private pure returns (int256) {
return numerator.mul(tokens).mul(haircut).div(Constants.PERCENTAGE_DECIMALS).div(liquidity);
}
/// @notice Returns the asset cash claim and the present value of the fCash asset (if it exists)
function getLiquidityTokenValue(
uint256 index,
CashGroupParameters memory cashGroup,
MarketParameters memory market,
PortfolioAsset[] memory assets,
uint256 blockTime,
bool riskAdjusted
) internal view returns (int256, int256) {
PortfolioAsset memory liquidityToken = assets[index];
{
(uint256 marketIndex, bool idiosyncratic) =
DateTime.getMarketIndex(
cashGroup.maxMarketIndex,
liquidityToken.maturity,
blockTime
);
// Liquidity tokens can never be idiosyncratic
require(!idiosyncratic); // dev: idiosyncratic liquidity token
// This market will always be initialized, if a liquidity token exists that means the
// market has some liquidity in it.
cashGroup.loadMarket(market, marketIndex, true, blockTime);
}
int256 assetCashClaim;
int256 fCashClaim;
if (riskAdjusted) {
(assetCashClaim, fCashClaim) = getHaircutCashClaims(liquidityToken, market, cashGroup);
} else {
(assetCashClaim, fCashClaim) = getCashClaims(liquidityToken, market);
}
// Find the matching fCash asset and net off the value, assumes that the portfolio is sorted and
// in that case we know the previous asset will be the matching fCash asset
if (index > 0) {
PortfolioAsset memory maybefCash = assets[index - 1];
if (
maybefCash.assetType == Constants.FCASH_ASSET_TYPE &&
maybefCash.currencyId == liquidityToken.currencyId &&
maybefCash.maturity == liquidityToken.maturity
) {
// Net off the fCashClaim here and we will discount it to present value in the second pass.
// WARNING: this modifies the portfolio in memory and therefore we cannot store this portfolio!
maybefCash.notional = maybefCash.notional.add(fCashClaim);
// This state will prevent the fCash asset from being stored.
maybefCash.storageState = AssetStorageState.RevertIfStored;
return (assetCashClaim, 0);
}
}
// If not matching fCash asset found then get the pv directly
if (riskAdjusted) {
int256 pv =
getRiskAdjustedPresentfCashValue(
cashGroup,
fCashClaim,
liquidityToken.maturity,
blockTime,
market.oracleRate
);
return (assetCashClaim, pv);
} else {
int256 pv =
getPresentfCashValue(fCashClaim, liquidityToken.maturity, blockTime, market.oracleRate);
return (assetCashClaim, pv);
}
}
/// @notice Returns present value of all assets in the cash group as asset cash and the updated
/// portfolio index where the function has ended.
/// @return the value of the cash group in asset cash
function getNetCashGroupValue(
PortfolioAsset[] memory assets,
CashGroupParameters memory cashGroup,
MarketParameters memory market,
uint256 blockTime,
uint256 portfolioIndex
) internal view returns (int256, uint256) {
int256 presentValueAsset;
int256 presentValueUnderlying;
// First calculate value of liquidity tokens because we need to net off fCash value
// before discounting to present value
for (uint256 i = portfolioIndex; i < assets.length; i++) {
if (!isLiquidityToken(assets[i].assetType)) continue;
if (assets[i].currencyId != cashGroup.currencyId) break;
(int256 assetCashClaim, int256 pv) =
getLiquidityTokenValue(
i,
cashGroup,
market,
assets,
blockTime,
true // risk adjusted
);
presentValueAsset = presentValueAsset.add(assetCashClaim);
presentValueUnderlying = presentValueUnderlying.add(pv);
}
uint256 j = portfolioIndex;
for (; j < assets.length; j++) {
PortfolioAsset memory a = assets[j];
if (a.assetType != Constants.FCASH_ASSET_TYPE) continue;
// If we hit a different currency id then we've accounted for all assets in this currency
// j will mark the index where we don't have this currency anymore
if (a.currencyId != cashGroup.currencyId) break;
uint256 oracleRate = cashGroup.calculateOracleRate(a.maturity, blockTime);
int256 pv =
getRiskAdjustedPresentfCashValue(
cashGroup,
a.notional,
a.maturity,
blockTime,
oracleRate
);
presentValueUnderlying = presentValueUnderlying.add(pv);
}
presentValueAsset = presentValueAsset.add(
cashGroup.assetRate.convertFromUnderlying(presentValueUnderlying)
);
return (presentValueAsset, j);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./Types.sol";
import "./Constants.sol";
import "../../interfaces/notional/IRewarder.sol";
import "../../interfaces/aave/ILendingPool.sol";
library LibStorage {
/// @dev Offset for the initial slot in lib storage, gives us this number of storage slots
/// available in StorageLayoutV1 and all subsequent storage layouts that inherit from it.
uint256 private constant STORAGE_SLOT_BASE = 1000000;
/// @dev Set to MAX_TRADED_MARKET_INDEX * 2, Solidity does not allow assigning constants from imported values
uint256 private constant NUM_NTOKEN_MARKET_FACTORS = 14;
/// @dev Theoretical maximum for MAX_PORTFOLIO_ASSETS, however, we limit this to MAX_TRADED_MARKET_INDEX
/// in practice. It is possible to exceed that value during liquidation up to 14 potential assets.
uint256 private constant MAX_PORTFOLIO_ASSETS = 16;
/// @dev Storage IDs for storage buckets. Each id maps to an internal storage
/// slot used for a particular mapping
/// WARNING: APPEND ONLY
enum StorageId {
Unused,
AccountStorage,
nTokenContext,
nTokenAddress,
nTokenDeposit,
nTokenInitialization,
Balance,
Token,
SettlementRate,
CashGroup,
Market,
AssetsBitmap,
ifCashBitmap,
PortfolioArray,
// WARNING: this nTokenTotalSupply storage object was used for a buggy version
// of the incentives calculation. It should only be used for accounts who have
// not claimed before the migration
nTokenTotalSupply_deprecated,
AssetRate,
ExchangeRate,
nTokenTotalSupply,
SecondaryIncentiveRewarder,
LendingPool
}
/// @dev Mapping from an account address to account context
function getAccountStorage() internal pure
returns (mapping(address => AccountContext) storage store)
{
uint256 slot = _getStorageSlot(StorageId.AccountStorage);
assembly { store.slot := slot }
}
/// @dev Mapping from an nToken address to nTokenContext
function getNTokenContextStorage() internal pure
returns (mapping(address => nTokenContext) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenContext);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to nTokenAddress
function getNTokenAddressStorage() internal pure
returns (mapping(uint256 => address) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenAddress);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to uint32 fixed length array of
/// deposit factors. Deposit shares and leverage thresholds are stored striped to
/// reduce the number of storage reads.
function getNTokenDepositStorage() internal pure
returns (mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenDeposit);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to fixed length array of initialization factors,
/// stored striped like deposit shares.
function getNTokenInitStorage() internal pure
returns (mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenInitialization);
assembly { store.slot := slot }
}
/// @dev Mapping from account to currencyId to it's balance storage for that currency
function getBalanceStorage() internal pure
returns (mapping(address => mapping(uint256 => BalanceStorage)) storage store)
{
uint256 slot = _getStorageSlot(StorageId.Balance);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to a boolean for underlying or asset token to
/// the TokenStorage
function getTokenStorage() internal pure
returns (mapping(uint256 => mapping(bool => TokenStorage)) storage store)
{
uint256 slot = _getStorageSlot(StorageId.Token);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to maturity to its corresponding SettlementRate
function getSettlementRateStorage() internal pure
returns (mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store)
{
uint256 slot = _getStorageSlot(StorageId.SettlementRate);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to maturity to its tightly packed cash group parameters
function getCashGroupStorage() internal pure
returns (mapping(uint256 => bytes32) storage store)
{
uint256 slot = _getStorageSlot(StorageId.CashGroup);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to maturity to settlement date for a market
function getMarketStorage() internal pure
returns (mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store)
{
uint256 slot = _getStorageSlot(StorageId.Market);
assembly { store.slot := slot }
}
/// @dev Mapping from account to currency id to its assets bitmap
function getAssetsBitmapStorage() internal pure
returns (mapping(address => mapping(uint256 => bytes32)) storage store)
{
uint256 slot = _getStorageSlot(StorageId.AssetsBitmap);
assembly { store.slot := slot }
}
/// @dev Mapping from account to currency id to its maturity to its corresponding ifCash balance
function getifCashBitmapStorage() internal pure
returns (mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store)
{
uint256 slot = _getStorageSlot(StorageId.ifCashBitmap);
assembly { store.slot := slot }
}
/// @dev Mapping from account to its fixed length array of portfolio assets
function getPortfolioArrayStorage() internal pure
returns (mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store)
{
uint256 slot = _getStorageSlot(StorageId.PortfolioArray);
assembly { store.slot := slot }
}
function getDeprecatedNTokenTotalSupplyStorage() internal pure
returns (mapping(address => nTokenTotalSupplyStorage_deprecated) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenTotalSupply_deprecated);
assembly { store.slot := slot }
}
/// @dev Mapping from nToken address to its total supply values
function getNTokenTotalSupplyStorage() internal pure
returns (mapping(address => nTokenTotalSupplyStorage) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenTotalSupply);
assembly { store.slot := slot }
}
/// @dev Returns the exchange rate between an underlying currency and asset for trading
/// and free collateral. Mapping is from currency id to rate storage object.
function getAssetRateStorage() internal pure
returns (mapping(uint256 => AssetRateStorage) storage store)
{
uint256 slot = _getStorageSlot(StorageId.AssetRate);
assembly { store.slot := slot }
}
/// @dev Returns the exchange rate between an underlying currency and ETH for free
/// collateral purposes. Mapping is from currency id to rate storage object.
function getExchangeRateStorage() internal pure
returns (mapping(uint256 => ETHRateStorage) storage store)
{
uint256 slot = _getStorageSlot(StorageId.ExchangeRate);
assembly { store.slot := slot }
}
/// @dev Returns the address of a secondary incentive rewarder for an nToken if it exists
function getSecondaryIncentiveRewarder() internal pure
returns (mapping(address => IRewarder) storage store)
{
uint256 slot = _getStorageSlot(StorageId.SecondaryIncentiveRewarder);
assembly { store.slot := slot }
}
/// @dev Returns the address of the lending pool
function getLendingPool() internal pure returns (LendingPoolStorage storage store) {
uint256 slot = _getStorageSlot(StorageId.LendingPool);
assembly { store.slot := slot }
}
/// @dev Get the storage slot given a storage ID.
/// @param storageId An entry in `StorageId`
/// @return slot The storage slot.
function _getStorageSlot(StorageId storageId)
private
pure
returns (uint256 slot)
{
// This should never overflow with a reasonable `STORAGE_SLOT_EXP`
// because Solidity will do a range check on `storageId` during the cast.
return uint256(storageId) + STORAGE_SLOT_BASE;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../AccountContextHandler.sol";
import "../markets/CashGroup.sol";
import "../valuation/AssetHandler.sol";
import "../../math/Bitmap.sol";
import "../../math/SafeInt256.sol";
import "../../global/LibStorage.sol";
import "../../global/Constants.sol";
import "../../global/Types.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library BitmapAssetsHandler {
using SafeMath for uint256;
using SafeInt256 for int256;
using Bitmap for bytes32;
using CashGroup for CashGroupParameters;
using AccountContextHandler for AccountContext;
function getAssetsBitmap(address account, uint256 currencyId) internal view returns (bytes32 assetsBitmap) {
mapping(address => mapping(uint256 => bytes32)) storage store = LibStorage.getAssetsBitmapStorage();
return store[account][currencyId];
}
function setAssetsBitmap(
address account,
uint256 currencyId,
bytes32 assetsBitmap
) internal {
require(assetsBitmap.totalBitsSet() <= Constants.MAX_BITMAP_ASSETS, "Over max assets");
mapping(address => mapping(uint256 => bytes32)) storage store = LibStorage.getAssetsBitmapStorage();
store[account][currencyId] = assetsBitmap;
}
function getifCashNotional(
address account,
uint256 currencyId,
uint256 maturity
) internal view returns (int256 notional) {
mapping(address => mapping(uint256 =>
mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage();
return store[account][currencyId][maturity].notional;
}
/// @notice Adds multiple assets to a bitmap portfolio
function addMultipleifCashAssets(
address account,
AccountContext memory accountContext,
PortfolioAsset[] memory assets
) internal {
require(accountContext.isBitmapEnabled()); // dev: bitmap currency not set
uint256 currencyId = accountContext.bitmapCurrencyId;
for (uint256 i; i < assets.length; i++) {
PortfolioAsset memory asset = assets[i];
if (asset.notional == 0) continue;
require(asset.currencyId == currencyId); // dev: invalid asset in set ifcash assets
require(asset.assetType == Constants.FCASH_ASSET_TYPE); // dev: invalid asset in set ifcash assets
int256 finalNotional;
finalNotional = addifCashAsset(
account,
currencyId,
asset.maturity,
accountContext.nextSettleTime,
asset.notional
);
if (finalNotional < 0)
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT;
}
}
/// @notice Add an ifCash asset in the bitmap and mapping. Updates the bitmap in memory
/// but not in storage.
/// @return the updated assets bitmap and the final notional amount
function addifCashAsset(
address account,
uint256 currencyId,
uint256 maturity,
uint256 nextSettleTime,
int256 notional
) internal returns (int256) {
bytes32 assetsBitmap = getAssetsBitmap(account, currencyId);
mapping(address => mapping(uint256 =>
mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage();
ifCashStorage storage fCashSlot = store[account][currencyId][maturity];
(uint256 bitNum, bool isExact) = DateTime.getBitNumFromMaturity(nextSettleTime, maturity);
require(isExact); // dev: invalid maturity in set ifcash asset
if (assetsBitmap.isBitSet(bitNum)) {
// Bit is set so we read and update the notional amount
int256 finalNotional = notional.add(fCashSlot.notional);
require(type(int128).min <= finalNotional && finalNotional <= type(int128).max); // dev: bitmap notional overflow
fCashSlot.notional = int128(finalNotional);
// If the new notional is zero then turn off the bit
if (finalNotional == 0) {
assetsBitmap = assetsBitmap.setBit(bitNum, false);
}
setAssetsBitmap(account, currencyId, assetsBitmap);
return finalNotional;
}
if (notional != 0) {
// Bit is not set so we turn it on and update the mapping directly, no read required.
require(type(int128).min <= notional && notional <= type(int128).max); // dev: bitmap notional overflow
fCashSlot.notional = int128(notional);
assetsBitmap = assetsBitmap.setBit(bitNum, true);
setAssetsBitmap(account, currencyId, assetsBitmap);
}
return notional;
}
/// @notice Returns the present value of an asset
function getPresentValue(
address account,
uint256 currencyId,
uint256 maturity,
uint256 blockTime,
CashGroupParameters memory cashGroup,
bool riskAdjusted
) internal view returns (int256) {
int256 notional = getifCashNotional(account, currencyId, maturity);
// In this case the asset has matured and the total value is just the notional amount
if (maturity <= blockTime) {
return notional;
} else {
uint256 oracleRate = cashGroup.calculateOracleRate(maturity, blockTime);
if (riskAdjusted) {
return AssetHandler.getRiskAdjustedPresentfCashValue(
cashGroup,
notional,
maturity,
blockTime,
oracleRate
);
} else {
return AssetHandler.getPresentfCashValue(
notional,
maturity,
blockTime,
oracleRate
);
}
}
}
function getNetPresentValueFromBitmap(
address account,
uint256 currencyId,
uint256 nextSettleTime,
uint256 blockTime,
CashGroupParameters memory cashGroup,
bool riskAdjusted,
bytes32 assetsBitmap
) internal view returns (int256 totalValueUnderlying, bool hasDebt) {
uint256 bitNum = assetsBitmap.getNextBitNum();
while (bitNum != 0) {
uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum);
int256 pv = getPresentValue(
account,
currencyId,
maturity,
blockTime,
cashGroup,
riskAdjusted
);
totalValueUnderlying = totalValueUnderlying.add(pv);
if (pv < 0) hasDebt = true;
// Turn off the bit and look for the next one
assetsBitmap = assetsBitmap.setBit(bitNum, false);
bitNum = assetsBitmap.getNextBitNum();
}
}
/// @notice Get the net present value of all the ifCash assets
function getifCashNetPresentValue(
address account,
uint256 currencyId,
uint256 nextSettleTime,
uint256 blockTime,
CashGroupParameters memory cashGroup,
bool riskAdjusted
) internal view returns (int256 totalValueUnderlying, bool hasDebt) {
bytes32 assetsBitmap = getAssetsBitmap(account, currencyId);
return getNetPresentValueFromBitmap(
account,
currencyId,
nextSettleTime,
blockTime,
cashGroup,
riskAdjusted,
assetsBitmap
);
}
/// @notice Returns the ifCash assets as an array
function getifCashArray(
address account,
uint256 currencyId,
uint256 nextSettleTime
) internal view returns (PortfolioAsset[] memory) {
bytes32 assetsBitmap = getAssetsBitmap(account, currencyId);
uint256 index = assetsBitmap.totalBitsSet();
PortfolioAsset[] memory assets = new PortfolioAsset[](index);
index = 0;
uint256 bitNum = assetsBitmap.getNextBitNum();
while (bitNum != 0) {
uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum);
int256 notional = getifCashNotional(account, currencyId, maturity);
PortfolioAsset memory asset = assets[index];
asset.currencyId = currencyId;
asset.maturity = maturity;
asset.assetType = Constants.FCASH_ASSET_TYPE;
asset.notional = notional;
index += 1;
// Turn off the bit and look for the next one
assetsBitmap = assetsBitmap.setBit(bitNum, false);
bitNum = assetsBitmap.getNextBitNum();
}
return assets;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../interfaces/chainlink/AggregatorV2V3Interface.sol";
import "../../interfaces/notional/AssetRateAdapter.sol";
/// @notice Different types of internal tokens
/// - UnderlyingToken: underlying asset for a cToken (except for Ether)
/// - cToken: Compound interest bearing token
/// - cETH: Special handling for cETH tokens
/// - Ether: the one and only
/// - NonMintable: tokens that do not have an underlying (therefore not cTokens)
/// - aToken: Aave interest bearing tokens
enum TokenType {UnderlyingToken, cToken, cETH, Ether, NonMintable, aToken}
/// @notice Specifies the different trade action types in the system. Each trade action type is
/// encoded in a tightly packed bytes32 object. Trade action type is the first big endian byte of the
/// 32 byte trade action object. The schemas for each trade action type are defined below.
enum TradeActionType {
// (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 minImpliedRate, uint120 unused)
Lend,
// (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 maxImpliedRate, uint128 unused)
Borrow,
// (uint8 TradeActionType, uint8 MarketIndex, uint88 assetCashAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused)
AddLiquidity,
// (uint8 TradeActionType, uint8 MarketIndex, uint88 tokenAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused)
RemoveLiquidity,
// (uint8 TradeActionType, uint32 Maturity, int88 fCashResidualAmount, uint128 unused)
PurchaseNTokenResidual,
// (uint8 TradeActionType, address CounterpartyAddress, int88 fCashAmountToSettle)
SettleCashDebt
}
/// @notice Specifies different deposit actions that can occur during BalanceAction or BalanceActionWithTrades
enum DepositActionType {
// No deposit action
None,
// Deposit asset cash, depositActionAmount is specified in asset cash external precision
DepositAsset,
// Deposit underlying tokens that are mintable to asset cash, depositActionAmount is specified in underlying token
// external precision
DepositUnderlying,
// Deposits specified asset cash external precision amount into an nToken and mints the corresponding amount of
// nTokens into the account
DepositAssetAndMintNToken,
// Deposits specified underlying in external precision, mints asset cash, and uses that asset cash to mint nTokens
DepositUnderlyingAndMintNToken,
// Redeems an nToken balance to asset cash. depositActionAmount is specified in nToken precision. Considered a deposit action
// because it deposits asset cash into an account. If there are fCash residuals that cannot be sold off, will revert.
RedeemNToken,
// Converts specified amount of asset cash balance already in Notional to nTokens. depositActionAmount is specified in
// Notional internal 8 decimal precision.
ConvertCashToNToken
}
/// @notice Used internally for PortfolioHandler state
enum AssetStorageState {NoChange, Update, Delete, RevertIfStored}
/****** Calldata objects ******/
/// @notice Defines a balance action for batchAction
struct BalanceAction {
// Deposit action to take (if any)
DepositActionType actionType;
uint16 currencyId;
// Deposit action amount must correspond to the depositActionType, see documentation above.
uint256 depositActionAmount;
// Withdraw an amount of asset cash specified in Notional internal 8 decimal precision
uint256 withdrawAmountInternalPrecision;
// If set to true, will withdraw entire cash balance. Useful if there may be an unknown amount of asset cash
// residual left from trading.
bool withdrawEntireCashBalance;
// If set to true, will redeem asset cash to the underlying token on withdraw.
bool redeemToUnderlying;
}
/// @notice Defines a balance action with a set of trades to do as well
struct BalanceActionWithTrades {
DepositActionType actionType;
uint16 currencyId;
uint256 depositActionAmount;
uint256 withdrawAmountInternalPrecision;
bool withdrawEntireCashBalance;
bool redeemToUnderlying;
// Array of tightly packed 32 byte objects that represent trades. See TradeActionType documentation
bytes32[] trades;
}
/****** In memory objects ******/
/// @notice Internal object that represents settled cash balances
struct SettleAmount {
uint256 currencyId;
int256 netCashChange;
}
/// @notice Internal object that represents a token
struct Token {
address tokenAddress;
bool hasTransferFee;
int256 decimals;
TokenType tokenType;
uint256 maxCollateralBalance;
}
/// @notice Internal object that represents an nToken portfolio
struct nTokenPortfolio {
CashGroupParameters cashGroup;
PortfolioState portfolioState;
int256 totalSupply;
int256 cashBalance;
uint256 lastInitializedTime;
bytes6 parameters;
address tokenAddress;
}
/// @notice Internal object used during liquidation
struct LiquidationFactors {
address account;
// Aggregate free collateral of the account denominated in ETH underlying, 8 decimal precision
int256 netETHValue;
// Amount of net local currency asset cash before haircuts and buffers available
int256 localAssetAvailable;
// Amount of net collateral currency asset cash before haircuts and buffers available
int256 collateralAssetAvailable;
// Haircut value of nToken holdings denominated in asset cash, will be local or collateral nTokens based
// on liquidation type
int256 nTokenHaircutAssetValue;
// nToken parameters for calculating liquidation amount
bytes6 nTokenParameters;
// ETH exchange rate from local currency to ETH
ETHRate localETHRate;
// ETH exchange rate from collateral currency to ETH
ETHRate collateralETHRate;
// Asset rate for the local currency, used in cross currency calculations to calculate local asset cash required
AssetRateParameters localAssetRate;
// Used during currency liquidations if the account has liquidity tokens
CashGroupParameters collateralCashGroup;
// Used during currency liquidations if it is only a calculation, defaults to false
bool isCalculation;
}
/// @notice Internal asset array portfolio state
struct PortfolioState {
// Array of currently stored assets
PortfolioAsset[] storedAssets;
// Array of new assets to add
PortfolioAsset[] newAssets;
uint256 lastNewAssetIndex;
// Holds the length of stored assets after accounting for deleted assets
uint256 storedAssetLength;
}
/// @notice In memory ETH exchange rate used during free collateral calculation.
struct ETHRate {
// The decimals (i.e. 10^rateDecimalPlaces) of the exchange rate, defined by the rate oracle
int256 rateDecimals;
// The exchange rate from base to ETH (if rate invert is required it is already done)
int256 rate;
// Amount of buffer as a multiple with a basis of 100 applied to negative balances.
int256 buffer;
// Amount of haircut as a multiple with a basis of 100 applied to positive balances
int256 haircut;
// Liquidation discount as a multiple with a basis of 100 applied to the exchange rate
// as an incentive given to liquidators.
int256 liquidationDiscount;
}
/// @notice Internal object used to handle balance state during a transaction
struct BalanceState {
uint16 currencyId;
// Cash balance stored in balance state at the beginning of the transaction
int256 storedCashBalance;
// nToken balance stored at the beginning of the transaction
int256 storedNTokenBalance;
// The net cash change as a result of asset settlement or trading
int256 netCashChange;
// Net asset transfers into or out of the account
int256 netAssetTransferInternalPrecision;
// Net token transfers into or out of the account
int256 netNTokenTransfer;
// Net token supply change from minting or redeeming
int256 netNTokenSupplyChange;
// The last time incentives were claimed for this currency
uint256 lastClaimTime;
// Accumulator for incentives that the account no longer has a claim over
uint256 accountIncentiveDebt;
}
/// @dev Asset rate used to convert between underlying cash and asset cash
struct AssetRateParameters {
// Address of the asset rate oracle
AssetRateAdapter rateOracle;
// The exchange rate from base to quote (if invert is required it is already done)
int256 rate;
// The decimals of the underlying, the rate converts to the underlying decimals
int256 underlyingDecimals;
}
/// @dev Cash group when loaded into memory
struct CashGroupParameters {
uint16 currencyId;
uint256 maxMarketIndex;
AssetRateParameters assetRate;
bytes32 data;
}
/// @dev A portfolio asset when loaded in memory
struct PortfolioAsset {
// Asset currency id
uint256 currencyId;
uint256 maturity;
// Asset type, fCash or liquidity token.
uint256 assetType;
// fCash amount or liquidity token amount
int256 notional;
// Used for managing portfolio asset state
uint256 storageSlot;
// The state of the asset for when it is written to storage
AssetStorageState storageState;
}
/// @dev Market object as represented in memory
struct MarketParameters {
bytes32 storageSlot;
uint256 maturity;
// Total amount of fCash available for purchase in the market.
int256 totalfCash;
// Total amount of cash available for purchase in the market.
int256 totalAssetCash;
// Total amount of liquidity tokens (representing a claim on liquidity) in the market.
int256 totalLiquidity;
// This is the previous annualized interest rate in RATE_PRECISION that the market traded
// at. This is used to calculate the rate anchor to smooth interest rates over time.
uint256 lastImpliedRate;
// Time lagged version of lastImpliedRate, used to value fCash assets at market rates while
// remaining resistent to flash loan attacks.
uint256 oracleRate;
// This is the timestamp of the previous trade
uint256 previousTradeTime;
}
/****** Storage objects ******/
/// @dev Token object in storage:
/// 20 bytes for token address
/// 1 byte for hasTransferFee
/// 1 byte for tokenType
/// 1 byte for tokenDecimals
/// 9 bytes for maxCollateralBalance (may not always be set)
struct TokenStorage {
// Address of the token
address tokenAddress;
// Transfer fees will change token deposit behavior
bool hasTransferFee;
TokenType tokenType;
uint8 decimalPlaces;
// Upper limit on how much of this token the contract can hold at any time
uint72 maxCollateralBalance;
}
/// @dev Exchange rate object as it is represented in storage, total storage is 25 bytes.
struct ETHRateStorage {
// Address of the rate oracle
AggregatorV2V3Interface rateOracle;
// The decimal places of precision that the rate oracle uses
uint8 rateDecimalPlaces;
// True of the exchange rate must be inverted
bool mustInvert;
// NOTE: both of these governance values are set with BUFFER_DECIMALS precision
// Amount of buffer to apply to the exchange rate for negative balances.
uint8 buffer;
// Amount of haircut to apply to the exchange rate for positive balances
uint8 haircut;
// Liquidation discount in percentage point terms, 106 means a 6% discount
uint8 liquidationDiscount;
}
/// @dev Asset rate oracle object as it is represented in storage, total storage is 21 bytes.
struct AssetRateStorage {
// Address of the rate oracle
AssetRateAdapter rateOracle;
// The decimal places of the underlying asset
uint8 underlyingDecimalPlaces;
}
/// @dev Governance parameters for a cash group, total storage is 9 bytes + 7 bytes for liquidity token haircuts
/// and 7 bytes for rate scalars, total of 23 bytes. Note that this is stored packed in the storage slot so there
/// are no indexes stored for liquidityTokenHaircuts or rateScalars, maxMarketIndex is used instead to determine the
/// length.
struct CashGroupSettings {
// Index of the AMMs on chain that will be made available. Idiosyncratic fCash
// that is dated less than the longest AMM will be tradable.
uint8 maxMarketIndex;
// Time window in 5 minute increments that the rate oracle will be averaged over
uint8 rateOracleTimeWindow5Min;
// Total fees per trade, specified in BPS
uint8 totalFeeBPS;
// Share of the fees given to the protocol, denominated in percentage
uint8 reserveFeeShare;
// Debt buffer specified in 5 BPS increments
uint8 debtBuffer5BPS;
// fCash haircut specified in 5 BPS increments
uint8 fCashHaircut5BPS;
// If an account has a negative cash balance, it can be settled by incurring debt at the 3 month market. This
// is the basis points for the penalty rate that will be added the current 3 month oracle rate.
uint8 settlementPenaltyRate5BPS;
// If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for
uint8 liquidationfCashHaircut5BPS;
// If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for
uint8 liquidationDebtBuffer5BPS;
// Liquidity token haircut applied to cash claims, specified as a percentage between 0 and 100
uint8[] liquidityTokenHaircuts;
// Rate scalar used to determine the slippage of the market
uint8[] rateScalars;
}
/// @dev Holds account level context information used to determine settlement and
/// free collateral actions. Total storage is 28 bytes
struct AccountContext {
// Used to check when settlement must be triggered on an account
uint40 nextSettleTime;
// For lenders that never incur debt, we use this flag to skip the free collateral check.
bytes1 hasDebt;
// Length of the account's asset array
uint8 assetArrayLength;
// If this account has bitmaps set, this is the corresponding currency id
uint16 bitmapCurrencyId;
// 9 total active currencies possible (2 bytes each)
bytes18 activeCurrencies;
}
/// @dev Holds nToken context information mapped via the nToken address, total storage is
/// 16 bytes
struct nTokenContext {
// Currency id that the nToken represents
uint16 currencyId;
// Annual incentive emission rate denominated in WHOLE TOKENS (multiply by
// INTERNAL_TOKEN_PRECISION to get the actual rate)
uint32 incentiveAnnualEmissionRate;
// The last block time at utc0 that the nToken was initialized at, zero if it
// has never been initialized
uint32 lastInitializedTime;
// Length of the asset array, refers to the number of liquidity tokens an nToken
// currently holds
uint8 assetArrayLength;
// Each byte is a specific nToken parameter
bytes5 nTokenParameters;
// Reserved bytes for future usage
bytes15 _unused;
// Set to true if a secondary rewarder is set
bool hasSecondaryRewarder;
}
/// @dev Holds account balance information, total storage 32 bytes
struct BalanceStorage {
// Number of nTokens held by the account
uint80 nTokenBalance;
// Last time the account claimed their nTokens
uint32 lastClaimTime;
// Incentives that the account no longer has a claim over
uint56 accountIncentiveDebt;
// Cash balance of the account
int88 cashBalance;
}
/// @dev Holds information about a settlement rate, total storage 25 bytes
struct SettlementRateStorage {
uint40 blockTime;
uint128 settlementRate;
uint8 underlyingDecimalPlaces;
}
/// @dev Holds information about a market, total storage is 42 bytes so this spans
/// two storage words
struct MarketStorage {
// Total fCash in the market
uint80 totalfCash;
// Total asset cash in the market
uint80 totalAssetCash;
// Last annualized interest rate the market traded at
uint32 lastImpliedRate;
// Last recorded oracle rate for the market
uint32 oracleRate;
// Last time a trade was made
uint32 previousTradeTime;
// This is stored in slot + 1
uint80 totalLiquidity;
}
struct ifCashStorage {
// Notional amount of fCash at the slot, limited to int128 to allow for
// future expansion
int128 notional;
}
/// @dev A single portfolio asset in storage, total storage of 19 bytes
struct PortfolioAssetStorage {
// Currency Id for the asset
uint16 currencyId;
// Maturity of the asset
uint40 maturity;
// Asset type (fCash or Liquidity Token marker)
uint8 assetType;
// Notional
int88 notional;
}
/// @dev nToken total supply factors for the nToken, includes factors related
/// to claiming incentives, total storage 32 bytes. This is the deprecated version
struct nTokenTotalSupplyStorage_deprecated {
// Total supply of the nToken
uint96 totalSupply;
// Integral of the total supply used for calculating the average total supply
uint128 integralTotalSupply;
// Last timestamp the supply value changed, used for calculating the integralTotalSupply
uint32 lastSupplyChangeTime;
}
/// @dev nToken total supply factors for the nToken, includes factors related
/// to claiming incentives, total storage 32 bytes.
struct nTokenTotalSupplyStorage {
// Total supply of the nToken
uint96 totalSupply;
// How many NOTE incentives should be issued per nToken in 1e18 precision
uint128 accumulatedNOTEPerNToken;
// Last timestamp when the accumulation happened
uint32 lastAccumulatedTime;
}
/// @dev Used in view methods to return account balances in a developer friendly manner
struct AccountBalance {
uint16 currencyId;
int256 cashBalance;
int256 nTokenBalance;
uint256 lastClaimTime;
uint256 accountIncentiveDebt;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
/// @title All shared constants for the Notional system should be declared here.
library Constants {
uint8 internal constant CETH_DECIMAL_PLACES = 8;
// Token precision used for all internal balances, TokenHandler library ensures that we
// limit the dust amount caused by precision mismatches
int256 internal constant INTERNAL_TOKEN_PRECISION = 1e8;
uint256 internal constant INCENTIVE_ACCUMULATION_PRECISION = 1e18;
// ETH will be initialized as the first currency
uint256 internal constant ETH_CURRENCY_ID = 1;
uint8 internal constant ETH_DECIMAL_PLACES = 18;
int256 internal constant ETH_DECIMALS = 1e18;
// Used to prevent overflow when converting decimal places to decimal precision values via
// 10**decimalPlaces. This is a safe value for int256 and uint256 variables. We apply this
// constraint when storing decimal places in governance.
uint256 internal constant MAX_DECIMAL_PLACES = 36;
// Address of the reserve account
address internal constant RESERVE = address(0);
// Most significant bit
bytes32 internal constant MSB =
0x8000000000000000000000000000000000000000000000000000000000000000;
// Each bit set in this mask marks where an active market should be in the bitmap
// if the first bit refers to the reference time. Used to detect idiosyncratic
// fcash in the nToken accounts
bytes32 internal constant ACTIVE_MARKETS_MASK = (
MSB >> ( 90 - 1) | // 3 month
MSB >> (105 - 1) | // 6 month
MSB >> (135 - 1) | // 1 year
MSB >> (147 - 1) | // 2 year
MSB >> (183 - 1) | // 5 year
MSB >> (211 - 1) | // 10 year
MSB >> (251 - 1) // 20 year
);
// Basis for percentages
int256 internal constant PERCENTAGE_DECIMALS = 100;
// Max number of traded markets, also used as the maximum number of assets in a portfolio array
uint256 internal constant MAX_TRADED_MARKET_INDEX = 7;
// Max number of fCash assets in a bitmap, this is based on the gas costs of calculating free collateral
// for a bitmap portfolio
uint256 internal constant MAX_BITMAP_ASSETS = 20;
uint256 internal constant FIVE_MINUTES = 300;
// Internal date representations, note we use a 6/30/360 week/month/year convention here
uint256 internal constant DAY = 86400;
// We use six day weeks to ensure that all time references divide evenly
uint256 internal constant WEEK = DAY * 6;
uint256 internal constant MONTH = WEEK * 5;
uint256 internal constant QUARTER = MONTH * 3;
uint256 internal constant YEAR = QUARTER * 4;
// These constants are used in DateTime.sol
uint256 internal constant DAYS_IN_WEEK = 6;
uint256 internal constant DAYS_IN_MONTH = 30;
uint256 internal constant DAYS_IN_QUARTER = 90;
// Offsets for each time chunk denominated in days
uint256 internal constant MAX_DAY_OFFSET = 90;
uint256 internal constant MAX_WEEK_OFFSET = 360;
uint256 internal constant MAX_MONTH_OFFSET = 2160;
uint256 internal constant MAX_QUARTER_OFFSET = 7650;
// Offsets for each time chunk denominated in bits
uint256 internal constant WEEK_BIT_OFFSET = 90;
uint256 internal constant MONTH_BIT_OFFSET = 135;
uint256 internal constant QUARTER_BIT_OFFSET = 195;
// This is a constant that represents the time period that all rates are normalized by, 360 days
uint256 internal constant IMPLIED_RATE_TIME = 360 * DAY;
// Number of decimal places that rates are stored in, equals 100%
int256 internal constant RATE_PRECISION = 1e9;
// One basis point in RATE_PRECISION terms
uint256 internal constant BASIS_POINT = uint256(RATE_PRECISION / 10000);
// Used to when calculating the amount to deleverage of a market when minting nTokens
uint256 internal constant DELEVERAGE_BUFFER = 300 * BASIS_POINT;
// Used for scaling cash group factors
uint256 internal constant FIVE_BASIS_POINTS = 5 * BASIS_POINT;
// Used for residual purchase incentive and cash withholding buffer
uint256 internal constant TEN_BASIS_POINTS = 10 * BASIS_POINT;
// This is the ABDK64x64 representation of RATE_PRECISION
// RATE_PRECISION_64x64 = ABDKMath64x64.fromUint(RATE_PRECISION)
int128 internal constant RATE_PRECISION_64x64 = 0x3b9aca000000000000000000;
int128 internal constant LOG_RATE_PRECISION_64x64 = 382276781265598821176;
// Limit the market proportion so that borrowing cannot hit extremely high interest rates
int256 internal constant MAX_MARKET_PROPORTION = RATE_PRECISION * 99 / 100;
uint8 internal constant FCASH_ASSET_TYPE = 1;
// Liquidity token asset types are 1 + marketIndex (where marketIndex is 1-indexed)
uint8 internal constant MIN_LIQUIDITY_TOKEN_INDEX = 2;
uint8 internal constant MAX_LIQUIDITY_TOKEN_INDEX = 8;
// Used for converting bool to bytes1, solidity does not have a native conversion
// method for this
bytes1 internal constant BOOL_FALSE = 0x00;
bytes1 internal constant BOOL_TRUE = 0x01;
// Account context flags
bytes1 internal constant HAS_ASSET_DEBT = 0x01;
bytes1 internal constant HAS_CASH_DEBT = 0x02;
bytes2 internal constant ACTIVE_IN_PORTFOLIO = 0x8000;
bytes2 internal constant ACTIVE_IN_BALANCES = 0x4000;
bytes2 internal constant UNMASK_FLAGS = 0x3FFF;
uint16 internal constant MAX_CURRENCIES = uint16(UNMASK_FLAGS);
// Equal to 100% of all deposit amounts for nToken liquidity across fCash markets.
int256 internal constant DEPOSIT_PERCENT_BASIS = 1e8;
// nToken Parameters: there are offsets in the nTokenParameters bytes6 variable returned
// in nTokenHandler. Each constant represents a position in the byte array.
uint8 internal constant LIQUIDATION_HAIRCUT_PERCENTAGE = 0;
uint8 internal constant CASH_WITHHOLDING_BUFFER = 1;
uint8 internal constant RESIDUAL_PURCHASE_TIME_BUFFER = 2;
uint8 internal constant PV_HAIRCUT_PERCENTAGE = 3;
uint8 internal constant RESIDUAL_PURCHASE_INCENTIVE = 4;
// Liquidation parameters
// Default percentage of collateral that a liquidator is allowed to liquidate, will be higher if the account
// requires more collateral to be liquidated
int256 internal constant DEFAULT_LIQUIDATION_PORTION = 40;
// Percentage of local liquidity token cash claim delivered to the liquidator for liquidating liquidity tokens
int256 internal constant TOKEN_REPO_INCENTIVE_PERCENT = 30;
// Pause Router liquidation enabled states
bytes1 internal constant LOCAL_CURRENCY_ENABLED = 0x01;
bytes1 internal constant COLLATERAL_CURRENCY_ENABLED = 0x02;
bytes1 internal constant LOCAL_FCASH_ENABLED = 0x04;
bytes1 internal constant CROSS_CURRENCY_FCASH_ENABLED = 0x08;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/Constants.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library DateTime {
using SafeMath for uint256;
/// @notice Returns the current reference time which is how all the AMM dates are calculated.
function getReferenceTime(uint256 blockTime) internal pure returns (uint256) {
require(blockTime >= Constants.QUARTER);
return blockTime - (blockTime % Constants.QUARTER);
}
/// @notice Truncates a date to midnight UTC time
function getTimeUTC0(uint256 time) internal pure returns (uint256) {
require(time >= Constants.DAY);
return time - (time % Constants.DAY);
}
/// @notice These are the predetermined market offsets for trading
/// @dev Markets are 1-indexed because the 0 index means that no markets are listed for the cash group.
function getTradedMarket(uint256 index) internal pure returns (uint256) {
if (index == 1) return Constants.QUARTER;
if (index == 2) return 2 * Constants.QUARTER;
if (index == 3) return Constants.YEAR;
if (index == 4) return 2 * Constants.YEAR;
if (index == 5) return 5 * Constants.YEAR;
if (index == 6) return 10 * Constants.YEAR;
if (index == 7) return 20 * Constants.YEAR;
revert("Invalid index");
}
/// @notice Determines if the maturity falls on one of the valid on chain market dates.
function isValidMarketMaturity(
uint256 maxMarketIndex,
uint256 maturity,
uint256 blockTime
) internal pure returns (bool) {
require(maxMarketIndex > 0, "CG: no markets listed");
require(maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: market index bound");
if (maturity % Constants.QUARTER != 0) return false;
uint256 tRef = DateTime.getReferenceTime(blockTime);
for (uint256 i = 1; i <= maxMarketIndex; i++) {
if (maturity == tRef.add(DateTime.getTradedMarket(i))) return true;
}
return false;
}
/// @notice Determines if an idiosyncratic maturity is valid and returns the bit reference that is the case.
function isValidMaturity(
uint256 maxMarketIndex,
uint256 maturity,
uint256 blockTime
) internal pure returns (bool) {
uint256 tRef = DateTime.getReferenceTime(blockTime);
uint256 maxMaturity = tRef.add(DateTime.getTradedMarket(maxMarketIndex));
// Cannot trade past max maturity
if (maturity > maxMaturity) return false;
// prettier-ignore
(/* */, bool isValid) = DateTime.getBitNumFromMaturity(blockTime, maturity);
return isValid;
}
/// @notice Returns the market index for a given maturity, if the maturity is idiosyncratic
/// will return the nearest market index that is larger than the maturity.
/// @return uint marketIndex, bool isIdiosyncratic
function getMarketIndex(
uint256 maxMarketIndex,
uint256 maturity,
uint256 blockTime
) internal pure returns (uint256, bool) {
require(maxMarketIndex > 0, "CG: no markets listed");
require(maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: market index bound");
uint256 tRef = DateTime.getReferenceTime(blockTime);
for (uint256 i = 1; i <= maxMarketIndex; i++) {
uint256 marketMaturity = tRef.add(DateTime.getTradedMarket(i));
// If market matches then is not idiosyncratic
if (marketMaturity == maturity) return (i, false);
// Returns the market that is immediately greater than the maturity
if (marketMaturity > maturity) return (i, true);
}
revert("CG: no market found");
}
/// @notice Given a bit number and the reference time of the first bit, returns the bit number
/// of a given maturity.
/// @return bitNum and a true or false if the maturity falls on the exact bit
function getBitNumFromMaturity(uint256 blockTime, uint256 maturity)
internal
pure
returns (uint256, bool)
{
uint256 blockTimeUTC0 = getTimeUTC0(blockTime);
// Maturities must always divide days evenly
if (maturity % Constants.DAY != 0) return (0, false);
// Maturity cannot be in the past
if (blockTimeUTC0 >= maturity) return (0, false);
// Overflow check done above
// daysOffset has no remainders, checked above
uint256 daysOffset = (maturity - blockTimeUTC0) / Constants.DAY;
// These if statements need to fall through to the next one
if (daysOffset <= Constants.MAX_DAY_OFFSET) {
return (daysOffset, true);
} else if (daysOffset <= Constants.MAX_WEEK_OFFSET) {
// (daysOffset - MAX_DAY_OFFSET) is the days overflow into the week portion, must be > 0
// (blockTimeUTC0 % WEEK) / DAY is the offset into the week portion
// This returns the offset from the previous max offset in days
uint256 offsetInDays =
daysOffset -
Constants.MAX_DAY_OFFSET +
(blockTimeUTC0 % Constants.WEEK) /
Constants.DAY;
return (
// This converts the offset in days to its corresponding bit position, truncating down
// if it does not divide evenly into DAYS_IN_WEEK
Constants.WEEK_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_WEEK,
(offsetInDays % Constants.DAYS_IN_WEEK) == 0
);
} else if (daysOffset <= Constants.MAX_MONTH_OFFSET) {
uint256 offsetInDays =
daysOffset -
Constants.MAX_WEEK_OFFSET +
(blockTimeUTC0 % Constants.MONTH) /
Constants.DAY;
return (
Constants.MONTH_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_MONTH,
(offsetInDays % Constants.DAYS_IN_MONTH) == 0
);
} else if (daysOffset <= Constants.MAX_QUARTER_OFFSET) {
uint256 offsetInDays =
daysOffset -
Constants.MAX_MONTH_OFFSET +
(blockTimeUTC0 % Constants.QUARTER) /
Constants.DAY;
return (
Constants.QUARTER_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_QUARTER,
(offsetInDays % Constants.DAYS_IN_QUARTER) == 0
);
}
// This is the maximum 1-indexed bit num, it is never valid because it is beyond the 20
// year max maturity
return (256, false);
}
/// @notice Given a bit number and a block time returns the maturity that the bit number
/// should reference. Bit numbers are one indexed.
function getMaturityFromBitNum(uint256 blockTime, uint256 bitNum)
internal
pure
returns (uint256)
{
require(bitNum != 0); // dev: cash group get maturity from bit num is zero
require(bitNum <= 256); // dev: cash group get maturity from bit num overflow
uint256 blockTimeUTC0 = getTimeUTC0(blockTime);
uint256 firstBit;
if (bitNum <= Constants.WEEK_BIT_OFFSET) {
return blockTimeUTC0 + bitNum * Constants.DAY;
} else if (bitNum <= Constants.MONTH_BIT_OFFSET) {
firstBit =
blockTimeUTC0 +
Constants.MAX_DAY_OFFSET * Constants.DAY -
// This backs up to the day that is divisible by a week
(blockTimeUTC0 % Constants.WEEK);
return firstBit + (bitNum - Constants.WEEK_BIT_OFFSET) * Constants.WEEK;
} else if (bitNum <= Constants.QUARTER_BIT_OFFSET) {
firstBit =
blockTimeUTC0 +
Constants.MAX_WEEK_OFFSET * Constants.DAY -
(blockTimeUTC0 % Constants.MONTH);
return firstBit + (bitNum - Constants.MONTH_BIT_OFFSET) * Constants.MONTH;
} else {
firstBit =
blockTimeUTC0 +
Constants.MAX_MONTH_OFFSET * Constants.DAY -
(blockTimeUTC0 % Constants.QUARTER);
return firstBit + (bitNum - Constants.QUARTER_BIT_OFFSET) * Constants.QUARTER;
}
}
}
// SPDX-License-Identifier: BSD-4-Clause
/*
* ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^0.5.0 || ^0.6.0 || ^0.7.0;
/**
* Smart contract library of mathematical functions operating with signed
* 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is
* basically a simple fraction whose numerator is signed 128-bit integer and
* denominator is 2^64. As long as denominator is always the same, there is no
* need to store it, thus in Solidity signed 64.64-bit fixed point numbers are
* represented by int128 type holding only the numerator.
*/
library ABDKMath64x64 {
/*
* Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/*
* Maximum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Convert signed 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromInt (int256 x) internal pure returns (int128) {
require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* Convert signed 64.64 fixed point number into signed 64-bit integer number
* rounding down.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64-bit integer number
*/
function toInt (int128 x) internal pure returns (int64) {
return int64 (x >> 64);
}
/**
* Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromUInt (uint256 x) internal pure returns (int128) {
require (x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* Convert signed 64.64 fixed point number into unsigned 64-bit integer
* number rounding down. Revert on underflow.
*
* @param x signed 64.64-bit fixed point number
* @return unsigned 64-bit integer number
*/
function toUInt (int128 x) internal pure returns (uint64) {
require (x >= 0);
return uint64 (x >> 64);
}
/**
* Convert signed 128.128 fixed point number into signed 64.64-bit fixed point
* number rounding down. Revert on overflow.
*
* @param x signed 128.128-bin fixed point number
* @return signed 64.64-bit fixed point number
*/
function from128x128 (int256 x) internal pure returns (int128) {
int256 result = x >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Convert signed 64.64 fixed point number into signed 128.128 fixed point
* number.
*
* @param x signed 64.64-bit fixed point number
* @return signed 128.128 fixed point number
*/
function to128x128 (int128 x) internal pure returns (int256) {
return int256 (x) << 64;
}
/**
* Calculate x + y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function add (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) + y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x - y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sub (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) - y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x * y rounding down. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function mul (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) * y >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x * y rounding towards zero, where x is signed 64.64 fixed point
* number and y is signed 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y signed 256-bit integer number
* @return signed 256-bit integer number
*/
function muli (int128 x, int256 y) internal pure returns (int256) {
if (x == MIN_64x64) {
require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&
y <= 0x1000000000000000000000000000000000000000000000000);
return -y << 63;
} else {
bool negativeResult = false;
if (x < 0) {
x = -x;
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint256 absoluteResult = mulu (x, uint256 (y));
if (negativeResult) {
require (absoluteResult <=
0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256 (absoluteResult);
}
}
}
/**
* Calculate x * y rounding down, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y unsigned 256-bit integer number
* @return unsigned 256-bit integer number
*/
function mulu (int128 x, uint256 y) internal pure returns (uint256) {
if (y == 0) return 0;
require (x >= 0);
uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = uint256 (x) * (y >> 128);
require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
hi <<= 64;
require (hi <=
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);
return hi + lo;
}
/**
* Calculate x / y rounding towards zero. Revert on overflow or when y is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function div (int128 x, int128 y) internal pure returns (int128) {
require (y != 0);
int256 result = (int256 (x) << 64) / y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x / y rounding towards zero, where x and y are signed 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x signed 256-bit integer number
* @param y signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divi (int256 x, int256 y) internal pure returns (int128) {
require (y != 0);
bool negativeResult = false;
if (x < 0) {
x = -x; // We rely on overflow behavior here
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint128 absoluteResult = divuu (uint256 (x), uint256 (y));
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divu (uint256 x, uint256 y) internal pure returns (int128) {
require (y != 0);
uint128 result = divuu (x, y);
require (result <= uint128 (MAX_64x64));
return int128 (result);
}
/**
* Calculate -x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function neg (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return -x;
}
/**
* Calculate |x|. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function abs (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return x < 0 ? -x : x;
}
/**
* Calculate 1 / x rounding towards zero. Revert on overflow or when x is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function inv (int128 x) internal pure returns (int128) {
require (x != 0);
int256 result = int256 (0x100000000000000000000000000000000) / x;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function avg (int128 x, int128 y) internal pure returns (int128) {
return int128 ((int256 (x) + int256 (y)) >> 1);
}
/**
* Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.
* Revert on overflow or in case x * y is negative.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function gavg (int128 x, int128 y) internal pure returns (int128) {
int256 m = int256 (x) * int256 (y);
require (m >= 0);
require (m <
0x4000000000000000000000000000000000000000000000000000000000000000);
return int128 (sqrtu (uint256 (m)));
}
/**
* Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y uint256 value
* @return signed 64.64-bit fixed point number
*/
function pow (int128 x, uint256 y) internal pure returns (int128) {
bool negative = x < 0 && y & 1 == 1;
uint256 absX = uint128 (x < 0 ? -x : x);
uint256 absResult;
absResult = 0x100000000000000000000000000000000;
if (absX <= 0x10000000000000000) {
absX <<= 63;
while (y != 0) {
if (y & 0x1 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x2 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x4 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x8 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
y >>= 4;
}
absResult >>= 64;
} else {
uint256 absXShift = 63;
if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }
if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }
if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }
if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }
if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }
if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }
uint256 resultShift = 0;
while (y != 0) {
require (absXShift < 64);
if (y & 0x1 != 0) {
absResult = absResult * absX >> 127;
resultShift += absXShift;
if (absResult > 0x100000000000000000000000000000000) {
absResult >>= 1;
resultShift += 1;
}
}
absX = absX * absX >> 127;
absXShift <<= 1;
if (absX >= 0x100000000000000000000000000000000) {
absX >>= 1;
absXShift += 1;
}
y >>= 1;
}
require (resultShift < 64);
absResult >>= 64 - resultShift;
}
int256 result = negative ? -int256 (absResult) : int256 (absResult);
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate sqrt (x) rounding down. Revert if x < 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sqrt (int128 x) internal pure returns (int128) {
require (x >= 0);
return int128 (sqrtu (uint256 (x) << 64));
}
/**
* Calculate binary logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function log_2 (int128 x) internal pure returns (int128) {
require (x > 0);
int256 msb = 0;
int256 xc = x;
if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 result = msb - 64 << 64;
uint256 ux = uint256 (x) << uint256 (127 - msb);
for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * int256 (b);
}
return int128 (result);
}
/**
* Calculate natural logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function ln (int128 x) internal pure returns (int128) {
require (x > 0);
return int128 (
uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128);
}
/**
* Calculate binary exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp_2 (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
uint256 result = 0x80000000000000000000000000000000;
if (x & 0x8000000000000000 > 0)
result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;
if (x & 0x4000000000000000 > 0)
result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;
if (x & 0x2000000000000000 > 0)
result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;
if (x & 0x1000000000000000 > 0)
result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;
if (x & 0x800000000000000 > 0)
result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;
if (x & 0x400000000000000 > 0)
result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;
if (x & 0x200000000000000 > 0)
result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;
if (x & 0x100000000000000 > 0)
result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;
if (x & 0x80000000000000 > 0)
result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;
if (x & 0x40000000000000 > 0)
result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;
if (x & 0x20000000000000 > 0)
result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;
if (x & 0x10000000000000 > 0)
result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;
if (x & 0x8000000000000 > 0)
result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;
if (x & 0x4000000000000 > 0)
result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;
if (x & 0x2000000000000 > 0)
result = result * 0x1000162E525EE054754457D5995292026 >> 128;
if (x & 0x1000000000000 > 0)
result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;
if (x & 0x800000000000 > 0)
result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;
if (x & 0x400000000000 > 0)
result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;
if (x & 0x200000000000 > 0)
result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;
if (x & 0x100000000000 > 0)
result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;
if (x & 0x80000000000 > 0)
result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;
if (x & 0x40000000000 > 0)
result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;
if (x & 0x20000000000 > 0)
result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;
if (x & 0x10000000000 > 0)
result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;
if (x & 0x8000000000 > 0)
result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;
if (x & 0x4000000000 > 0)
result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;
if (x & 0x2000000000 > 0)
result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;
if (x & 0x1000000000 > 0)
result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;
if (x & 0x800000000 > 0)
result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;
if (x & 0x400000000 > 0)
result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;
if (x & 0x200000000 > 0)
result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;
if (x & 0x100000000 > 0)
result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;
if (x & 0x80000000 > 0)
result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;
if (x & 0x40000000 > 0)
result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;
if (x & 0x20000000 > 0)
result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;
if (x & 0x10000000 > 0)
result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;
if (x & 0x8000000 > 0)
result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;
if (x & 0x4000000 > 0)
result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;
if (x & 0x2000000 > 0)
result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;
if (x & 0x1000000 > 0)
result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;
if (x & 0x800000 > 0)
result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;
if (x & 0x400000 > 0)
result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;
if (x & 0x200000 > 0)
result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;
if (x & 0x100000 > 0)
result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;
if (x & 0x80000 > 0)
result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;
if (x & 0x40000 > 0)
result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;
if (x & 0x20000 > 0)
result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;
if (x & 0x10000 > 0)
result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;
if (x & 0x8000 > 0)
result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;
if (x & 0x4000 > 0)
result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;
if (x & 0x2000 > 0)
result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;
if (x & 0x1000 > 0)
result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;
if (x & 0x800 > 0)
result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;
if (x & 0x400 > 0)
result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;
if (x & 0x200 > 0)
result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;
if (x & 0x100 > 0)
result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;
if (x & 0x80 > 0)
result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;
if (x & 0x40 > 0)
result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;
if (x & 0x20 > 0)
result = result * 0x100000000000000162E42FEFA39EF366F >> 128;
if (x & 0x10 > 0)
result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;
if (x & 0x8 > 0)
result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;
if (x & 0x4 > 0)
result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;
if (x & 0x2 > 0)
result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;
if (x & 0x1 > 0)
result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;
result >>= uint256 (63 - (x >> 64));
require (result <= uint256 (MAX_64x64));
return int128 (result);
}
/**
* Calculate natural exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
return exp_2 (
int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return unsigned 64.64-bit fixed point number
*/
function divuu (uint256 x, uint256 y) private pure returns (uint128) {
require (y != 0);
uint256 result;
if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
result = (x << 64) / y;
else {
uint256 msb = 192;
uint256 xc = x >> 192;
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 hi = result * (y >> 128);
uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 xh = x >> 192;
uint256 xl = x << 64;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
lo = hi << 128;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
assert (xh == hi >> 128);
result += xl / y;
}
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint128 (result);
}
/**
* Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
* number.
*
* @param x unsigned 256-bit integer number
* @return unsigned 128-bit integer number
*/
function sqrtu (uint256 x) private pure returns (uint128) {
if (x == 0) return 0;
else {
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }
if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }
if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }
if (xx >= 0x10000) { xx >>= 16; r <<= 8; }
if (xx >= 0x100) { xx >>= 8; r <<= 4; }
if (xx >= 0x10) { xx >>= 4; r <<= 2; }
if (xx >= 0x8) { r <<= 1; }
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return uint128 (r < r1 ? r : r1);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
import "./AggregatorInterface.sol";
import "./AggregatorV3Interface.sol";
interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface
{
}
// SPDX-License-Identifier: GPL-v3
pragma solidity >=0.7.0;
/// @notice Used as a wrapper for tokens that are interest bearing for an
/// underlying token. Follows the cToken interface, however, can be adapted
/// for other interest bearing tokens.
interface AssetRateAdapter {
function token() external view returns (address);
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
function underlying() external view returns (address);
function getExchangeRateStateful() external returns (int256);
function getExchangeRateView() external view returns (int256);
function getAnnualizedSupplyRate() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
interface AggregatorInterface {
function latestAnswer() external view returns (int256);
function latestTimestamp() external view returns (uint256);
function latestRound() external view returns (uint256);
function getAnswer(uint256 roundId) external view returns (int256);
function getTimestamp(uint256 roundId) external view returns (uint256);
event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt);
event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt);
}
// 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: GPL-3.0-only
pragma solidity ^0.7.0;
interface IRewarder {
function claimRewards(
address account,
uint16 currencyId,
uint256 nTokenBalanceBefore,
uint256 nTokenBalanceAfter,
int256 netNTokenSupplyChange,
uint256 NOTETokensClaimed
) external;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
struct LendingPoolStorage {
ILendingPool lendingPool;
}
interface ILendingPool {
/**
* @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.
* - E.g. User deposits 100 USDC and gets in return 100 aUSDC
* @param asset The address of the underlying asset to deposit
* @param amount The amount to be deposited
* @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
* is a different wallet
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
/**
* @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned
* E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC
* @param asset The address of the underlying asset to withdraw
* @param amount The underlying amount to be withdrawn
* - Send the value type(uint256).max in order to withdraw the whole aToken balance
* @param to Address that will receive the underlying, same as msg.sender if the user
* wants to receive it on his own wallet, or a different address if the beneficiary is a
* different wallet
* @return The final amount withdrawn
**/
function withdraw(
address asset,
uint256 amount,
address to
) external returns (uint256);
/**
* @dev Returns the normalized income normalized income of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The reserve's normalized income
*/
function getReserveNormalizedIncome(address asset) external view returns (uint256);
/**
* @dev Returns the state and configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The state of the reserve
**/
function getReserveData(address asset) external view returns (ReserveData memory);
// refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties.
struct ReserveData {
//stores the reserve configuration
ReserveConfigurationMap configuration;
//the liquidity index. Expressed in ray
uint128 liquidityIndex;
//variable borrow index. Expressed in ray
uint128 variableBorrowIndex;
//the current supply rate. Expressed in ray
uint128 currentLiquidityRate;
//the current variable borrow rate. Expressed in ray
uint128 currentVariableBorrowRate;
//the current stable borrow rate. Expressed in ray
uint128 currentStableBorrowRate;
uint40 lastUpdateTimestamp;
//tokens addresses
address aTokenAddress;
address stableDebtTokenAddress;
address variableDebtTokenAddress;
//address of the interest rate strategy
address interestRateStrategyAddress;
//the id of the reserve. Represents the position in the list of the active reserves
uint8 id;
}
struct ReserveConfigurationMap {
//bit 0-15: LTV
//bit 16-31: Liq. threshold
//bit 32-47: Liq. bonus
//bit 48-55: Decimals
//bit 56: Reserve is active
//bit 57: reserve is frozen
//bit 58: borrowing is enabled
//bit 59: stable rate borrowing enabled
//bit 60-63: reserved
//bit 64-79: reserve factor
uint256 data;
}
struct UserConfigurationMap {
uint256 data;
}
enum InterestRateMode {NONE, STABLE, VARIABLE}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./TokenHandler.sol";
import "../nToken/nTokenHandler.sol";
import "../nToken/nTokenSupply.sol";
import "../../math/SafeInt256.sol";
import "../../external/MigrateIncentives.sol";
import "../../../interfaces/notional/IRewarder.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library Incentives {
using SafeMath for uint256;
using SafeInt256 for int256;
/// @notice Calculates the total incentives to claim including those claimed under the previous
/// less accurate calculation. Once an account is migrated it will only claim incentives under
/// the more accurate regime
function calculateIncentivesToClaim(
BalanceState memory balanceState,
address tokenAddress,
uint256 accumulatedNOTEPerNToken,
uint256 finalNTokenBalance
) internal view returns (uint256 incentivesToClaim) {
if (balanceState.lastClaimTime > 0) {
// If lastClaimTime is set then the account had incentives under the
// previous regime. Will calculate the final amount of incentives to claim here
// under the previous regime.
incentivesToClaim = MigrateIncentives.migrateAccountFromPreviousCalculation(
tokenAddress,
balanceState.storedNTokenBalance.toUint(),
balanceState.lastClaimTime,
// In this case the accountIncentiveDebt is stored as lastClaimIntegralSupply under
// the old calculation
balanceState.accountIncentiveDebt
);
// This marks the account as migrated and lastClaimTime will no longer be used
balanceState.lastClaimTime = 0;
// This value will be set immediately after this, set this to zero so that the calculation
// establishes a new baseline.
balanceState.accountIncentiveDebt = 0;
}
// If an account was migrated then they have no accountIncentivesDebt and should accumulate
// incentives based on their share since the new regime calculation started.
// If an account is just initiating their nToken balance then storedNTokenBalance will be zero
// and they will have no incentives to claim.
// This calculation uses storedNTokenBalance which is the balance of the account up until this point,
// this is important to ensure that the account does not claim for nTokens that they will mint or
// redeem on a going forward basis.
// The calculation below has the following precision:
// storedNTokenBalance (INTERNAL_TOKEN_PRECISION)
// MUL accumulatedNOTEPerNToken (INCENTIVE_ACCUMULATION_PRECISION)
// DIV INCENTIVE_ACCUMULATION_PRECISION
// = INTERNAL_TOKEN_PRECISION - (accountIncentivesDebt) INTERNAL_TOKEN_PRECISION
incentivesToClaim = incentivesToClaim.add(
balanceState.storedNTokenBalance.toUint()
.mul(accumulatedNOTEPerNToken)
.div(Constants.INCENTIVE_ACCUMULATION_PRECISION)
.sub(balanceState.accountIncentiveDebt)
);
// Update accountIncentivesDebt denominated in INTERNAL_TOKEN_PRECISION which marks the portion
// of the accumulatedNOTE that the account no longer has a claim over. Use the finalNTokenBalance
// here instead of storedNTokenBalance to mark the overall incentives claim that the account
// does not have a claim over. We do not aggregate this value with the previous accountIncentiveDebt
// because accumulatedNOTEPerNToken is already an aggregated value.
// The calculation below has the following precision:
// finalNTokenBalance (INTERNAL_TOKEN_PRECISION)
// MUL accumulatedNOTEPerNToken (INCENTIVE_ACCUMULATION_PRECISION)
// DIV INCENTIVE_ACCUMULATION_PRECISION
// = INTERNAL_TOKEN_PRECISION
balanceState.accountIncentiveDebt = finalNTokenBalance
.mul(accumulatedNOTEPerNToken)
.div(Constants.INCENTIVE_ACCUMULATION_PRECISION);
}
/// @notice Incentives must be claimed every time nToken balance changes.
/// @dev BalanceState.accountIncentiveDebt is updated in place here
function claimIncentives(
BalanceState memory balanceState,
address account,
uint256 finalNTokenBalance
) internal returns (uint256 incentivesToClaim) {
uint256 blockTime = block.timestamp;
address tokenAddress = nTokenHandler.nTokenAddress(balanceState.currencyId);
// This will updated the nToken storage and return what the accumulatedNOTEPerNToken
// is up until this current block time in 1e18 precision
uint256 accumulatedNOTEPerNToken = nTokenSupply.changeNTokenSupply(
tokenAddress,
balanceState.netNTokenSupplyChange,
blockTime
);
incentivesToClaim = calculateIncentivesToClaim(
balanceState,
tokenAddress,
accumulatedNOTEPerNToken,
finalNTokenBalance
);
// If a secondary incentive rewarder is set, then call it
IRewarder rewarder = nTokenHandler.getSecondaryRewarder(tokenAddress);
if (address(rewarder) != address(0)) {
rewarder.claimRewards(
account,
balanceState.currencyId,
// When this method is called from finalize, the storedNTokenBalance has not
// been updated to finalNTokenBalance yet so this is the balance before the change.
balanceState.storedNTokenBalance.toUint(),
finalNTokenBalance,
// When the rewarder is called, totalSupply has been updated already so may need to
// adjust its calculation using the net supply change figure here. Supply change
// may be zero when nTokens are transferred.
balanceState.netNTokenSupplyChange,
incentivesToClaim
);
}
if (incentivesToClaim > 0) TokenHandler.transferIncentive(account, incentivesToClaim);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../math/SafeInt256.sol";
import "../../global/LibStorage.sol";
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../../global/Deployments.sol";
import "./protocols/AaveHandler.sol";
import "./protocols/CompoundHandler.sol";
import "./protocols/GenericToken.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/// @notice Handles all external token transfers and events
library TokenHandler {
using SafeInt256 for int256;
using SafeMath for uint256;
function setMaxCollateralBalance(uint256 currencyId, uint72 maxCollateralBalance) internal {
mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage();
TokenStorage storage tokenStorage = store[currencyId][false];
tokenStorage.maxCollateralBalance = maxCollateralBalance;
}
function getAssetToken(uint256 currencyId) internal view returns (Token memory) {
return _getToken(currencyId, false);
}
function getUnderlyingToken(uint256 currencyId) internal view returns (Token memory) {
return _getToken(currencyId, true);
}
/// @notice Gets token data for a particular currency id, if underlying is set to true then returns
/// the underlying token. (These may not always exist)
function _getToken(uint256 currencyId, bool underlying) private view returns (Token memory) {
mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage();
TokenStorage storage tokenStorage = store[currencyId][underlying];
return
Token({
tokenAddress: tokenStorage.tokenAddress,
hasTransferFee: tokenStorage.hasTransferFee,
// No overflow, restricted on storage
decimals: int256(10**tokenStorage.decimalPlaces),
tokenType: tokenStorage.tokenType,
maxCollateralBalance: tokenStorage.maxCollateralBalance
});
}
/// @notice Sets a token for a currency id.
function setToken(
uint256 currencyId,
bool underlying,
TokenStorage memory tokenStorage
) internal {
mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage();
if (tokenStorage.tokenType == TokenType.Ether && currencyId == Constants.ETH_CURRENCY_ID) {
// Hardcoded parameters for ETH just to make sure we don't get it wrong.
TokenStorage storage ts = store[currencyId][true];
ts.tokenAddress = address(0);
ts.hasTransferFee = false;
ts.tokenType = TokenType.Ether;
ts.decimalPlaces = Constants.ETH_DECIMAL_PLACES;
ts.maxCollateralBalance = 0;
return;
}
// Check token address
require(tokenStorage.tokenAddress != address(0), "TH: address is zero");
// Once a token is set we cannot override it. In the case that we do need to do change a token address
// then we should explicitly upgrade this method to allow for a token to be changed.
Token memory token = _getToken(currencyId, underlying);
require(
token.tokenAddress == tokenStorage.tokenAddress || token.tokenAddress == address(0),
"TH: token cannot be reset"
);
require(0 < tokenStorage.decimalPlaces
&& tokenStorage.decimalPlaces <= Constants.MAX_DECIMAL_PLACES, "TH: invalid decimals");
// Validate token type
require(tokenStorage.tokenType != TokenType.Ether); // dev: ether can only be set once
if (underlying) {
// Underlying tokens cannot have max collateral balances, the contract only has a balance temporarily
// during mint and redeem actions.
require(tokenStorage.maxCollateralBalance == 0); // dev: underlying cannot have max collateral balance
require(tokenStorage.tokenType == TokenType.UnderlyingToken); // dev: underlying token inconsistent
} else {
require(tokenStorage.tokenType != TokenType.UnderlyingToken); // dev: underlying token inconsistent
}
if (tokenStorage.tokenType == TokenType.cToken || tokenStorage.tokenType == TokenType.aToken) {
// Set the approval for the underlying so that we can mint cTokens or aTokens
Token memory underlyingToken = getUnderlyingToken(currencyId);
// cTokens call transfer from the tokenAddress, but aTokens use the LendingPool
// to initiate all transfers
address approvalAddress = tokenStorage.tokenType == TokenType.cToken ?
tokenStorage.tokenAddress :
address(LibStorage.getLendingPool().lendingPool);
// ERC20 tokens should return true on success for an approval, but Tether
// does not return a value here so we use the NonStandard interface here to
// check that the approval was successful.
IEIP20NonStandard(underlyingToken.tokenAddress).approve(
approvalAddress,
type(uint256).max
);
GenericToken.checkReturnCode();
}
store[currencyId][underlying] = tokenStorage;
}
/**
* @notice If a token is mintable then will mint it. At this point we expect to have the underlying
* balance in the contract already.
* @param assetToken the asset token to mint
* @param underlyingAmountExternal the amount of underlying to transfer to the mintable token
* @return the amount of asset tokens minted, will always be a positive integer
*/
function mint(Token memory assetToken, uint16 currencyId, uint256 underlyingAmountExternal) internal returns (int256) {
// aTokens return the principal plus interest value when calling the balanceOf selector. We cannot use this
// value in internal accounting since it will not allow individual users to accrue aToken interest. Use the
// scaledBalanceOf function call instead for internal accounting.
bytes4 balanceOfSelector = assetToken.tokenType == TokenType.aToken ?
AaveHandler.scaledBalanceOfSelector :
GenericToken.defaultBalanceOfSelector;
uint256 startingBalance = GenericToken.checkBalanceViaSelector(assetToken.tokenAddress, address(this), balanceOfSelector);
if (assetToken.tokenType == TokenType.aToken) {
Token memory underlyingToken = getUnderlyingToken(currencyId);
AaveHandler.mint(underlyingToken, underlyingAmountExternal);
} else if (assetToken.tokenType == TokenType.cToken) {
CompoundHandler.mint(assetToken, underlyingAmountExternal);
} else if (assetToken.tokenType == TokenType.cETH) {
CompoundHandler.mintCETH(assetToken);
} else {
revert(); // dev: non mintable token
}
uint256 endingBalance = GenericToken.checkBalanceViaSelector(assetToken.tokenAddress, address(this), balanceOfSelector);
// This is the starting and ending balance in external precision
return SafeInt256.toInt(endingBalance.sub(startingBalance));
}
/**
* @notice If a token is redeemable to underlying will redeem it and transfer the underlying balance
* to the account
* @param assetToken asset token to redeem
* @param currencyId the currency id of the token
* @param account account to transfer the underlying to
* @param assetAmountExternal the amount to transfer in asset token denomination and external precision
* @return the actual amount of underlying tokens transferred. this is used as a return value back to the
* user, is not used for internal accounting purposes
*/
function redeem(
Token memory assetToken,
uint256 currencyId,
address account,
uint256 assetAmountExternal
) internal returns (int256) {
uint256 transferAmount;
if (assetToken.tokenType == TokenType.cETH) {
transferAmount = CompoundHandler.redeemCETH(assetToken, account, assetAmountExternal);
} else {
Token memory underlyingToken = getUnderlyingToken(currencyId);
if (assetToken.tokenType == TokenType.aToken) {
transferAmount = AaveHandler.redeem(underlyingToken, account, assetAmountExternal);
} else if (assetToken.tokenType == TokenType.cToken) {
transferAmount = CompoundHandler.redeem(assetToken, underlyingToken, account, assetAmountExternal);
} else {
revert(); // dev: non redeemable token
}
}
// Use the negative value here to signify that assets have left the protocol
return SafeInt256.toInt(transferAmount).neg();
}
/// @notice Handles transfers into and out of the system denominated in the external token decimal
/// precision.
function transfer(
Token memory token,
address account,
uint256 currencyId,
int256 netTransferExternal
) internal returns (int256 actualTransferExternal) {
// This will be true in all cases except for deposits where the token has transfer fees. For
// aTokens this value is set before convert from scaled balances to principal plus interest
actualTransferExternal = netTransferExternal;
if (token.tokenType == TokenType.aToken) {
Token memory underlyingToken = getUnderlyingToken(currencyId);
// aTokens need to be converted when we handle the transfer since the external balance format
// is not the same as the internal balance format that we use
netTransferExternal = AaveHandler.convertFromScaledBalanceExternal(
underlyingToken.tokenAddress,
netTransferExternal
);
}
if (netTransferExternal > 0) {
// Deposits must account for transfer fees.
int256 netDeposit = _deposit(token, account, uint256(netTransferExternal));
// If an aToken has a transfer fee this will still return a balance figure
// in scaledBalanceOf terms due to the selector
if (token.hasTransferFee) actualTransferExternal = netDeposit;
} else if (token.tokenType == TokenType.Ether) {
// netTransferExternal can only be negative or zero at this point
GenericToken.transferNativeTokenOut(account, uint256(netTransferExternal.neg()));
} else {
GenericToken.safeTransferOut(
token.tokenAddress,
account,
// netTransferExternal is zero or negative here
uint256(netTransferExternal.neg())
);
}
}
/// @notice Handles token deposits into Notional. If there is a transfer fee then we must
/// calculate the net balance after transfer. Amounts are denominated in the destination token's
/// precision.
function _deposit(
Token memory token,
address account,
uint256 amount
) private returns (int256) {
uint256 startingBalance;
uint256 endingBalance;
bytes4 balanceOfSelector = token.tokenType == TokenType.aToken ?
AaveHandler.scaledBalanceOfSelector :
GenericToken.defaultBalanceOfSelector;
if (token.hasTransferFee) {
startingBalance = GenericToken.checkBalanceViaSelector(token.tokenAddress, address(this), balanceOfSelector);
}
GenericToken.safeTransferIn(token.tokenAddress, account, amount);
if (token.hasTransferFee || token.maxCollateralBalance > 0) {
// If aTokens have a max collateral balance then it will be applied against the scaledBalanceOf. This is probably
// the correct behavior because if collateral accrues interest over time we should not somehow go over the
// maxCollateralBalance due to the passage of time.
endingBalance = GenericToken.checkBalanceViaSelector(token.tokenAddress, address(this), balanceOfSelector);
}
if (token.maxCollateralBalance > 0) {
int256 internalPrecisionBalance = convertToInternal(token, SafeInt256.toInt(endingBalance));
// Max collateral balance is stored as uint72, no overflow
require(internalPrecisionBalance <= SafeInt256.toInt(token.maxCollateralBalance)); // dev: over max collateral balance
}
// Math is done in uint inside these statements and will revert on negative
if (token.hasTransferFee) {
return SafeInt256.toInt(endingBalance.sub(startingBalance));
} else {
return SafeInt256.toInt(amount);
}
}
function convertToInternal(Token memory token, int256 amount) internal pure returns (int256) {
// If token decimals > INTERNAL_TOKEN_PRECISION:
// on deposit: resulting dust will accumulate to protocol
// on withdraw: protocol may lose dust amount. However, withdraws are only calculated based
// on a conversion from internal token precision to external token precision so therefore dust
// amounts cannot be specified for withdraws.
// If token decimals < INTERNAL_TOKEN_PRECISION then this will add zeros to the
// end of amount and will not result in dust.
if (token.decimals == Constants.INTERNAL_TOKEN_PRECISION) return amount;
return amount.mul(Constants.INTERNAL_TOKEN_PRECISION).div(token.decimals);
}
function convertToExternal(Token memory token, int256 amount) internal pure returns (int256) {
if (token.decimals == Constants.INTERNAL_TOKEN_PRECISION) return amount;
// If token decimals > INTERNAL_TOKEN_PRECISION then this will increase amount
// by adding a number of zeros to the end and will not result in dust.
// If token decimals < INTERNAL_TOKEN_PRECISION:
// on deposit: Deposits are specified in external token precision and there is no loss of precision when
// tokens are converted from external to internal precision
// on withdraw: this calculation will round down such that the protocol retains the residual cash balance
return amount.mul(token.decimals).div(Constants.INTERNAL_TOKEN_PRECISION);
}
function transferIncentive(address account, uint256 tokensToTransfer) internal {
GenericToken.safeTransferOut(Deployments.NOTE_TOKEN_ADDRESS, account, tokensToTransfer);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
import "./Bitmap.sol";
/**
* Packs an uint value into a "floating point" storage slot. Used for storing
* lastClaimIntegralSupply values in balance storage. For these values, we don't need
* to maintain exact precision but we don't want to be limited by storage size overflows.
*
* A floating point value is defined by the 48 most significant bits and an 8 bit number
* of bit shifts required to restore its precision. The unpacked value will always be less
* than the packed value with a maximum absolute loss of precision of (2 ** bitShift) - 1.
*/
library FloatingPoint56 {
function packTo56Bits(uint256 value) internal pure returns (uint56) {
uint256 bitShift;
// If the value is over the uint48 max value then we will shift it down
// given the index of the most significant bit. We store this bit shift
// in the least significant byte of the 56 bit slot available.
if (value > type(uint48).max) bitShift = (Bitmap.getMSB(value) - 47);
uint256 shiftedValue = value >> bitShift;
return uint56((shiftedValue << 8) | bitShift);
}
function unpackFrom56Bits(uint256 value) internal pure returns (uint256) {
// The least significant 8 bits will be the amount to bit shift
uint256 bitShift = uint256(uint8(value));
return ((value >> 8) << bitShift);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./nTokenSupply.sol";
import "../markets/CashGroup.sol";
import "../markets/AssetRate.sol";
import "../portfolio/PortfolioHandler.sol";
import "../balances/BalanceHandler.sol";
import "../../global/LibStorage.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library nTokenHandler {
using SafeInt256 for int256;
/// @dev Mirror of the value in LibStorage, solidity compiler does not allow assigning
/// two constants to each other.
uint256 private constant NUM_NTOKEN_MARKET_FACTORS = 14;
/// @notice Returns an account context object that is specific to nTokens.
function getNTokenContext(address tokenAddress)
internal
view
returns (
uint16 currencyId,
uint256 incentiveAnnualEmissionRate,
uint256 lastInitializedTime,
uint8 assetArrayLength,
bytes5 parameters
)
{
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
currencyId = context.currencyId;
incentiveAnnualEmissionRate = context.incentiveAnnualEmissionRate;
lastInitializedTime = context.lastInitializedTime;
assetArrayLength = context.assetArrayLength;
parameters = context.nTokenParameters;
}
/// @notice Returns the nToken token address for a given currency
function nTokenAddress(uint256 currencyId) internal view returns (address tokenAddress) {
mapping(uint256 => address) storage store = LibStorage.getNTokenAddressStorage();
return store[currencyId];
}
/// @notice Called by governance to set the nToken token address and its reverse lookup. Cannot be
/// reset once this is set.
function setNTokenAddress(uint16 currencyId, address tokenAddress) internal {
mapping(uint256 => address) storage addressStore = LibStorage.getNTokenAddressStorage();
require(addressStore[currencyId] == address(0), "PT: token address exists");
mapping(address => nTokenContext) storage contextStore = LibStorage.getNTokenContextStorage();
nTokenContext storage context = contextStore[tokenAddress];
require(context.currencyId == 0, "PT: currency exists");
// This will initialize all other context slots to zero
context.currencyId = currencyId;
addressStore[currencyId] = tokenAddress;
}
/// @notice Set nToken token collateral parameters
function setNTokenCollateralParameters(
address tokenAddress,
uint8 residualPurchaseIncentive10BPS,
uint8 pvHaircutPercentage,
uint8 residualPurchaseTimeBufferHours,
uint8 cashWithholdingBuffer10BPS,
uint8 liquidationHaircutPercentage
) internal {
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
require(liquidationHaircutPercentage <= Constants.PERCENTAGE_DECIMALS, "Invalid haircut");
// The pv haircut percentage must be less than the liquidation percentage or else liquidators will not
// get profit for liquidating nToken.
require(pvHaircutPercentage < liquidationHaircutPercentage, "Invalid pv haircut");
// Ensure that the cash withholding buffer is greater than the residual purchase incentive or
// the nToken may not have enough cash to pay accounts to buy its negative ifCash
require(residualPurchaseIncentive10BPS <= cashWithholdingBuffer10BPS, "Invalid discounts");
bytes5 parameters =
(bytes5(uint40(residualPurchaseIncentive10BPS)) |
(bytes5(uint40(pvHaircutPercentage)) << 8) |
(bytes5(uint40(residualPurchaseTimeBufferHours)) << 16) |
(bytes5(uint40(cashWithholdingBuffer10BPS)) << 24) |
(bytes5(uint40(liquidationHaircutPercentage)) << 32));
// Set the parameters
context.nTokenParameters = parameters;
}
/// @notice Sets a secondary rewarder contract on an nToken so that incentives can come from a different
/// contract, aside from the native NOTE token incentives.
function setSecondaryRewarder(
uint16 currencyId,
IRewarder rewarder
) internal {
address tokenAddress = nTokenAddress(currencyId);
// nToken must exist for a secondary rewarder
require(tokenAddress != address(0));
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
// Setting the rewarder to address(0) will disable it. We use a context setting here so that
// we can save a storage read before getting the rewarder
context.hasSecondaryRewarder = (address(rewarder) != address(0));
LibStorage.getSecondaryIncentiveRewarder()[tokenAddress] = rewarder;
}
/// @notice Returns the secondary rewarder if it is set
function getSecondaryRewarder(address tokenAddress) internal view returns (IRewarder) {
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
if (context.hasSecondaryRewarder) {
return LibStorage.getSecondaryIncentiveRewarder()[tokenAddress];
} else {
return IRewarder(address(0));
}
}
function setArrayLengthAndInitializedTime(
address tokenAddress,
uint8 arrayLength,
uint256 lastInitializedTime
) internal {
require(lastInitializedTime >= 0 && uint256(lastInitializedTime) < type(uint32).max); // dev: next settle time overflow
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
context.lastInitializedTime = uint32(lastInitializedTime);
context.assetArrayLength = arrayLength;
}
/// @notice Returns the array of deposit shares and leverage thresholds for nTokens
function getDepositParameters(uint256 currencyId, uint256 maxMarketIndex)
internal
view
returns (int256[] memory depositShares, int256[] memory leverageThresholds)
{
mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenDepositStorage();
uint32[NUM_NTOKEN_MARKET_FACTORS] storage depositParameters = store[currencyId];
(depositShares, leverageThresholds) = _getParameters(depositParameters, maxMarketIndex, false);
}
/// @notice Sets the deposit parameters
/// @dev We pack the values in alternating between the two parameters into either one or two
// storage slots depending on the number of markets. This is to save storage reads when we use the parameters.
function setDepositParameters(
uint256 currencyId,
uint32[] calldata depositShares,
uint32[] calldata leverageThresholds
) internal {
require(
depositShares.length <= Constants.MAX_TRADED_MARKET_INDEX,
"PT: deposit share length"
);
require(depositShares.length == leverageThresholds.length, "PT: leverage share length");
uint256 shareSum;
for (uint256 i; i < depositShares.length; i++) {
// This cannot overflow in uint 256 with 9 max slots
shareSum = shareSum + depositShares[i];
require(
leverageThresholds[i] > 0 && leverageThresholds[i] < Constants.RATE_PRECISION,
"PT: leverage threshold"
);
}
// Total deposit share must add up to 100%
require(shareSum == uint256(Constants.DEPOSIT_PERCENT_BASIS), "PT: deposit shares sum");
mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenDepositStorage();
uint32[NUM_NTOKEN_MARKET_FACTORS] storage depositParameters = store[currencyId];
_setParameters(depositParameters, depositShares, leverageThresholds);
}
/// @notice Sets the initialization parameters for the markets, these are read only when markets
/// are initialized
function setInitializationParameters(
uint256 currencyId,
uint32[] calldata annualizedAnchorRates,
uint32[] calldata proportions
) internal {
require(annualizedAnchorRates.length <= Constants.MAX_TRADED_MARKET_INDEX, "PT: annualized anchor rates length");
require(proportions.length == annualizedAnchorRates.length, "PT: proportions length");
for (uint256 i; i < proportions.length; i++) {
// Proportions must be between zero and the rate precision
require(annualizedAnchorRates[i] > 0, "NT: anchor rate zero");
require(
proportions[i] > 0 && proportions[i] < Constants.RATE_PRECISION,
"PT: invalid proportion"
);
}
mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenInitStorage();
uint32[NUM_NTOKEN_MARKET_FACTORS] storage initParameters = store[currencyId];
_setParameters(initParameters, annualizedAnchorRates, proportions);
}
/// @notice Returns the array of initialization parameters for a given currency.
function getInitializationParameters(uint256 currencyId, uint256 maxMarketIndex)
internal
view
returns (int256[] memory annualizedAnchorRates, int256[] memory proportions)
{
mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenInitStorage();
uint32[NUM_NTOKEN_MARKET_FACTORS] storage initParameters = store[currencyId];
(annualizedAnchorRates, proportions) = _getParameters(initParameters, maxMarketIndex, true);
}
function _getParameters(
uint32[NUM_NTOKEN_MARKET_FACTORS] storage slot,
uint256 maxMarketIndex,
bool noUnset
) private view returns (int256[] memory, int256[] memory) {
uint256 index = 0;
int256[] memory array1 = new int256[](maxMarketIndex);
int256[] memory array2 = new int256[](maxMarketIndex);
for (uint256 i; i < maxMarketIndex; i++) {
array1[i] = slot[index];
index++;
array2[i] = slot[index];
index++;
if (noUnset) {
require(array1[i] > 0 && array2[i] > 0, "PT: init value zero");
}
}
return (array1, array2);
}
function _setParameters(
uint32[NUM_NTOKEN_MARKET_FACTORS] storage slot,
uint32[] calldata array1,
uint32[] calldata array2
) private {
uint256 index = 0;
for (uint256 i = 0; i < array1.length; i++) {
slot[index] = array1[i];
index++;
slot[index] = array2[i];
index++;
}
}
function loadNTokenPortfolioNoCashGroup(nTokenPortfolio memory nToken, uint16 currencyId)
internal
view
{
nToken.tokenAddress = nTokenAddress(currencyId);
// prettier-ignore
(
/* currencyId */,
/* incentiveRate */,
uint256 lastInitializedTime,
uint8 assetArrayLength,
bytes5 parameters
) = getNTokenContext(nToken.tokenAddress);
// prettier-ignore
(
uint256 totalSupply,
/* accumulatedNOTEPerNToken */,
/* lastAccumulatedTime */
) = nTokenSupply.getStoredNTokenSupplyFactors(nToken.tokenAddress);
nToken.lastInitializedTime = lastInitializedTime;
nToken.totalSupply = int256(totalSupply);
nToken.parameters = parameters;
nToken.portfolioState = PortfolioHandler.buildPortfolioState(
nToken.tokenAddress,
assetArrayLength,
0
);
// prettier-ignore
(
nToken.cashBalance,
/* nTokenBalance */,
/* lastClaimTime */,
/* accountIncentiveDebt */
) = BalanceHandler.getBalanceStorage(nToken.tokenAddress, currencyId);
}
/// @notice Uses buildCashGroupStateful
function loadNTokenPortfolioStateful(nTokenPortfolio memory nToken, uint16 currencyId)
internal
{
loadNTokenPortfolioNoCashGroup(nToken, currencyId);
nToken.cashGroup = CashGroup.buildCashGroupStateful(currencyId);
}
/// @notice Uses buildCashGroupView
function loadNTokenPortfolioView(nTokenPortfolio memory nToken, uint16 currencyId)
internal
view
{
loadNTokenPortfolioNoCashGroup(nToken, currencyId);
nToken.cashGroup = CashGroup.buildCashGroupView(currencyId);
}
/// @notice Returns the next settle time for the nToken which is 1 quarter away
function getNextSettleTime(nTokenPortfolio memory nToken) internal pure returns (uint256) {
if (nToken.lastInitializedTime == 0) return 0;
return DateTime.getReferenceTime(nToken.lastInitializedTime) + Constants.QUARTER;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./nTokenHandler.sol";
import "../../global/LibStorage.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library nTokenSupply {
using SafeInt256 for int256;
using SafeMath for uint256;
/// @notice Retrieves stored nToken supply and related factors. Do not use accumulatedNOTEPerNToken for calculating
/// incentives! Use `getUpdatedAccumulatedNOTEPerNToken` instead.
function getStoredNTokenSupplyFactors(address tokenAddress)
internal
view
returns (
uint256 totalSupply,
uint256 accumulatedNOTEPerNToken,
uint256 lastAccumulatedTime
)
{
mapping(address => nTokenTotalSupplyStorage) storage store = LibStorage.getNTokenTotalSupplyStorage();
nTokenTotalSupplyStorage storage nTokenStorage = store[tokenAddress];
totalSupply = nTokenStorage.totalSupply;
// NOTE: DO NOT USE THIS RETURNED VALUE FOR CALCULATING INCENTIVES. The accumulatedNOTEPerNToken
// must be updated given the block time. Use `getUpdatedAccumulatedNOTEPerNToken` instead
accumulatedNOTEPerNToken = nTokenStorage.accumulatedNOTEPerNToken;
lastAccumulatedTime = nTokenStorage.lastAccumulatedTime;
}
/// @notice Returns the updated accumulated NOTE per nToken for calculating incentives
function getUpdatedAccumulatedNOTEPerNToken(address tokenAddress, uint256 blockTime)
internal view
returns (
uint256 totalSupply,
uint256 accumulatedNOTEPerNToken,
uint256 lastAccumulatedTime
)
{
(
totalSupply,
accumulatedNOTEPerNToken,
lastAccumulatedTime
) = getStoredNTokenSupplyFactors(tokenAddress);
// nToken totalSupply is never allowed to drop to zero but we check this here to avoid
// divide by zero errors during initialization. Also ensure that lastAccumulatedTime is not
// zero to avoid a massive accumulation amount on initialization.
if (blockTime > lastAccumulatedTime && lastAccumulatedTime > 0 && totalSupply > 0) {
// prettier-ignore
(
/* currencyId */,
uint256 emissionRatePerYear,
/* initializedTime */,
/* assetArrayLength */,
/* parameters */
) = nTokenHandler.getNTokenContext(tokenAddress);
uint256 additionalNOTEAccumulatedPerNToken = _calculateAdditionalNOTE(
// Emission rate is denominated in whole tokens, scale to 1e8 decimals here
emissionRatePerYear.mul(uint256(Constants.INTERNAL_TOKEN_PRECISION)),
// Time since last accumulation (overflow checked above)
blockTime - lastAccumulatedTime,
totalSupply
);
accumulatedNOTEPerNToken = accumulatedNOTEPerNToken.add(additionalNOTEAccumulatedPerNToken);
require(accumulatedNOTEPerNToken < type(uint128).max); // dev: accumulated NOTE overflow
}
}
/// @notice additionalNOTEPerNToken accumulated since last accumulation time in 1e18 precision
function _calculateAdditionalNOTE(
uint256 emissionRatePerYear,
uint256 timeSinceLastAccumulation,
uint256 totalSupply
)
private
pure
returns (uint256)
{
// If we use 18 decimal places as the accumulation precision then we will overflow uint128 when
// a single nToken has accumulated 3.4 x 10^20 NOTE tokens. This isn't possible since the max
// NOTE that can accumulate is 10^16 (100 million NOTE in 1e8 precision) so we should be safe
// using 18 decimal places and uint128 storage slot
// timeSinceLastAccumulation (SECONDS)
// accumulatedNOTEPerSharePrecision (1e18)
// emissionRatePerYear (INTERNAL_TOKEN_PRECISION)
// DIVIDE BY
// YEAR (SECONDS)
// totalSupply (INTERNAL_TOKEN_PRECISION)
return timeSinceLastAccumulation
.mul(Constants.INCENTIVE_ACCUMULATION_PRECISION)
.mul(emissionRatePerYear)
.div(Constants.YEAR)
// totalSupply > 0 is checked in the calling function
.div(totalSupply);
}
/// @notice Updates the nToken token supply amount when minting or redeeming.
/// @param tokenAddress address of the nToken
/// @param netChange positive or negative change to the total nToken supply
/// @param blockTime current block time
/// @return accumulatedNOTEPerNToken updated to the given block time
function changeNTokenSupply(
address tokenAddress,
int256 netChange,
uint256 blockTime
) internal returns (uint256) {
(
uint256 totalSupply,
uint256 accumulatedNOTEPerNToken,
/* uint256 lastAccumulatedTime */
) = getUpdatedAccumulatedNOTEPerNToken(tokenAddress, blockTime);
// Update storage variables
mapping(address => nTokenTotalSupplyStorage) storage store = LibStorage.getNTokenTotalSupplyStorage();
nTokenTotalSupplyStorage storage nTokenStorage = store[tokenAddress];
int256 newTotalSupply = int256(totalSupply).add(netChange);
// We allow newTotalSupply to equal zero here even though it is prevented from being redeemed down to
// exactly zero by other internal logic inside nTokenRedeem. This is meant to be purely an overflow check.
require(0 <= newTotalSupply && uint256(newTotalSupply) < type(uint96).max); // dev: nToken supply overflow
nTokenStorage.totalSupply = uint96(newTotalSupply);
// NOTE: overflow checked inside getUpdatedAccumulatedNOTEPerNToken so that behavior here mirrors what
// the user would see if querying the view function
nTokenStorage.accumulatedNOTEPerNToken = uint128(accumulatedNOTEPerNToken);
require(blockTime < type(uint32).max); // dev: block time overflow
nTokenStorage.lastAccumulatedTime = uint32(blockTime);
return accumulatedNOTEPerNToken;
}
/// @notice Called by governance to set the new emission rate
function setIncentiveEmissionRate(address tokenAddress, uint32 newEmissionsRate, uint256 blockTime) internal {
// Ensure that the accumulatedNOTEPerNToken updates to the current block time before we update the
// emission rate
changeNTokenSupply(tokenAddress, 0, blockTime);
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
context.incentiveAnnualEmissionRate = newEmissionsRate;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../global/LibStorage.sol";
import "../internal/nToken/nTokenHandler.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @notice Deployed library for migration of incentives from the old (inaccurate) calculation
* to a newer, more accurate calculation based on SushiSwap MasterChef math. The more accurate
* calculation is inside `Incentives.sol` and this library holds the legacy calculation. System
* migration code can be found in `MigrateIncentivesFix.sol`
*/
library MigrateIncentives {
using SafeMath for uint256;
/// @notice Calculates the claimable incentives for a particular nToken and account in the
/// previous regime. This should only ever be called ONCE for an account / currency combination
/// to get the incentives accrued up until the migration date.
function migrateAccountFromPreviousCalculation(
address tokenAddress,
uint256 nTokenBalance,
uint256 lastClaimTime,
uint256 lastClaimIntegralSupply
) external view returns (uint256) {
(
uint256 finalEmissionRatePerYear,
uint256 finalTotalIntegralSupply,
uint256 finalMigrationTime
) = _getMigratedIncentiveValues(tokenAddress);
// This if statement should never be true but we return 0 just in case
if (lastClaimTime == 0 || lastClaimTime >= finalMigrationTime) return 0;
// No overflow here, checked above. All incentives are claimed up until finalMigrationTime
// using the finalTotalIntegralSupply. Both these values are set on migration and will not
// change.
uint256 timeSinceMigration = finalMigrationTime - lastClaimTime;
// (timeSinceMigration * INTERNAL_TOKEN_PRECISION * finalEmissionRatePerYear) / YEAR
uint256 incentiveRate =
timeSinceMigration
.mul(uint256(Constants.INTERNAL_TOKEN_PRECISION))
// Migration emission rate is stored as is, denominated in whole tokens
.mul(finalEmissionRatePerYear).mul(uint256(Constants.INTERNAL_TOKEN_PRECISION))
.div(Constants.YEAR);
// Returns the average supply using the integral of the total supply.
uint256 avgTotalSupply = finalTotalIntegralSupply.sub(lastClaimIntegralSupply).div(timeSinceMigration);
if (avgTotalSupply == 0) return 0;
uint256 incentivesToClaim = nTokenBalance.mul(incentiveRate).div(avgTotalSupply);
// incentiveRate has a decimal basis of 1e16 so divide by token precision to reduce to 1e8
incentivesToClaim = incentivesToClaim.div(uint256(Constants.INTERNAL_TOKEN_PRECISION));
return incentivesToClaim;
}
function _getMigratedIncentiveValues(
address tokenAddress
) private view returns (
uint256 finalEmissionRatePerYear,
uint256 finalTotalIntegralSupply,
uint256 finalMigrationTime
) {
mapping(address => nTokenTotalSupplyStorage_deprecated) storage store = LibStorage.getDeprecatedNTokenTotalSupplyStorage();
nTokenTotalSupplyStorage_deprecated storage d_nTokenStorage = store[tokenAddress];
// The total supply value is overridden as emissionRatePerYear during the initialization
finalEmissionRatePerYear = d_nTokenStorage.totalSupply;
finalTotalIntegralSupply = d_nTokenStorage.integralTotalSupply;
finalMigrationTime = d_nTokenStorage.lastSupplyChangeTime;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
/// @title Hardcoded deployed contracts are listed here. These are hardcoded to reduce
/// gas costs for immutable addresses. They must be updated per environment that Notional
/// is deployed to.
library Deployments {
address internal constant NOTE_TOKEN_ADDRESS = 0xCFEAead4947f0705A14ec42aC3D44129E1Ef3eD5;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../../global/Types.sol";
import "../../../global/LibStorage.sol";
import "../../../math/SafeInt256.sol";
import "../TokenHandler.sol";
import "../../../../interfaces/aave/IAToken.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library AaveHandler {
using SafeMath for uint256;
using SafeInt256 for int256;
int256 internal constant RAY = 1e27;
int256 internal constant halfRAY = RAY / 2;
bytes4 internal constant scaledBalanceOfSelector = IAToken.scaledBalanceOf.selector;
/**
* @notice Mints an amount of aTokens corresponding to the the underlying.
* @param underlyingToken address of the underlying token to pass to Aave
* @param underlyingAmountExternal amount of underlying to deposit, in external precision
*/
function mint(Token memory underlyingToken, uint256 underlyingAmountExternal) internal {
// In AaveV3 this method is renamed to supply() but deposit() is still available for
// backwards compatibility: https://github.com/aave/aave-v3-core/blob/master/contracts/protocol/pool/Pool.sol#L755
// We use deposit here so that mainnet-fork tests against Aave v2 will pass.
LibStorage.getLendingPool().lendingPool.deposit(
underlyingToken.tokenAddress,
underlyingAmountExternal,
address(this),
0
);
}
/**
* @notice Redeems and sends an amount of aTokens to the specified account
* @param underlyingToken address of the underlying token to pass to Aave
* @param account account to receive the underlying
* @param assetAmountExternal amount of aTokens in scaledBalanceOf terms
*/
function redeem(
Token memory underlyingToken,
address account,
uint256 assetAmountExternal
) internal returns (uint256 underlyingAmountExternal) {
underlyingAmountExternal = convertFromScaledBalanceExternal(
underlyingToken.tokenAddress,
SafeInt256.toInt(assetAmountExternal)
).toUint();
LibStorage.getLendingPool().lendingPool.withdraw(
underlyingToken.tokenAddress,
underlyingAmountExternal,
account
);
}
/**
* @notice Takes an assetAmountExternal (in this case is the Aave balanceOf representing principal plus interest)
* and returns another assetAmountExternal value which represents the Aave scaledBalanceOf (representing a proportional
* claim on Aave principal plus interest onto the future). This conversion ensures that depositors into Notional will
* receive future Aave interest.
* @dev There is no loss of precision within this function since it does the exact same calculation as Aave.
* @param currencyId is the currency id
* @param assetAmountExternal an Aave token amount representing principal plus interest supplied by the user. This must
* be positive in this function, this method is only called when depositing aTokens directly
* @return scaledAssetAmountExternal the Aave scaledBalanceOf equivalent. The decimal precision of this value will
* be in external precision.
*/
function convertToScaledBalanceExternal(uint256 currencyId, int256 assetAmountExternal) internal view returns (int256) {
if (assetAmountExternal == 0) return 0;
require(assetAmountExternal > 0);
Token memory underlyingToken = TokenHandler.getUnderlyingToken(currencyId);
// We know that this value must be positive
int256 index = _getReserveNormalizedIncome(underlyingToken.tokenAddress);
// Mimic the WadRay math performed by Aave (but do it in int256 instead)
int256 halfIndex = index / 2;
// Overflow will occur when: (a * RAY + halfIndex) > int256.max
require(assetAmountExternal <= (type(int256).max - halfIndex) / RAY);
// if index is zero then this will revert
return (assetAmountExternal * RAY + halfIndex) / index;
}
/**
* @notice Takes an assetAmountExternal (in this case is the internal scaledBalanceOf in external decimal precision)
* and returns another assetAmountExternal value which represents the Aave balanceOf representing the principal plus interest
* that will be transferred. This is required to maintain compatibility with Aave's ERC20 transfer functions.
* @dev There is no loss of precision because this does exactly what Aave's calculation would do
* @param underlyingToken token address of the underlying asset
* @param netScaledBalanceExternal an amount representing the scaledBalanceOf in external decimal precision calculated from
* Notional cash balances. This amount may be positive or negative depending on if assets are being deposited (positive) or
* withdrawn (negative).
* @return netBalanceExternal the Aave balanceOf equivalent as a signed integer
*/
function convertFromScaledBalanceExternal(address underlyingToken, int256 netScaledBalanceExternal) internal view returns (int256 netBalanceExternal) {
if (netScaledBalanceExternal == 0) return 0;
// We know that this value must be positive
int256 index = _getReserveNormalizedIncome(underlyingToken);
// Use the absolute value here so that the halfRay rounding is applied correctly for negative values
int256 abs = netScaledBalanceExternal.abs();
// Mimic the WadRay math performed by Aave (but do it in int256 instead)
// Overflow will occur when: (abs * index + halfRay) > int256.max
// Here the first term is computed at compile time so it just does a division. If index is zero then
// solidity will revert.
require(abs <= (type(int256).max - halfRAY) / index);
int256 absScaled = (abs * index + halfRAY) / RAY;
return netScaledBalanceExternal > 0 ? absScaled : absScaled.neg();
}
/// @dev getReserveNormalizedIncome returns a uint256, so we know that the return value here is
/// always positive even though we are converting to a signed int
function _getReserveNormalizedIncome(address underlyingAsset) private view returns (int256) {
return
SafeInt256.toInt(
LibStorage.getLendingPool().lendingPool.getReserveNormalizedIncome(underlyingAsset)
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./GenericToken.sol";
import "../../../../interfaces/compound/CErc20Interface.sol";
import "../../../../interfaces/compound/CEtherInterface.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../global/Types.sol";
library CompoundHandler {
using SafeMath for uint256;
// Return code for cTokens that represents no error
uint256 internal constant COMPOUND_RETURN_CODE_NO_ERROR = 0;
function mintCETH(Token memory token) internal {
// Reverts on error
CEtherInterface(token.tokenAddress).mint{value: msg.value}();
}
function mint(Token memory token, uint256 underlyingAmountExternal) internal returns (int256) {
uint256 success = CErc20Interface(token.tokenAddress).mint(underlyingAmountExternal);
require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Mint");
}
function redeemCETH(
Token memory assetToken,
address account,
uint256 assetAmountExternal
) internal returns (uint256 underlyingAmountExternal) {
// Although the contract should never end with any ETH or underlying token balances, we still do this
// starting and ending check in the case that tokens are accidentally sent to the contract address. They
// will not be sent to some lucky address in a windfall.
uint256 startingBalance = address(this).balance;
uint256 success = CErc20Interface(assetToken.tokenAddress).redeem(assetAmountExternal);
require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Redeem");
uint256 endingBalance = address(this).balance;
underlyingAmountExternal = endingBalance.sub(startingBalance);
// Withdraws the underlying amount out to the destination account
GenericToken.transferNativeTokenOut(account, underlyingAmountExternal);
}
function redeem(
Token memory assetToken,
Token memory underlyingToken,
address account,
uint256 assetAmountExternal
) internal returns (uint256 underlyingAmountExternal) {
// Although the contract should never end with any ETH or underlying token balances, we still do this
// starting and ending check in the case that tokens are accidentally sent to the contract address. They
// will not be sent to some lucky address in a windfall.
uint256 startingBalance = GenericToken.checkBalanceViaSelector(underlyingToken.tokenAddress, address(this), GenericToken.defaultBalanceOfSelector);
uint256 success = CErc20Interface(assetToken.tokenAddress).redeem(assetAmountExternal);
require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Redeem");
uint256 endingBalance = GenericToken.checkBalanceViaSelector(underlyingToken.tokenAddress, address(this), GenericToken.defaultBalanceOfSelector);
underlyingAmountExternal = endingBalance.sub(startingBalance);
// Withdraws the underlying amount out to the destination account
GenericToken.safeTransferOut(underlyingToken.tokenAddress, account, underlyingAmountExternal);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
import "../../../../interfaces/IEIP20NonStandard.sol";
library GenericToken {
bytes4 internal constant defaultBalanceOfSelector = IEIP20NonStandard.balanceOf.selector;
/**
* @dev Manually checks the balance of an account using the method selector. Reduces bytecode size and allows
* for overriding the balanceOf selector to use scaledBalanceOf for aTokens
*/
function checkBalanceViaSelector(
address token,
address account,
bytes4 balanceOfSelector
) internal returns (uint256 balance) {
(bool success, bytes memory returnData) = token.staticcall(abi.encodeWithSelector(balanceOfSelector, account));
require(success);
(balance) = abi.decode(returnData, (uint256));
}
function transferNativeTokenOut(
address account,
uint256 amount
) internal {
// This does not work with contracts, but is reentrancy safe. If contracts want to withdraw underlying
// ETH they will have to withdraw the cETH token and then redeem it manually.
payable(account).transfer(amount);
}
function safeTransferOut(
address token,
address account,
uint256 amount
) internal {
IEIP20NonStandard(token).transfer(account, amount);
checkReturnCode();
}
function safeTransferIn(
address token,
address account,
uint256 amount
) internal {
IEIP20NonStandard(token).transferFrom(account, address(this), amount);
checkReturnCode();
}
function checkReturnCode() internal pure {
bool success;
uint256[1] memory result;
assembly {
switch returndatasize()
case 0 {
// This is a non-standard ERC-20
success := 1 // set success to true
}
case 32 {
// This is a compliant ERC-20
returndatacopy(result, 0, 32)
success := mload(result) // Set `success = returndata` of external call
}
default {
// This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "ERC20");
}
}
// 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: GPL-3.0-only
pragma solidity ^0.7.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IAToken {
/**
* @dev Returns the scaled balance of the user. The scaled balance is the sum of all the
* updated stored balance divided by the reserve's liquidity index at the moment of the update
* @param user The user whose balance is calculated
* @return The scaled balance of the user
**/
function scaledBalanceOf(address user) external view returns (uint256);
function UNDERLYING_ASSET_ADDRESS() external view returns (address);
function symbol() external view returns (string memory);
}
interface IScaledBalanceToken {
/**
* @dev Returns the scaled balance of the user. The scaled balance is the sum of all the
* updated stored balance divided by the reserve's liquidity index at the moment of the update
* @param user The user whose balance is calculated
* @return The scaled balance of the user
**/
function scaledBalanceOf(address user) external view returns (uint256);
/**
* @dev Returns the scaled balance of the user and the scaled total supply.
* @param user The address of the user
* @return The scaled balance of the user
* @return The scaled balance and the scaled total supply
**/
function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256);
/**
* @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index)
* @return The scaled total supply
**/
function scaledTotalSupply() external view returns (uint256);
}
interface IATokenFull is IScaledBalanceToken, IERC20 {
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.7.0;
import "./CTokenInterface.sol";
interface CErc20Interface {
/*** User Interface ***/
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, CTokenInterface cTokenCollateral) external returns (uint);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.7.0;
interface CEtherInterface {
function mint() external payable;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface IEIP20NonStandard {
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transferFrom(address src, address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `approve` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved
*/
function approve(address spender, uint256 amount) external;
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return remaining The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.7.0;
interface CTokenInterface {
/*** User Interface ***/
function underlying() external view returns (address);
function transfer(address dst, uint amount) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function borrowBalanceStored(address account) external view returns (uint);
function exchangeRateCurrent() external returns (uint);
function exchangeRateStored() external view returns (uint);
function getCash() external view returns (uint);
function accrueInterest() external returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../global/Types.sol";
import "../global/Constants.sol";
/// @notice Helper methods for bitmaps, they are big-endian and 1-indexed.
library Bitmap {
/// @notice Set a bit on or off in a bitmap, index is 1-indexed
function setBit(
bytes32 bitmap,
uint256 index,
bool setOn
) internal pure returns (bytes32) {
require(index >= 1 && index <= 256); // dev: set bit index bounds
if (setOn) {
return bitmap | (Constants.MSB >> (index - 1));
} else {
return bitmap & ~(Constants.MSB >> (index - 1));
}
}
/// @notice Check if a bit is set
function isBitSet(bytes32 bitmap, uint256 index) internal pure returns (bool) {
require(index >= 1 && index <= 256); // dev: set bit index bounds
return ((bitmap << (index - 1)) & Constants.MSB) == Constants.MSB;
}
/// @notice Count the total bits set
function totalBitsSet(bytes32 bitmap) internal pure returns (uint256) {
uint256 x = uint256(bitmap);
x = (x & 0x5555555555555555555555555555555555555555555555555555555555555555) + (x >> 1 & 0x5555555555555555555555555555555555555555555555555555555555555555);
x = (x & 0x3333333333333333333333333333333333333333333333333333333333333333) + (x >> 2 & 0x3333333333333333333333333333333333333333333333333333333333333333);
x = (x & 0x0707070707070707070707070707070707070707070707070707070707070707) + (x >> 4);
x = (x & 0x000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F) + (x >> 8 & 0x000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F);
x = x + (x >> 16);
x = x + (x >> 32);
x = x + (x >> 64);
return (x & 0xFF) + (x >> 128 & 0xFF);
}
// Does a binary search over x to get the position of the most significant bit
function getMSB(uint256 x) internal pure returns (uint256 msb) {
// If x == 0 then there is no MSB and this method will return zero. That would
// be the same as the return value when x == 1 (MSB is zero indexed), so instead
// we have this require here to ensure that the values don't get mixed up.
require(x != 0); // dev: get msb zero value
if (x >= 0x100000000000000000000000000000000) {
x >>= 128;
msb += 128;
}
if (x >= 0x10000000000000000) {
x >>= 64;
msb += 64;
}
if (x >= 0x100000000) {
x >>= 32;
msb += 32;
}
if (x >= 0x10000) {
x >>= 16;
msb += 16;
}
if (x >= 0x100) {
x >>= 8;
msb += 8;
}
if (x >= 0x10) {
x >>= 4;
msb += 4;
}
if (x >= 0x4) {
x >>= 2;
msb += 2;
}
if (x >= 0x2) msb += 1; // No need to shift xc anymore
}
/// @dev getMSB returns a zero indexed bit number where zero is the first bit counting
/// from the right (little endian). Asset Bitmaps are counted from the left (big endian)
/// and one indexed.
function getNextBitNum(bytes32 bitmap) internal pure returns (uint256 bitNum) {
// Short circuit the search if bitmap is all zeros
if (bitmap == 0x00) return 0;
return 255 - getMSB(uint256(bitmap)) + 1;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../balances/TokenHandler.sol";
import "../../math/SafeInt256.sol";
import "../../../interfaces/chainlink/AggregatorV2V3Interface.sol";
library ExchangeRate {
using SafeInt256 for int256;
/// @notice Converts a balance to ETH from a base currency. Buffers or haircuts are
/// always applied in this method.
/// @param er exchange rate object from base to ETH
/// @return the converted balance denominated in ETH with Constants.INTERNAL_TOKEN_PRECISION
function convertToETH(ETHRate memory er, int256 balance) internal pure returns (int256) {
int256 multiplier = balance > 0 ? er.haircut : er.buffer;
// We are converting internal balances here so we know they have INTERNAL_TOKEN_PRECISION decimals
// internalDecimals * rateDecimals * multiplier / (rateDecimals * multiplierDecimals)
// Therefore the result is in ethDecimals
int256 result =
balance.mul(er.rate).mul(multiplier).div(Constants.PERCENTAGE_DECIMALS).div(
er.rateDecimals
);
return result;
}
/// @notice Converts the balance denominated in ETH to the equivalent value in a base currency.
/// Buffers and haircuts ARE NOT applied in this method.
/// @param er exchange rate object from base to ETH
/// @param balance amount (denominated in ETH) to convert
function convertETHTo(ETHRate memory er, int256 balance) internal pure returns (int256) {
// We are converting internal balances here so we know they have INTERNAL_TOKEN_PRECISION decimals
// internalDecimals * rateDecimals / rateDecimals
int256 result = balance.mul(er.rateDecimals).div(er.rate);
return result;
}
/// @notice Calculates the exchange rate between two currencies via ETH. Returns the rate denominated in
/// base exchange rate decimals: (baseRateDecimals * quoteRateDecimals) / quoteRateDecimals
/// @param baseER base exchange rate struct
/// @param quoteER quote exchange rate struct
function exchangeRate(ETHRate memory baseER, ETHRate memory quoteER)
internal
pure
returns (int256)
{
return baseER.rate.mul(quoteER.rateDecimals).div(quoteER.rate);
}
/// @notice Returns an ETHRate object used to calculate free collateral
function buildExchangeRate(uint256 currencyId) internal view returns (ETHRate memory) {
mapping(uint256 => ETHRateStorage) storage store = LibStorage.getExchangeRateStorage();
ETHRateStorage storage ethStorage = store[currencyId];
int256 rateDecimals;
int256 rate;
if (currencyId == Constants.ETH_CURRENCY_ID) {
// ETH rates will just be 1e18, but will still have buffers, haircuts,
// and liquidation discounts
rateDecimals = Constants.ETH_DECIMALS;
rate = Constants.ETH_DECIMALS;
} else {
// prettier-ignore
(
/* roundId */,
rate,
/* uint256 startedAt */,
/* updatedAt */,
/* answeredInRound */
) = ethStorage.rateOracle.latestRoundData();
require(rate > 0, "Invalid rate");
// No overflow, restricted on storage
rateDecimals = int256(10**ethStorage.rateDecimalPlaces);
if (ethStorage.mustInvert) {
rate = rateDecimals.mul(rateDecimals).div(rate);
}
}
return
ETHRate({
rateDecimals: rateDecimals,
rate: rate,
buffer: ethStorage.buffer,
haircut: ethStorage.haircut,
liquidationDiscount: ethStorage.liquidationDiscount
});
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./nTokenHandler.sol";
import "../portfolio/BitmapAssetsHandler.sol";
import "../../math/SafeInt256.sol";
import "../../math/Bitmap.sol";
library nTokenCalculations {
using Bitmap for bytes32;
using SafeInt256 for int256;
using AssetRate for AssetRateParameters;
using CashGroup for CashGroupParameters;
/// @notice Returns the nToken present value denominated in asset terms.
function getNTokenAssetPV(nTokenPortfolio memory nToken, uint256 blockTime)
internal
view
returns (int256)
{
int256 totalAssetPV;
int256 totalUnderlyingPV;
{
uint256 nextSettleTime = nTokenHandler.getNextSettleTime(nToken);
// If the first asset maturity has passed (the 3 month), this means that all the LTs must
// be settled except the 6 month (which is now the 3 month). We don't settle LTs except in
// initialize markets so we calculate the cash value of the portfolio here.
if (nextSettleTime <= blockTime) {
// NOTE: this condition should only be present for a very short amount of time, which is the window between
// when the markets are no longer tradable at quarter end and when the new markets have been initialized.
// We time travel back to one second before maturity to value the liquidity tokens. Although this value is
// not strictly correct the different should be quite slight. We do this to ensure that free collateral checks
// for withdraws and liquidations can still be processed. If this condition persists for a long period of time then
// the entire protocol will have serious problems as markets will not be tradable.
blockTime = nextSettleTime - 1;
}
}
// This is the total value in liquid assets
(int256 totalAssetValueInMarkets, /* int256[] memory netfCash */) = getNTokenMarketValue(nToken, blockTime);
// Then get the total value in any idiosyncratic fCash residuals (if they exist)
bytes32 ifCashBits = getNTokenifCashBits(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.lastInitializedTime,
blockTime,
nToken.cashGroup.maxMarketIndex
);
int256 ifCashResidualUnderlyingPV = 0;
if (ifCashBits != 0) {
// Non idiosyncratic residuals have already been accounted for
(ifCashResidualUnderlyingPV, /* hasDebt */) = BitmapAssetsHandler.getNetPresentValueFromBitmap(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.lastInitializedTime,
blockTime,
nToken.cashGroup,
false, // nToken present value calculation does not use risk adjusted values
ifCashBits
);
}
// Return the total present value denominated in asset terms
return totalAssetValueInMarkets
.add(nToken.cashGroup.assetRate.convertFromUnderlying(ifCashResidualUnderlyingPV))
.add(nToken.cashBalance);
}
/**
* @notice Handles the case when liquidity tokens should be withdrawn in proportion to their amounts
* in the market. This will be the case when there is no idiosyncratic fCash residuals in the nToken
* portfolio.
* @param nToken portfolio object for nToken
* @param nTokensToRedeem amount of nTokens to redeem
* @param tokensToWithdraw array of liquidity tokens to withdraw from each market, proportional to
* the account's share of the total supply
* @param netfCash an empty array to hold net fCash values calculated later when the tokens are actually
* withdrawn from markets
*/
function _getProportionalLiquidityTokens(
nTokenPortfolio memory nToken,
int256 nTokensToRedeem
) private pure returns (int256[] memory tokensToWithdraw, int256[] memory netfCash) {
uint256 numMarkets = nToken.portfolioState.storedAssets.length;
tokensToWithdraw = new int256[](numMarkets);
netfCash = new int256[](numMarkets);
for (uint256 i = 0; i < numMarkets; i++) {
int256 totalTokens = nToken.portfolioState.storedAssets[i].notional;
tokensToWithdraw[i] = totalTokens.mul(nTokensToRedeem).div(nToken.totalSupply);
}
}
/**
* @notice Returns the number of liquidity tokens to withdraw from each market if the nToken
* has idiosyncratic residuals during nToken redeem. In this case the redeemer will take
* their cash from the rest of the fCash markets, redeeming around the nToken.
* @param nToken portfolio object for nToken
* @param nTokensToRedeem amount of nTokens to redeem
* @param blockTime block time
* @param ifCashBits the bits in the bitmap that represent ifCash assets
* @return tokensToWithdraw array of tokens to withdraw from each corresponding market
* @return netfCash array of netfCash amounts to go back to the account
*/
function getLiquidityTokenWithdraw(
nTokenPortfolio memory nToken,
int256 nTokensToRedeem,
uint256 blockTime,
bytes32 ifCashBits
) internal view returns (int256[] memory, int256[] memory) {
// If there are no ifCash bits set then this will just return the proportion of all liquidity tokens
if (ifCashBits == 0) return _getProportionalLiquidityTokens(nToken, nTokensToRedeem);
(
int256 totalAssetValueInMarkets,
int256[] memory netfCash
) = getNTokenMarketValue(nToken, blockTime);
int256[] memory tokensToWithdraw = new int256[](netfCash.length);
// NOTE: this total portfolio asset value does not include any cash balance the nToken may hold.
// The redeemer will always get a proportional share of this cash balance and therefore we don't
// need to account for it here when we calculate the share of liquidity tokens to withdraw. We are
// only concerned with the nToken's portfolio assets in this method.
int256 totalPortfolioAssetValue;
{
// Returns the risk adjusted net present value for the idiosyncratic residuals
(int256 underlyingPV, /* hasDebt */) = BitmapAssetsHandler.getNetPresentValueFromBitmap(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.lastInitializedTime,
blockTime,
nToken.cashGroup,
true, // use risk adjusted here to assess a penalty for withdrawing around the residual
ifCashBits
);
// NOTE: we do not include cash balance here because the account will always take their share
// of the cash balance regardless of the residuals
totalPortfolioAssetValue = totalAssetValueInMarkets.add(
nToken.cashGroup.assetRate.convertFromUnderlying(underlyingPV)
);
}
// Loops through each liquidity token and calculates how much the redeemer can withdraw to get
// the requisite amount of present value after adjusting for the ifCash residual value that is
// not accessible via redemption.
for (uint256 i = 0; i < tokensToWithdraw.length; i++) {
int256 totalTokens = nToken.portfolioState.storedAssets[i].notional;
// Redeemer's baseline share of the liquidity tokens based on total supply:
// redeemerShare = totalTokens * nTokensToRedeem / totalSupply
// Scalar factor to account for residual value (need to inflate the tokens to withdraw
// proportional to the value locked up in ifCash residuals):
// scaleFactor = totalPortfolioAssetValue / totalAssetValueInMarkets
// Final math equals:
// tokensToWithdraw = redeemerShare * scalarFactor
// tokensToWithdraw = (totalTokens * nTokensToRedeem * totalPortfolioAssetValue)
// / (totalAssetValueInMarkets * totalSupply)
tokensToWithdraw[i] = totalTokens
.mul(nTokensToRedeem)
.mul(totalPortfolioAssetValue);
tokensToWithdraw[i] = tokensToWithdraw[i]
.div(totalAssetValueInMarkets)
.div(nToken.totalSupply);
// This is the share of net fcash that will be credited back to the account
netfCash[i] = netfCash[i].mul(tokensToWithdraw[i]).div(totalTokens);
}
return (tokensToWithdraw, netfCash);
}
/// @notice Returns the value of all the liquid assets in an nToken portfolio which are defined by
/// the liquidity tokens held in each market and their corresponding fCash positions. The formula
/// can be described as:
/// totalAssetValue = sum_per_liquidity_token(cashClaim + presentValue(netfCash))
/// where netfCash = fCashClaim + fCash
/// and fCash refers the the fCash position at the corresponding maturity
function getNTokenMarketValue(nTokenPortfolio memory nToken, uint256 blockTime)
internal
view
returns (int256 totalAssetValue, int256[] memory netfCash)
{
uint256 numMarkets = nToken.portfolioState.storedAssets.length;
netfCash = new int256[](numMarkets);
MarketParameters memory market;
for (uint256 i = 0; i < numMarkets; i++) {
// Load the corresponding market into memory
nToken.cashGroup.loadMarket(market, i + 1, true, blockTime);
PortfolioAsset memory liquidityToken = nToken.portfolioState.storedAssets[i];
uint256 maturity = liquidityToken.maturity;
// Get the fCash claims and fCash assets. We do not use haircut versions here because
// nTokenRedeem does not require it and getNTokenPV does not use it (a haircut is applied
// at the end of the calculation to the entire PV instead).
(int256 assetCashClaim, int256 fCashClaim) = AssetHandler.getCashClaims(liquidityToken, market);
// fCash is denominated in underlying
netfCash[i] = fCashClaim.add(
BitmapAssetsHandler.getifCashNotional(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
maturity
)
);
// This calculates for a single liquidity token:
// assetCashClaim + convertToAssetCash(pv(netfCash))
int256 netAssetValueInMarket = assetCashClaim.add(
nToken.cashGroup.assetRate.convertFromUnderlying(
AssetHandler.getPresentfCashValue(
netfCash[i],
maturity,
blockTime,
// No need to call cash group for oracle rate, it is up to date here
// and we are assured to be referring to this market.
market.oracleRate
)
)
);
// Calculate the running total
totalAssetValue = totalAssetValue.add(netAssetValueInMarket);
}
}
/// @notice Returns just the bits in a bitmap that are idiosyncratic
function getNTokenifCashBits(
address tokenAddress,
uint256 currencyId,
uint256 lastInitializedTime,
uint256 blockTime,
uint256 maxMarketIndex
) internal view returns (bytes32) {
// If max market index is less than or equal to 2, there are never ifCash assets by construction
if (maxMarketIndex <= 2) return bytes32(0);
bytes32 assetsBitmap = BitmapAssetsHandler.getAssetsBitmap(tokenAddress, currencyId);
// Handles the case when there are no assets at the first initialization
if (assetsBitmap == 0) return assetsBitmap;
uint256 tRef = DateTime.getReferenceTime(blockTime);
if (tRef == lastInitializedTime) {
// This is a more efficient way to turn off ifCash assets in the common case when the market is
// initialized immediately
return assetsBitmap & ~(Constants.ACTIVE_MARKETS_MASK);
} else {
// In this branch, initialize markets has occurred past the time above. It would occur in these
// two scenarios (both should be exceedingly rare):
// 1. initializing a cash group with 3+ markets for the first time (not beginning on the tRef)
// 2. somehow initialize markets has been delayed for more than 24 hours
for (uint i = 1; i <= maxMarketIndex; i++) {
// In this loop we get the maturity of each active market and turn off the corresponding bit
// one by one. It is less efficient than the option above.
uint256 maturity = tRef + DateTime.getTradedMarket(i);
(uint256 bitNum, /* */) = DateTime.getBitNumFromMaturity(lastInitializedTime, maturity);
assetsBitmap = assetsBitmap.setBit(bitNum, false);
}
return assetsBitmap;
}
}
} | dev: storage lastImpliedRate overflow
| require(0 < lastImpliedRate && lastImpliedRate <= type(uint32).max); | 12,218 | [
1,
5206,
30,
2502,
1142,
2828,
2092,
4727,
9391,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2583,
12,
20,
411,
1142,
2828,
2092,
4727,
597,
1142,
2828,
2092,
4727,
1648,
618,
12,
11890,
1578,
2934,
1896,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xefaCa6Fc316B3B2Aa6c55FF5E02a62A85d4391e8/sources/contracts/storage/Vault.sol | * @dev Returns the vault's combined debt (consolidated and unconsolidated), for the current epoch./ | function currentDebt(Data storage self) internal view returns (int256) {
return currentEpoch(self).totalDebt();
}
| 16,517,285 | [
1,
1356,
326,
9229,
1807,
8224,
18202,
88,
261,
8559,
7953,
690,
471,
6301,
7008,
7953,
690,
3631,
364,
326,
783,
7632,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
783,
758,
23602,
12,
751,
2502,
365,
13,
2713,
1476,
1135,
261,
474,
5034,
13,
288,
203,
3639,
327,
783,
14638,
12,
2890,
2934,
4963,
758,
23602,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-08-30
*/
pragma solidity ^0.4.23;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization
control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the
sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to 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;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than
minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns
(bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
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 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) {
require((_value == 0 ) || (allowed[msg.sender][_spender] == 0));
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;
}
}
contract ATG is StandardToken{
string public constant name = "ATG Token"; // solium-disable-line uppercase
string public constant symbol = "ATG"; // solium-disable-line uppercase
uint8 public constant decimals = 6; // solium-disable-line uppercase
uint256 public constant INITIAL_SUPPLY = 1000000000000000;
uint256 public constant MAX_SUPPLY = 100 * 10000 * 10000 * (10 **
uint256(decimals));
/**
* @dev Constructor that gives msg.sender all of existing tokens.
*/
constructor() ATG() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
emit Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
/**
* The fallback function.
*/
function() payable public {
revert();
}
} | solium-disable-line uppercase
| string public constant name = "ATG Token"; | 7,717,865 | [
1,
18281,
5077,
17,
8394,
17,
1369,
18966,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1080,
1071,
5381,
508,
273,
315,
789,
43,
3155,
14432,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/137/0x7d561bE86eBCB1d8353f98c21Bef7232343598a8/sources/WebaverseERC721.sol | * @dev Get the address for for the minter of the token @param tokenId ID of the token we are querying @return Address of the minter/ | function getMinter(uint256 tokenId) public view returns (address) {
return minters[tokenId];
}
| 4,669,329 | [
1,
967,
326,
1758,
364,
364,
326,
1131,
387,
434,
326,
1147,
225,
1147,
548,
1599,
434,
326,
1147,
732,
854,
23936,
327,
5267,
434,
326,
1131,
387,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2108,
2761,
12,
11890,
5034,
1147,
548,
13,
1071,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
327,
1131,
5432,
63,
2316,
548,
15533,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0x326BfE5CAC27e68631E64f58FD43cB5Bef9c7a2b/sources/@thirdweb-dev/contracts/base/Staking721Base.sol | @dev ERC20 Reward Token address. See {_mintRewards} below. @dev The address of the native token wrapper contract. @dev Total amount of reward tokens in the contract. | ) Staking721(_stakingToken) {
_setupOwner(_defaultAdmin);
_setStakingCondition(_timeUnit, _rewardsPerUnitTime);
rewardToken = _rewardToken;
nativeTokenWrapper = _nativeTokenWrapper;
}
| 5,564,988 | [
1,
654,
39,
3462,
534,
359,
1060,
3155,
1758,
18,
2164,
288,
67,
81,
474,
17631,
14727,
97,
5712,
18,
225,
1021,
1758,
434,
326,
6448,
1147,
4053,
6835,
18,
225,
10710,
3844,
434,
19890,
2430,
316,
326,
6835,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
262,
934,
6159,
27,
5340,
24899,
334,
6159,
1345,
13,
288,
203,
3639,
389,
8401,
5541,
24899,
1886,
4446,
1769,
203,
3639,
389,
542,
510,
6159,
3418,
24899,
957,
2802,
16,
389,
266,
6397,
2173,
2802,
950,
1769,
203,
203,
3639,
19890,
1345,
273,
389,
266,
2913,
1345,
31,
203,
3639,
6448,
1345,
3611,
273,
389,
13635,
1345,
3611,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/11155111/0xfe8B57856f174428B4ff1CdC39d1EA9929697A65/sources/contracts/Ticketing.sol | Define structure of a ticket | contract TicketingSystemNew is ERC721Enumerable, Ownable {
struct Ticket {
}
struct OwnerInfo {
uint256[] ticketIds;
uint256 totalTickets;
}
mapping(uint256 => Ticket) public tickets;
mapping(address => OwnerInfo) public ownerInfo;
uint256[] public usedTicketIds;
using Strings for uint256;
string public baseURI = "";
string public baseExtension = ".json";
uint256 public maxSupply = 1000000000000;
uint256 public maxMintAmount = 1;
bool public paused = false;
uint256 public ticketId;
event TicketCreated(
string ticketType,
uint256 validUntil,
address owner,
uint256 amount,
uint256 _ticketId,
uint256 timestamp,
string ipfsAddress
);
event TicketUsed(uint256 _ticketId, address user);
event ConfirmedTicketUse(uint256 _ticketId, address user);
event ContractPaused(address account);
event ContractUnpaused(address account);
constructor() ERC721("TicketingSystem", "E-TICKET") {}
function mint(string memory _ticketType, uint256 _validUntil) public payable {
require(block.timestamp <= _validUntil, "Invalid ticket validity");
require(paused == false, "You Cannot Purchase Tickets Now. System is Temporarily Unavailable");
require(ticketId < maxSupply, "Maximum number of tickets already minted");
Ticket storage newTicket = tickets[ticketId];
OwnerInfo storage ownerData = ownerInfo[msg.sender];
newTicket.ticketType = _ticketType;
newTicket.validUntil = _validUntil;
newTicket.owner = msg.sender;
newTicket.amount = msg.value;
newTicket.timestamp = block.timestamp;
newTicket.ipfsAddress = baseURI;
ownerData.ticketIds.push(ticketId);
ownerData.totalTickets += 1;
_safeMint(msg.sender, ticketId);
bool mintSuccessful = (owner() == msg.sender);
if (mintSuccessful) {
emit TicketCreated(
_ticketType,
_validUntil,
msg.sender,
msg.value,
ticketId,
block.timestamp,
newTicket.ipfsAddress
);
ticketId++;
revert("Ticket creation failed. Please try again.");
}
}
function mint(string memory _ticketType, uint256 _validUntil) public payable {
require(block.timestamp <= _validUntil, "Invalid ticket validity");
require(paused == false, "You Cannot Purchase Tickets Now. System is Temporarily Unavailable");
require(ticketId < maxSupply, "Maximum number of tickets already minted");
Ticket storage newTicket = tickets[ticketId];
OwnerInfo storage ownerData = ownerInfo[msg.sender];
newTicket.ticketType = _ticketType;
newTicket.validUntil = _validUntil;
newTicket.owner = msg.sender;
newTicket.amount = msg.value;
newTicket.timestamp = block.timestamp;
newTicket.ipfsAddress = baseURI;
ownerData.ticketIds.push(ticketId);
ownerData.totalTickets += 1;
_safeMint(msg.sender, ticketId);
bool mintSuccessful = (owner() == msg.sender);
if (mintSuccessful) {
emit TicketCreated(
_ticketType,
_validUntil,
msg.sender,
msg.value,
ticketId,
block.timestamp,
newTicket.ipfsAddress
);
ticketId++;
revert("Ticket creation failed. Please try again.");
}
}
} else {
and can only be called by the owner of the ticket
function confirmTicketUse(uint256 _ticketId) external {
require(msg.sender == tickets[_ticketId].owner, "Not ticket owner");
tickets[_ticketId].confirmTicketUse = true;
emit ConfirmedTicketUse(_ticketId, msg.sender);
}
function useTicket(uint256 _ticketId) external onlyOwner {
require(tickets[_ticketId].confirmTicketUse, "Ticket use not confirmed by owner");
require(!tickets[_ticketId].used, "Ticket has already been used");
require(block.timestamp <= tickets[_ticketId].validUntil, "Ticket validity has expired");
tickets[_ticketId].used = true;
usedTicketIds.push(_ticketId);
emit TicketUsed(_ticketId, msg.sender);
}
function getUsedTickets() external view onlyOwner returns (uint256[] memory) {
return usedTicketIds;
}
function pause() external onlyOwner {
paused = true;
}
function unpause() external onlyOwner {
paused = false;
}
function getBalance() public view returns (uint256) {
return address(this).balance;
}
function withdraw() external onlyOwner {
uint256 balance = address(this).balance;
require(balance > 0, "Contract balance is zero");
payable(msg.sender).transfer(balance);
}
function getTicket(uint256 _ticketId)
external
view
returns (
string memory,
uint256,
uint256,
address,
uint256,
uint256,
string memory,
bool,
bool
)
{
Ticket storage ticket = tickets[_ticketId];
return (
ticket.ticketType,
ticket.validUntil,
ticket.amount,
ticket.owner,
ticket.timestamp,
_ticketId,
ticket.ipfsAddress,
ticket.used,
ticket.confirmTicketUse
);
}
function getValidTicketCount(address _user) external view returns (uint256) {
uint256 validCount = 0;
OwnerInfo storage ownerData = ownerInfo[_user];
for (uint256 i = 0; i < ownerData.ticketIds.length; i++) {
uint256 ValidticketId = ownerData.ticketIds[i];
if (tickets[ValidticketId].validUntil >= block.timestamp && !tickets[ValidticketId].used) {
validCount++;
}
}
return validCount;
}
function getValidTicketCount(address _user) external view returns (uint256) {
uint256 validCount = 0;
OwnerInfo storage ownerData = ownerInfo[_user];
for (uint256 i = 0; i < ownerData.ticketIds.length; i++) {
uint256 ValidticketId = ownerData.ticketIds[i];
if (tickets[ValidticketId].validUntil >= block.timestamp && !tickets[ValidticketId].used) {
validCount++;
}
}
return validCount;
}
function getValidTicketCount(address _user) external view returns (uint256) {
uint256 validCount = 0;
OwnerInfo storage ownerData = ownerInfo[_user];
for (uint256 i = 0; i < ownerData.ticketIds.length; i++) {
uint256 ValidticketId = ownerData.ticketIds[i];
if (tickets[ValidticketId].validUntil >= block.timestamp && !tickets[ValidticketId].used) {
validCount++;
}
}
return validCount;
}
function getUsedTicketCount(address _user) external view returns (uint256) {
uint256 UsedTicketCount = 0;
OwnerInfo storage ownerData = ownerInfo[_user];
for (uint256 i = 0; i < ownerData.ticketIds.length; i++) {
uint256 UsedticketId = ownerData.ticketIds[i];
if (tickets[UsedticketId].used) {
UsedTicketCount++;
}
}
return UsedTicketCount;
}
function getUsedTicketCount(address _user) external view returns (uint256) {
uint256 UsedTicketCount = 0;
OwnerInfo storage ownerData = ownerInfo[_user];
for (uint256 i = 0; i < ownerData.ticketIds.length; i++) {
uint256 UsedticketId = ownerData.ticketIds[i];
if (tickets[UsedticketId].used) {
UsedTicketCount++;
}
}
return UsedTicketCount;
}
function getUsedTicketCount(address _user) external view returns (uint256) {
uint256 UsedTicketCount = 0;
OwnerInfo storage ownerData = ownerInfo[_user];
for (uint256 i = 0; i < ownerData.ticketIds.length; i++) {
uint256 UsedticketId = ownerData.ticketIds[i];
if (tickets[UsedticketId].used) {
UsedTicketCount++;
}
}
return UsedTicketCount;
}
}
| 3,817,784 | [
1,
11644,
3695,
434,
279,
9322,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
13588,
21747,
3163,
1908,
353,
4232,
39,
27,
5340,
3572,
25121,
16,
14223,
6914,
288,
203,
203,
203,
565,
1958,
22023,
288,
203,
565,
289,
203,
203,
203,
565,
1958,
16837,
966,
288,
203,
3639,
2254,
5034,
8526,
9322,
2673,
31,
203,
3639,
2254,
5034,
2078,
6264,
2413,
31,
203,
565,
289,
203,
203,
565,
2874,
12,
11890,
5034,
516,
22023,
13,
1071,
24475,
31,
7010,
565,
2874,
12,
2867,
516,
16837,
966,
13,
1071,
3410,
966,
31,
203,
565,
2254,
5034,
8526,
1071,
1399,
13614,
2673,
31,
203,
203,
565,
1450,
8139,
364,
2254,
5034,
31,
203,
565,
533,
1071,
1026,
3098,
273,
1408,
31,
203,
565,
533,
1071,
1026,
3625,
273,
3552,
1977,
14432,
203,
565,
2254,
5034,
1071,
943,
3088,
1283,
273,
15088,
9449,
31,
203,
565,
2254,
5034,
1071,
943,
49,
474,
6275,
273,
404,
31,
203,
565,
1426,
1071,
17781,
273,
629,
31,
203,
565,
2254,
5034,
1071,
9322,
548,
31,
203,
203,
565,
871,
22023,
6119,
12,
203,
3639,
533,
9322,
559,
16,
203,
3639,
2254,
5034,
923,
9716,
16,
203,
3639,
1758,
3410,
16,
203,
3639,
2254,
5034,
3844,
16,
203,
3639,
2254,
5034,
389,
16282,
548,
16,
203,
3639,
2254,
5034,
2858,
16,
203,
3639,
533,
2359,
2556,
1887,
203,
565,
11272,
7010,
203,
203,
565,
871,
22023,
6668,
12,
11890,
5034,
389,
16282,
548,
16,
1758,
729,
1769,
203,
203,
565,
871,
9675,
11222,
13614,
3727,
12,
11890,
5034,
389,
16282,
548,
16,
1758,
729,
1769,
203,
203,
565,
871,
13456,
28590,
12,
2867,
2
] |
./full_match/3/0xe3B2430Bb2D361De1568B58Fcb70Db83AE3b128a/sources/contracts/uniswapv2/UniswapV2ERC20.sol | keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); | contract UniswapV2ERC20 {
using SafeMathUniswap for uint;
string public constant name = '1COINSWAP LP Token';
string public constant symbol = '1CS-LP';
uint8 public constant decimals = 18;
uint public totalSupply;
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
bytes32 public DOMAIN_SEPARATOR;
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public nonces;
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
constructor() public {
uint chainId;
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
constructor() public {
uint chainId;
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
function _mint(address to, uint value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external returns (bool) {
if (allowance[from][msg.sender] != uint(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external returns (bool) {
if (allowance[from][msg.sender] != uint(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
require(deadline >= block.timestamp, 'UniswapV2: EXPIRED');
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE');
_approve(owner, spender, value);
}
}
| 8,107,011 | [
1,
79,
24410,
581,
5034,
2932,
9123,
305,
12,
2867,
3410,
16,
2867,
17571,
264,
16,
11890,
5034,
460,
16,
11890,
5034,
7448,
16,
11890,
5034,
14096,
2225,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
1351,
291,
91,
438,
58,
22,
654,
39,
3462,
288,
203,
565,
1450,
14060,
10477,
984,
291,
91,
438,
364,
2254,
31,
203,
203,
565,
533,
1071,
5381,
508,
273,
296,
21,
3865,
706,
18746,
2203,
511,
52,
3155,
13506,
203,
565,
533,
1071,
5381,
3273,
273,
296,
21,
4596,
17,
14461,
13506,
203,
565,
2254,
28,
1071,
5381,
15105,
273,
6549,
31,
203,
565,
2254,
225,
1071,
2078,
3088,
1283,
31,
203,
565,
2874,
12,
2867,
516,
2254,
13,
1071,
11013,
951,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
3719,
1071,
1699,
1359,
31,
203,
203,
565,
1731,
1578,
1071,
27025,
67,
4550,
31,
203,
565,
1731,
1578,
1071,
5381,
10950,
6068,
67,
2399,
15920,
273,
374,
92,
26,
73,
11212,
329,
8906,
2138,
70,
21,
70,
10580,
74,
24,
72,
21,
74,
26,
4630,
7301,
3030,
74,
15168,
6260,
507,
22,
507,
8906,
1611,
5558,
22214,
69,
26035,
71,
1105,
5193,
25,
72,
26,
25452,
71,
29,
31,
203,
565,
2874,
12,
2867,
516,
2254,
13,
1071,
1661,
764,
31,
203,
203,
565,
871,
1716,
685,
1125,
12,
2867,
8808,
3410,
16,
1758,
8808,
17571,
264,
16,
2254,
460,
1769,
203,
565,
871,
12279,
12,
2867,
8808,
628,
16,
1758,
8808,
358,
16,
2254,
460,
1769,
203,
203,
203,
565,
3885,
1435,
1071,
288,
203,
3639,
2254,
2687,
548,
31,
203,
3639,
19931,
288,
203,
5411,
2687,
548,
519,
2687,
350,
1435,
203,
3639,
289,
203,
3639,
27025,
67,
4550,
273,
417,
24410,
581,
5034,
12,
2
] |
pragma solidity 0.6.3;
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;
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @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;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library Address {
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;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
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);
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
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 functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
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);
}
}
}
}
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 {
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract MasterChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 pid;
uint256 amount; // How many LP tokens the user has provided.
uint256 reward;
uint256 rewardPaid;
uint256 userRewardPerTokenPaid;
uint256 start;
}
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. Pizzas to distribute per block.
uint256 lastRewardTime; // Last block number that Pizzas distribution occurs.
uint256 accPizzaPerShare; // Accumulated Pizzas per share, times 1e18. See below.
uint256 totalPool;
}
// Info of each pool.
PoolInfo[] public poolInfo;
struct User {
uint id;
address referrer;
uint256[] referAmount;
uint256 referReward;
uint256[] referCount;
uint256 referRewardPerTokenPaid;
}
mapping(address => User) public users;
uint public lastUserId = 2;
mapping(uint256 => address) public regisUser;
bool initialized = false;
//uint256 public initreward = 1250*1e18;
uint256 public starttime;
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public totalMinted = 0;
uint256 constant public PERCENTS_DIVIDER = 1000;
uint256 constant public TIME_STEP = 1 days;
IERC20 public pizza ;
address public defaultReferAddr;
address public projectAddress;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// Bonus muliplier for early pizza makers.
uint256 public constant BONUS_MULTIPLIER = 1;
uint256[2] public referrRewardPercent = [15,5];
event RewardPaid(address indexed user, uint256 reward);
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event Registration(address indexed user, address indexed referrer, uint indexed userId, uint referrerId);
//constructor
// function initContract
constructor (IERC20 _pizza,uint256 _rewardRate,uint256 _starttime,uint256 _periodFinish,address _defaultReferAddr,address _projectAddress) public onlyOwner{
require(initialized == false,"has initialized");
pizza = _pizza;
rewardRate = _rewardRate;
starttime = _starttime;
periodFinish = _periodFinish;
defaultReferAddr = _defaultReferAddr;
projectAddress = _projectAddress;
User memory user = User({
id: 1,
referrer: address(0),
referAmount:new uint256[](2),
referReward:0,
referCount:new uint256[](2),
referRewardPerTokenPaid:0
});
users[defaultReferAddr] = user;
regisUser[1] = defaultReferAddr;
initialized = true;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
function isUserExists(address user) public view returns (bool) {
return (users[user].id != 0);
}
function registrationExt(address referrerAddress) external {
registration(msg.sender, referrerAddress);
}
function registration(address userAddress, address referrerAddress) private {
//require(msg.value == 0.05 ether, "registration cost 0.05");
require(!isUserExists(userAddress), "user exists");
require(isUserExists(referrerAddress), "referrer not exists");
// uint32 size;
//assembly {
// size := extcodesize(userAddress)
// }
//require(size == 0, "cannot be a contract");
require(!Address.isContract(userAddress), "cannot be a contract");
User memory user = User({
id: lastUserId,
referrer: referrerAddress,
referAmount:new uint256[](2),
referReward:0,
referCount:new uint256[](2),
referRewardPerTokenPaid:0
});
regisUser[lastUserId] = userAddress;
users[userAddress] = user;
users[referrerAddress].referCount[0] = users[referrerAddress].referCount[0].add(1);
address _refer = users[referrerAddress].referrer;
if(_refer != address(0)){
users[_refer].referCount[1] = users[_refer].referCount[1].add(1);
}
lastUserId++;
emit Registration(userAddress, referrerAddress, users[userAddress].id, users[referrerAddress].id);
}
// 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 addLp(uint256 _allocPoint, IERC20 _lpToken) public onlyOwner {
uint256 lastRewardTime = block.timestamp > starttime ? block.timestamp : starttime;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardTime: lastRewardTime,
accPizzaPerShare: 0,
totalPool:0
}));
}
// Update the given pool's Pizza allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint) public onlyOwner {
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
function setTotalAllocPoint(uint256 _totalAllocPoint) public onlyOwner{
totalAllocPoint = _totalAllocPoint;
}
function setRewardRate(uint256 _rewardRate) public onlyOwner {
rewardRate = _rewardRate;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= periodFinish) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= periodFinish) {
return _to.sub(_from);
} else {
return periodFinish.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(periodFinish)
);
}
}
function getRewardRate() public view returns(uint256){
return rewardRate;
}
function pendingPizza(uint256 _pid, address _user) public view returns (uint256) {
// PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
// uint256 accPizzaPerShare = pool.accPizzaPerShare;
// uint256 lpSupply = pool.totalPool;
uint256 result = user.reward;
// if (block.timestamp > pool.lastRewardTime && lpSupply != 0) {
// uint256 multiplier = getMultiplier(pool.lastRewardTime, block.timestamp);
// uint256 pizzaReward = multiplier.mul(getRewardRate()).mul(pool.allocPoint).div(totalAllocPoint);
// accPizzaPerShare = pool.accPizzaPerShare.add(pizzaReward.mul(1e18).div(lpSupply));
// }
result = (user.amount.mul(getRewardRate()).div(PERCENTS_DIVIDER)).mul(block.timestamp.sub(user.start)).div(TIME_STEP);
if(result >= user.amount) {
result = user.amount;
}
return result;
}
function pendingAllPizza(address _user) public view returns (uint256) {
uint256 result = 0;
for(uint256 i = 0;i< poolInfo.length;i++ ){
result = result.add(pendingPizza(i,_user));
}
return result;
}
function allPizzaAmount(address _user) public view returns (uint256) {
uint256 result = 0;
for(uint256 i = 0;i< poolInfo.length;i++ ){
UserInfo storage user = userInfo[i][_user];
result = result.add(pendingPizza(i,_user).add(user.rewardPaid));
}
return result;
}
function getAllDeposit(address _user) public view returns (uint256) {
uint256 result = 0;
for(uint256 i = 0;i< poolInfo.length;i++ ){
UserInfo storage user = userInfo[i][_user];
result = result.add(user.amount);
}
return result;
}
function getReferCount(address userAddress) public view returns(uint256[] memory){
if(isUserExists(userAddress)){
return users[userAddress].referCount;
}
return new uint256[](2);
}
function getReferAmount(address _user,uint256 _index) public view returns(uint256){
if(isUserExists(_user)){
return users[_user].referAmount[_index];
}
return 0;
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid,address _user) internal {
PoolInfo storage pool = poolInfo[_pid];
if (block.timestamp <= pool.lastRewardTime) {
return;
}
uint256 lpSupply = pool.totalPool;
if (lpSupply == 0) {
pool.lastRewardTime = block.timestamp;
return;
}
UserInfo storage user = userInfo[_pid][_user];
uint256 multiplier = getMultiplier(pool.lastRewardTime, block.timestamp);
uint256 pizzaReward = multiplier.mul(getRewardRate()).mul(pool.allocPoint).div(totalAllocPoint);
totalMinted = totalMinted.add(pizzaReward);
//pizza.mint(address(this), pizzaReward);
pool.accPizzaPerShare = pool.accPizzaPerShare.add(pizzaReward.mul(1e18).div(lpSupply));
user.reward = user.amount.mul((pool.accPizzaPerShare).sub(user.userRewardPerTokenPaid)).div(1e18).add(user.reward);
user.userRewardPerTokenPaid = pool.accPizzaPerShare;
pool.lastRewardTime = block.timestamp;
}
// Deposit LP tokens to MasterChef for pizza allocation.
function deposit(uint256 _pid, uint256 _amount) public checkStart {
require(isUserExists(msg.sender), "user don't exists");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount == 0, "user deposited");
// updatePool(_pid,msg.sender);
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.pid = _pid;
user.start = block.timestamp;
pool.totalPool = pool.totalPool.add(_amount);
address _referrer = users[msg.sender].referrer;
for(uint256 i = 0;i<2;i++){
if(_referrer!= address(0) && isUserExists(_referrer)){
users[_referrer].referAmount[i] = _amount.add(users[_referrer].referAmount[i]);
_referrer = users[_referrer].referrer;
}else break;
}
}
emit Deposit(msg.sender, _pid, _amount);
}
function getReward(uint256 _pid) public {
// PoolInfo storage pool = poolInfo[_pid];
// UserInfo storage user = userInfo[_pid][msg.sender];
// uint256 accPizzaPerShare = pool.accPizzaPerShare;
// uint256 lpSupply = pool.totalPool;
// if (block.timestamp > pool.lastRewardTime && lpSupply != 0) {
// uint256 multiplier = getMultiplier(pool.lastRewardTime, block.timestamp);
// uint256 pizzaReward = multiplier.mul(getRewardRate()).mul(pool.allocPoint).div(totalAllocPoint);
// accPizzaPerShare = pool.accPizzaPerShare.add(pizzaReward.mul(1e18).div(lpSupply));
// }
// uint256 reward = user.amount.mul((accPizzaPerShare).sub(user.userRewardPerTokenPaid)).div(1e18).add(user.reward);
// if (reward > 0) {
// safePizzaTransfer(msg.sender, reward);
// user.rewardPaid = user.rewardPaid.add(reward);
// user.reward = 0;
// emit RewardPaid(msg.sender, reward);
// }
// user.userRewardPerTokenPaid = accPizzaPerShare;
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public{
UserInfo storage user = userInfo[_pid][msg.sender];
PoolInfo storage pool = poolInfo[_pid];
require(user.amount >= _amount, "withdraw: not good");
// updatePool(_pid,msg.sender);
user.reward = (user.amount.mul(getRewardRate()).div(PERCENTS_DIVIDER)).mul(block.timestamp.sub(user.start)).div(TIME_STEP);
require(user.reward >= _amount, "withdraw: not 2 amount");
if(user.reward >= _amount) {
user.reward = _amount;
}
safePizzaTransfer(msg.sender, _amount);
// safePizzaTransfer(projectAddress, user.reward.mul(10).div(100));
user.rewardPaid = user.rewardPaid.add(user.reward);
emit RewardPaid(msg.sender, user.rewardPaid);
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
pool.totalPool = pool.totalPool.sub(_amount);
address _referrer = users[msg.sender].referrer;
for(uint256 i = 0;i<2;i++){
if(_referrer!= address(0) && isUserExists(_referrer)){
users[_referrer].referAmount[i] = users[_referrer].referAmount[i].sub(_amount);
users[_referrer].referReward = users[_referrer].referReward.add(user.reward.mul(referrRewardPercent[i]).div(100));
safePizzaTransfer(_referrer, user.reward.mul(referrRewardPercent[i]).div(100));
_referrer = users[_referrer].referrer;
}else break;
}
}
user.reward = 0;
user.amount = 0;
emit Withdraw(msg.sender, _pid, _amount);
}
// Safe pizza transfer function, just in case if rounding error causes pool to not have enough pizzas.
function safePizzaTransfer(address _to, uint256 _amount) internal {
uint256 pizzaBal = pizza.balanceOf(address(this));
if (_amount > pizzaBal) {
pizza.transfer(_to, pizzaBal);
} else {
pizza.transfer(_to, _amount);
}
}
modifier checkStart(){
require(block.timestamp > starttime,"not start");
_;
}
} | Safe pizza transfer function, just in case if rounding error causes pool to not have enough pizzas. | function safePizzaTransfer(address _to, uint256 _amount) internal {
uint256 pizzaBal = pizza.balanceOf(address(this));
if (_amount > pizzaBal) {
pizza.transfer(_to, pizzaBal);
pizza.transfer(_to, _amount);
}
}
| 1,347,992 | [
1,
9890,
293,
452,
11939,
7412,
445,
16,
2537,
316,
648,
309,
13885,
555,
14119,
2845,
358,
486,
1240,
7304,
293,
25695,
345,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4183,
52,
452,
11939,
5912,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
2713,
288,
203,
3639,
2254,
5034,
293,
452,
11939,
38,
287,
273,
293,
452,
11939,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
309,
261,
67,
8949,
405,
293,
452,
11939,
38,
287,
13,
288,
203,
5411,
293,
452,
11939,
18,
13866,
24899,
869,
16,
293,
452,
11939,
38,
287,
1769,
203,
5411,
293,
452,
11939,
18,
13866,
24899,
869,
16,
389,
8949,
1769,
203,
3639,
289,
203,
565,
289,
27699,
203,
202,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity ^0.6.10;
pragma experimental "ABIEncoderV2";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol";
import { IController } from "../../interfaces/IController.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IExchangeAdapter } from "../../interfaces/IExchangeAdapter.sol";
import { IIntegrationRegistry } from "../../interfaces/IIntegrationRegistry.sol";
import { Invoke } from "../lib/Invoke.sol";
import { ISetToken } from "../../interfaces/ISetToken.sol";
import { ModuleBase } from "../lib/ModuleBase.sol";
import { Position } from "../lib/Position.sol";
import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol";
/**
* @title TradeModule
* @author Set Protocol
*
* Module that enables SetTokens to perform atomic trades using Decentralized Exchanges
* such as 1inch or Kyber. Integrations mappings are stored on the IntegrationRegistry contract.
*/
contract TradeModule is ModuleBase, ReentrancyGuard {
using SafeCast for int256;
using SafeMath for uint256;
using Invoke for ISetToken;
using Position for ISetToken;
using PreciseUnitMath for uint256;
/* ============ Struct ============ */
struct TradeInfo {
ISetToken setToken; // Instance of SetToken
IExchangeAdapter exchangeAdapter; // Instance of exchange adapter contract
address sendToken; // Address of token being sold
address receiveToken; // Address of token being bought
uint256 setTotalSupply; // Total supply of SetToken in Precise Units (10^18)
uint256 totalSendQuantity; // Total quantity of sold token (position unit x total supply)
uint256 totalMinReceiveQuantity; // Total minimum quantity of token to receive back
uint256 preTradeSendTokenBalance; // Total initial balance of token being sold
uint256 preTradeReceiveTokenBalance; // Total initial balance of token being bought
}
/* ============ Events ============ */
event ComponentExchanged(
ISetToken indexed _setToken,
address indexed _sendToken,
address indexed _receiveToken,
IExchangeAdapter _exchangeAdapter,
uint256 _totalSendAmount,
uint256 _totalReceiveAmount,
uint256 _protocolFee
);
/* ============ Constants ============ */
// 0 index stores the fee % charged in the trade function
uint256 constant internal TRADE_MODULE_PROTOCOL_FEE_INDEX = 0;
/* ============ Constructor ============ */
constructor(IController _controller) public ModuleBase(_controller) {}
/* ============ External Functions ============ */
/**
* Initializes this module to the SetToken. Only callable by the SetToken's manager.
*
* @param _setToken Instance of the SetToken to initialize
*/
function initialize(
ISetToken _setToken
)
external
onlyValidAndPendingSet(_setToken)
onlySetManager(_setToken, msg.sender)
{
_setToken.initializeModule();
}
/**
* Executes a trade on a supported DEX. Only callable by the SetToken's manager.
* @dev Although the SetToken units are passed in for the send and receive quantities, the total quantity
* sent and received is the quantity of SetToken units multiplied by the SetToken totalSupply.
*
* @param _setToken Instance of the SetToken to trade
* @param _exchangeName Human readable name of the exchange in the integrations registry
* @param _sendToken Address of the token to be sent to the exchange
* @param _sendQuantity Units of token in SetToken sent to the exchange
* @param _receiveToken Address of the token that will be received from the exchange
* @param _minReceiveQuantity Min units of token in SetToken to be received from the exchange
* @param _data Arbitrary bytes to be used to construct trade call data
*/
function trade(
ISetToken _setToken,
string memory _exchangeName,
address _sendToken,
uint256 _sendQuantity,
address _receiveToken,
uint256 _minReceiveQuantity,
bytes memory _data
)
external
nonReentrant
onlyManagerAndValidSet(_setToken)
{
TradeInfo memory tradeInfo = _createTradeInfo(
_setToken,
_exchangeName,
_sendToken,
_receiveToken,
_sendQuantity,
_minReceiveQuantity
);
_validatePreTradeData(tradeInfo, _sendQuantity);
_executeTrade(tradeInfo, _data);
uint256 exchangedQuantity = _validatePostTrade(tradeInfo);
uint256 protocolFee = _accrueProtocolFee(tradeInfo, exchangedQuantity);
(
uint256 netSendAmount,
uint256 netReceiveAmount
) = _updateSetTokenPositions(tradeInfo);
emit ComponentExchanged(
_setToken,
_sendToken,
_receiveToken,
tradeInfo.exchangeAdapter,
netSendAmount,
netReceiveAmount,
protocolFee
);
}
/**
* Removes this module from the SetToken, via call by the SetToken. Left with empty logic
* here because there are no check needed to verify removal.
*/
function removeModule() external override {}
/* ============ Internal Functions ============ */
/**
* Create and return TradeInfo struct
*
* @param _setToken Instance of the SetToken to trade
* @param _exchangeName Human readable name of the exchange in the integrations registry
* @param _sendToken Address of the token to be sent to the exchange
* @param _receiveToken Address of the token that will be received from the exchange
* @param _sendQuantity Units of token in SetToken sent to the exchange
* @param _minReceiveQuantity Min units of token in SetToken to be received from the exchange
*
* return TradeInfo Struct containing data for trade
*/
function _createTradeInfo(
ISetToken _setToken,
string memory _exchangeName,
address _sendToken,
address _receiveToken,
uint256 _sendQuantity,
uint256 _minReceiveQuantity
)
internal
view
returns (TradeInfo memory)
{
TradeInfo memory tradeInfo;
tradeInfo.setToken = _setToken;
tradeInfo.exchangeAdapter = IExchangeAdapter(getAndValidateAdapter(_exchangeName));
tradeInfo.sendToken = _sendToken;
tradeInfo.receiveToken = _receiveToken;
tradeInfo.setTotalSupply = _setToken.totalSupply();
tradeInfo.totalSendQuantity = Position.getDefaultTotalNotional(tradeInfo.setTotalSupply, _sendQuantity);
tradeInfo.totalMinReceiveQuantity = Position.getDefaultTotalNotional(tradeInfo.setTotalSupply, _minReceiveQuantity);
tradeInfo.preTradeSendTokenBalance = IERC20(_sendToken).balanceOf(address(_setToken));
tradeInfo.preTradeReceiveTokenBalance = IERC20(_receiveToken).balanceOf(address(_setToken));
return tradeInfo;
}
/**
* Validate pre trade data. Check exchange is valid, token quantity is valid.
*
* @param _tradeInfo Struct containing trade information used in internal functions
* @param _sendQuantity Units of token in SetToken sent to the exchange
*/
function _validatePreTradeData(TradeInfo memory _tradeInfo, uint256 _sendQuantity) internal view {
require(_tradeInfo.totalSendQuantity > 0, "Token to sell must be nonzero");
require(
_tradeInfo.setToken.hasSufficientDefaultUnits(_tradeInfo.sendToken, _sendQuantity),
"Unit cant be greater than existing"
);
}
/**
* Invoke approve for send token, get method data and invoke trade in the context of the SetToken.
*
* @param _tradeInfo Struct containing trade information used in internal functions
* @param _data Arbitrary bytes to be used to construct trade call data
*/
function _executeTrade(
TradeInfo memory _tradeInfo,
bytes memory _data
)
internal
{
// Get spender address from exchange adapter and invoke approve for exact amount on SetToken
_tradeInfo.setToken.invokeApprove(
_tradeInfo.sendToken,
_tradeInfo.exchangeAdapter.getSpender(),
_tradeInfo.totalSendQuantity
);
(
address targetExchange,
uint256 callValue,
bytes memory methodData
) = _tradeInfo.exchangeAdapter.getTradeCalldata(
_tradeInfo.sendToken,
_tradeInfo.receiveToken,
address(_tradeInfo.setToken),
_tradeInfo.totalSendQuantity,
_tradeInfo.totalMinReceiveQuantity,
_data
);
_tradeInfo.setToken.invoke(targetExchange, callValue, methodData);
}
/**
* Validate post trade data.
*
* @param _tradeInfo Struct containing trade information used in internal functions
* @return uint256 Total quantity of receive token that was exchanged
*/
function _validatePostTrade(TradeInfo memory _tradeInfo) internal view returns (uint256) {
uint256 exchangedQuantity = IERC20(_tradeInfo.receiveToken)
.balanceOf(address(_tradeInfo.setToken))
.sub(_tradeInfo.preTradeReceiveTokenBalance);
require(
exchangedQuantity >= _tradeInfo.totalMinReceiveQuantity,
"Slippage greater than allowed"
);
return exchangedQuantity;
}
/**
* Retrieve fee from controller and calculate total protocol fee and send from SetToken to protocol recipient
*
* @param _tradeInfo Struct containing trade information used in internal functions
* @return uint256 Amount of receive token taken as protocol fee
*/
function _accrueProtocolFee(TradeInfo memory _tradeInfo, uint256 _exchangedQuantity) internal returns (uint256) {
uint256 protocolFeeTotal = getModuleFee(TRADE_MODULE_PROTOCOL_FEE_INDEX, _exchangedQuantity);
payProtocolFeeFromSetToken(_tradeInfo.setToken, _tradeInfo.receiveToken, protocolFeeTotal);
return protocolFeeTotal;
}
/**
* Update SetToken positions
*
* @param _tradeInfo Struct containing trade information used in internal functions
* @return uint256 Amount of sendTokens used in the trade
* @return uint256 Amount of receiveTokens received in the trade (net of fees)
*/
function _updateSetTokenPositions(TradeInfo memory _tradeInfo) internal returns (uint256, uint256) {
(uint256 currentSendTokenBalance,,) = _tradeInfo.setToken.calculateAndEditDefaultPosition(
_tradeInfo.sendToken,
_tradeInfo.setTotalSupply,
_tradeInfo.preTradeSendTokenBalance
);
(uint256 currentReceiveTokenBalance,,) = _tradeInfo.setToken.calculateAndEditDefaultPosition(
_tradeInfo.receiveToken,
_tradeInfo.setTotalSupply,
_tradeInfo.preTradeReceiveTokenBalance
);
return (
_tradeInfo.preTradeSendTokenBalance.sub(currentSendTokenBalance),
currentReceiveTokenBalance.sub(_tradeInfo.preTradeReceiveTokenBalance)
);
}
} | * Initializes this module to the SetToken. Only callable by the SetToken's manager. @param _setToken Instance of the SetToken to initialize/ | function initialize(
ISetToken _setToken
)
external
onlyValidAndPendingSet(_setToken)
onlySetManager(_setToken, msg.sender)
{
_setToken.initializeModule();
}
| 2,507,669 | [
1,
9685,
333,
1605,
358,
326,
1000,
1345,
18,
5098,
4140,
635,
326,
1000,
1345,
1807,
3301,
18,
225,
389,
542,
1345,
1171,
5180,
434,
326,
1000,
1345,
358,
4046,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4046,
12,
203,
3639,
467,
694,
1345,
389,
542,
1345,
203,
565,
262,
203,
3639,
3903,
203,
3639,
1338,
1556,
1876,
8579,
694,
24899,
542,
1345,
13,
203,
3639,
1338,
694,
1318,
24899,
542,
1345,
16,
1234,
18,
15330,
13,
203,
565,
288,
203,
3639,
389,
542,
1345,
18,
11160,
3120,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// 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 SVGCrowdsale
* @dev SVGCrowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overriden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropiate to concatenate
* behavior.
*/
contract SVGCrowdsale {
using SafeMath for uint256;
// The token being sold
ERC20 public token;
// Address where funds are collected
address public wallet;
// Amount of wei raised
uint256 public weiRaised;
//current round total
uint256 public currentRound;
//block-time when it was deployed
uint startTime = now;
//Time Crowdsale completed
uint256 public completedAt;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
event LogFundingSuccessful(
uint _totalRaised
);
/**
* @param _wallet Address where collected funds will be forwarded to
* @param _token Address of the token being sold
*/
constructor(address _wallet, ERC20 _token) public {
require(_wallet != address(0));
require(_token != address(0));
wallet = _wallet;
token = _token;
}
//rate
uint[5] tablePrices = [
13334,
11429,
10000,
9091,
8000
];
//caps
uint256[5] caps = [
10000500e18,
10000375e18,
10000000e18,
10000100e18,
10000000e18
];
//5 tranches
enum Tranches {
Round1,
Round2,
Round3,
Round4,
Round5,
Successful
}
Tranches public tranches = Tranches.Round1; //Set Private stage
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = getTokenAmount(weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
processPurchase(_beneficiary, tokens);
emit TokenPurchase(
msg.sender,
_beneficiary,
weiAmount,
tokens
);
updatePurchasingState(_beneficiary, weiAmount);
forwardFunds();
checkIfFundingCompleteOrExpired();
postValidatePurchase(_beneficiary, weiAmount);
}
/**
* @dev This method update the current state of tranches and currentRound.
*/
function checkIfFundingCompleteOrExpired() internal {
if(tranches != Tranches.Successful){
if(currentRound > caps[0] && tranches == Tranches.Round1){//plus 8weeks
tranches = Tranches.Round2;
currentRound = 0;
}
else if(currentRound > caps[1] && tranches == Tranches.Round2){ //plus 4weeks
tranches = Tranches.Round3;
currentRound = 0;
}
else if(currentRound > caps[2] && tranches == Tranches.Round3){ //plus 3weeks
tranches = Tranches.Round4;
currentRound = 0;
}
else if(currentRound > caps[3] && tranches == Tranches.Round4){ //plus 3weeks
tranches = Tranches.Round5;
currentRound = 0;
}
}
else {
tranches = Tranches.Successful;
completedAt = now;
}
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal{
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.transfer(_beneficiary, _tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function processPurchase(address _beneficiary, uint256 _tokenAmount )internal{
_deliverTokens(_beneficiary, _tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param _beneficiary Address receiving the tokens
* @param _weiAmount Value in wei involved in the purchase
*/
function updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal {
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
uint256 tokenBought;
if(tranches == Tranches.Round1){
tokenBought = _weiAmount.mul(tablePrices[0]);
require(SafeMath.add(currentRound, tokenBought) <= caps[0]);
}else if(tranches == Tranches.Round2){
tokenBought = _weiAmount.mul(tablePrices[1]);
require(SafeMath.add(currentRound, tokenBought) <= caps[1]);
}else if(tranches == Tranches.Round3){
tokenBought = _weiAmount.mul(tablePrices[2]);
require(SafeMath.add(currentRound, tokenBought) <= caps[2]);
}else if(tranches == Tranches.Round4){
tokenBought = _weiAmount.mul(tablePrices[3]);
require(SafeMath.add(currentRound, tokenBought) <= caps[3]);
}else if(tranches == Tranches.Round5){
tokenBought = _weiAmount.mul(tablePrices[4]);
require(SafeMath.add(currentRound, tokenBought) <= caps[4]);
}else{
revert();
}
return tokenBought;
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function forwardFunds() internal {
wallet.transfer(msg.value);
}
} | * @dev low level token purchase DO NOT OVERRIDE @param _beneficiary Address performing the token purchase/ calculate token amount to be created update state | function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
uint256 tokens = getTokenAmount(weiAmount);
weiRaised = weiRaised.add(weiAmount);
processPurchase(_beneficiary, tokens);
emit TokenPurchase(
msg.sender,
_beneficiary,
weiAmount,
tokens
);
updatePurchasingState(_beneficiary, weiAmount);
forwardFunds();
checkIfFundingCompleteOrExpired();
postValidatePurchase(_beneficiary, weiAmount);
}
| 890,742 | [
1,
821,
1801,
1147,
23701,
5467,
4269,
22577,
25382,
225,
389,
70,
4009,
74,
14463,
814,
5267,
14928,
326,
1147,
23701,
19,
4604,
1147,
3844,
358,
506,
2522,
1089,
919,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
30143,
5157,
12,
2867,
389,
70,
4009,
74,
14463,
814,
13,
1071,
8843,
429,
288,
203,
203,
565,
2254,
5034,
732,
77,
6275,
273,
1234,
18,
1132,
31,
203,
565,
389,
1484,
4270,
23164,
24899,
70,
4009,
74,
14463,
814,
16,
732,
77,
6275,
1769,
203,
203,
565,
2254,
5034,
2430,
273,
9162,
6275,
12,
1814,
77,
6275,
1769,
203,
203,
565,
732,
77,
12649,
5918,
273,
732,
77,
12649,
5918,
18,
1289,
12,
1814,
77,
6275,
1769,
203,
203,
565,
1207,
23164,
24899,
70,
4009,
74,
14463,
814,
16,
2430,
1769,
203,
377,
203,
565,
3626,
3155,
23164,
12,
203,
1377,
1234,
18,
15330,
16,
203,
1377,
389,
70,
4009,
74,
14463,
814,
16,
203,
1377,
732,
77,
6275,
16,
203,
1377,
2430,
203,
565,
11272,
203,
203,
565,
1089,
10262,
343,
11730,
1119,
24899,
70,
4009,
74,
14463,
814,
16,
732,
77,
6275,
1769,
203,
203,
565,
5104,
42,
19156,
5621,
203,
377,
203,
565,
19130,
42,
14351,
6322,
1162,
10556,
5621,
203,
377,
203,
565,
1603,
4270,
23164,
24899,
70,
4009,
74,
14463,
814,
16,
732,
77,
6275,
1769,
203,
225,
289,
203,
21281,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.3;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "./interfaces/IReserve.sol";
import "./interfaces/ISortedOracles.sol";
import "../common/FixidityLib.sol";
import "../common/Initializable.sol";
import "../common/UsingRegistry.sol";
import "../common/libraries/ReentrancyGuard.sol";
/**
* @title Ensures price stability of StableTokens with respect to their pegs
*/
contract Reserve is IReserve, Ownable, Initializable, UsingRegistry, ReentrancyGuard {
using SafeMath for uint256;
using FixidityLib for FixidityLib.Fraction;
struct TobinTaxCache {
uint128 numerator;
uint128 timestamp;
}
mapping(address => bool) public isToken;
address[] private _tokens;
TobinTaxCache public tobinTaxCache;
uint256 public tobinTaxStalenessThreshold;
uint256 public constant TOBIN_TAX_NUMERATOR = 5000000000000000000000; // 0.005
mapping(address => bool) public isSpender;
mapping(address => bool) public isOtherReserveAddress;
address[] public otherReserveAddresses;
bytes32[] public assetAllocationSymbols;
mapping(bytes32 => uint256) public assetAllocationWeights;
uint256 public lastSpendingDay;
uint256 public spendingLimit;
FixidityLib.Fraction private spendingRatio;
uint256 public frozenReserveGoldStartBalance;
uint256 public frozenReserveGoldStartDay;
uint256 public frozenReserveGoldDays;
event TobinTaxStalenessThresholdSet(uint256 value);
event DailySpendingRatioSet(uint256 ratio);
event TokenAdded(address indexed token);
event TokenRemoved(address indexed token, uint256 index);
event SpenderAdded(address indexed spender);
event SpenderRemoved(address indexed spender);
event OtherReserveAddressAdded(address indexed otherReserveAddress);
event OtherReserveAddressRemoved(address indexed otherReserveAddress, uint256 index);
event AssetAllocationSet(bytes32[] symbols, uint256[] weights);
event ReserveGoldTransferred(address indexed spender, address indexed to, uint256 value);
modifier isStableToken(address token) {
require(isToken[token], "token addr was never registered");
_;
}
function() external payable {} // solhint-disable no-empty-blocks
/**
* @notice Used in place of the constructor to allow the contract to be upgradable via proxy.
* @param registryAddress The address of the registry core smart contract.
* @param _tobinTaxStalenessThreshold The initial number of seconds to cache tobin tax value for.
* @param _frozenGold The balance of reserve gold that is frozen.
* @param _frozenDays The number of days during which the frozen gold thaws.
*/
function initialize(
address registryAddress,
uint256 _tobinTaxStalenessThreshold,
uint256 _spendingRatio,
uint256 _frozenGold,
uint256 _frozenDays,
bytes32[] calldata _assetAllocationSymbols,
uint256[] calldata _assetAllocationWeights
) external initializer {
_transferOwnership(msg.sender);
setRegistry(registryAddress);
setTobinTaxStalenessThreshold(_tobinTaxStalenessThreshold);
setDailySpendingRatio(_spendingRatio);
setFrozenGold(_frozenGold, _frozenDays);
setAssetAllocations(_assetAllocationSymbols, _assetAllocationWeights);
}
/**
* @notice Sets the number of seconds to cache the tobin tax value for.
* @param value The number of seconds to cache the tobin tax value for.
*/
function setTobinTaxStalenessThreshold(uint256 value) public onlyOwner {
require(value > 0, "value was zero");
tobinTaxStalenessThreshold = value;
emit TobinTaxStalenessThresholdSet(value);
}
/**
* @notice Set the ratio of reserve that is spendable per day.
* @param ratio Spending ratio as unwrapped Fraction.
*/
function setDailySpendingRatio(uint256 ratio) public onlyOwner {
spendingRatio = FixidityLib.wrap(ratio);
require(spendingRatio.lte(FixidityLib.fixed1()), "spending ratio cannot be larger than 1");
emit DailySpendingRatioSet(ratio);
}
/**
* @notice Get daily spending ratio.
* @return Spending ratio as unwrapped Fraction.
*/
function getDailySpendingRatio() public view returns (uint256) {
return spendingRatio.unwrap();
}
/**
* @notice Sets the balance of reserve gold frozen from transfer.
* @param frozenGold The amount of cGLD frozen.
* @param frozenDays The number of days the frozen cGLD thaws over.
*/
function setFrozenGold(uint256 frozenGold, uint256 frozenDays) public onlyOwner {
require(frozenGold <= address(this).balance, "Cannot freeze more than balance");
frozenReserveGoldStartBalance = frozenGold;
frozenReserveGoldStartDay = now / 1 days;
frozenReserveGoldDays = frozenDays;
}
/**
* @notice Sets target allocations for Celo Gold and a diversified basket of non-Celo assets.
* @param symbols The symbol of each asset in the Reserve portfolio.
* @param weights The weight for the corresponding asset as unwrapped Fixidity.Fraction.
*/
function setAssetAllocations(bytes32[] memory symbols, uint256[] memory weights)
public
onlyOwner
{
require(symbols.length == weights.length, "Array length mismatch");
FixidityLib.Fraction memory sum = FixidityLib.wrap(0);
for (uint256 i = 0; i < weights.length; i = i.add(1)) {
sum = sum.add(FixidityLib.wrap(weights[i]));
}
require(sum.equals(FixidityLib.fixed1()), "Sum of asset allocation must be 1");
for (uint256 i = 0; i < assetAllocationSymbols.length; i = i.add(1)) {
delete assetAllocationWeights[assetAllocationSymbols[i]];
}
assetAllocationSymbols = symbols;
for (uint256 i = 0; i < symbols.length; i = i.add(1)) {
require(assetAllocationWeights[symbols[i]] == 0, "Cannot set weight twice");
assetAllocationWeights[symbols[i]] = weights[i];
}
require(assetAllocationWeights["cGLD"] != 0, "Must set cGLD asset weight");
emit AssetAllocationSet(symbols, weights);
}
/**
* @notice Add a token that the reserve will stabilize.
* @param token The address of the token being stabilized.
* @return Returns true if the transaction succeeds.
*/
function addToken(address token) external onlyOwner nonReentrant returns (bool) {
require(!isToken[token], "token addr already registered");
// Require an exchange rate between the new token and Gold exists.
address sortedOraclesAddress = registry.getAddressForOrDie(SORTED_ORACLES_REGISTRY_ID);
ISortedOracles sortedOracles = ISortedOracles(sortedOraclesAddress);
uint256 tokenAmount;
uint256 goldAmount;
(tokenAmount, goldAmount) = sortedOracles.medianRate(token);
require(goldAmount > 0, "median rate returned 0 gold");
isToken[token] = true;
_tokens.push(token);
emit TokenAdded(token);
return true;
}
/**
* @notice Remove a token that the reserve will no longer stabilize.
* @param token The address of the token no longer being stabilized.
* @param index The index of the token in _tokens.
* @return Returns true if the transaction succeeds.
*/
function removeToken(address token, uint256 index)
external
onlyOwner
isStableToken(token)
returns (bool)
{
require(
index < _tokens.length && _tokens[index] == token,
"index into tokens list not mapped to token"
);
isToken[token] = false;
address lastItem = _tokens[_tokens.length.sub(1)];
_tokens[index] = lastItem;
_tokens.length = _tokens.length.sub(1);
emit TokenRemoved(token, index);
return true;
}
/**
* @notice Add a reserve address whose balance shall be included in the reserve ratio.
* @param reserveAddress The reserve address to add.
* @return Returns true if the transaction succeeds.
*/
function addOtherReserveAddress(address reserveAddress)
external
onlyOwner
nonReentrant
returns (bool)
{
require(!isOtherReserveAddress[reserveAddress], "reserve addr already added");
isOtherReserveAddress[reserveAddress] = true;
otherReserveAddresses.push(reserveAddress);
emit OtherReserveAddressAdded(reserveAddress);
return true;
}
/**
* @notice Remove reserve address whose balance shall no longer be included in the reserve ratio.
* @param reserveAddress The reserve address to remove.
* @param index The index of the reserve address in otherReserveAddresses.
* @return Returns true if the transaction succeeds.
*/
function removeOtherReserveAddress(address reserveAddress, uint256 index)
external
onlyOwner
returns (bool)
{
require(isOtherReserveAddress[reserveAddress], "reserve addr was never added");
require(
index < otherReserveAddresses.length && otherReserveAddresses[index] == reserveAddress,
"index into reserve list not mapped to address"
);
isOtherReserveAddress[reserveAddress] = false;
address lastItem = otherReserveAddresses[otherReserveAddresses.length.sub(1)];
otherReserveAddresses[index] = lastItem;
otherReserveAddresses.length = otherReserveAddresses.length.sub(1);
emit OtherReserveAddressRemoved(reserveAddress, index);
return true;
}
/**
* @notice Gives an address permission to spend Reserve funds.
* @param spender The address that is allowed to spend Reserve funds.
*/
function addSpender(address spender) external onlyOwner {
isSpender[spender] = true;
emit SpenderAdded(spender);
}
/**
* @notice Takes away an address's permission to spend Reserve funds.
* @param spender The address that is to be no longer allowed to spend Reserve funds.
*/
function removeSpender(address spender) external onlyOwner {
isSpender[spender] = false;
emit SpenderRemoved(spender);
}
/**
* @notice Transfer gold to a whitelisted address subject to reserve spending limits.
* @param to The address that will receive the gold.
* @param value The amount of gold to transfer.
* @return Returns true if the transaction succeeds.
*/
function transferGold(address payable to, uint256 value) external returns (bool) {
require(isSpender[msg.sender], "sender not allowed to transfer Reserve funds");
require(isOtherReserveAddress[to], "can only transfer to other reserve address");
uint256 currentDay = now / 1 days;
if (currentDay > lastSpendingDay) {
uint256 balance = getUnfrozenReserveGoldBalance();
lastSpendingDay = currentDay;
spendingLimit = spendingRatio.multiply(FixidityLib.newFixed(balance)).fromFixed();
}
require(spendingLimit >= value, "Exceeding spending limit");
spendingLimit = spendingLimit.sub(value);
return _transferGold(to, value);
}
/**
* @notice Transfer unfrozen gold to any address.
* @param to The address that will receive the gold.
* @param value The amount of gold to transfer.
* @return Returns true if the transaction succeeds.
*/
function _transferGold(address payable to, uint256 value) internal returns (bool) {
require(value <= getUnfrozenBalance(), "Exceeding unfrozen reserves");
to.transfer(value);
emit ReserveGoldTransferred(msg.sender, to, value);
return true;
}
/**
* @notice Transfer unfrozen gold to any address, used for one side of CP-DOTO.
* @param to The address that will receive the gold.
* @param value The amount of gold to transfer.
* @return Returns true if the transaction succeeds.
*/
function transferExchangeGold(address payable to, uint256 value)
external
onlyRegisteredContract(EXCHANGE_REGISTRY_ID)
returns (bool)
{
return _transferGold(to, value);
}
/**
* @notice Returns the tobin tax, recomputing it if it's stale.
* @return The tobin tax amount as a fraction.
*/
function getOrComputeTobinTax() external nonReentrant returns (uint256, uint256) {
// solhint-disable-next-line not-rely-on-time
if (now.sub(tobinTaxCache.timestamp) > tobinTaxStalenessThreshold) {
tobinTaxCache.numerator = uint128(computeTobinTax().unwrap());
tobinTaxCache.timestamp = uint128(now); // solhint-disable-line not-rely-on-time
}
return (uint256(tobinTaxCache.numerator), FixidityLib.fixed1().unwrap());
}
/**
* @notice Returns the list of stabilized token addresses.
* @return An array of addresses of stabilized tokens.
*/
function getTokens() external view returns (address[] memory) {
return _tokens;
}
/**
* @notice Returns the list other addresses included in the reserve total.
* @return An array of other addresses included in the reserve total.
*/
function getOtherReserveAddresses() external view returns (address[] memory) {
return otherReserveAddresses;
}
/**
* @notice Returns a list of token symbols that have been allocated.
* @return An array of token symbols that have been allocated.
*/
function getAssetAllocationSymbols() external view returns (bytes32[] memory) {
return assetAllocationSymbols;
}
/**
* @notice Returns a list of weights used for the allocation of reserve assets.
* @return An array of a list of weights used for the allocation of reserve assets.
*/
function getAssetAllocationWeights() external view returns (uint256[] memory) {
uint256[] memory weights = new uint256[](assetAllocationSymbols.length);
for (uint256 i = 0; i < assetAllocationSymbols.length; i = i.add(1)) {
weights[i] = assetAllocationWeights[assetAllocationSymbols[i]];
}
return weights;
}
/**
* @notice Returns the amount of unfrozen Celo Gold in the reserve.
* @return The total unfrozen Celo Gold in the reserve.
*/
function getUnfrozenBalance() public view returns (uint256) {
uint256 balance = address(this).balance;
uint256 frozenReserveGold = getFrozenReserveGoldBalance();
return balance > frozenReserveGold ? balance.sub(frozenReserveGold) : 0;
}
/**
* @notice Returns the amount of Celo Gold included in the reserve.
* @return The Celo Gold amount included in the reserve.
*/
function getReserveGoldBalance() public view returns (uint256) {
return address(this).balance.add(getOtherReserveAddressesGoldBalance());
}
/**
* @notice Returns the amount of Celo Gold included in other reserve addresses.
* @return The Celo Gold amount included in other reserve addresses.
*/
function getOtherReserveAddressesGoldBalance() public view returns (uint256) {
uint256 reserveGoldBalance = 0;
for (uint256 i = 0; i < otherReserveAddresses.length; i = i.add(1)) {
reserveGoldBalance = reserveGoldBalance.add(otherReserveAddresses[i].balance);
}
return reserveGoldBalance;
}
/**
* @notice Returns the amount of unfrozen Celo Gold included in the reserve.
* @return The unfrozen Celo Gold amount included in the reserve.
*/
function getUnfrozenReserveGoldBalance() public view returns (uint256) {
return getUnfrozenBalance().add(getOtherReserveAddressesGoldBalance());
}
/**
* @notice Returns the amount of frozen Celo Gold in the reserve.
* @return The total frozen Celo Gold in the reserve.
*/
function getFrozenReserveGoldBalance() public view returns (uint256) {
uint256 currentDay = now / 1 days;
uint256 frozenDays = currentDay.sub(frozenReserveGoldStartDay);
if (frozenDays >= frozenReserveGoldDays) return 0;
return
frozenReserveGoldStartBalance.sub(
frozenReserveGoldStartBalance.mul(frozenDays).div(frozenReserveGoldDays)
);
}
/**
* @notice Computes the ratio of current reserve balance to total stable token valuation.
* @return Reserve ratio in a fixed point format.
*/
function getReserveRatio() public view returns (uint256) {
address sortedOraclesAddress = registry.getAddressForOrDie(SORTED_ORACLES_REGISTRY_ID);
ISortedOracles sortedOracles = ISortedOracles(sortedOraclesAddress);
uint256 reserveGoldBalance = getUnfrozenReserveGoldBalance();
uint256 stableTokensValueInGold = 0;
FixidityLib.Fraction memory cgldWeight = FixidityLib.wrap(assetAllocationWeights["cGLD"]);
for (uint256 i = 0; i < _tokens.length; i = i.add(1)) {
uint256 stableAmount;
uint256 goldAmount;
(stableAmount, goldAmount) = sortedOracles.medianRate(_tokens[i]);
uint256 stableTokenSupply = IERC20(_tokens[i]).totalSupply();
uint256 aStableTokenValueInGold = stableTokenSupply.mul(goldAmount).div(stableAmount);
stableTokensValueInGold = stableTokensValueInGold.add(aStableTokenValueInGold);
}
return
FixidityLib
.newFixed(reserveGoldBalance)
.divide(cgldWeight)
.divide(FixidityLib.newFixed(stableTokensValueInGold))
.unwrap();
}
/*
* Internal functions
*/
/**
* @notice Computes a tobin tax based on the reserve ratio.
* @return The numerator of the tobin tax amount, where the denominator is 1000.
*/
function computeTobinTax() private view returns (FixidityLib.Fraction memory) {
// The protocol calls for a 0.5% transfer tax on Celo Gold when the reserve ratio <= 2.
FixidityLib.Fraction memory ratio = FixidityLib.wrap(getReserveRatio());
if (ratio.gte(FixidityLib.newFixed(2))) {
return FixidityLib.wrap(0);
} else {
return FixidityLib.wrap(TOBIN_TAX_NUMERATOR);
}
}
}
| * @notice Used in place of the constructor to allow the contract to be upgradable via proxy. @param registryAddress The address of the registry core smart contract. @param _tobinTaxStalenessThreshold The initial number of seconds to cache tobin tax value for. @param _frozenGold The balance of reserve gold that is frozen. @param _frozenDays The number of days during which the frozen gold thaws./ | function initialize(
address registryAddress,
uint256 _tobinTaxStalenessThreshold,
uint256 _spendingRatio,
uint256 _frozenGold,
uint256 _frozenDays,
bytes32[] calldata _assetAllocationSymbols,
uint256[] calldata _assetAllocationWeights
) external initializer {
_transferOwnership(msg.sender);
setRegistry(registryAddress);
setTobinTaxStalenessThreshold(_tobinTaxStalenessThreshold);
setDailySpendingRatio(_spendingRatio);
setFrozenGold(_frozenGold, _frozenDays);
setAssetAllocations(_assetAllocationSymbols, _assetAllocationWeights);
}
| 2,528,217 | [
1,
6668,
316,
3166,
434,
326,
3885,
358,
1699,
326,
6835,
358,
506,
731,
9974,
429,
3970,
2889,
18,
225,
4023,
1887,
1021,
1758,
434,
326,
4023,
2922,
13706,
6835,
18,
225,
389,
869,
4757,
7731,
510,
287,
15681,
7614,
1021,
2172,
1300,
434,
3974,
358,
1247,
358,
4757,
5320,
460,
364,
18,
225,
389,
28138,
43,
1673,
1021,
11013,
434,
20501,
20465,
716,
353,
12810,
18,
225,
389,
28138,
9384,
1021,
1300,
434,
4681,
4982,
1492,
326,
12810,
20465,
286,
6850,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
4046,
12,
203,
565,
1758,
4023,
1887,
16,
203,
565,
2254,
5034,
389,
869,
4757,
7731,
510,
287,
15681,
7614,
16,
203,
565,
2254,
5034,
389,
87,
9561,
8541,
16,
203,
565,
2254,
5034,
389,
28138,
43,
1673,
16,
203,
565,
2254,
5034,
389,
28138,
9384,
16,
203,
565,
1731,
1578,
8526,
745,
892,
389,
9406,
17353,
14821,
16,
203,
565,
2254,
5034,
8526,
745,
892,
389,
9406,
17353,
16595,
203,
225,
262,
3903,
12562,
288,
203,
565,
389,
13866,
5460,
12565,
12,
3576,
18,
15330,
1769,
203,
565,
444,
4243,
12,
9893,
1887,
1769,
203,
565,
19892,
4757,
7731,
510,
287,
15681,
7614,
24899,
869,
4757,
7731,
510,
287,
15681,
7614,
1769,
203,
565,
444,
40,
12857,
55,
9561,
8541,
24899,
87,
9561,
8541,
1769,
203,
565,
24340,
9808,
43,
1673,
24899,
28138,
43,
1673,
16,
389,
28138,
9384,
1769,
203,
565,
444,
6672,
8763,
1012,
24899,
9406,
17353,
14821,
16,
389,
9406,
17353,
16595,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;
// Sources flattened with hardhat v2.9.0 https://hardhat.org
// File @openzeppelin/contracts/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
/**
* @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 @chainlink/contracts/src/v0.8/vendor/[email protected]
/**
* @dev A library for working with mutable byte buffers in Solidity.
*
* Byte buffers are mutable and expandable, and provide a variety of primitives
* for writing to them. At any time you can fetch a bytes object containing the
* current contents of the buffer. The bytes object should not be stored between
* operations, as it may change due to resizing of the buffer.
*/
library BufferChainlink {
/**
* @dev Represents a mutable buffer. Buffers have a current value (buf) and
* a capacity. The capacity may be longer than the current value, in
* which case it can be extended without the need to allocate more memory.
*/
struct buffer {
bytes buf;
uint256 capacity;
}
/**
* @dev Initializes a buffer with an initial capacity.
* @param buf The buffer to initialize.
* @param capacity The number of bytes of space to allocate the buffer.
* @return The buffer, for chaining.
*/
function init(buffer memory buf, uint256 capacity) internal pure returns (buffer memory) {
if (capacity % 32 != 0) {
capacity += 32 - (capacity % 32);
}
// Allocate space for the buffer data
buf.capacity = capacity;
assembly {
let ptr := mload(0x40)
mstore(buf, ptr)
mstore(ptr, 0)
mstore(0x40, add(32, add(ptr, capacity)))
}
return buf;
}
/**
* @dev Initializes a new buffer from an existing bytes object.
* Changes to the buffer may mutate the original value.
* @param b The bytes object to initialize the buffer with.
* @return A new buffer.
*/
function fromBytes(bytes memory b) internal pure returns (buffer memory) {
buffer memory buf;
buf.buf = b;
buf.capacity = b.length;
return buf;
}
function resize(buffer memory buf, uint256 capacity) private pure {
bytes memory oldbuf = buf.buf;
init(buf, capacity);
append(buf, oldbuf);
}
function max(uint256 a, uint256 b) private pure returns (uint256) {
if (a > b) {
return a;
}
return b;
}
/**
* @dev Sets buffer length to 0.
* @param buf The buffer to truncate.
* @return The original buffer, for chaining..
*/
function truncate(buffer memory buf) internal pure returns (buffer memory) {
assembly {
let bufptr := mload(buf)
mstore(bufptr, 0)
}
return buf;
}
/**
* @dev Writes a byte string to a buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param off The start offset to write to.
* @param data The data to append.
* @param len The number of bytes to copy.
* @return The original buffer, for chaining.
*/
function write(
buffer memory buf,
uint256 off,
bytes memory data,
uint256 len
) internal pure returns (buffer memory) {
require(len <= data.length);
if (off + len > buf.capacity) {
resize(buf, max(buf.capacity, len + off) * 2);
}
uint256 dest;
uint256 src;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Start address = buffer address + offset + sizeof(buffer length)
dest := add(add(bufptr, 32), off)
// Update buffer length if we're extending it
if gt(add(len, off), buflen) {
mstore(bufptr, add(len, off))
}
src := add(data, 32)
}
// Copy word-length chunks while possible
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
unchecked {
uint256 mask = (256**(32 - len)) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
return buf;
}
/**
* @dev Appends a byte string to a buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @param len The number of bytes to copy.
* @return The original buffer, for chaining.
*/
function append(
buffer memory buf,
bytes memory data,
uint256 len
) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, data, len);
}
/**
* @dev Appends a byte string to a buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function append(buffer memory buf, bytes memory data) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, data, data.length);
}
/**
* @dev Writes a byte to the buffer. Resizes if doing so would exceed the
* capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write the byte at.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function writeUint8(
buffer memory buf,
uint256 off,
uint8 data
) internal pure returns (buffer memory) {
if (off >= buf.capacity) {
resize(buf, buf.capacity * 2);
}
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Address = buffer address + sizeof(buffer length) + off
let dest := add(add(bufptr, off), 32)
mstore8(dest, data)
// Update buffer length if we extended it
if eq(off, buflen) {
mstore(bufptr, add(buflen, 1))
}
}
return buf;
}
/**
* @dev Appends a byte to the buffer. Resizes if doing so would exceed the
* capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function appendUint8(buffer memory buf, uint8 data) internal pure returns (buffer memory) {
return writeUint8(buf, buf.buf.length, data);
}
/**
* @dev Writes up to 32 bytes to the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write at.
* @param data The data to append.
* @param len The number of bytes to write (left-aligned).
* @return The original buffer, for chaining.
*/
function write(
buffer memory buf,
uint256 off,
bytes32 data,
uint256 len
) private pure returns (buffer memory) {
if (len + off > buf.capacity) {
resize(buf, (len + off) * 2);
}
unchecked {
uint256 mask = (256**len) - 1;
// Right-align data
data = data >> (8 * (32 - len));
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Address = buffer address + sizeof(buffer length) + off + len
let dest := add(add(bufptr, off), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
// Update buffer length if we extended it
if gt(add(off, len), mload(bufptr)) {
mstore(bufptr, add(off, len))
}
}
}
return buf;
}
/**
* @dev Writes a bytes20 to the buffer. Resizes if doing so would exceed the
* capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write at.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function writeBytes20(
buffer memory buf,
uint256 off,
bytes20 data
) internal pure returns (buffer memory) {
return write(buf, off, bytes32(data), 20);
}
/**
* @dev Appends a bytes20 to the buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chhaining.
*/
function appendBytes20(buffer memory buf, bytes20 data) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, bytes32(data), 20);
}
/**
* @dev Appends a bytes32 to the buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function appendBytes32(buffer memory buf, bytes32 data) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, data, 32);
}
/**
* @dev Writes an integer to the buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write at.
* @param data The data to append.
* @param len The number of bytes to write (right-aligned).
* @return The original buffer, for chaining.
*/
function writeInt(
buffer memory buf,
uint256 off,
uint256 data,
uint256 len
) private pure returns (buffer memory) {
if (len + off > buf.capacity) {
resize(buf, (len + off) * 2);
}
uint256 mask = (256**len) - 1;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Address = buffer address + off + sizeof(buffer length) + len
let dest := add(add(bufptr, off), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
// Update buffer length if we extended it
if gt(add(off, len), mload(bufptr)) {
mstore(bufptr, add(off, len))
}
}
return buf;
}
/**
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function appendInt(
buffer memory buf,
uint256 data,
uint256 len
) internal pure returns (buffer memory) {
return writeInt(buf, buf.buf.length, data, len);
}
}
// File @chainlink/contracts/src/v0.8/vendor/[email protected]
library CBORChainlink {
using BufferChainlink for BufferChainlink.buffer;
uint8 private constant MAJOR_TYPE_INT = 0;
uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;
uint8 private constant MAJOR_TYPE_BYTES = 2;
uint8 private constant MAJOR_TYPE_STRING = 3;
uint8 private constant MAJOR_TYPE_ARRAY = 4;
uint8 private constant MAJOR_TYPE_MAP = 5;
uint8 private constant MAJOR_TYPE_TAG = 6;
uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7;
uint8 private constant TAG_TYPE_BIGNUM = 2;
uint8 private constant TAG_TYPE_NEGATIVE_BIGNUM = 3;
function encodeFixedNumeric(BufferChainlink.buffer memory buf, uint8 major, uint64 value) private pure {
if(value <= 23) {
buf.appendUint8(uint8((major << 5) | value));
} else if (value <= 0xFF) {
buf.appendUint8(uint8((major << 5) | 24));
buf.appendInt(value, 1);
} else if (value <= 0xFFFF) {
buf.appendUint8(uint8((major << 5) | 25));
buf.appendInt(value, 2);
} else if (value <= 0xFFFFFFFF) {
buf.appendUint8(uint8((major << 5) | 26));
buf.appendInt(value, 4);
} else {
buf.appendUint8(uint8((major << 5) | 27));
buf.appendInt(value, 8);
}
}
function encodeIndefiniteLengthType(BufferChainlink.buffer memory buf, uint8 major) private pure {
buf.appendUint8(uint8((major << 5) | 31));
}
function encodeUInt(BufferChainlink.buffer memory buf, uint value) internal pure {
if(value > 0xFFFFFFFFFFFFFFFF) {
encodeBigNum(buf, value);
} else {
encodeFixedNumeric(buf, MAJOR_TYPE_INT, uint64(value));
}
}
function encodeInt(BufferChainlink.buffer memory buf, int value) internal pure {
if(value < -0x10000000000000000) {
encodeSignedBigNum(buf, value);
} else if(value > 0xFFFFFFFFFFFFFFFF) {
encodeBigNum(buf, uint(value));
} else if(value >= 0) {
encodeFixedNumeric(buf, MAJOR_TYPE_INT, uint64(uint256(value)));
} else {
encodeFixedNumeric(buf, MAJOR_TYPE_NEGATIVE_INT, uint64(uint256(-1 - value)));
}
}
function encodeBytes(BufferChainlink.buffer memory buf, bytes memory value) internal pure {
encodeFixedNumeric(buf, MAJOR_TYPE_BYTES, uint64(value.length));
buf.append(value);
}
function encodeBigNum(BufferChainlink.buffer memory buf, uint value) internal pure {
buf.appendUint8(uint8((MAJOR_TYPE_TAG << 5) | TAG_TYPE_BIGNUM));
encodeBytes(buf, abi.encode(value));
}
function encodeSignedBigNum(BufferChainlink.buffer memory buf, int input) internal pure {
buf.appendUint8(uint8((MAJOR_TYPE_TAG << 5) | TAG_TYPE_NEGATIVE_BIGNUM));
encodeBytes(buf, abi.encode(uint256(-1 - input)));
}
function encodeString(BufferChainlink.buffer memory buf, string memory value) internal pure {
encodeFixedNumeric(buf, MAJOR_TYPE_STRING, uint64(bytes(value).length));
buf.append(bytes(value));
}
function startArray(BufferChainlink.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY);
}
function startMap(BufferChainlink.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP);
}
function endSequence(BufferChainlink.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE);
}
}
// File @chainlink/contracts/src/v0.8/[email protected]
/**
* @title Library for common Chainlink functions
* @dev Uses imported CBOR library for encoding to buffer
*/
library Chainlink {
uint256 internal constant defaultBufferSize = 256; // solhint-disable-line const-name-snakecase
using CBORChainlink for BufferChainlink.buffer;
struct Request {
bytes32 id;
address callbackAddress;
bytes4 callbackFunctionId;
uint256 nonce;
BufferChainlink.buffer buf;
}
/**
* @notice Initializes a Chainlink request
* @dev Sets the ID, callback address, and callback function signature on the request
* @param self The uninitialized request
* @param jobId The Job Specification ID
* @param callbackAddr The callback address
* @param callbackFunc The callback function signature
* @return The initialized request
*/
function initialize(
Request memory self,
bytes32 jobId,
address callbackAddr,
bytes4 callbackFunc
) internal pure returns (Chainlink.Request memory) {
BufferChainlink.init(self.buf, defaultBufferSize);
self.id = jobId;
self.callbackAddress = callbackAddr;
self.callbackFunctionId = callbackFunc;
return self;
}
/**
* @notice Sets the data for the buffer without encoding CBOR on-chain
* @dev CBOR can be closed with curly-brackets {} or they can be left off
* @param self The initialized request
* @param data The CBOR data
*/
function setBuffer(Request memory self, bytes memory data) internal pure {
BufferChainlink.init(self.buf, data.length);
BufferChainlink.append(self.buf, data);
}
/**
* @notice Adds a string value to the request with a given key name
* @param self The initialized request
* @param key The name of the key
* @param value The string value to add
*/
function add(
Request memory self,
string memory key,
string memory value
) internal pure {
self.buf.encodeString(key);
self.buf.encodeString(value);
}
/**
* @notice Adds a bytes value to the request with a given key name
* @param self The initialized request
* @param key The name of the key
* @param value The bytes value to add
*/
function addBytes(
Request memory self,
string memory key,
bytes memory value
) internal pure {
self.buf.encodeString(key);
self.buf.encodeBytes(value);
}
/**
* @notice Adds a int256 value to the request with a given key name
* @param self The initialized request
* @param key The name of the key
* @param value The int256 value to add
*/
function addInt(
Request memory self,
string memory key,
int256 value
) internal pure {
self.buf.encodeString(key);
self.buf.encodeInt(value);
}
/**
* @notice Adds a uint256 value to the request with a given key name
* @param self The initialized request
* @param key The name of the key
* @param value The uint256 value to add
*/
function addUint(
Request memory self,
string memory key,
uint256 value
) internal pure {
self.buf.encodeString(key);
self.buf.encodeUInt(value);
}
/**
* @notice Adds an array of strings to the request with a given key name
* @param self The initialized request
* @param key The name of the key
* @param values The array of string values to add
*/
function addStringArray(
Request memory self,
string memory key,
string[] memory values
) internal pure {
self.buf.encodeString(key);
self.buf.startArray();
for (uint256 i = 0; i < values.length; i++) {
self.buf.encodeString(values[i]);
}
self.buf.endSequence();
}
}
// File @chainlink/contracts/src/v0.8/interfaces/[email protected]
interface ENSInterface {
// 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);
function setSubnodeOwner(
bytes32 node,
bytes32 label,
address owner
) external;
function setResolver(bytes32 node, address resolver) external;
function setOwner(bytes32 node, address owner) external;
function setTTL(bytes32 node, uint64 ttl) external;
function owner(bytes32 node) external view returns (address);
function resolver(bytes32 node) external view returns (address);
function ttl(bytes32 node) external view returns (uint64);
}
// File @chainlink/contracts/src/v0.8/interfaces/[email protected]
interface LinkTokenInterface {
function allowance(address owner, address spender) external view returns (uint256 remaining);
function approve(address spender, uint256 value) external returns (bool success);
function balanceOf(address owner) external view returns (uint256 balance);
function decimals() external view returns (uint8 decimalPlaces);
function decreaseApproval(address spender, uint256 addedValue) external returns (bool success);
function increaseApproval(address spender, uint256 subtractedValue) external;
function name() external view returns (string memory tokenName);
function symbol() external view returns (string memory tokenSymbol);
function totalSupply() external view returns (uint256 totalTokensIssued);
function transfer(address to, uint256 value) external returns (bool success);
function transferAndCall(
address to,
uint256 value,
bytes calldata data
) external returns (bool success);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool success);
}
// File @chainlink/contracts/src/v0.8/interfaces/[email protected]
interface ChainlinkRequestInterface {
function oracleRequest(
address sender,
uint256 requestPrice,
bytes32 serviceAgreementID,
address callbackAddress,
bytes4 callbackFunctionId,
uint256 nonce,
uint256 dataVersion,
bytes calldata data
) external;
function cancelOracleRequest(
bytes32 requestId,
uint256 payment,
bytes4 callbackFunctionId,
uint256 expiration
) external;
}
// File @chainlink/contracts/src/v0.8/interfaces/[email protected]
interface OracleInterface {
function fulfillOracleRequest(
bytes32 requestId,
uint256 payment,
address callbackAddress,
bytes4 callbackFunctionId,
uint256 expiration,
bytes32 data
) external returns (bool);
function isAuthorizedSender(address node) external view returns (bool);
function withdraw(address recipient, uint256 amount) external;
function withdrawable() external view returns (uint256);
}
// File @chainlink/contracts/src/v0.8/interfaces/[email protected]
interface OperatorInterface is OracleInterface, ChainlinkRequestInterface {
function operatorRequest(
address sender,
uint256 payment,
bytes32 specId,
bytes4 callbackFunctionId,
uint256 nonce,
uint256 dataVersion,
bytes calldata data
) external;
function fulfillOracleRequest2(
bytes32 requestId,
uint256 payment,
address callbackAddress,
bytes4 callbackFunctionId,
uint256 expiration,
bytes calldata data
) external returns (bool);
function ownerTransferAndCall(
address to,
uint256 value,
bytes calldata data
) external returns (bool success);
function distributeFunds(address payable[] calldata receivers, uint256[] calldata amounts) external payable;
function getAuthorizedSenders() external returns (address[] memory);
function setAuthorizedSenders(address[] calldata senders) external;
function getForwarder() external returns (address);
}
// File @chainlink/contracts/src/v0.8/interfaces/[email protected]
interface PointerInterface {
function getAddress() external view returns (address);
}
// File @chainlink/contracts/src/v0.8/vendor/[email protected]
abstract contract ENSResolver_Chainlink {
function addr(bytes32 node) public view virtual returns (address);
}
// File @chainlink/contracts/src/v0.8/[email protected]
/**
* @title The ChainlinkClient contract
* @notice Contract writers can inherit this contract in order to create requests for the
* Chainlink network
*/
abstract contract ChainlinkClient {
using Chainlink for Chainlink.Request;
uint256 internal constant LINK_DIVISIBILITY = 10**18;
uint256 private constant AMOUNT_OVERRIDE = 0;
address private constant SENDER_OVERRIDE = address(0);
uint256 private constant ORACLE_ARGS_VERSION = 1;
uint256 private constant OPERATOR_ARGS_VERSION = 2;
bytes32 private constant ENS_TOKEN_SUBNAME = keccak256("link");
bytes32 private constant ENS_ORACLE_SUBNAME = keccak256("oracle");
address private constant LINK_TOKEN_POINTER = 0xC89bD4E1632D3A43CB03AAAd5262cbe4038Bc571;
ENSInterface private s_ens;
bytes32 private s_ensNode;
LinkTokenInterface private s_link;
OperatorInterface private s_oracle;
uint256 private s_requestCount = 1;
mapping(bytes32 => address) private s_pendingRequests;
event ChainlinkRequested(bytes32 indexed id);
event ChainlinkFulfilled(bytes32 indexed id);
event ChainlinkCancelled(bytes32 indexed id);
/**
* @notice Creates a request that can hold additional parameters
* @param specId The Job Specification ID that the request will be created for
* @param callbackAddr address to operate the callback on
* @param callbackFunctionSignature function signature to use for the callback
* @return A Chainlink Request struct in memory
*/
function buildChainlinkRequest(
bytes32 specId,
address callbackAddr,
bytes4 callbackFunctionSignature
) internal pure returns (Chainlink.Request memory) {
Chainlink.Request memory req;
return req.initialize(specId, callbackAddr, callbackFunctionSignature);
}
/**
* @notice Creates a request that can hold additional parameters
* @param specId The Job Specification ID that the request will be created for
* @param callbackFunctionSignature function signature to use for the callback
* @return A Chainlink Request struct in memory
*/
function buildOperatorRequest(bytes32 specId, bytes4 callbackFunctionSignature)
internal
view
returns (Chainlink.Request memory)
{
Chainlink.Request memory req;
return req.initialize(specId, address(this), callbackFunctionSignature);
}
/**
* @notice Creates a Chainlink request to the stored oracle address
* @dev Calls `chainlinkRequestTo` with the stored oracle address
* @param req The initialized Chainlink Request
* @param payment The amount of LINK to send for the request
* @return requestId The request ID
*/
function sendChainlinkRequest(Chainlink.Request memory req, uint256 payment) internal returns (bytes32) {
return sendChainlinkRequestTo(address(s_oracle), req, payment);
}
/**
* @notice Creates a Chainlink request to the specified oracle address
* @dev Generates and stores a request ID, increments the local nonce, and uses `transferAndCall` to
* send LINK which creates a request on the target oracle contract.
* Emits ChainlinkRequested event.
* @param oracleAddress The address of the oracle for the request
* @param req The initialized Chainlink Request
* @param payment The amount of LINK to send for the request
* @return requestId The request ID
*/
function sendChainlinkRequestTo(
address oracleAddress,
Chainlink.Request memory req,
uint256 payment
) internal returns (bytes32 requestId) {
uint256 nonce = s_requestCount;
s_requestCount = nonce + 1;
bytes memory encodedRequest = abi.encodeWithSelector(
ChainlinkRequestInterface.oracleRequest.selector,
SENDER_OVERRIDE, // Sender value - overridden by onTokenTransfer by the requesting contract's address
AMOUNT_OVERRIDE, // Amount value - overridden by onTokenTransfer by the actual amount of LINK sent
req.id,
address(this),
req.callbackFunctionId,
nonce,
ORACLE_ARGS_VERSION,
req.buf.buf
);
return _rawRequest(oracleAddress, nonce, payment, encodedRequest);
}
/**
* @notice Creates a Chainlink request to the stored oracle address
* @dev This function supports multi-word response
* @dev Calls `sendOperatorRequestTo` with the stored oracle address
* @param req The initialized Chainlink Request
* @param payment The amount of LINK to send for the request
* @return requestId The request ID
*/
function sendOperatorRequest(Chainlink.Request memory req, uint256 payment) internal returns (bytes32) {
return sendOperatorRequestTo(address(s_oracle), req, payment);
}
/**
* @notice Creates a Chainlink request to the specified oracle address
* @dev This function supports multi-word response
* @dev Generates and stores a request ID, increments the local nonce, and uses `transferAndCall` to
* send LINK which creates a request on the target oracle contract.
* Emits ChainlinkRequested event.
* @param oracleAddress The address of the oracle for the request
* @param req The initialized Chainlink Request
* @param payment The amount of LINK to send for the request
* @return requestId The request ID
*/
function sendOperatorRequestTo(
address oracleAddress,
Chainlink.Request memory req,
uint256 payment
) internal returns (bytes32 requestId) {
uint256 nonce = s_requestCount;
s_requestCount = nonce + 1;
bytes memory encodedRequest = abi.encodeWithSelector(
OperatorInterface.operatorRequest.selector,
SENDER_OVERRIDE, // Sender value - overridden by onTokenTransfer by the requesting contract's address
AMOUNT_OVERRIDE, // Amount value - overridden by onTokenTransfer by the actual amount of LINK sent
req.id,
req.callbackFunctionId,
nonce,
OPERATOR_ARGS_VERSION,
req.buf.buf
);
return _rawRequest(oracleAddress, nonce, payment, encodedRequest);
}
/**
* @notice Make a request to an oracle
* @param oracleAddress The address of the oracle for the request
* @param nonce used to generate the request ID
* @param payment The amount of LINK to send for the request
* @param encodedRequest data encoded for request type specific format
* @return requestId The request ID
*/
function _rawRequest(
address oracleAddress,
uint256 nonce,
uint256 payment,
bytes memory encodedRequest
) private returns (bytes32 requestId) {
requestId = keccak256(abi.encodePacked(this, nonce));
s_pendingRequests[requestId] = oracleAddress;
emit ChainlinkRequested(requestId);
require(s_link.transferAndCall(oracleAddress, payment, encodedRequest), "unable to transferAndCall to oracle");
}
/**
* @notice Allows a request to be cancelled if it has not been fulfilled
* @dev Requires keeping track of the expiration value emitted from the oracle contract.
* Deletes the request from the `pendingRequests` mapping.
* Emits ChainlinkCancelled event.
* @param requestId The request ID
* @param payment The amount of LINK sent for the request
* @param callbackFunc The callback function specified for the request
* @param expiration The time of the expiration for the request
*/
function cancelChainlinkRequest(
bytes32 requestId,
uint256 payment,
bytes4 callbackFunc,
uint256 expiration
) internal {
OperatorInterface requested = OperatorInterface(s_pendingRequests[requestId]);
delete s_pendingRequests[requestId];
emit ChainlinkCancelled(requestId);
requested.cancelOracleRequest(requestId, payment, callbackFunc, expiration);
}
/**
* @notice the next request count to be used in generating a nonce
* @dev starts at 1 in order to ensure consistent gas cost
* @return returns the next request count to be used in a nonce
*/
function getNextRequestCount() internal view returns (uint256) {
return s_requestCount;
}
/**
* @notice Sets the stored oracle address
* @param oracleAddress The address of the oracle contract
*/
function setChainlinkOracle(address oracleAddress) internal {
s_oracle = OperatorInterface(oracleAddress);
}
/**
* @notice Sets the LINK token address
* @param linkAddress The address of the LINK token contract
*/
function setChainlinkToken(address linkAddress) internal {
s_link = LinkTokenInterface(linkAddress);
}
/**
* @notice Sets the Chainlink token address for the public
* network as given by the Pointer contract
*/
function setPublicChainlinkToken() internal {
setChainlinkToken(PointerInterface(LINK_TOKEN_POINTER).getAddress());
}
/**
* @notice Retrieves the stored address of the LINK token
* @return The address of the LINK token
*/
function chainlinkTokenAddress() internal view returns (address) {
return address(s_link);
}
/**
* @notice Retrieves the stored address of the oracle contract
* @return The address of the oracle contract
*/
function chainlinkOracleAddress() internal view returns (address) {
return address(s_oracle);
}
/**
* @notice Allows for a request which was created on another contract to be fulfilled
* on this contract
* @param oracleAddress The address of the oracle contract that will fulfill the request
* @param requestId The request ID used for the response
*/
function addChainlinkExternalRequest(address oracleAddress, bytes32 requestId) internal notPendingRequest(requestId) {
s_pendingRequests[requestId] = oracleAddress;
}
/**
* @notice Sets the stored oracle and LINK token contracts with the addresses resolved by ENS
* @dev Accounts for subnodes having different resolvers
* @param ensAddress The address of the ENS contract
* @param node The ENS node hash
*/
function useChainlinkWithENS(address ensAddress, bytes32 node) internal {
s_ens = ENSInterface(ensAddress);
s_ensNode = node;
bytes32 linkSubnode = keccak256(abi.encodePacked(s_ensNode, ENS_TOKEN_SUBNAME));
ENSResolver_Chainlink resolver = ENSResolver_Chainlink(s_ens.resolver(linkSubnode));
setChainlinkToken(resolver.addr(linkSubnode));
updateChainlinkOracleWithENS();
}
/**
* @notice Sets the stored oracle contract with the address resolved by ENS
* @dev This may be called on its own as long as `useChainlinkWithENS` has been called previously
*/
function updateChainlinkOracleWithENS() internal {
bytes32 oracleSubnode = keccak256(abi.encodePacked(s_ensNode, ENS_ORACLE_SUBNAME));
ENSResolver_Chainlink resolver = ENSResolver_Chainlink(s_ens.resolver(oracleSubnode));
setChainlinkOracle(resolver.addr(oracleSubnode));
}
/**
* @notice Ensures that the fulfillment is valid for this contract
* @dev Use if the contract developer prefers methods instead of modifiers for validation
* @param requestId The request ID for fulfillment
*/
function validateChainlinkCallback(bytes32 requestId)
internal
recordChainlinkFulfillment(requestId)
// solhint-disable-next-line no-empty-blocks
{
}
/**
* @dev Reverts if the sender is not the oracle of the request.
* Emits ChainlinkFulfilled event.
* @param requestId The request ID for fulfillment
*/
modifier recordChainlinkFulfillment(bytes32 requestId) {
require(msg.sender == s_pendingRequests[requestId], "Source must be the oracle of the request");
delete s_pendingRequests[requestId];
emit ChainlinkFulfilled(requestId);
_;
}
/**
* @dev Reverts if the request is already pending
* @param requestId The request ID for fulfillment
*/
modifier notPendingRequest(bytes32 requestId) {
require(s_pendingRequests[requestId] == address(0), "Request is already pending");
_;
}
}
// File contracts/Math/BokkyPooBahsDateTimeLibrary.sol
// ----------------------------------------------------------------------------
// BokkyPooBah's DateTime Library v1.01
//
// A gas-efficient Solidity date and time library
//
// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary
//
// Tested date range 1970/01/01 to 2345/12/31
//
// Conventions:
// Unit | Range | Notes
// :-------- |:-------------:|:-----
// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC
// year | 1970 ... 2345 |
// month | 1 ... 12 |
// day | 1 ... 31 |
// hour | 0 ... 23 |
// minute | 0 ... 59 |
// second | 0 ... 59 |
// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday
//
//
// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.
// ----------------------------------------------------------------------------
library BokkyPooBahsDateTimeLibrary {
uint constant SECONDS_PER_DAY = 24 * 60 * 60;
uint constant SECONDS_PER_HOUR = 60 * 60;
uint constant SECONDS_PER_MINUTE = 60;
int constant OFFSET19700101 = 2440588;
uint constant DOW_MON = 1;
uint constant DOW_TUE = 2;
uint constant DOW_WED = 3;
uint constant DOW_THU = 4;
uint constant DOW_FRI = 5;
uint constant DOW_SAT = 6;
uint constant DOW_SUN = 7;
// ------------------------------------------------------------------------
// Calculate the number of days from 1970/01/01 to year/month/day using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and subtracting the offset 2440588 so that 1970/01/01 is day 0
//
// days = day
// - 32075
// + 1461 * (year + 4800 + (month - 14) / 12) / 4
// + 367 * (month - 2 - (month - 14) / 12 * 12) / 12
// - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4
// - offset
// ------------------------------------------------------------------------
function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) {
require(year >= 1970);
int _year = int(year);
int _month = int(month);
int _day = int(day);
int __days = _day
- 32075
+ 1461 * (_year + 4800 + (_month - 14) / 12) / 4
+ 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12
- 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4
- OFFSET19700101;
_days = uint(__days);
}
// ------------------------------------------------------------------------
// Calculate year/month/day from the number of days since 1970/01/01 using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and adding the offset 2440588 so that 1970/01/01 is day 0
//
// int L = days + 68569 + offset
// int N = 4 * L / 146097
// L = L - (146097 * N + 3) / 4
// year = 4000 * (L + 1) / 1461001
// L = L - 1461 * year / 4 + 31
// month = 80 * L / 2447
// dd = L - 2447 * month / 80
// L = month / 11
// month = month + 2 - 12 * L
// year = 100 * (N - 49) + year + L
// ------------------------------------------------------------------------
function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) {
int __days = int(_days);
int L = __days + 68569 + OFFSET19700101;
int N = 4 * L / 146097;
L = L - (146097 * N + 3) / 4;
int _year = 4000 * (L + 1) / 1461001;
L = L - 1461 * _year / 4 + 31;
int _month = 80 * L / 2447;
int _day = L - 2447 * _month / 80;
L = _month / 11;
_month = _month + 2 - 12 * L;
_year = 100 * (N - 49) + _year + L;
year = uint(_year);
month = uint(_month);
day = uint(_day);
}
function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) {
timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY;
}
function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) {
timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second;
}
function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) {
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) {
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
uint secs = timestamp % SECONDS_PER_DAY;
hour = secs / SECONDS_PER_HOUR;
secs = secs % SECONDS_PER_HOUR;
minute = secs / SECONDS_PER_MINUTE;
second = secs % SECONDS_PER_MINUTE;
}
function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) {
if (year >= 1970 && month > 0 && month <= 12) {
uint daysInMonth = _getDaysInMonth(year, month);
if (day > 0 && day <= daysInMonth) {
valid = true;
}
}
}
function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) {
if (isValidDate(year, month, day)) {
if (hour < 24 && minute < 60 && second < 60) {
valid = true;
}
}
}
function isLeapYear(uint timestamp) internal pure returns (bool leapYear) {
(uint year,,) = _daysToDate(timestamp / SECONDS_PER_DAY);
leapYear = _isLeapYear(year);
}
function _isLeapYear(uint year) internal pure returns (bool leapYear) {
leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
function isWeekDay(uint timestamp) internal pure returns (bool weekDay) {
weekDay = getDayOfWeek(timestamp) <= DOW_FRI;
}
function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) {
weekEnd = getDayOfWeek(timestamp) >= DOW_SAT;
}
function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) {
(uint year, uint month,) = _daysToDate(timestamp / SECONDS_PER_DAY);
daysInMonth = _getDaysInMonth(year, month);
}
function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) {
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
daysInMonth = 31;
} else if (month != 2) {
daysInMonth = 30;
} else {
daysInMonth = _isLeapYear(year) ? 29 : 28;
}
}
// 1 = Monday, 7 = Sunday
function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) {
uint _days = timestamp / SECONDS_PER_DAY;
dayOfWeek = (_days + 3) % 7 + 1;
}
function getYear(uint timestamp) internal pure returns (uint year) {
(year,,) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getMonth(uint timestamp) internal pure returns (uint month) {
(,month,) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getDay(uint timestamp) internal pure returns (uint day) {
(,,day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getHour(uint timestamp) internal pure returns (uint hour) {
uint secs = timestamp % SECONDS_PER_DAY;
hour = secs / SECONDS_PER_HOUR;
}
function getMinute(uint timestamp) internal pure returns (uint minute) {
uint secs = timestamp % SECONDS_PER_HOUR;
minute = secs / SECONDS_PER_MINUTE;
}
function getSecond(uint timestamp) internal pure returns (uint second) {
second = timestamp % SECONDS_PER_MINUTE;
}
function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) {
(uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY);
year += _years;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) {
(uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY);
month += _months;
year += (month - 1) / 12;
month = (month - 1) % 12 + 1;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _days * SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _hours * SECONDS_PER_HOUR;
require(newTimestamp >= timestamp);
}
function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE;
require(newTimestamp >= timestamp);
}
function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _seconds;
require(newTimestamp >= timestamp);
}
function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) {
(uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY);
year -= _years;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) {
(uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY);
uint yearMonth = year * 12 + (month - 1) - _months;
year = yearMonth / 12;
month = yearMonth % 12 + 1;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _days * SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _hours * SECONDS_PER_HOUR;
require(newTimestamp <= timestamp);
}
function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE;
require(newTimestamp <= timestamp);
}
function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _seconds;
require(newTimestamp <= timestamp);
}
function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) {
require(fromTimestamp <= toTimestamp);
(uint fromYear,,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY);
(uint toYear,,) = _daysToDate(toTimestamp / SECONDS_PER_DAY);
_years = toYear - fromYear;
}
function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) {
require(fromTimestamp <= toTimestamp);
(uint fromYear, uint fromMonth,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY);
(uint toYear, uint toMonth,) = _daysToDate(toTimestamp / SECONDS_PER_DAY);
_months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;
}
function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) {
require(fromTimestamp <= toTimestamp);
_days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY;
}
function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) {
require(fromTimestamp <= toTimestamp);
_hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR;
}
function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) {
require(fromTimestamp <= toTimestamp);
_minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE;
}
function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) {
require(fromTimestamp <= toTimestamp);
_seconds = toTimestamp - fromTimestamp;
}
}
// File contracts/Math/BokkyPooBahsDateTimeContract.sol
// ----------------------------------------------------------------------------
// BokkyPooBah's DateTime Library v1.00 - Contract Instance
//
// A gas-efficient Solidity date and time library
//
// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary
//
// Tested date range 1970/01/01 to 2345/12/31
//
// Conventions:
// Unit | Range | Notes
// :-------- |:-------------:|:-----
// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC
// year | 1970 ... 2345 |
// month | 1 ... 12 |
// day | 1 ... 31 |
// hour | 0 ... 23 |
// minute | 0 ... 59 |
// second | 0 ... 59 |
// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday
//
//
// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018.
//
// GNU Lesser General Public License 3.0
// https://www.gnu.org/licenses/lgpl-3.0.en.html
// ----------------------------------------------------------------------------
contract BokkyPooBahsDateTimeContract {
uint public constant SECONDS_PER_DAY = 24 * 60 * 60;
uint public constant SECONDS_PER_HOUR = 60 * 60;
uint public constant SECONDS_PER_MINUTE = 60;
int public constant OFFSET19700101 = 2440588;
uint public constant DOW_MON = 1;
uint public constant DOW_TUE = 2;
uint public constant DOW_WED = 3;
uint public constant DOW_THU = 4;
uint public constant DOW_FRI = 5;
uint public constant DOW_SAT = 6;
uint public constant DOW_SUN = 7;
function _now() public view returns (uint timestamp) {
timestamp = block.timestamp;
}
function _nowDateTime() public view returns (uint year, uint month, uint day, uint hour, uint minute, uint second) {
(year, month, day, hour, minute, second) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(block.timestamp);
}
function _daysFromDate(uint year, uint month, uint day) public pure returns (uint _days) {
return BokkyPooBahsDateTimeLibrary._daysFromDate(year, month, day);
}
function _daysToDate(uint _days) public pure returns (uint year, uint month, uint day) {
return BokkyPooBahsDateTimeLibrary._daysToDate(_days);
}
function timestampFromDate(uint year, uint month, uint day) public pure returns (uint timestamp) {
return BokkyPooBahsDateTimeLibrary.timestampFromDate(year, month, day);
}
function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) public pure returns (uint timestamp) {
return BokkyPooBahsDateTimeLibrary.timestampFromDateTime(year, month, day, hour, minute, second);
}
function timestampToDate(uint timestamp) public pure returns (uint year, uint month, uint day) {
(year, month, day) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp);
}
function timestampToDateTime(uint timestamp) public pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) {
(year, month, day, hour, minute, second) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(timestamp);
}
function isValidDate(uint year, uint month, uint day) public pure returns (bool valid) {
valid = BokkyPooBahsDateTimeLibrary.isValidDate(year, month, day);
}
function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) public pure returns (bool valid) {
valid = BokkyPooBahsDateTimeLibrary.isValidDateTime(year, month, day, hour, minute, second);
}
function isLeapYear(uint timestamp) public pure returns (bool leapYear) {
leapYear = BokkyPooBahsDateTimeLibrary.isLeapYear(timestamp);
}
function _isLeapYear(uint year) public pure returns (bool leapYear) {
leapYear = BokkyPooBahsDateTimeLibrary._isLeapYear(year);
}
function isWeekDay(uint timestamp) public pure returns (bool weekDay) {
weekDay = BokkyPooBahsDateTimeLibrary.isWeekDay(timestamp);
}
function isWeekEnd(uint timestamp) public pure returns (bool weekEnd) {
weekEnd = BokkyPooBahsDateTimeLibrary.isWeekEnd(timestamp);
}
function getDaysInMonth(uint timestamp) public pure returns (uint daysInMonth) {
daysInMonth = BokkyPooBahsDateTimeLibrary.getDaysInMonth(timestamp);
}
function _getDaysInMonth(uint year, uint month) public pure returns (uint daysInMonth) {
daysInMonth = BokkyPooBahsDateTimeLibrary._getDaysInMonth(year, month);
}
function getDayOfWeek(uint timestamp) public pure returns (uint dayOfWeek) {
dayOfWeek = BokkyPooBahsDateTimeLibrary.getDayOfWeek(timestamp);
}
function getYear(uint timestamp) public pure returns (uint year) {
year = BokkyPooBahsDateTimeLibrary.getYear(timestamp);
}
function getMonth(uint timestamp) public pure returns (uint month) {
month = BokkyPooBahsDateTimeLibrary.getMonth(timestamp);
}
function getDay(uint timestamp) public pure returns (uint day) {
day = BokkyPooBahsDateTimeLibrary.getDay(timestamp);
}
function getHour(uint timestamp) public pure returns (uint hour) {
hour = BokkyPooBahsDateTimeLibrary.getHour(timestamp);
}
function getMinute(uint timestamp) public pure returns (uint minute) {
minute = BokkyPooBahsDateTimeLibrary.getMinute(timestamp);
}
function getSecond(uint timestamp) public pure returns (uint second) {
second = BokkyPooBahsDateTimeLibrary.getSecond(timestamp);
}
function addYears(uint timestamp, uint _years) public pure returns (uint newTimestamp) {
newTimestamp = BokkyPooBahsDateTimeLibrary.addYears(timestamp, _years);
}
function addMonths(uint timestamp, uint _months) public pure returns (uint newTimestamp) {
newTimestamp = BokkyPooBahsDateTimeLibrary.addMonths(timestamp, _months);
}
function addDays(uint timestamp, uint _days) public pure returns (uint newTimestamp) {
newTimestamp = BokkyPooBahsDateTimeLibrary.addDays(timestamp, _days);
}
function addHours(uint timestamp, uint _hours) public pure returns (uint newTimestamp) {
newTimestamp = BokkyPooBahsDateTimeLibrary.addHours(timestamp, _hours);
}
function addMinutes(uint timestamp, uint _minutes) public pure returns (uint newTimestamp) {
newTimestamp = BokkyPooBahsDateTimeLibrary.addMinutes(timestamp, _minutes);
}
function addSeconds(uint timestamp, uint _seconds) public pure returns (uint newTimestamp) {
newTimestamp = BokkyPooBahsDateTimeLibrary.addSeconds(timestamp, _seconds);
}
function subYears(uint timestamp, uint _years) public pure returns (uint newTimestamp) {
newTimestamp = BokkyPooBahsDateTimeLibrary.subYears(timestamp, _years);
}
function subMonths(uint timestamp, uint _months) public pure returns (uint newTimestamp) {
newTimestamp = BokkyPooBahsDateTimeLibrary.subMonths(timestamp, _months);
}
function subDays(uint timestamp, uint _days) public pure returns (uint newTimestamp) {
newTimestamp = BokkyPooBahsDateTimeLibrary.subDays(timestamp, _days);
}
function subHours(uint timestamp, uint _hours) public pure returns (uint newTimestamp) {
newTimestamp = BokkyPooBahsDateTimeLibrary.subHours(timestamp, _hours);
}
function subMinutes(uint timestamp, uint _minutes) public pure returns (uint newTimestamp) {
newTimestamp = BokkyPooBahsDateTimeLibrary.subMinutes(timestamp, _minutes);
}
function subSeconds(uint timestamp, uint _seconds) public pure returns (uint newTimestamp) {
newTimestamp = BokkyPooBahsDateTimeLibrary.subSeconds(timestamp, _seconds);
}
function diffYears(uint fromTimestamp, uint toTimestamp) public pure returns (uint _years) {
_years = BokkyPooBahsDateTimeLibrary.diffYears(fromTimestamp, toTimestamp);
}
function diffMonths(uint fromTimestamp, uint toTimestamp) public pure returns (uint _months) {
_months = BokkyPooBahsDateTimeLibrary.diffMonths(fromTimestamp, toTimestamp);
}
function diffDays(uint fromTimestamp, uint toTimestamp) public pure returns (uint _days) {
_days = BokkyPooBahsDateTimeLibrary.diffDays(fromTimestamp, toTimestamp);
}
function diffHours(uint fromTimestamp, uint toTimestamp) public pure returns (uint _hours) {
_hours = BokkyPooBahsDateTimeLibrary.diffHours(fromTimestamp, toTimestamp);
}
function diffMinutes(uint fromTimestamp, uint toTimestamp) public pure returns (uint _minutes) {
_minutes = BokkyPooBahsDateTimeLibrary.diffMinutes(fromTimestamp, toTimestamp);
}
function diffSeconds(uint fromTimestamp, uint toTimestamp) public pure returns (uint _seconds) {
_seconds = BokkyPooBahsDateTimeLibrary.diffSeconds(fromTimestamp, toTimestamp);
}
}
// File contracts/Staking/Owned.sol
// https://docs.synthetix.io/contracts/Owned
contract Owned {
address public owner;
address public nominatedOwner;
constructor (address _owner) public {
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
function nominateNewOwner(address _owner) external onlyOwner {
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
function acceptOwnership() external {
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner {
require(msg.sender == owner, "Only the contract owner may perform this action");
_;
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
// File contracts/Oracle/CPITrackerOracle.sol
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ========================= CPITrackerOracle =========================
// ====================================================================
// Pull in CPI data and track it in 2022 dollars
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Reviewer(s) / Contributor(s)
// Sam Kazemian: https://github.com/samkazemian
// Rich Gee: https://github.com/zer0blockchain
// Dennis: https://github.com/denett
// References
// https://docs.chain.link/docs/make-a-http-get-request/#api-consumer-example
contract CPITrackerOracle is Owned, ChainlinkClient {
using Chainlink for Chainlink.Request;
// Core
BokkyPooBahsDateTimeContract public time_contract;
address public timelock_address;
address public bot_address;
// Data
uint256 public price_starting_dollars = 1e18;
uint256 public stored_result = 27880200000; // Dec 2021 CPI-U, 278.802 * 100000000
// Chainlink
address public oracle;
bytes32 public jobId;
uint256 public fee;
// Tracking
uint256 public stored_year = 2021;
uint256 public stored_month = 12;
uint256 public lastUpdateTime;
// Misc
string[13] public month_names;
// Constants
uint256 public constant RESULT_MULTIPLIER = 100000000;
/* ========== MODIFIERS ========== */
modifier onlyByOwnGov() {
require(msg.sender == owner || msg.sender == timelock_address, "Not owner or timelock");
_;
}
modifier onlyByOwnGovBot() {
require(msg.sender == owner || msg.sender == timelock_address || msg.sender == bot_address, "Not owner, tlck, or bot");
_;
}
/* ========== CONSTRUCTOR ========== */
constructor (
address _creator_address,
address _timelock_address
) Owned(_creator_address) {
timelock_address = _timelock_address;
// Initialize the array. Cannot be done in the declaration
month_names = [
'',
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
];
// CPI [Ethereum]
// =================================
setPublicChainlinkToken();
time_contract = BokkyPooBahsDateTimeContract(0x90503D86E120B3B309CEBf00C2CA013aB3624736);
oracle = 0x049Bd8C3adC3fE7d3Fc2a44541d955A537c2A484;
jobId = "74295b9df3264781bf904d9e596a2e57";
fee = 1e18; // 1 LINK
// CPI [Polygon Mainnet]
// =================================
// setChainlinkToken(0x53E0bca35eC356BD5ddDFebbD1Fc0fD03FaBad39);
// time_contract = BokkyPooBahsDateTimeContract(0x998da4fCB229Db1AA84395ef6f0c6be6Ef3dbE58);
// oracle = 0x9B44870bcc35734c08e40F847cC068c0bA618194;
// jobId = "8107f18343a24980b2fe7d3c8f32630f";
// fee = 1e17; // 0.1 LINK
// CPI [Polygon Mumbai]
// =================================
// setChainlinkToken(0x326C977E6efc84E512bB9C30f76E30c160eD06FB);
// time_contract = BokkyPooBahsDateTimeContract(0x0000000000000000000000000000000000000000);
// oracle = 0x3c30c5c415B2410326297F0f65f5Cbb32f3aefCc;
// jobId = "32c3e7b12fe44665a4e2bb87aa9779af";
// fee = 1e17; // 0.1 LINK
}
/* ========== VIEWS ========== */
function upcomingCPIParams() public view returns (
uint256 upcoming_year,
uint256 upcoming_month,
uint256 upcoming_timestamp
) {
if (stored_month == 12) {
upcoming_year = stored_year + 1;
upcoming_month = 1;
}
else {
upcoming_year = stored_year;
upcoming_month = stored_month + 1;
}
// Data is usually released by the 15th day of the next month
// https://www.usinflationcalculator.com/inflation/consumer-price-index-release-schedule/
upcoming_timestamp = time_contract.timestampFromDate(upcoming_year, upcoming_month, 15);
}
function lastPrice() public view returns (uint256) {
return price_starting_dollars;
}
function lastIndex() public view returns (uint256) {
return stored_result;
}
/* ========== MUTATIVE ========== */
function requestCPIData() public onlyByOwnGovBot returns (bytes32 requestId)
{
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
// Get the upcoming CPI params
(uint256 upcoming_year, uint256 upcoming_month, uint256 upcoming_timestamp) = upcomingCPIParams();
// Don't update too fast
require(block.timestamp >= upcoming_timestamp, "Too early");
request.add("serie", "CUSR0000SA0"); // CPI-U: https://data.bls.gov/timeseries/CUSR0000SA0
request.add("month", month_names[upcoming_month]);
request.add("year", Strings.toString(upcoming_year));
return sendChainlinkRequestTo(oracle, request, fee);
}
/**
* Callback function
*/
function fulfill(bytes32 _requestId, uint256 result) public recordChainlinkFulfillment(_requestId)
{
// Update the starting dollars amount
price_starting_dollars = (price_starting_dollars * result) / stored_result;
// Update the raw result
stored_result = result;
// Update the timestamp
lastUpdateTime = block.timestamp;
// Update the year and month
(uint256 result_year, uint256 result_month, ) = upcomingCPIParams();
stored_year = result_year;
stored_month = result_month;
emit CPIUpdated(result_year, result_month, result, price_starting_dollars);
}
/* ========== RESTRICTED FUNCTIONS ========== */
function setTimelock(address _new_timelock_address) external onlyByOwnGov {
timelock_address = _new_timelock_address;
}
function setBot(address _new_bot_address) external onlyByOwnGov {
bot_address = _new_bot_address;
}
/* ========== EVENTS ========== */
event CPIUpdated(uint256 year, uint256 month, uint256 result, uint256 price_starting_dollars);
} | Data is usually released by the 15th day of the next month https:www.usinflationcalculator.com/inflation/consumer-price-index-release-schedule/ | upcoming_timestamp = time_contract.timestampFromDate(upcoming_year, upcoming_month, 15);
| 13,755,931 | [
1,
751,
353,
11234,
15976,
635,
326,
4711,
451,
2548,
434,
326,
1024,
3138,
2333,
30,
5591,
18,
407,
267,
2242,
367,
12780,
639,
18,
832,
19,
267,
2242,
367,
19,
13230,
17,
8694,
17,
1615,
17,
9340,
17,
10676,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
731,
5522,
67,
5508,
273,
813,
67,
16351,
18,
5508,
1265,
1626,
12,
416,
5522,
67,
6874,
16,
731,
5522,
67,
7496,
16,
4711,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/4/0x81129272624Ee080669df4c9dfc4e6E9e19644E1/sources/browser/Untitled.sol | Set the symbol for display purposes
| symbol = "TNT"; | 783,865 | [
1,
694,
326,
3273,
364,
2562,
13694,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
3273,
273,
315,
56,
1784,
14432,
27573,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0xb1B79A8A5729DbBF91CBC1dc135B588e36009B17/sources/contracts/WAYSPACE.sol | ,-. ,-. ,-. `-' `-' `-' /|\ /|\ /|\ | | | ,----------. / \ / \ / \ |ERC721Drop| Caller FeeRecipient FundsRecipient `----+-----' | | withdraw() | | | -------------------------------------------------------------------------> | | | | | | | | ________________________________________________________________________________________________________ ! ALT / caller is not admin or manager? | | ! !_____/ | | | | ! ! | revert Access_WithdrawNotAllowed() | ! ! | <------------------------------------------------------------------------- ! !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! !~[noop]~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! | | | | | | send fee amount | | | <---------------------------------------------------- | | | | | | | | | | | ____________________________________________________________ | | | ! ALT / send unsuccesful? ! | | | !_____/ | ! | | | ! |----. ! | | | ! | | revert Withdraw_FundsSendFailure() ! | | | ! |<---' ! | | | !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! | | | !~[noop]~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! | | | | | | | send remaining funds amount| | | | <--------------------------- | | | | | | | | | | | ____________________________________________________________ | | | ! ALT / send unsuccesful? ! | | | !_____/ | ! | | | ! |----. ! | | | ! | | revert Withdraw_FundsSendFailure() ! | | | ! |<---' ! | | | !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! | | | !~[noop]~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! Caller FeeRecipient FundsRecipient ,----+-----. ,-. ,-. ,-. |ERC721Drop| `-' `-' `-' `----------' /|\ /|\ /|\ | | | / \ / \ / \ @notice This withdraws ETH from the contract to the contract owner. Payout recipient | function withdraw() external nonReentrant {
address sender = _msgSender();
uint256 funds = address(this).balance;
if (
!hasRole(DEFAULT_ADMIN_ROLE, sender) &&
!hasRole(SALES_MANAGER_ROLE, sender) &&
sender != config.fundsRecipient
) {
revert Access_WithdrawNotAllowed();
}
(bool successFunds, ) = config.fundsRecipient.call{
value: funds,
gas: FUNDS_SEND_GAS_LIMIT
}("");
if (!successFunds) {
revert Withdraw_FundsSendFailure();
}
}
| 858,154 | [
1,
16,
17,
18,
5375,
269,
17,
18,
8227,
269,
17,
18,
15604,
1375,
6627,
5375,
1375,
6627,
8227,
1375,
6627,
15604,
342,
8960,
5375,
342,
8960,
8227,
342,
8960,
13491,
571,
10792,
571,
13491,
571,
8227,
269,
15392,
18,
15604,
342,
521,
5375,
342,
521,
8227,
342,
521,
5397,
571,
654,
39,
27,
5340,
7544,
96,
5397,
20646,
5411,
30174,
18241,
5411,
478,
19156,
18241,
7734,
1375,
553,
15,
553,
6627,
15604,
571,
10792,
571,
6647,
598,
9446,
1435,
282,
571,
18701,
571,
15604,
571,
8879,
788,
34,
15604,
571,
10792,
571,
13491,
571,
18701,
571,
15604,
571,
10792,
571,
13491,
571,
18701,
571,
1850,
389,
21157,
21157,
21157,
21157,
21157,
21157,
7198,
31268,
1850,
401,
30939,
225,
342,
225,
4894,
353,
486,
3981,
578,
3301,
35,
5375,
571,
18701,
571,
9079,
401,
1850,
401,
7198,
67,
19,
1377,
571,
10792,
571,
13491,
571,
18701,
571,
9079,
401,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
565,
445,
598,
9446,
1435,
3903,
1661,
426,
8230,
970,
288,
203,
3639,
1758,
5793,
273,
389,
3576,
12021,
5621,
203,
3639,
2254,
5034,
284,
19156,
273,
1758,
12,
2211,
2934,
12296,
31,
203,
203,
3639,
309,
261,
203,
5411,
401,
5332,
2996,
12,
5280,
67,
15468,
67,
16256,
16,
5793,
13,
597,
203,
5411,
401,
5332,
2996,
12,
5233,
11386,
67,
19402,
67,
16256,
16,
5793,
13,
597,
203,
5411,
5793,
480,
642,
18,
74,
19156,
18241,
203,
3639,
262,
288,
203,
5411,
15226,
5016,
67,
1190,
9446,
19354,
5621,
203,
3639,
289,
203,
203,
3639,
261,
6430,
2216,
42,
19156,
16,
262,
273,
642,
18,
74,
19156,
18241,
18,
1991,
95,
203,
5411,
460,
30,
284,
19156,
16,
203,
5411,
16189,
30,
478,
2124,
3948,
67,
21675,
67,
43,
3033,
67,
8283,
203,
3639,
289,
2932,
8863,
203,
3639,
309,
16051,
4768,
42,
19156,
13,
288,
203,
5411,
15226,
3423,
9446,
67,
42,
19156,
3826,
5247,
5621,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xf8C252D2d9CC62cAd16ef0A69687f6AE6bFd2617/sources/contracts/token/QWA.sol | @dev PRIVATE function to swap `ethTokenAmount` for ETH @dev Invoked in `swapBack()` | function swapTokens(
uint256 ethTokenAmount,
uint256 totalTokensToSwap
) private returns (uint256 ethBalance_, uint256 ethForBacking_) {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = WETH;
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
ethTokenAmount,
0,
path,
address(this),
block.timestamp
);
ethBalance_ = address(this).balance;
ethForBacking_ = (ethBalance_ * tokensForBacking) / (totalTokensToSwap - tokensForLiquidity / 2);
address backingToken = backingTokens[backingSwapping];
if (backingToken == WETH) {
IERC20(WETH).transfer(treasury, ethForBacking_);
if (backingTokensV3Fee[backingSwapping] == 0) {
path[0] = WETH;
path[1] = backingToken;
0,
path,
treasury,
block.timestamp
);
IUniswapV3Router.ExactInputSingleParams memory params = IUniswapV3Router.ExactInputSingleParams({
tokenIn: WETH,
tokenOut: backingToken,
fee: backingTokensV3Fee[backingSwapping],
recipient: treasury,
deadline: block.timestamp,
amountIn: ethForBacking_,
amountOutMinimum: 0,
sqrtPriceLimitX96: 0
});
}
}
if (backingSwapping == backingTokens.length - 1) backingSwapping = 0;
else ++backingSwapping;
}
| 4,908,992 | [
1,
20055,
445,
358,
7720,
1375,
546,
1345,
6275,
68,
364,
512,
2455,
225,
5454,
14276,
316,
1375,
22270,
2711,
20338,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7720,
5157,
12,
203,
3639,
2254,
5034,
13750,
1345,
6275,
16,
203,
3639,
2254,
5034,
2078,
5157,
774,
12521,
203,
565,
262,
3238,
1135,
261,
11890,
5034,
13750,
13937,
67,
16,
2254,
5034,
13750,
1290,
2711,
310,
67,
13,
288,
203,
3639,
1758,
8526,
3778,
589,
273,
394,
1758,
8526,
12,
22,
1769,
203,
3639,
589,
63,
20,
65,
273,
1758,
12,
2211,
1769,
203,
3639,
589,
63,
21,
65,
273,
678,
1584,
44,
31,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
18,
22270,
14332,
5157,
1290,
1584,
44,
6289,
310,
14667,
1398,
5912,
5157,
12,
203,
5411,
13750,
1345,
6275,
16,
203,
5411,
374,
16,
203,
5411,
589,
16,
203,
5411,
1758,
12,
2211,
3631,
203,
5411,
1203,
18,
5508,
203,
3639,
11272,
203,
203,
3639,
13750,
13937,
67,
273,
1758,
12,
2211,
2934,
12296,
31,
203,
203,
3639,
13750,
1290,
2711,
310,
67,
273,
261,
546,
13937,
67,
380,
2430,
1290,
2711,
310,
13,
342,
261,
4963,
5157,
774,
12521,
300,
2430,
1290,
48,
18988,
24237,
342,
576,
1769,
203,
203,
3639,
1758,
15394,
1345,
273,
15394,
5157,
63,
823,
310,
12521,
1382,
15533,
203,
203,
3639,
309,
261,
823,
310,
1345,
422,
678,
1584,
44,
13,
288,
203,
5411,
467,
654,
39,
3462,
12,
59,
1584,
44,
2934,
13866,
12,
27427,
345,
22498,
16,
13750,
1290,
2711,
310,
67,
1769,
203,
5411,
309,
261,
823,
310,
5157,
58,
23,
14667,
63,
823,
310,
12521,
1382,
65,
422,
374,
13,
288,
203,
7734,
589,
63,
20,
65,
273,
2
] |
./partial_match/1/0x7d000609a3c0C6Ba13DD318E56934CB5523Ba431/sources/IERC20.sol | * @dev Interface of the ERC20 standard as defined in the EIP./ | interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
pragma solidity ~0.8.0;
}
| 4,344,236 | [
1,
1358,
434,
326,
4232,
39,
3462,
4529,
487,
2553,
316,
326,
512,
2579,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5831,
467,
654,
39,
3462,
288,
203,
565,
445,
2078,
3088,
1283,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
11013,
951,
12,
2867,
2236,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
7412,
12,
2867,
8027,
16,
2254,
5034,
3844,
13,
3903,
1135,
261,
6430,
1769,
203,
203,
565,
445,
1699,
1359,
12,
2867,
3410,
16,
1758,
17571,
264,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
6617,
537,
12,
2867,
17571,
264,
16,
2254,
5034,
3844,
13,
3903,
1135,
261,
6430,
1769,
203,
203,
565,
445,
7412,
1265,
12,
2867,
5793,
16,
1758,
8027,
16,
2254,
5034,
3844,
13,
3903,
1135,
261,
6430,
1769,
203,
203,
565,
871,
12279,
12,
2867,
8808,
628,
16,
1758,
8808,
358,
16,
2254,
5034,
460,
1769,
203,
203,
565,
871,
1716,
685,
1125,
12,
2867,
8808,
3410,
16,
1758,
8808,
17571,
264,
16,
2254,
5034,
460,
1769,
203,
683,
9454,
18035,
560,
4871,
20,
18,
28,
18,
20,
31,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.8;
/**
*
* Manages data storage for a single CypherPoker hand (round), and provides some publicly-available utility functions.
*
* (C)opyright 2016
*
* This source code is protected by copyright and distributed under license.
* Please see the root LICENSE file for terms and conditions.
*
*/
contract PokerHandData {
//Single card definition including card's sorting index within the entire deck (1-52), suit value (0 to 3), and value (1 to 13 or 14 if aces are high)
struct Card {
uint index;
uint suit;
uint value;
}
//A group of Card structs.
struct CardGroup {
Card[] cards;
}
//Encryption / decryption key definition including the encryption key, decryption key, and prime modulus.
struct Key {
uint256 encKey;
uint256 decKey;
uint256 prime;
}
address public owner; //the contract's owner / publisher
address[] public authorizedGameContracts; //the "PokerHand*" contracts exclusively authorized to make changes in this contract's data. This value may only be changed when initReady is ready.
uint public numAuthorizedContracts; //set when authorizedGameContracts is set
address[] public players; //players, in order of play, who must agree to contract before game play may begin; the last player is the dealer, player 1 (index 0) is small blind, player 2 (index 2) is the big blind
uint256 public buyIn; //buy-in value, in wei, required in order to agree to the contract
mapping (address => bool) public agreed; //true for all players who agreed to this contract; only players in "players" struct may agree
uint256 public prime; //shared prime modulus
uint256 public baseCard; //base or first plaintext card in the deck (all subsequent cards are quadratic residues modulo prime)
mapping (address => uint256) public playerBets; //stores cumulative bets per betting round (reset before next)
mapping (address => uint256) public playerChips; //the players' chips, wallets, or purses on which players draw on to make bets, currently equivalent to the wei value sent to the contract.
mapping (address => bool) public playerHasBet; //true if the player has placed a bet during the current active betting round (since bets of 0 are valid)
bool public bigBlindHasBet; //set to true after initial big blind commitment in order to allow big blind to raise during first round
uint256 public pot; //total cumulative pot for hand
uint public betPosition; //current betting player index (in players array)
mapping (address => uint256[52]) public encryptedDeck; //incrementally encrypted decks; deck of players[players.length-1] is the final encrypted deck
mapping (address => uint256[2]) public privateCards; //selected encrypted private/hole cards per player
struct DecryptPrivateCardsStruct {
address sourceAddr; //the source player providing the partially decrypted cards
address targetAddr; //the target player for whom the partially decrypted cards are intended
uint256[2] cards; //the two partially decrypted private/hole cards
}
DecryptPrivateCardsStruct[] public privateDecryptCards; //stores partially decrypted private/hole cards for players
uint256[5] public publicCards; //selected encrypted public cards
mapping (address => uint256[5]) public publicDecryptCards; //stores partially decrypted public/community cards
mapping (address => Key[]) public playerKeys; //players' crypto keypairs
//Indexes to the cards comprising the players' best hands. Indexes 0 and 1 are the players' private cards and 2 to 6 are indexes
//of public cards. All five values are supplied during teh final L1Validate call and must be unique and be in the range 0 to 6 in order to be valid.
mapping (address => uint[5]) public playerBestHands;
mapping (address => Card[]) public playerCards; //final decrypted cards for players (as generated from playerBestHands)
mapping (address => uint256) public results; //hand ranks per player or numeric score representing actions (1=fold lost, 2=fold win, 3=concede loss, 4=concede win, otherwise hand score)
mapping (address => address) public declaredWinner; //address of the self-declared winner of the contract (may be challenged)
address[] public winner; //address of the hand's/contract's resolved or actual winner(s)
uint public lastActionBlock; //block number of the last valid player action that was committed. This value is set to the current block on every new valid action.
uint public timeoutBlocks; //the number of blocks that may elapse before the next valid player's (lack of) action is considered to have timed out
uint public initBlock; //the block number on which the "initialize" function was called; used to validate signed transactions
mapping (address => uint) public nonces; //unique nonces used per contract to ensure that signed transactions aren't re-used
mapping (address => uint) public validationIndex; //highest successfully completed validation index for each player
address public challenger; //the address of the current contract challenger / validation initiator
bool public complete; //contract is completed.
bool public initReady; //contract is ready for initialization call (all data reset)
/**
* Phase values:
* 0 - Agreement (not all players have agreed to contract yet)contract
* 1 - Encrypted deck storage (all players have agreed to contract)
* 2 - Private/hole cards selection
* 3 - Interim private cards decryption
* 4 - Betting
* 5 - Flop cards selection
* 6 - Interim flop cards decryption
* 7 - Betting
* 8 - Turn card selection
* 9 - Interim turn card decryption
* 10 - Betting
* 11 - River card selection
* 12 - Interim river card decryption
* 13 - Betting
* 14 - Declare winner
* 15 - Resolution
* 16 - Level 1 challenge - submit crypto keys
* 17 - Level 2 challenge - full contract verification
* 18 - Payout / hand complete
* 19 - Mid-game challenge
* 20 - Hand complete (unchallenged / signed contract game)
* 21 - Contract complete (unchallenged / signed contract game)
*/
mapping (address => uint8) public phases;
/**
* Contract constructor.
*/
constructor() public {
owner = msg.sender;
complete = true;
initReady = true; //ready for initialize
}
/**
* Modifier for functions to allow access only by addresses contained in the "authorizedGameContracts" array.
*/
modifier onlyAuthorized {
uint allowedContractsFound = 0;
for (uint count=0; count<authorizedGameContracts.length; count++) {
if (msg.sender == authorizedGameContracts[count]) {
allowedContractsFound++;
}
}
if (allowedContractsFound == 0) {
revert();
}
_;
}
/**
* Anonymous fallback function.
*/
function () external {
revert();
}
/*
* Sets the "agreed" flag to true for the transaction sender. Only accounts registered during the "initialize"
* call are allowed to agree. Once all valid players have agreed the block timeout is started and the next
* player must commit the next valid action before the timeout has elapsed.
*
* The value sent with this function invocation must equal the "buyIn" value (wei) exactly, otherwise
* an exception is thrown and any included value is refunded. Only when the buy-in value is matched exactly
* will the "agreed" flag for the player be set and the phase updated to 1.
*
* @param nonce A unique nonce to store for the player for this contract. This value must not be re-used until the contract is closed
* and paid-out in order to prevent re-use of signed transactions.
*/
function agreeToContract(uint256 nonce) payable public {
bool found = false;
for (uint count=0; count<players.length; count++) {
if (msg.sender == players[count]) {
found = true;
}
}
if (found == false) {
revert();
}
if (playerChips[msg.sender] == 0) {
if (msg.value != buyIn) {
revert();
}
//include additional validation deposit calculations here if desired
playerChips[msg.sender] = msg.value;
}
agreed[msg.sender]=true;
phases[msg.sender]=1;
playerBets[msg.sender] = 0;
playerHasBet[msg.sender] = false;
validationIndex[msg.sender] = 0;
nonces[msg.sender] = nonce;
}
/**
* Initializes the data contract.
*
* @param primeVal The shared prime modulus on which plaintext card values are based and from which encryption/decryption keys are derived.
* @param baseCardVal The value of the base or first card of the plaintext deck. The next 51 ascending quadratic residues modulo primeVal are assumed to
* comprise the remainder of the deck (see "getCardIndex" for calculations).
* @param buyInVal The exact per-player buy-in value, in wei, that must be sent when agreeing to the contract. Must be greater than 0.
* @param timeoutBlocksVal The number of blocks that elapse between the current block and lastActionBlock before the current valid player is
* considered to have timed / dropped out if they haven't committed a valid action. A minimum of 2 blocks (roughly 24 seconds), is imposed but
* a slightly higher value is highly recommended.
*
*/
function initialize(uint256 primeVal, uint256 baseCardVal, uint256 buyInVal, uint timeoutBlocksVal) public onlyAuthorized {
prime = primeVal;
baseCard = baseCardVal;
buyIn = buyInVal;
timeoutBlocks = timeoutBlocksVal;
initBlock = block.number;
initReady = false;
}
/**
* Accesses partially decrypted private/hole cards for a player that has agreed to the contract.
*
* @param sourceAddr The source player that provided the partially decrypted cards for the target.
* @param targetAddr The target player for whom the partially descrypted cards were intended.
* @param cardIndex The index of the card (0 or 1) to retrieve.
*
* @return The partially decrypted private card record found at the specified index for the specified player.
*/
function getPrivateDecryptCard(address sourceAddr, address targetAddr, uint cardIndex) view public returns (uint256) {
for (uint8 count=0; count < privateDecryptCards.length; count++) {
if ((privateDecryptCards[count].sourceAddr == sourceAddr) && (privateDecryptCards[count].targetAddr == targetAddr)) {
return (privateDecryptCards[count].cards[cardIndex]);
}
}
}
/**
* Checks if all valild/agreed players are at a specific game phase.
*
* @param phaseNum The phase number that all agreed players should be at.
*
* @return True if all agreed players are at the specified game phase, false otherwise.
*/
function allPlayersAtPhase(uint phaseNum) public view returns (bool) {
for (uint count=0; count < players.length; count++) {
if (phases[players[count]] != phaseNum) {
return (false);
}
}
return (true);
}
//---------------------------------------------------
// PUBLICLY ACCESSIBLE UTILITY FUNCTIONS
//---------------------------------------------------
/**
* @return The number of players in the 'players' array.
*/
function num_Players() public view returns (uint) {
return (players.length);
}
/**
* @param target The address of the target agreed player for which to retrieve the number of stored keypairs.
*
* @return The number of keypairs stored for the target player address.
*/
function num_Keys(address target) public view returns (uint) {
return (playerKeys[target].length);
}
/**
* @param target The address of the target agreed player for which to retrieve the number of cards in the 'playerCards' array.
*
* @return The number of cards stored for the target player in the 'playerCards' array.
*/
function num_PlayerCards(address target) public view returns (uint) {
return (playerCards[target].length);
}
/**
* @param targetAddr The address of the target agreed player for which to retrieve the number of cards in the 'privateCards' array.
*
* @return The number of cards stored for the target player in the 'privateCards' array.
*/
function num_PrivateCards(address targetAddr) public returns (uint) {
return (DataUtils.arrayLength2(privateCards[targetAddr]));
}
/**
* @return The number of cards stored in the 'publicCards' array.
*/
function num_PublicCards() public returns (uint) {
return (DataUtils.arrayLength5(publicCards));
}
/**
* @param sourceAddr The source or sending address of the player who stored the partially-decrypted private cards for the
* player specified by the 'targetAddr' address.
* @param targetAddr The target address of the player for whom the partially-decrypted cards are being stored by the 'sourceAddr'
* player's address.
*
* @return The number of partially-decrypted private cards stored for the 'targetAddr' player by the 'sourceAddr' player.
*/
function num_PrivateDecryptCards(address sourceAddr, address targetAddr) public returns (uint) {
for (uint8 count=0; count < privateDecryptCards.length; count++) {
if ((privateDecryptCards[count].sourceAddr == sourceAddr) && (privateDecryptCards[count].targetAddr == targetAddr)) {
return (privateDecryptCards[count].cards.length);
}
}
return (0);
}
/**
* @return The number of addresses stored in the 'winner' array.
*/
function num_winner() public returns (uint) {
return (winner.length);
}
/**
* Sets the 'authorizedGameContracts' array to the specified addresses. The 'initReady' and 'complete' flags must
* be trued before this function is invoked otherwise an exception is thrown.
*
* @param contractAddresses An array of addresses that are to be authorized to invoke functions in this contract once it's
* been initialized. Typically these are addresses of external "PokerHand*" contracts but may include standard account
* addresses as well.
*/
function setAuthorizedGameContracts (address[] memory contractAddresses) public {
if ((initReady == false) || (complete == false)) {
revert();
}
authorizedGameContracts=contractAddresses;
numAuthorizedContracts = authorizedGameContracts.length;
}
//---------------------------------------------------
// AUTHORIZED CONTRACT / ADDRESS UTILITY FUNCTIONS
//---------------------------------------------------
/**
* Adds a card for a specific player to the end of the 'playerCards' array.
*
* @param playerAddress The target address of the agreed player for whom to store the card.
* @param index The index value of the card to store.
* @param suit The suit value of the card to store.
* @param value The face value of the card to store.
*/
function add_playerCard(address playerAddress, uint index, uint suit, uint value) public onlyAuthorized {
playerCards[playerAddress].push(Card(index, suit, value));
}
/**
* Updates a card for a specific player within the 'playerCards' array.
*
* @param playerAddress The target address of the agreed player for whom to update the card.
* @param cardIndex The index of the card within the 'playerCards' array for the 'playerAddress' player.
* @param index The index value of the card to update.
* @param suit The suit value of the card to update.
* @param value The face value of the card to update.
*/
function update_playerCard(address playerAddress, uint cardIndex, uint index, uint suit, uint value) public onlyAuthorized {
playerCards[playerAddress][cardIndex].index = index;
playerCards[playerAddress][cardIndex].suit = suit;
playerCards[playerAddress][cardIndex].value = value;
}
/**
* Sets the validation index value for a specific player address.
*
* @param playerAddress The address of the player to set the validation index value for.
* @param index The validation index value to set.
*/
function set_validationIndex(address playerAddress, uint index) public onlyAuthorized {
if (index == 0) {
} else {
validationIndex[playerAddress] = index;
}
}
/**
* Sets or resets a result value for an agreed player in the 'results' array.
*
* @param playerAddress The address of the player to set the result for.
* @param result The result value to set. If 0 the entry is removed from the 'results' array.
*/
function set_result(address playerAddress, uint256 result) public onlyAuthorized {
if (result == 0) {
delete results[playerAddress];
} else {
results[playerAddress] = result;
}
}
/**
* Sets the 'complete' flag value.
*
* @param completeSet The value to set the 'complete' flag to.
*/
function set_complete (bool completeSet) public onlyAuthorized {
complete = completeSet;
}
/**
* Sets a public card value in the 'publicCards' array.
*
* @param card The card value to set.
* @param index The index within the 'publicCards' array to set the value to.
*/
function set_publicCard (uint256 card, uint index) public onlyAuthorized {
publicCards[index] = card;
}
/**
* Adds newly encrypted cards for an address or clears out the 'encryptedDeck' data for the address.
*
* @param fromAddr The target address of the player for which to set the encrypted cdeck values.
* @param cards The array of cards encrypted by the 'fromAddr' player to store in the 'encryptedDeck' array. If this is
* an empty array the elements for the 'fromAddr' player address are cleared from the 'encryptedDeck' array.
*/
function set_encryptedDeck (address fromAddr, uint256[] memory cards) public onlyAuthorized {
if (cards.length == 0) {
/*
for (uint count2=0; count2<52; count2++) {
delete encryptedDeck[fromAddr][count2];
}
*/
delete encryptedDeck[fromAddr];
} else {
for (uint8 count=0; count < cards.length; count++) {
encryptedDeck[fromAddr][DataUtils.arrayLength52(encryptedDeck[fromAddr])] = cards[count];
}
}
}
/**
* Adds or resets private card selection(s) for a player address to the 'privateCards' array.
*
* @param fromAddr The player address for which to add private card selections.
* @param cards The card(s) to add to the 'privateCards' array for the 'fromAddr' player address. If this is an
* empty array the existing elements in 'privateCards' for the 'fromAddr' address are cleared.
*/
function set_privateCards (address fromAddr, uint256[] memory cards) public onlyAuthorized {
if (cards.length == 0) {
for (uint8 count=0; count<2; count++) {
delete privateCards[fromAddr][count];
}
delete privateCards[fromAddr];
for (uint8 count= 0; count<playerCards[fromAddr].length; count++) {
delete playerCards[fromAddr][count];
}
delete playerCards[fromAddr];
} else {
for (uint8 count=0; count<cards.length; count++) {
privateCards[fromAddr][DataUtils.arrayLength2(privateCards[fromAddr])] = cards[count];
}
}
}
/**
* Sets the betting position as an offset within the players array. The current betting player address is 'players[betPosition]'.
*
* @param betPositionVal The bet position value to assign to the 'betPosition' variable.
*/
function set_betPosition (uint betPositionVal) public onlyAuthorized {
betPosition = betPositionVal;
}
/**
* Sets the 'bigBlindHasBet' flag value. When true this flag indicates that at least one complete round of betting has completed.
*
* @param bigBlindHasBetVal The value to assign to the 'bigBlindHasBet' variable.
*
*/
function set_bigBlindHasBet (bool bigBlindHasBetVal) public onlyAuthorized {
bigBlindHasBet = bigBlindHasBetVal;
}
/**
* Sets the 'playerHasBet' flag for a specific agreed player address. When true this flag indicates that the associated player
* has bet during this round of betting.
*
* @param fromAddr The agreed player address to set the 'playerHasBet' flag for.
* @param hasBet The value to assign to the 'playerHasBet' array for the 'fromAddr' player address.
*/
function set_playerHasBet (address fromAddr, bool hasBet) public onlyAuthorized {
playerHasBet[fromAddr] = hasBet;
}
/**
* Sets the bet value for a player in the 'playerBets' array.
*
* @param fromAddr The address of the agreed player for which to set the bet value.
* @param betVal The bet value, in wei, to set for the 'fromAddr' player address.
*/
function set_playerBets (address fromAddr, uint betVal) public onlyAuthorized {
playerBets[fromAddr] = betVal;
}
/**
* Sets the chips value for a player in the 'playerChips' array.
*
* @param forAddr The agreed player address for which to set the chips value.
* @param numChips The number of chips, in wei, to set for the 'forAddr' player address.
*/
function set_playerChips (address forAddr, uint numChips) public onlyAuthorized {
playerChips[forAddr] = numChips;
}
/**
* Sets the 'pot' variable value.
*
* @param potVal The pot value, in wei, to assign to the 'pot' variable.
*/
function set_pot (uint potVal) public onlyAuthorized {
pot = potVal;
}
/**
* Sets the contract agreed value of a player in the 'agreed' array.
*
* @param fromAddr The address of the player for which to set the agreement flag. This player should
* appear in the 'players' array.
* @param agreedVal The value to assign to the 'agreed' array for the 'fromAddr' player address.
*/
function set_agreed (address fromAddr, bool agreedVal) public onlyAuthorized {
agreed[fromAddr] = agreedVal;
}
/**
* Adds a winning player's address to the end of the 'winner' array.
*
* @param winnerAddress The agreed player address to add to the end of the 'winner' array.
*/
function add_winner (address winnerAddress) public onlyAuthorized {
winner.push(winnerAddress);
}
/**
* Clears/resets the contents of the 'winner' array.
*/
function clear_winner () public onlyAuthorized {
winner.length=0;
}
/**
* Sets or resets the 'players' array with the addresses supplied, optionally resetting 'nonces' and 'initReady' values.
*
* @param newPlayers The addresses of the players to assign to the 'players' array. Each of these
* addresses must agree to the contract before a game can begin. If an empty array is supplied, the 'players'
* and 'nonces' arrays are cleared/reset, and the 'initReady' flag is set to true.
*/
function new_players (address[] memory newPlayers) public onlyAuthorized {
if (newPlayers.length == 0) {
for (uint count=0; count<players.length; count++) {
delete nonces[players[count]];
}
}
players = newPlayers;
if (newPlayers.length == 0) {
initReady=true;
}
}
/**
* Sets the game phase in the 'phases' array for a specific player address.
*
* @param fromAddr The agreed player address for which to set the phase value.
* @param phaseNum The phase number to set for the 'fromAddr' player address.
*/
function set_phase (address fromAddr, uint8 phaseNum) public onlyAuthorized {
phases[fromAddr] = phaseNum;
}
/**
* Sets the last action block time value, 'lastActionBlock', for this contract.
*
* @param blockNum The block number to assign to the 'lastActionlock' variable.
*/
function set_lastActionBlock(uint blockNum) public onlyAuthorized {
lastActionBlock = blockNum;
}
/**
* Sets or resets the partial private card decryptions in the 'privateDecryptCards' array for a player address from a decrypting player.
*
* @param fromAddr The sending or decrypting agreed player address that is supplying the partially-decrypted card values.
* @param cards The partially-decrypted cards being stored for the 'targetAddr' player address. If this is an empty array
* all of the elements of 'privateDecryptCards' are cleared / reset (for all players).
* @param targetAddr The target agreed player address to whom the partially-decrypted card selections belong.
*/
function set_privateDecryptCards (address fromAddr, uint256[] memory cards, address targetAddr) public onlyAuthorized {
if (cards.length == 0) {
for (uint8 count=0; count < privateDecryptCards.length; count++) {
delete privateDecryptCards[count];
}
} else {
uint structIndex = privateDecryptCardsIndex(fromAddr, targetAddr);
for (uint8 count=0; count < cards.length; count++) {
privateDecryptCards[structIndex].cards[DataUtils.arrayLength2(privateDecryptCards[structIndex].cards)] = cards[count];
}
}
}
/**
* Adds or resets encrypted public card selections to the 'publicCards' array.
*
* @param fromAddr The sending agreed player address storing the public card values.
* @param cards The encrypted public card(s) selection(s) to add to the 'publicCards' array. If this array is empty then the entire
* 'publicCards' array is reset.
*/
function set_publicCards (address fromAddr, uint256[] memory cards) public onlyAuthorized {
if (cards.length == 0) {
for (uint8 count = 0; count < 5; count++) {
publicCards[count]=1;
}
} else {
for (uint8 count=0; count < cards.length; count++) {
publicCards[DataUtils.arrayLength5(publicCards)] = cards[count];
}
}
}
/**
* Stores up to 5 partially decrypted public or community cards from a target player. The player must must have agreed to the
* contract, and must be at phase 6, 9, or 12. Multiple invocations may be used to store cards during the multi-card
* phase (6) if desired.
*
* In order to correlate decryptions during subsequent rounds cards are stored at matching indexes for players involved.
* To illustrate this, in the following example players 1 and 2 decrypted the first three cards and players 2 and 3 decrypted the following
* two cards:
*
* publicDecryptCards(player 1) = [0x32] [0x22] [0x5A] [ 0x0] [ 0x0] <- partially decrypted only the first three cards
* publicDecryptCards(player 2) = [0x75] [0xF5] [0x9B] [0x67] [0xF1] <- partially decrypted all five cards
* publicDecryptCards(player 3) = [ 0x0] [ 0x0] [ 0x0] [0x1C] [0x22] <- partially decrypted only the last two cards
*
* The number of players involved in the partial decryption of any card at a specific index should be the total number of players minus one
* (players.length - 1), since the final decryption results in the fully decrypted card and therefore doesn't need to be stored.
*
* @param fromAddr The sending or decrypting agreed player storing the partially-decrypted public card values.
* @param cards The partially-decrypted card value(s) to store. If this parameter is an empty array the 'publicDecrypCards' and
* 'playerBestHands' arrays are reset/cleared.
*/
function set_publicDecryptCards (address fromAddr, uint256[] memory cards) public onlyAuthorized {
if (cards.length == 0) {
/*
for (uint count=0; count<5; count++) {
delete publicDecryptCards[fromAddr][count];
delete playerBestHands[fromAddr][count];
}
*/
delete publicDecryptCards[fromAddr];
delete playerBestHands[fromAddr];
} else {
(uint maxLength, uint playersAtMaxLength) = publicDecryptCardsInfo();
//adjust maxLength value to use as index
if ((playersAtMaxLength < (players.length - 1)) && (maxLength > 0)) {
maxLength--;
}
for (uint count=0; count < cards.length; count++) {
publicDecryptCards[fromAddr][maxLength] = cards[count];
maxLength++;
}
}
}
/**
* Sets the 'declaredWinner' address declared by a player.
*
* @param fromAddr The agreed player address storing a declared winner address.
* @param winnerAddr The declared agreed player address being stored by the 'fromAddr' player address.
*/
function add_declaredWinner(address fromAddr, address winnerAddr) public onlyAuthorized {
if (winnerAddr == address(0)) {
delete declaredWinner[fromAddr];
} else {
declaredWinner[fromAddr] = winnerAddr;
}
}
/**
* Returns the index / position of the 'privateDecryptCards' struct for a specific source and target player address
* combination. If the combination doesn't exist it is created and the index of the new element is returned.
*
* @param sourceAddr The address of the source or sending player.
* @param targetAddr The address of the target player to whom the associated partially decrypted cards belong.
*
* @return The index of the element within the privateDecryptCards array that matched the source and target addresses.
* The element may be new if no matching element can be found.
*/
function privateDecryptCardsIndex (address sourceAddr, address targetAddr) public onlyAuthorized returns (uint) {
for (uint count=0; count < privateDecryptCards.length; count++) {
if ((privateDecryptCards[count].sourceAddr == sourceAddr) && (privateDecryptCards[count].targetAddr == targetAddr)) {
return (count);
}
}
//none found, create a new one
uint256[2] memory tmp;
privateDecryptCards.push(DecryptPrivateCardsStruct(sourceAddr, targetAddr, tmp));
return (privateDecryptCards.length - 1);
}
/**
* Sets an encrypted card in the 'playerBestHands' array for a specific player address.
*
* @param fromAddr The player for which to store the encrypted card.
* @param cardIndex The 0-based card index within the 'playerBestHands' array for the 'fromAddr' address to set.
* @param card The encrypted card value to set for the 'fromAddr' player at index 'cardIndex' within the 'playerBestHands' array.
*/
function set_playerBestHands(address fromAddr, uint cardIndex, uint256 card) public onlyAuthorized {
playerBestHands[fromAddr][cardIndex] = card;
}
/**
* Adds encryption and decryption keys to the 'playerKeys' array for an agreed player address.
*
* @param fromAddr The agreed player address for which to set the encryption and decryption keys.
* @param encKeys The encryption keys to store for the 'fromAddr' player address.
* @param decKeys The decryption keys to store for the 'fromAddr' player address.
*/
function add_playerKeys(address fromAddr, uint256[] memory encKeys, uint256[] memory decKeys) public onlyAuthorized {
//caller guarantees that the number of encryption keys matches number decryption keys
for (uint count=0; count<encKeys.length; count++) {
playerKeys[fromAddr].push(Key(encKeys[count], decKeys[count], prime));
}
}
/**
* Deletes / clears the 'playerKeys' array for an agreed player address.
*
* @param fromAddr The agreed player address for which to clear entries (encryption and decryption keys), from the 'playerKeys' array.
*/
function remove_playerKeys(address fromAddr) public onlyAuthorized {
delete playerKeys[fromAddr];
}
/**
* Sets the 'challenger' address.
*
* @param challengerAddr The address of the challenging player to assign to the 'challenger' variable.
*/
function set_challenger(address challengerAddr) public onlyAuthorized {
challenger = challengerAddr;
}
/**
* Send an amount, up to and including the current contract's value, to an address. This address does not need to be a player address.
*
* @param toAddr The address to send some or all of the contract's value to.
* @param amount The amount, in wei, to send to the 'toAddr' address.
*
* @return The result of the "toAddr.send" operation.
*/
function pay (address payable toAddr, uint amount) public onlyAuthorized returns (bool) {
if (toAddr.send(amount)) {
return (true);
}
return (false);
}
/**
* @return Information about the 'publicDecryptCards' array. The tuple includes a 'maxLength' property which
* is the maximum length of 'publicDecryptCards' for all agreed players (some players may have stored fewer cards), and
* 'playersAtMaxLength' which is a count of players that have stored 'maxLength' cards in the 'publicDecryptCards' array.
*/
function publicDecryptCardsInfo() public returns (uint maxLength, uint playersAtMaxLength) {
uint currentLength = 0;
maxLength = 0;
for (uint8 count=0; count < players.length; count++) {
currentLength = DataUtils.arrayLength5(publicDecryptCards[players[count]]);
if (currentLength > maxLength) {
maxLength = currentLength;
}
}
playersAtMaxLength = 0;
for (uint8 count=0; count < players.length; count++) {
currentLength = DataUtils.arrayLength5(publicDecryptCards[players[count]]);
if (currentLength == maxLength) {
playersAtMaxLength++;
}
}
}
/**
* Returns the length number of elements stored by a player address in the 'encryptedDeck' array.
*
* @param fromAddr The address for which to retrieve the number of stored elements.
*
* @return The number of elements stored by 'fromAddr' in the 'encryptedDeck' array.
*/
function length_encryptedDeck(address fromAddr) public returns (uint) {
return (DataUtils.arrayLength52(encryptedDeck[fromAddr]));
}
}
library DataUtils {
/**
* Returns the number of elements in a non-dynamic, 52-element array. The final element in the array that is
* greater than 1 is considered the end of the array even if all preceeding elements are less than 2.
*
* @param inputArray The non-dynamic storage array to check for length.
*
*/
function arrayLength52(uint[52] memory inputArray) internal returns (uint) {
for (uint count=52; count>0; count--) {
if ((inputArray[count-1] > 1)) {
return (count);
}
}
return (0);
}
/**
* Returns the number of elements in a non-dynamic, 5-element array. The final element in the array that is
* greater than 1 is considered the end of the array even if all preceeding elements are less than 2.
*
* @param inputArray The non-dynamic storage array to check for length..
*
*/
function arrayLength5(uint[5] memory inputArray) internal returns (uint) {
for (uint count=5; count>0; count--) {
if ((inputArray[count-1] > 1)) {
return (count);
}
}
return (0);
}
/**
* Returns the number of elements in a non-dynamic, 2-element array. The final element in the array that is
* greater than 1 is considered the end of the array even if all preceeding elements are less than 2.
*
* @param inputArray The non-dynamic storage array to check for length.
*
*/
function arrayLength2(uint[2] memory inputArray) internal returns (uint) {
for (uint count=2; count>0; count--) {
if ((inputArray[count-1] > 1)) {
return (count);
}
}
return (0);
}
}
contract PokerHandValidator {
struct Card {
uint index;
uint suit;
uint value;
}
struct Key {
uint256 encKey;
uint256 decKey;
uint256 prime;
}
address public owner;
address public lastSender;
PokerHandData public pokerHandData;
Card[5] public workCards;
Card[] public sortedGroup;
Card[][] public sortedGroups;
Card[][15] public cardGroups;
// function PokerHandValidator () {}
function () external {}
modifier isAuthorized {
PokerHandData handData = PokerHandData(msg.sender);
bool found = false;
for (uint count=0; count<handData.numAuthorizedContracts(); count++) {
if (handData.authorizedGameContracts(count) == msg.sender) {
found = true;
break;
}
}
if (!found) {
revert();
}
_;
}
function challenge (address dataAddr, address challenger) public isAuthorized returns (bool) {}
function validate(address dataAddr, address msgSender) public isAuthorized returns (bool) {}
function decryptCard(address target, uint cardIndex) private {}
function validateCard(address target, uint cardIndex) private {}
function generateScore(address target) private {}
function checkDecryptedCard (address sender, uint256 cardValue) private returns (bool) {}
function modExp(uint256 base, uint256 exp, uint256 mod) internal returns (uint256 result) {}
function getCardIndex(uint256 value, uint256 baseCard, uint256 prime) public view returns (uint256 index) {}
function calculateHandScore() private returns (uint256) {}
function groupWorkCards(bool byValue) private {}
function clearGroups() private {}
function sortWorkCards(bool acesHigh) private {}
function scoreStraights(bool acesHigh) private returns (uint256) {}
function scoreGroups(bool valueGroups, bool acesHigh) private returns (uint256) {}
function checkGroupExists(uint8 memberCount) private returns (bool) {}
function addCardValues(uint256 startingValue, bool acesHigh) private returns (uint256) {}
function getSortedGroupLength32(uint8 index) private returns (uint32) {}
}
| * Contract constructor./ | constructor() public {
owner = msg.sender;
complete = true;
}
| 15,866,842 | [
1,
8924,
3885,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
12316,
1435,
1071,
288,
203,
202,
202,
8443,
273,
1234,
18,
15330,
31,
203,
202,
202,
6226,
273,
638,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x1fE24F25b1Cf609B9c4e7E12D802e3640dFA5e43/sources/CGGToken.sol | * @dev transfer token to a contract address with additional data if the recipient is a contact. @param _to The address to transfer to. @param _value The amount to be transferred. @param _data The extra data to be passed to the receiving contract./ | function transferAndCall(address _to, uint _value, bytes memory _data)
public
returns (bool success)
{
super.transfer(_to, _value);
emit Transfer(msg.sender, _to, _value, _data);
if (isContract(_to)) {
IERC677Receiver receiver = IERC677Receiver(_to);
receiver.onTokenTransfer(msg.sender, _value, _data);
}
return true;
}
| 4,468,484 | [
1,
13866,
1147,
358,
279,
6835,
1758,
598,
3312,
501,
309,
326,
8027,
353,
279,
5388,
18,
225,
389,
869,
1021,
1758,
358,
7412,
358,
18,
225,
389,
1132,
1021,
3844,
358,
506,
906,
4193,
18,
225,
389,
892,
1021,
2870,
501,
358,
506,
2275,
358,
326,
15847,
6835,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7412,
1876,
1477,
12,
2867,
389,
869,
16,
2254,
389,
1132,
16,
1731,
3778,
389,
892,
13,
203,
3639,
1071,
203,
3639,
1135,
261,
6430,
2216,
13,
203,
565,
288,
203,
3639,
2240,
18,
13866,
24899,
869,
16,
389,
1132,
1769,
203,
3639,
3626,
12279,
12,
3576,
18,
15330,
16,
389,
869,
16,
389,
1132,
16,
389,
892,
1769,
203,
3639,
309,
261,
291,
8924,
24899,
869,
3719,
288,
203,
5411,
467,
654,
39,
26,
4700,
12952,
5971,
273,
467,
654,
39,
26,
4700,
12952,
24899,
869,
1769,
203,
5411,
5971,
18,
265,
1345,
5912,
12,
3576,
18,
15330,
16,
389,
1132,
16,
389,
892,
1769,
203,
3639,
289,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GEO
pragma solidity 0.6.12;
import "./libs/Ownable.sol";
import "./libs/ERC20.sol";
import "./libs/SafeMath.sol";
contract TANToken is ERC20("TANToken", "TAN"), Ownable {
uint256 internal constant DIST_EPOCH = 30 days;
uint256 internal constant BLOCK_TIME = 6 seconds;
uint256 internal constant SUPPLY_RATE = 1; // 1% of RemainingSupply
uint256 internal constant FARM_RATE = 66; // 66% goes to Farming
uint256 internal constant TEAM_RATE = 1; // 1% give 1% as team allocation
uint256 internal constant DAO_RATE = 11; // 11% goes to the DAO
uint256 internal constant GTH_RATE = 11; // 11% goes to Growth fund (For Development and Marketing intiatives)
uint256 internal constant ILP_RATE = 11; // 11% will be used to bootstrap initial Liquidty Pools.
bool internal IsAfterFirstEpoch;
uint256 internal NextDistributionTimestamp;
uint256 public FarmSupply;
uint256 public CirculatingSupply;
uint256 public SupplyPerEpoch;
uint256 public SupplyPerBlock;
event supplyUpdated(uint256 amount);
constructor (
uint256 _maxSupply,
address _dao,
address _gth,
address _ilp,
address _team
) public {
_mint(_dao, _maxSupply.mul(DAO_RATE).div(100));
_mint(_gth, _maxSupply.mul(GTH_RATE).div(100));
_mint(_ilp, _maxSupply.mul(ILP_RATE).div(100));
_mint(_team, _maxSupply.mul(TEAM_RATE).div(100));
FarmSupply = _maxSupply.mul(FARM_RATE).div(100);
CirculatingSupply = 0;
SupplyPerEpoch = _calculateSupplyPerEpoch(FarmSupply, CirculatingSupply);
SupplyPerBlock = _perEpochToPerBlock(SupplyPerEpoch);
NextDistributionTimestamp = block.timestamp;
}
function updateSupply() public onlyOwner {
require(block.timestamp >= NextDistributionTimestamp, "TANToken: Not ready to update supply!");
if (IsAfterFirstEpoch) {
CirculatingSupply = CirculatingSupply.add(SupplyPerEpoch);
SupplyPerEpoch = _calculateSupplyPerEpoch(FarmSupply, CirculatingSupply);
} else {
IsAfterFirstEpoch = true;
}
SupplyPerBlock = _perEpochToPerBlock(SupplyPerEpoch);
NextDistributionTimestamp = NextDistributionTimestamp.add(DIST_EPOCH);
emit supplyUpdated(SupplyPerEpoch);
}
function _calculateSupplyPerEpoch (
uint256 _farmSupplyValue,
uint256 _circulatingValue
) internal pure returns(uint256) {
return _farmSupplyValue.sub(_circulatingValue).mul(SUPPLY_RATE).div(100);
}
function _perEpochToPerBlock (
uint256 perEpochValue
) internal pure returns (uint256) {
return perEpochValue.mul(BLOCK_TIME).div(DIST_EPOCH);
}
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (Craftsman).
function mint(
address _to,
uint256 _amount
) public onlyOwner {
_mint(_to, _amount);
}
}
| 1% of RemainingSupply
| uint256 internal constant SUPPLY_RATE = 1; | 5,449,190 | [
1,
21,
9,
434,
2663,
3280,
3088,
1283,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
5034,
2713,
5381,
16459,
23893,
67,
24062,
273,
404,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: BlueOak-1.0.0
pragma solidity 0.8.9;
import "contracts/libraries/Fixed.sol";
import "contracts/p0/RToken.sol";
import "contracts/p0/mixins/Component.sol";
import "contracts/p1/RToken.sol";
import "contracts/interfaces/IBackingManager.sol";
import "contracts/interfaces/IBasketHandler.sol";
import "contracts/plugins/mocks/ERC20Mock.sol";
import "contracts/fuzz/Mocks.sol";
import "contracts/fuzz/Utils.sol";
/* TODO: Here's a few of the many ways that this test could be improved:
- Decorate basically everything with events for clues about test failures
- Have the MockBasketHandler and MockBackingManager save an "event" log, representing the
state-change events that they've been issued, so that we can ensure the equivalence of the
function call sequence that each RToken emits
- Get these mocks to be more active, so they exercise more of the RToken space.
- In particular, make the referesher functions do more of what they're intended to do
- Have the mock contracts act wildly, possibly represented by more actions from the
RTokenDiffTest contract, to mock out changes that might effect the RToken (but that the
RToken probably doesn't model directly)
- Change the mock basket model from "token A" to "switches between token A and token B" or use
- Or something yet more ambitious? This could be practically anything we can drive from
random actions.
- It *might* be that these mocked-out component models are really useful for other fuzz tests too
*/
contract MockBackingManager is IBackingManager, ComponentMock {
function init(
IMain,
uint32,
uint192,
uint192,
uint192
) external {}
function grantRTokenAllowance(IERC20) external {}
function manageTokens(IERC20[] memory) external {}
/// Settle any auctions that can be settled
function settleTrade(IERC20) external virtual override {}
function claimAndSweepRewards() external virtual override {}
function trades(IERC20) external view virtual override returns (ITrade) {
return ITrade(address(0));
}
/// @return {%} The maximum trade slippage acceptable
function maxTradeSlippage() external view virtual override returns (uint192) {
return 1e16;
}
/// @return {UoA} The smallest amount of value worth trading
function dustAmount() external view virtual override returns (uint192) {
return 2e20;
}
}
contract MockBasketHandler is IBasketHandler, ComponentMock {
using FixLib for uint192;
/* The mock basket we're running with, here, is always either 100% A or 100% B.
* Each is always assumed to have a price of 1 UoA.
* We can (and maybe should) build something with wider behavior
*/
// Is the basket 100% A (instead of 100% B?)
bool public modeA = true;
IERC20 public tokenA;
IERC20 public tokenB;
uint256 public nonce = 0;
uint256 public timestamp;
constructor(IERC20 tokenA_, IERC20 tokenB_) {
tokenA = tokenA_;
tokenB = tokenB_;
timestamp = block.timestamp;
}
function init(IMain) external {}
function token() private view returns (IERC20) {
return modeA ? tokenA : tokenB;
}
/// Set the prime basket
function setPrimeBasket(IERC20[] memory, uint192[] memory) external {}
/// Set the backup configuration for a given target
function setBackupConfig(
bytes32,
uint256,
IERC20[] calldata
) external {}
/// Default the basket in order to schedule a basket refresh
function disableBasket() external {}
/// Governance-controlled setter to cause a basket switch explicitly
function refreshBasket() external {
// TODO: modeA = !modeA, and we do all the needed trades and handle capitalization
++nonce;
timestamp = block.timestamp;
}
/// @return If the BackingManager has sufficient collateral to redeem the entire RToken supply
function fullyCapitalized() external pure returns (bool) {
return true;
}
/// @return status The worst CollateralStatus of all collateral in the basket
function status() external pure returns (CollateralStatus) {
return CollateralStatus.SOUND;
}
/// @return {tok/BU} The whole token quantity of token in the reference basket
function quantity(IERC20 erc20) external view returns (uint192) {
return token() == erc20 ? FIX_ONE : FIX_ZERO;
}
/// @param amount {BU}
/// @return erc20s The addresses of the ERC20 tokens in the reference basket
/// @return quantities {qTok} The quantity of each ERC20 token to issue `amount` baskets
function quote(uint192 amount, RoundingMode rounding)
external
view
returns (address[] memory erc20s, uint256[] memory quantities)
{
erc20s = new address[](1);
erc20s[0] = modeA ? address(tokenA) : address(tokenB);
quantities = new uint256[](1);
quantities[0] = amount.shiftl(18).toUint(rounding);
}
/// @return baskets {BU} The quantity of complete baskets at an address. A balance for BUs
function basketsHeldBy(address acct) external view returns (uint192 baskets) {
int8 decimals = int8(IERC20Metadata(address(token())).decimals());
baskets = shiftl_toFix(token().balanceOf(acct), -decimals);
}
/// @return p {UoA/BU} The protocol's best guess at what a BU would be priced at in UoA
function price() external pure returns (uint192 p) {
return FIX_ONE;
}
/// @return nonce_ The basket nonce, a monotonically increasing unique identifier
/// @return timestamp_ The timestamp at which the basket was last set
function lastSet() external view returns (uint256 nonce_, uint256 timestamp_) {
nonce_ = nonce;
timestamp_ = timestamp;
}
}
contract RTokenTestSystem is MainMock {
using FixLib for uint192;
ERC20Mock public baseA;
ERC20Mock public baseB;
constructor(IRToken rToken_) {
DeploymentParams memory params = defaultParams();
Components memory components;
baseA = new ERC20Mock("Base Token A", "A$");
baseB = new ERC20Mock("Base Token B", "B$");
for (uint256 i = 0; i < USERS.length; i++) {
baseA.mint(USERS[i], 1e24);
baseB.mint(USERS[i], 1e24);
}
init(components, IERC20(address(0)), 0);
basketHandler = new MockBasketHandler(baseA, baseB);
basketHandler.init(this);
backingManager = new MockBackingManager();
backingManager.init(
this,
params.tradingDelay,
params.backingBuffer,
params.maxTradeSlippage,
params.dustAmount
);
rToken = rToken_;
rToken.init(this, "RToken", "RTK", "rtoken://1", params.issuanceRate);
}
}
contract RTokenP0Test is RTokenP0 {
function _msgSender() internal view virtual override returns (address) {
return MainMock(address(main)).sender();
}
}
contract RTokenP1Test is RTokenP1 {
function _msgSender() internal view virtual override returns (address) {
return MainMock(address(main)).sender();
}
}
contract RTokenDiffTest {
using FixLib for uint192;
address[] public USERS = [address(0x10000), address(0x20000), address(0x30000)];
RTokenTestSystem public p0;
RTokenTestSystem public p1;
modifier fromSender() {
p0.setSender(msg.sender);
p1.setSender(msg.sender);
_;
p0.setSender(address(0));
p1.setSender(address(0));
}
modifier fromBackingMgr() {
p0.setSender(address(p0.backingManager()));
p1.setSender(address(p1.backingManager()));
_;
p0.setSender(address(0));
p1.setSender(address(0));
}
constructor() {
p0 = new RTokenTestSystem(new RTokenP0Test());
p1 = new RTokenTestSystem(new RTokenP1Test());
}
// Actions and state modifiers
// ==== user actions, performed by 0x[123]0000. Melt
function issue(uint256 amount) external fromSender {
amount %= 1e36;
p0.rToken().issue(amount);
p1.rToken().issue(amount);
}
function cancel(uint256 endId, bool e) external fromSender {
p0.rToken().cancel(endId, e);
p1.rToken().cancel(endId, e);
}
function vest(address acct, uint256 endId) external fromSender {
p0.rToken().vest(acct, endId);
p1.rToken().vest(acct, endId);
}
// TODO: Add "cancel" and "vest" variations that are likely to succeed too
// i.e, ones that have valid endIDs
function redeem(uint256 amount) external fromSender {
amount %= 1e36;
p0.rToken().redeem(amount);
p1.rToken().redeem(amount);
}
function melt(uint256 amount) external fromSender {
amount %= 1e36;
p0.rToken().melt(amount);
p1.rToken().melt(amount);
}
function mint(address recipient, uint256 amount) external fromBackingMgr {
amount %= 1e36;
recipient = address((uint160(recipient) % 3) * 0x10000); // mint only to USERS
p0.rToken().mint(recipient, amount);
p1.rToken().mint(recipient, amount);
}
function setBasketsNeeded(uint192 basketsNeeded) external fromBackingMgr {
basketsNeeded %= 1e36;
p0.rToken().setBasketsNeeded(basketsNeeded);
p1.rToken().setBasketsNeeded(basketsNeeded);
}
// Auth on these is that the caller needs to be main.owner. That... should be this contract?
function setIssuanceRate(uint192 val) external {
val %= 1e24;
assert(p0.owner() == address(this)); // hope but verify
assert(p1.owner() == address(this));
RTokenP0(address(p0.rToken())).setIssuanceRate(val);
RTokenP1(address(p1.rToken())).setIssuanceRate(val);
}
// TODO: changes to MockERC20 balances
// Invariant: the observable rtoken prices are equal
function echidna_prices_equal() external view returns (bool) {
return p0.rToken().price() == p1.rToken().price();
}
function echidna_vesting_ids_equal() external view returns (bool) {
return
p0.rToken().endIdForVest(USERS[0]) == p1.rToken().endIdForVest(USERS[0]) &&
p0.rToken().endIdForVest(USERS[1]) == p1.rToken().endIdForVest(USERS[1]) &&
p0.rToken().endIdForVest(USERS[2]) == p1.rToken().endIdForVest(USERS[2]);
}
function echidna_baskets_needed_equal() external view returns (bool) {
return p0.rToken().basketsNeeded() == p1.rToken().basketsNeeded();
}
function all_balances_equal(address acct0, address acct1) internal view returns (bool) {
return
p0.baseA().balanceOf(acct0) == p1.baseA().balanceOf(acct1) &&
p0.baseB().balanceOf(acct0) == p1.baseB().balanceOf(acct1) &&
p0.rToken().balanceOf(acct0) == p1.rToken().balanceOf(acct1);
}
function echidna_user_balances_equal() external view returns (bool equal) {
equal =
all_balances_equal(address(p0.backingManager()), address(p1.backingManager())) &&
all_balances_equal(address(p0.basketHandler()), address(p1.basketHandler())) &&
all_balances_equal(address(p0), address(p1));
for (uint256 i = 0; i < USERS.length; i++) {
equal = equal && all_balances_equal(USERS[i], USERS[i]);
}
}
}
| Is the basket 100% A (instead of 100% B?) | contract MockBasketHandler is IBasketHandler, ComponentMock {
using FixLib for uint192;
bool public modeA = true;
IERC20 public tokenA;
IERC20 public tokenB;
uint256 public nonce = 0;
uint256 public timestamp;
constructor(IERC20 tokenA_, IERC20 tokenB_) {
tokenA = tokenA_;
tokenB = tokenB_;
timestamp = block.timestamp;
}
function init(IMain) external {}
function token() private view returns (IERC20) {
return modeA ? tokenA : tokenB;
}
function setPrimeBasket(IERC20[] memory, uint192[] memory) external {}
) external {}
function disableBasket() external {}
function setBackupConfig(
bytes32,
uint256,
IERC20[] calldata
function refreshBasket() external {
++nonce;
timestamp = block.timestamp;
}
function fullyCapitalized() external pure returns (bool) {
return true;
}
function status() external pure returns (CollateralStatus) {
return CollateralStatus.SOUND;
}
function quantity(IERC20 erc20) external view returns (uint192) {
return token() == erc20 ? FIX_ONE : FIX_ZERO;
}
function quote(uint192 amount, RoundingMode rounding)
external
view
returns (address[] memory erc20s, uint256[] memory quantities)
{
erc20s = new address[](1);
erc20s[0] = modeA ? address(tokenA) : address(tokenB);
quantities = new uint256[](1);
quantities[0] = amount.shiftl(18).toUint(rounding);
}
function basketsHeldBy(address acct) external view returns (uint192 baskets) {
int8 decimals = int8(IERC20Metadata(address(token())).decimals());
baskets = shiftl_toFix(token().balanceOf(acct), -decimals);
}
function price() external pure returns (uint192 p) {
return FIX_ONE;
}
function lastSet() external view returns (uint256 nonce_, uint256 timestamp_) {
nonce_ = nonce;
timestamp_ = timestamp;
}
}
| 1,833,290 | [
1,
2520,
326,
12886,
2130,
9,
432,
261,
8591,
684,
434,
2130,
9,
605,
8535,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
7867,
11324,
1503,
353,
467,
11324,
1503,
16,
5435,
9865,
288,
203,
565,
1450,
12139,
5664,
364,
2254,
15561,
31,
203,
203,
565,
1426,
1071,
1965,
37,
273,
638,
31,
203,
565,
467,
654,
39,
3462,
1071,
1147,
37,
31,
203,
565,
467,
654,
39,
3462,
1071,
1147,
38,
31,
203,
565,
2254,
5034,
1071,
7448,
273,
374,
31,
203,
565,
2254,
5034,
1071,
2858,
31,
203,
203,
565,
3885,
12,
45,
654,
39,
3462,
1147,
37,
67,
16,
467,
654,
39,
3462,
1147,
38,
67,
13,
288,
203,
3639,
1147,
37,
273,
1147,
37,
67,
31,
203,
3639,
1147,
38,
273,
1147,
38,
67,
31,
203,
3639,
2858,
273,
1203,
18,
5508,
31,
203,
565,
289,
203,
203,
203,
565,
445,
1208,
12,
3445,
530,
13,
3903,
2618,
203,
565,
445,
1147,
1435,
3238,
1476,
1135,
261,
45,
654,
39,
3462,
13,
288,
203,
3639,
327,
1965,
37,
692,
1147,
37,
294,
1147,
38,
31,
203,
565,
289,
203,
203,
203,
565,
445,
444,
23327,
11324,
12,
45,
654,
39,
3462,
8526,
3778,
16,
2254,
15561,
8526,
3778,
13,
3903,
2618,
203,
565,
262,
3903,
2618,
203,
565,
445,
4056,
11324,
1435,
3903,
2618,
203,
565,
445,
444,
6248,
809,
12,
203,
3639,
1731,
1578,
16,
203,
3639,
2254,
5034,
16,
203,
3639,
467,
654,
39,
3462,
8526,
745,
892,
203,
203,
203,
565,
445,
4460,
11324,
1435,
3903,
288,
203,
3639,
965,
12824,
31,
203,
3639,
2858,
273,
1203,
18,
5508,
31,
203,
565,
289,
203,
203,
565,
445,
7418,
4664,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import "forge-std/Test.sol";
import { EVM } from "../EVM.sol";
contract EVMTest is Test {
EVM evm;
function setUp() public {
evm = new EVM();
}
// 01 GAS 3: add(uint256, uint256)
function testAdd() public {
assertEq(evm.add(1, 2), 3);
// overflows on 2**256
assertEq(evm.add(1, (2**256 - 1)), 0);
// same as above
assertEq(
evm.add(
1,
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
),
0
);
}
// 02 GAS 5: mul(uint256, uint256)
function testMul() public {
assertEq(evm.mul(1, 2), 2);
// overflows on 2**256
assertEq(evm.mul(2, (2**256 - 1)), (2**256 - 2));
// same as above
assertEq(
evm.mul(
2,
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
),
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE
);
}
// 03 GAS 3: sub(uint256, uint256)
function testSub() public {
assertEq(evm.sub(10, 10), 0);
// underflow on 2**256
assertEq(evm.sub(0, 1), (2**256 - 1));
// same as above
assertEq(
evm.sub(0, 1),
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
);
}
// 04 GAS 3: div(uint256, uint256)
function testDiv() public {
assertEq(evm.div(10, 10), 1);
// underflow on 2**256 - if the denominator is 0, resuit=0.
assertEq(evm.div(1, 2), 0);
// underflow on 2**256
assertEq(evm.div((2**256 - 2), (2**256 - 1)), 0);
// same as above
assertEq(
evm.div(
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE,
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
),
0
);
}
// 05 GAS 5: sdiv(uint256, uint256)
function testSdiv() public {
assertEq(evm.sdiv(10, 10), 1);
// underflow on 2**256 - if the denominator is 0, resuit=0.
assertEq(evm.sdiv(1, 2), 0);
// overflows on -2**255
assertEq(evm.sdiv((2**256 - 2), (2**256 - 1)), 2);
// same as above
assertEq(
evm.sdiv(
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE,
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
),
2
);
}
// 06 GAS 5: mod(uint256, uint256)
function testMod() public {
assertEq(evm.mod(10, 3), 1);
// underflow on 2**256
assertEq(evm.mod(17, 5), 2);
}
// 07 GAS 5: smod(uint256, uint256)
function testSmod() public {
assertEq(evm.smod(10, 3), 1);
// underflow on 2**256
assertEq(evm.smod(17, 5), 2);
// underflows on -2**255
assertEq(
evm.smod((2**256 - 6), (2**256 - 4)),
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE
);
assertEq(
evm.smod(
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF8,
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD
),
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE
);
}
// 08 GAS 8: addMod(uint256, uint256, uint256)
function testAddMod() public {
assertEq(evm.addMod(10, 10, 8), 4);
assertEq(
evm.addMod(
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF,
2,
2
),
1
);
}
// 09 GAS 8: mulMod(uint256, uint256, uint256)
function testMulMod() public {
assertEq(evm.mulMod(10, 10, 8), 4);
assertEq(
evm.mulMod(
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF,
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF,
12
),
9
);
}
// 0A GAS 10: exp(uint256, uint256)
function testExp() public {
assertEq(evm.exp(10, 2), 100);
assertEq(evm.exp(2, 2), 4);
}
// 0B GAS 5: mulMod(uint256, uint256, uint256)
function testSignExtend() public {
assertEq(
evm.signExtend(0, 0xFF),
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
);
assertEq(evm.signExtend(0, 0x7F), 0x7F);
}
// 10 GAS 3: lt(uint256, uint256)
function testLt() public {
assertEq(evm.lt(9, 10), 1);
assertEq(evm.lt(10, 10), 0);
}
// 11 GAS 3: gt(uint256, uint256)
function testGt() public {
assertEq(evm.gt(10, 9), 1);
assertEq(evm.gt(10, 10), 0);
}
// 12 GAS 3: slt(uint256, uint256)
function testSlt() public {
assertEq(
evm.slt(
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF,
0
),
1
);
assertEq(evm.slt(10, 10), 0);
}
// 13 GAS 3: sgt(uint256, uint256)
function testSgt() public {
assertEq(
evm.sgt(
0,
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
),
1
);
assertEq(evm.sgt(10, 10), 0);
}
}
| 10 GAS 3: lt(uint256, uint256) | function testLt() public {
assertEq(evm.lt(9, 10), 1);
assertEq(evm.lt(10, 10), 0);
}
| 14,036,121 | [
1,
2163,
611,
3033,
890,
30,
13489,
12,
11890,
5034,
16,
2254,
5034,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
1842,
30247,
1435,
1071,
288,
203,
565,
1815,
19508,
12,
73,
3489,
18,
5618,
12,
29,
16,
1728,
3631,
404,
1769,
203,
565,
1815,
19508,
12,
73,
3489,
18,
5618,
12,
2163,
16,
1728,
3631,
374,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {IERC721Upgradeable as IERC721} from "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
/// @dev IP pool contract
abstract contract IPPool is OwnableUpgradeable {
event IPAdded(
address indexed token,
uint256 indexed tokenId,
address operator,
address tokenOwner
);
event IPRemoved(
address indexed token,
uint256 indexed tokenId,
address operator,
address tokenOwner
);
mapping(bytes32 => address) public ips; // keccak256(token|tokenId) => tokenOwner
struct IP {
address token;
uint256 tokenId;
}
IP[] public iplist;
function ipLength() external view returns(uint256) {
return iplist.length;
}
function allIP() external view returns(IP[] memory) {
return iplist;
}
function ipKey(address token, uint256 tokenId)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(token, tokenId));
}
function _IPAdd(
address token,
uint256 tokenId,
address owner
) internal {
bytes32 key = ipKey(token, tokenId);
if(ips[key] == address(0)) {
iplist.push(IP(token, tokenId));
}
ips[key] = owner;
emit IPAdded(token, tokenId, msg.sender, owner);
}
function _IPRemove(address token, uint256 tokenId) internal {
bytes32 key = ipKey(token, tokenId);
address owner = ips[key];
delete ips[key];
emit IPRemoved(token, tokenId, msg.sender, owner);
}
function _ownerOf(address token, uint256 tokenId)
internal
view
returns (address registedOwner)
{
bytes32 key = ipKey(token, tokenId);
registedOwner = ips[key];
}
function _chainId() internal view returns (uint256) {
uint256 _chainid;
assembly {
_chainid := chainid()
}
return _chainid;
}
function ownerOf(address token, uint256 tokenId)
external
view
virtual
returns (address registedOwner, address realOwner);
function chainId() external view virtual returns (uint256);
}
contract IPPoolShadow is IPPool {
uint256 public override chainId;
function initialize(uint256 _chainId) external initializer {
OwnableUpgradeable.__Ownable_init();
require(_chainId != IPPool._chainId(), "wrong chainId");
chainId = _chainId;
}
/// @dev add crossed IP, called by owner
function IPAdd(
address token,
uint256 tokenId,
address owner
) external onlyOwner {
IPPool._IPAdd(token, tokenId, owner);
}
/// @dev remove crossed IP, called by owner
function IPRemove(address token, uint256 tokenId) external onlyOwner {
IPPool._IPRemove(token, tokenId);
}
function ownerOf(address token, uint256 tokenId)
external
view
override
returns (address registedOwner, address realOwner)
{
registedOwner = realOwner = IPPool._ownerOf(token, tokenId);
}
}
contract IPPoolLocal is IPPool {
function initialize() external initializer {
OwnableUpgradeable.__Ownable_init();
}
/// @dev add token, called by user(IP owner)
/// @param token token which want to add into IP pool
/// @param tokenId tokenId
function IPAdd(IERC721 token, uint256 tokenId) external {
require(token.ownerOf(tokenId) == msg.sender, "only token owner");
IPPool._IPAdd(address(token), tokenId, msg.sender);
}
/// @dev remove IP, called by user(IP owner)
/// @param token token which want to remove from IP pool
/// @param tokenId tokenId
function IPRemove(IERC721 token, uint256 tokenId) external {
require(token.ownerOf(tokenId) == msg.sender, "only token owner");
IPPool._IPRemove(address(token), tokenId);
}
function ownerOf(address token, uint256 tokenId)
external
view
override
returns (address registedOwner, address realOwner)
{
registedOwner = IPPool._ownerOf(token, tokenId);
realOwner = IERC721(token).ownerOf(tokenId);
}
function chainId() external view override returns (uint256) {
return IPPool._chainId();
}
}
| keccak256(token|tokenId) => tokenOwner
| mapping(bytes32 => address) public ips; | 6,476,482 | [
1,
79,
24410,
581,
5034,
12,
2316,
96,
2316,
548,
13,
516,
1147,
5541,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
12,
3890,
1578,
516,
1758,
13,
1071,
13872,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/43114/0xa17946282a8fD1e1C0F2E484393F318D14C6A72F/sources/contracts/strategies/JoeLendingStrategyAvaxV1.sol | * @notice Reinvest rewards from staking contract to deposit tokens @dev Reverts if the expected amount of tokens are not returned from `stakingContract` @param joeRewards amount of JOE tokens to reinvest @param avaxBalance amount of AVAX to reinvest @param amount total amount of reward tokens to reinvest/ | function _reinvest(uint256 joeRewards, uint256 avaxBalance, uint256 amount) private {
if (joeRewards > 0) {
rewardController.claimReward(0, address(this));
uint256 joeAsWavax = DexLibrary.swap(
joeRewards,
address(rewardToken0),
address(rewardToken1),
swapPairToken0
);
WAVAX.withdraw(joeAsWavax);
}
uint256 fees = amount.mul(
DEV_FEE_BIPS.add(ADMIN_FEE_BIPS).add(REINVEST_REWARD_BIPS)
).div(BIPS_DIVISOR);
uint256 devFee = amount.mul(DEV_FEE_BIPS).div(BIPS_DIVISOR);
if (devFee > 0) {
_safeTransfer(address(rewardToken), devAddr, devFee);
}
uint256 adminFee = amount.mul(ADMIN_FEE_BIPS).div(BIPS_DIVISOR);
if (adminFee > 0) {
_safeTransfer(address(rewardToken), owner(), adminFee);
}
uint256 reinvestFee = amount.mul(REINVEST_REWARD_BIPS).div(BIPS_DIVISOR);
if (reinvestFee > 0) {
_safeTransfer(address(rewardToken), msg.sender, reinvestFee);
}
_stakeDepositTokens(amount.sub(fees));
emit Reinvest(totalDeposits(), totalSupply);
}
| 4,568,466 | [
1,
426,
5768,
395,
283,
6397,
628,
384,
6159,
6835,
358,
443,
1724,
2430,
225,
868,
31537,
309,
326,
2665,
3844,
434,
2430,
854,
486,
2106,
628,
1375,
334,
6159,
8924,
68,
225,
525,
15548,
17631,
14727,
3844,
434,
804,
51,
41,
2430,
358,
283,
5768,
395,
225,
1712,
651,
13937,
3844,
434,
15068,
2501,
358,
283,
5768,
395,
225,
3844,
2078,
3844,
434,
19890,
2430,
358,
283,
5768,
395,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
266,
5768,
395,
12,
11890,
5034,
525,
15548,
17631,
14727,
16,
2254,
5034,
1712,
651,
13937,
16,
2254,
5034,
3844,
13,
3238,
288,
203,
3639,
309,
261,
78,
15548,
17631,
14727,
405,
374,
13,
288,
203,
5411,
19890,
2933,
18,
14784,
17631,
1060,
12,
20,
16,
1758,
12,
2211,
10019,
203,
5411,
2254,
5034,
525,
15548,
1463,
59,
842,
651,
273,
463,
338,
9313,
18,
22270,
12,
203,
7734,
525,
15548,
17631,
14727,
16,
203,
7734,
1758,
12,
266,
2913,
1345,
20,
3631,
203,
7734,
1758,
12,
266,
2913,
1345,
21,
3631,
203,
7734,
7720,
4154,
1345,
20,
203,
5411,
11272,
203,
5411,
678,
5856,
2501,
18,
1918,
9446,
12,
78,
15548,
1463,
59,
842,
651,
1769,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
1656,
281,
273,
3844,
18,
16411,
12,
203,
5411,
2030,
58,
67,
8090,
41,
67,
38,
2579,
55,
18,
1289,
12,
15468,
67,
8090,
41,
67,
38,
2579,
55,
2934,
1289,
12,
862,
706,
3412,
882,
67,
862,
21343,
67,
38,
2579,
55,
13,
203,
3639,
262,
18,
2892,
12,
38,
2579,
55,
67,
2565,
26780,
916,
1769,
203,
203,
3639,
2254,
5034,
4461,
14667,
273,
3844,
18,
16411,
12,
15301,
67,
8090,
41,
67,
38,
2579,
55,
2934,
2892,
12,
38,
2579,
55,
67,
2565,
26780,
916,
1769,
203,
3639,
309,
261,
5206,
14667,
405,
374,
13,
288,
203,
5411,
389,
4626,
5912,
12,
2867,
12,
266,
2913,
1345,
3631,
4461,
3178,
16,
4461,
14667,
1769,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
3981,
2
] |
./full_match/80001/0x75400278D938725E7257Cd29b41eD7A9C9fe7c8B/sources/project:/contracts/RodoBridgeTitleNFT.sol | @dev Mints an NFT with a uri @param uri the full address for the metadata of this NFT | function _mintSingleNFT(string memory uri) internal returns (uint) {
uint tokenId = _tokenIds.current();
_safeMint(msg.sender, tokenId);
_tokenIds.increment();
_setTokenURI(tokenId, uri);
return tokenId;
}
| 875,482 | [
1,
49,
28142,
392,
423,
4464,
598,
279,
2003,
225,
2003,
326,
1983,
1758,
364,
326,
1982,
434,
333,
423,
4464,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
81,
474,
5281,
50,
4464,
12,
1080,
3778,
2003,
13,
2713,
1135,
261,
11890,
13,
288,
203,
3639,
2254,
1147,
548,
273,
389,
2316,
2673,
18,
2972,
5621,
203,
3639,
389,
4626,
49,
474,
12,
3576,
18,
15330,
16,
1147,
548,
1769,
203,
3639,
389,
2316,
2673,
18,
15016,
5621,
203,
3639,
389,
542,
1345,
3098,
12,
2316,
548,
16,
2003,
1769,
203,
4202,
327,
1147,
548,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0x559385E8728b7d8C98B3910e5531D8C49F861c31/sources/project:/contracts/main/MentaportERC721.sol | ---------------------------------------------------------------------------- External functions* @dev Change Mentaport account - Emits a {MentaportAccount} event./ | function changeMentaportAccount(address _newAddress) external nonReentrant {
require(hasRole(MENTAPORT_ROLE, msg.sender), "Caller is not mentaport");
_mentaportAccount = _newAddress;
emit MentaportAccount(msg.sender, _mentaportAccount);
}
| 1,916,281 | [
1,
5802,
7620,
11352,
4186,
225,
7576,
490,
319,
438,
499,
2236,
225,
300,
7377,
1282,
279,
288,
49,
319,
438,
499,
3032,
97,
871,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2549,
49,
319,
438,
499,
3032,
12,
2867,
389,
2704,
1887,
13,
3903,
1661,
426,
8230,
970,
288,
203,
3639,
2583,
12,
5332,
2996,
12,
3212,
2203,
3871,
67,
16256,
16,
1234,
18,
15330,
3631,
315,
11095,
353,
486,
312,
319,
438,
499,
8863,
203,
3639,
389,
475,
438,
499,
3032,
273,
389,
2704,
1887,
31,
203,
203,
3639,
3626,
490,
319,
438,
499,
3032,
12,
3576,
18,
15330,
16,
389,
475,
438,
499,
3032,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x3e4E8ECB65cB5bA5E791BB955F8Bbc5c9Ad421c7/sources/contracts/SPT.sol | * total number of tokens sent to the SPT address via the Addons contract (extra utility etc)/ | function totalFromAddons() public view override returns (uint256) {
return _totalFromAddons;
}
| 8,489,880 | [
1,
4963,
1300,
434,
2430,
3271,
358,
326,
348,
1856,
1758,
3970,
326,
1436,
7008,
6835,
261,
7763,
12788,
5527,
13176,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2078,
1265,
986,
7008,
1435,
1071,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
4963,
1265,
986,
7008,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0xFE4c0439D933821c973098d7E0BbE3DFa20D42D9/sources/contracts/BnbStaking.sol | (bool success,) = to.call{value:value}(new bytes(0)); | function safeTransferBNB(address to, uint256 value) internal {
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
| 5,634,906 | [
1,
12,
6430,
2216,
16,
13,
273,
358,
18,
1991,
95,
1132,
30,
1132,
97,
12,
2704,
1731,
12,
20,
10019,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4183,
5912,
15388,
38,
12,
2867,
358,
16,
2254,
5034,
460,
13,
2713,
288,
203,
3639,
2583,
12,
4768,
16,
296,
5912,
2276,
30,
512,
2455,
67,
16596,
6553,
67,
11965,
8284,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/97/0xF7FCC686158A97f82DE82437d4553E3Da017157d/sources/project_/contracts/core/erc721_upgradeable/LivNFTUpgradeable.sol | @dev An array containing the Dino struct for all Dinos in existence. The ID of each dino is actually an index into this array. | Dino[] private dinos;
| 3,263,676 | [
1,
979,
526,
4191,
326,
463,
15020,
1958,
364,
777,
463,
267,
538,
316,
15782,
18,
1021,
1599,
225,
434,
1517,
302,
15020,
353,
6013,
392,
770,
1368,
333,
526,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
463,
15020,
8526,
3238,
302,
267,
538,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./interfaces/IPancakeRouter02.sol";
import "./interfaces/IPancakeFactory.sol";
import "./BEP20.sol";
/// @author The Development Team
/// @title Token
contract ConquerUranus is BEP20("ConquerUranus", "ANVS", 18) {
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 _isExcludedFromReward;
address[] private _excludedFromReward;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 2543164 * 10**6 * 10**18;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
/// Control the amount on transfers to avoid dump price
uint256 public _maxTxAmount = (_tTotal * 5).div(1000);
uint256 private numTokensSellToAddToLiquidity = (_tTotal * 5).div(1000);
/// Fee state variables section
uint256 public _holderFee;
uint256 public _liquidityFee;
uint256 public _vaultFee;
uint256 public totalSendedToTheVoid;
uint256 public totalLiquidity;
IPancakeRouter02 public immutable pancakeRouter;
address public immutable pancakePair;
address public blackHoleVaultAddress;
address public spaceWasteVaultAddress;
address public devAddress;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled;
/// Event section
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
event Burn(address indexed burner, uint256 amount);
/// Modifiers section
/// Modifier that uses a mutex pattern for swaps
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
/// Modifier that restricts the users who can send to the void
modifier sendersToTheVoid {
require(
_msgSender() == owner() ||
_msgSender() == devAddress ||
_msgSender() == blackHoleVaultAddress
);
_;
}
/// Modifier that restricts a function only for vault address
modifier onlyVault {
require(_msgSender() == blackHoleVaultAddress);
_;
}
constructor (
address blackHoleVaultAddress_,
address devAddress_,
address routerAddress_,
address spaceWasteVaultAddress_
)
{
// Declaration of addresses
blackHoleVaultAddress = blackHoleVaultAddress_;
devAddress = devAddress_;
spaceWasteVaultAddress = spaceWasteVaultAddress_;
swapAndLiquifyEnabled = true;
_rOwned[_msgSender()] = _rTotal;
IPancakeRouter02 _pancakeRouter = IPancakeRouter02(routerAddress_);
// Creation of pancake pair for the token
pancakePair = IPancakeFactory(_pancakeRouter.factory())
.createPair(address(this), _pancakeRouter.WETH());
// set the rest of the contract variables
pancakeRouter = _pancakeRouter;
// Excluding main accounts from rewards
excludeFromReward(address(this));
excludeFromReward(owner());
excludeFromReward(blackHoleVaultAddress);
excludeFromReward(devAddress);
excludeFromReward(spaceWasteVaultAddress);
emit Transfer(address(0), _msgSender(), _tTotal);
}
//to recieve BNB from pancakeRouter when swaping
receive() external payable {}
/// This function include and account into reward system. Only an Owner can include.
/// @param account The address of the account to include
function includeInReward(address account) external onlyOwner {
require(_isExcludedFromReward[account], "Account is already excluded");
for (uint256 i = 0; i < _excludedFromReward.length; i++) {
if (_excludedFromReward[i] == account) {
_excludedFromReward[i] = _excludedFromReward[_excludedFromReward.length - 1];
_tOwned[account] = 0;
_isExcludedFromReward[account] = false;
_excludedFromReward.pop();
break;
}
}
}
/// This function permits change the holder fee percent
/// Only owner can change the fee
/// @param holderFee is the new fee for holders
function setHoldersFee(uint256 holderFee, uint256 liquidityFee, uint256 vaultFee) external onlyOwner {
_holderFee = holderFee;
_liquidityFee = liquidityFee;
_vaultFee = vaultFee;
}
/// This function sets the max percent for transfers
/// @param maxTxPercent is the new percentaje
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner {
_maxTxAmount = _tTotal.mul(maxTxPercent).div(
10**2
);
}
/// This function enable or disable the swap and liquify function
/// @param _enabled is the boolean value to set
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
/// This is the public function to send the half of tokens in vault to the black hole
/// and the other half to the dev wallet
/// @return a boolean value
function sendToTheVoidDevAndSpaceWasteWallet() public onlyVault returns (bool) {
// Take tokens from vault
uint256 amountToBlackHole = _tOwned[blackHoleVaultAddress].div(2);
uint256 amountToDistribute = _tOwned[blackHoleVaultAddress].sub(amountToBlackHole);
uint256 amountToDev = amountToDistribute.div(2);
uint256 amountToSpaceWasteVault = amountToDistribute.sub(amountToDev);
_tOwned[blackHoleVaultAddress] = 0;
// We distribute to black hole and developers wallet
// Sending to black hole
_sendToTheVoid(amountToBlackHole);
// Sending to devs wallet
_tOwned[devAddress] = _tOwned[devAddress].add(amountToDev);
_tOwned[spaceWasteVaultAddress] = _tOwned[spaceWasteVaultAddress].add(amountToSpaceWasteVault);
emit Transfer(blackHoleVaultAddress, devAddress, amountToDev);
emit Transfer(blackHoleVaultAddress, spaceWasteVaultAddress, amountToSpaceWasteVault);
return true;
}
/// This is the public function to send tokens to the black hole
/// @dev Only can burn Owner, Vault and Dev
/// @param amount the quantity to burn
/// @return a boolean value
function sendToTheVoid(uint256 amount) public sendersToTheVoid returns (bool) {
_sendToTheVoid(amount);
return true;
}
/// This function deliver an amount to the totalFees
/// @param tAmount is the quantity of token to deliver
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcludedFromReward[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);
}
/// This function exclude and account from reward, in case of the account have some reflection
/// pass it to tokens. Only an Owner can include.
/// @param account The address of the account to exclude
function excludeFromReward(address account) public onlyOwner {
require(!_isExcludedFromReward[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcludedFromReward[account] = true;
_excludedFromReward.push(account);
}
/// This function calculates the conversion from normal token to reflection
/// @param tAmount the quantity of token to convert
/// @param deductTransferFee boolean that indicates if the conversion deduct fees in calculus or not
/// @return the value in reflection
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;
}
}
/// This function calculates the conversion from reflection to normal token
/// @param rAmount the quantity of reflection to convert in token
/// @return the value in token
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);
}
/// This function returns the total supply of tokens
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
/// This functions shows the balance of an account
/// @param account the account to get the balance
/// @return an unsigned intger with the balance
function balanceOf(address account) public view override returns (uint256) {
if (_isExcludedFromReward[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
/// This function returns a boolean value depending on whether the account is
/// excluded from rewards.
/// @param account is the account to check if is excluded from reward
/// @return boolean value with the status
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcludedFromReward[account];
}
/// This function gets a list of excluded accounts from reward.
/// @return an array with the list of excluded accounts
function getExcludedFromReward() public view returns (address[] memory) {
return _excludedFromReward;
}
/// This functions return the total fees
/// @return an unsigned integer with the total fees
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
/// This function burns an amount defined by param
/// @param amount the amount that will be burn
function _sendToTheVoid(uint256 amount) internal {
require(amount <= _tTotal, "Amount must be less than total");
// Substract token to burn from sender account
if(_tOwned[_msgSender()] > 0 && amount <= _tOwned[_msgSender()]){
_tOwned[_msgSender()] = _tOwned[_msgSender()].sub(amount, "Amount to burn exceeds token owned");
}
// Only if account have reflection, but its not probably because dev, vault and owner are excluded from
// reward
uint256 ratedQuantity = amount.mul(_getRate());
if(_rOwned[_msgSender()] > 0 && ratedQuantity <= _rOwned[_msgSender()]){
_rOwned[_msgSender()] = _rOwned[_msgSender()].sub(ratedQuantity, "Amount to burn exceeds reflected token owned");
}
_tOwned[address(1)] = _tOwned[address(1)].add(amount);
_rOwned[address(1)] = _rOwned[address(1)].add(amount.mul(_getRate()));
totalSendedToTheVoid = totalSendedToTheVoid.add((amount));
emit Transfer(_msgSender(), address(1), amount);
}
///This function is responsible for transfering tokens, is modified from BEP20
/// and different functionalities have been added.
/// @param from sender of the transfer
/// @param to recipient of the transfer
/// @param amount quantity of tokens to transfer
function _transfer(address from, address to, uint256 amount) internal virtual override{
require(from != address(0), "BEP20: transfer from the zero address");
require(to != address(0), "BEP20: 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.");
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount) {
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
/// Cases of condition:
/// 1. The token balance of this contract is over the min number of
/// tokens that we need to initiate a swap + liquidity lock (overMinTokenBalance checks it)
/// 2. Avoid that don't get caught in a circular liquidity event using a mutex pattern with the modifier lockTheSwap.
/// variable inSwapAndLiquify controls it
/// 3. Avoid swap & liquify if sender is uniswap pair with from != pancakePair.
/// 4. swapAndLiquifyEnable, must be enabled :)
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != pancakePair &&
swapAndLiquifyEnabled
) {
contractTokenBalance = numTokensSellToAddToLiquidity;
//add liquidity
swapAndLiquify(contractTokenBalance);
}
// Transfer amount, it will take tax, burn, liquidity fee
_tokenTransfer(from,to,amount);
}
/// This function adds fee value to the total fee counter
/// @param rFee is the value to substract from rTotal
/// @param tFee is the value to add to tFeeTotal
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
/// This function sends token from an excluded from reward sender to excluded from reward recipient
/// @param sender is the account that sends tokens
/// @param recipient is the account that will receive tokens
/// @param tAmount is the quantity to send
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tVault) = _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);
_takeVault(tVault);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
/// This function is in charge of dividing the balance sheets in two
/// and making repurchases and liquidity additions.
/// @param contractTokenBalance only tokenBalance
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
// This part of code splits the contract balance into halves
uint256 half = contractTokenBalance.div(2);
uint256 otherHalf = contractTokenBalance.sub(half);
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// Swap tokens of the contract for ETH
swapTokensForETH(half); //
// The balance of ETH to swap
uint256 newBalance = address(this).balance.sub(initialBalance);
// Add liquidity to pancake
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
/// This function is in charge of taking a part of the tokens to buy BNB that will later
/// be added to the pair together with another amount of tokens.
/// @param tokenAmount is the quantity of tokens to change for BNB
function swapTokensForETH(uint256 tokenAmount) private {
// Generate the Pancake swap pair path of Token -> BNB
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = pancakeRouter.WETH();
/// Gives the approve to router for taking tokens
_approve(address(this), address(pancakeRouter), tokenAmount);
/// Make the swap to get BNB
pancakeRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of BNB
path,
address(this),
block.timestamp
);
}
/// This functions adds liquidity to pair
/// @param tokenAmount quantity of tokens to add
/// @param ethAmount quantity of BNB to add
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(pancakeRouter), tokenAmount);
// add the liquidity
pancakeRouter.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(),
block.timestamp
);
totalLiquidity = totalLiquidity.add(ethAmount);
}
/// This method is responsible for taking all fee, if takeFee is true
/// @param sender is the address of account which will send the tokens
/// @param recipient is the address of the account which will receive the tokens
/// @param amount is the quantity to transfer
function _tokenTransfer(address sender, address recipient, uint256 amount) private {
if (_isExcludedFromReward[sender] && !_isExcludedFromReward[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcludedFromReward[sender] && _isExcludedFromReward[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcludedFromReward[sender] && !_isExcludedFromReward[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcludedFromReward[sender] && _isExcludedFromReward[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
}
/// This function sends token from sender to recipient
/// @param sender is the account that sends tokens
/// @param recipient is the account that will receive tokens
/// @param tAmount is the quantity to send
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tVault) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_takeVault(tVault);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
/// This function sends token from sender to excluded from reward recipient
/// @param sender is the account that sends tokens
/// @param recipient is the account that will receive tokens
/// @param tAmount is the quantity to send
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tVault) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_takeVault(tVault);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
/// This function sends token from excluded from reward sender to recipient
/// @param sender is the account that sends tokens
/// @param recipient is the account that will receive tokens
/// @param tAmount is the quantity to send
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tVault) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_takeVault(tVault);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
/// This function add liquidity into the contract for rOwned and tOwned (if account is excluded from reward)
/// of the contract account
/// @param tLiquidity quantity of liquidity to add
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if(_isExcludedFromReward[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
/// This function add to vault the fee correspondant for it
/// @param tVault quantity of tokens to add in vault
function _takeVault(uint256 tVault) private {
uint256 currentRate = _getRate();
uint256 rVault = tVault.mul(currentRate);
_rOwned[blackHoleVaultAddress] = _rOwned[blackHoleVaultAddress].add(rVault);
if(_isExcludedFromReward[address(this)])
_tOwned[blackHoleVaultAddress] = _tOwned[blackHoleVaultAddress].add(tVault);
emit Transfer(_msgSender(), blackHoleVaultAddress, tVault);
}
/// This function calls _getTvalues and _getRValues to obtain all the values
/// @return the same values returned in _getTValues and _getRValues
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tVault) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, tVault, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity, tVault);
}
/// This function is used to calculate different tValues with tAmount
/// @param tAmount the value which is used to calculate
/// @return tFee Value calculated with tax fee percentaje over tAmount
/// @return tLiquidity Value calculated with liquidity fee percentaje over tAmount
/// @return tLiquidity Value calculated with vault fee percentaje over tAmount
/// @return tTransferAmount value extracted from the subtraction of tFee, tLiquidity and tVault over tAmount
function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256) {
(uint256 tFee, uint256 tLiquidity, uint256 tVault) = calculateFees(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity).sub(tVault);
return (tTransferAmount, tFee, tLiquidity, tVault);
}
/// This function obtains the rate calculated with the current supply
/// @return rate obtained with rSupply / tSupply
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
/// This function calculates rSupply and tSupply considering whether the account
/// is excluded from the reward or not
/// @return rSupply and tSupply || _rTotal and _tTotal depending on the conditions
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 tSupply = _tTotal; // add totalburned to avoid a decrease on reflection
uint256 rSupply = _rTotal;
for (uint256 i = 0; i < _excludedFromReward.length; i++) {
if (_rOwned[_excludedFromReward[i]] > rSupply || _tOwned[_excludedFromReward[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excludedFromReward[i]]);
tSupply = tSupply.sub(_tOwned[_excludedFromReward[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
/// This functions calculates fees for an amount
/// @param _amount the quantity to calculate its fee
/// @return fees for holders, liquidity and vault
function calculateFees(uint256 _amount) private view returns (uint256, uint256, uint256){
uint256 tFee = _amount.mul(_holderFee).div(10**2);
uint256 tLiquidity = _amount.mul(_liquidityFee).div(10**2);
uint256 tVault = _amount.mul(_vaultFee).div(10**2);
return (tFee, tLiquidity, tVault);
}
/// This function is used to calculate different tValues with tValues and the current rate
/// @param tAmount the value which is used to calculate
/// @param tFee is the tax fee of tAmount
/// @param tLiquidity is the liquidity fee of tAmount
/// @param currentRate rate obtained with the division rSupply / tSupply
/// @return rAmount the result obtained by multiplying tAmount by currentRate
/// @return rTransferAmount value extracted from the subtraction of rFee and rLiquidity over rAmount
/// @return tTransferAmount value extracted from the subtraction of tFee and tLiquidity over tAmount
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 tVault, 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).sub(tVault.mul(currentRate));
return (rAmount, rTransferAmount, rFee);
}
}
| This functions adds liquidity to pair @param tokenAmount quantity of tokens to add @param ethAmount quantity of BNB to add approve token transfer to cover all possible scenarios add the liquidity | function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(pancakeRouter), tokenAmount);
address(this),
tokenAmount,
owner(),
block.timestamp
);
totalLiquidity = totalLiquidity.add(ethAmount);
}
| 1,063,182 | [
1,
2503,
4186,
4831,
4501,
372,
24237,
358,
3082,
225,
1147,
6275,
10457,
434,
2430,
358,
527,
225,
13750,
6275,
10457,
434,
605,
20626,
358,
527,
6617,
537,
1147,
7412,
358,
5590,
777,
3323,
22456,
527,
326,
4501,
372,
24237,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
527,
48,
18988,
24237,
12,
11890,
5034,
1147,
6275,
16,
2254,
5034,
13750,
6275,
13,
3238,
288,
203,
3639,
389,
12908,
537,
12,
2867,
12,
2211,
3631,
1758,
12,
7355,
23780,
8259,
3631,
1147,
6275,
1769,
203,
203,
5411,
1758,
12,
2211,
3631,
203,
5411,
1147,
6275,
16,
203,
5411,
3410,
9334,
203,
5411,
1203,
18,
5508,
203,
3639,
11272,
203,
3639,
2078,
48,
18988,
24237,
273,
2078,
48,
18988,
24237,
18,
1289,
12,
546,
6275,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/3/0x7295C2BE0Fabca03ED3514C3dd99658EbC25f3f3/sources/browser/Contract_Code_v2_Min.sol | check and user teamLevel | uint8 teamLevel = user.teamLevel;
| 8,114,381 | [
1,
1893,
471,
729,
5927,
2355,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
28,
5927,
2355,
273,
729,
18,
10035,
2355,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
// 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/>.
library BConst {
uint public constant BONE = 10**18;
uint public constant MIN_BOUND_TOKENS = 2;
uint public constant MAX_BOUND_TOKENS = 8;
uint public constant DEFAULT_FEE = BONE * 3 / 1000; // 0.3%
uint public constant MIN_FEE = BONE / 10**6;
uint public constant MAX_FEE = BONE / 10;
uint public constant DEFAULT_COLLECTED_FEE = BONE / 2000; // 0.05%
uint public constant MAX_COLLECTED_FEE = BONE / 200; // 0.5%
uint public constant DEFAULT_EXIT_FEE = 0;
uint public constant MAX_EXIT_FEE = BONE / 1000; // 0.1%
uint public constant MIN_WEIGHT = BONE;
uint public constant MAX_WEIGHT = BONE * 50;
uint public constant MAX_TOTAL_WEIGHT = BONE * 50;
uint public constant MIN_BALANCE = BONE / 10**12;
uint public constant DEFAULT_INIT_POOL_SUPPLY = BONE * 100;
uint public constant MIN_INIT_POOL_SUPPLY = BONE / 1000;
uint public constant MAX_INIT_POOL_SUPPLY = BONE * 10**18;
uint public constant MIN_BPOW_BASE = 1 wei;
uint public constant MAX_BPOW_BASE = (2 * BONE) - 1 wei;
uint public constant BPOW_PRECISION = BONE / 10**10;
uint public constant MAX_IN_RATIO = BONE / 2;
uint public constant MAX_OUT_RATIO = (BONE / 3) + 1 wei;
}
// 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/>.
contract BNum {
function btoi(uint a)
internal pure
returns (uint)
{
return a / BConst.BONE;
}
function bfloor(uint a)
internal pure
returns (uint)
{
return btoi(a) * BConst.BONE;
}
function badd(uint a, uint b)
internal pure
returns (uint)
{
uint c = a + b;
require(c >= a, "add overflow");
return c;
}
function bsub(uint a, uint b)
internal pure
returns (uint)
{
(uint c, bool flag) = bsubSign(a, b);
require(!flag, "sub underflow");
return c;
}
function bsubSign(uint a, uint b)
internal pure
returns (uint, bool)
{
if (a >= b) {
return (a - b, false);
} else {
return (b - a, true);
}
}
function bmul(uint a, uint b)
internal pure
returns (uint)
{
uint c0 = a * b;
require(a == 0 || c0 / a == b, "mul overflow");
uint c1 = c0 + (BConst.BONE / 2);
require(c1 >= c0, "mul overflow");
uint c2 = c1 / BConst.BONE;
return c2;
}
function bdiv(uint a, uint b)
internal pure
returns (uint)
{
require(b != 0, "div by 0");
uint c0 = a * BConst.BONE;
require(a == 0 || c0 / a == BConst.BONE, "div internal"); // bmul overflow
uint c1 = c0 + (b / 2);
require(c1 >= c0, "div internal"); // badd require
uint c2 = c1 / b;
return c2;
}
// DSMath.wpow
function bpowi(uint a, uint n)
internal pure
returns (uint)
{
uint z = n % 2 != 0 ? a : BConst.BONE;
for (n /= 2; n != 0; n /= 2) {
a = bmul(a, a);
if (n % 2 != 0) {
z = bmul(z, a);
}
}
return z;
}
// Compute b^(e.w) by splitting it into (b^e)*(b^0.w).
// Use `bpowi` for `b^e` and `bpowK` for k iterations
// of approximation of b^0.w
function bpow(uint base, uint exp)
internal pure
returns (uint)
{
require(base >= BConst.MIN_BPOW_BASE, "base too low");
require(base <= BConst.MAX_BPOW_BASE, "base too high");
uint whole = bfloor(exp);
uint remain = bsub(exp, whole);
uint wholePow = bpowi(base, btoi(whole));
if (remain == 0) {
return wholePow;
}
uint partialResult = bpowApprox(base, remain, BConst.BPOW_PRECISION);
return bmul(wholePow, partialResult);
}
function bpowApprox(uint base, uint exp, uint precision)
internal pure
returns (uint)
{
// term 0:
uint a = exp;
(uint x, bool xneg) = bsubSign(base, BConst.BONE);
uint term = BConst.BONE;
uint sum = term;
bool negative = false;
// term(k) = numer / denom
// = (product(a - i - 1, i=1-->k) * x^k) / (k!)
// each iteration, multiply previous term by (a-(k-1)) * x / k
// continue until term is less than precision
for (uint i = 1; term >= precision; i++) {
uint bigK = i * BConst.BONE;
(uint c, bool cneg) = bsubSign(a, bsub(bigK, BConst.BONE));
term = bmul(term, bmul(c, x));
term = bdiv(term, bigK);
if (term == 0) break;
if (xneg) negative = !negative;
if (cneg) negative = !negative;
if (negative) {
sum = bsub(sum, term);
} else {
sum = badd(sum, term);
}
}
return sum;
}
}
// 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/>.
// Highly opinionated token implementation
interface IERC20 {
event Approval(address indexed src, address indexed dst, uint amt);
event Transfer(address indexed src, address indexed dst, uint amt);
function totalSupply() external view returns (uint);
function balanceOf(address whom) external view returns (uint);
function allowance(address src, address dst) external view returns (uint);
function approve(address dst, uint amt) external returns (bool);
function transfer(address dst, uint amt) external returns (bool);
function transferFrom(
address src, address dst, uint amt
) external returns (bool);
}
contract BTokenBase is BNum {
mapping(address => uint) internal _balance;
mapping(address => mapping(address=>uint)) internal _allowance;
uint internal _totalSupply;
event Approval(address indexed src, address indexed dst, uint amt);
event Transfer(address indexed src, address indexed dst, uint amt);
function _mint(uint amt) internal {
_balance[address(this)] = badd(_balance[address(this)], amt);
_totalSupply = badd(_totalSupply, amt);
emit Transfer(address(0), address(this), amt);
}
function _burn(uint amt) internal {
require(_balance[address(this)] >= amt, "!bal");
_balance[address(this)] = bsub(_balance[address(this)], amt);
_totalSupply = bsub(_totalSupply, amt);
emit Transfer(address(this), address(0), amt);
}
function _move(address src, address dst, uint amt) internal {
require(_balance[src] >= amt, "!bal");
_balance[src] = bsub(_balance[src], amt);
_balance[dst] = badd(_balance[dst], amt);
emit Transfer(src, dst, amt);
}
function _push(address to, uint amt) internal {
_move(address(this), to, amt);
}
function _pull(address from, uint amt) internal {
_move(from, address(this), amt);
}
}
contract BToken is BTokenBase, IERC20 {
string private _name = "Value Liquidity Provider";
string private _symbol = "VLP";
uint8 private _decimals = 18;
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
function allowance(address src, address dst) external override view returns (uint) {
return _allowance[src][dst];
}
function balanceOf(address whom) external override view returns (uint) {
return _balance[whom];
}
function totalSupply() public override view returns (uint) {
return _totalSupply;
}
function approve(address dst, uint amt) external override returns (bool) {
_allowance[msg.sender][dst] = amt;
emit Approval(msg.sender, dst, amt);
return true;
}
function increaseApproval(address dst, uint amt) external returns (bool) {
_allowance[msg.sender][dst] = badd(_allowance[msg.sender][dst], amt);
emit Approval(msg.sender, dst, _allowance[msg.sender][dst]);
return true;
}
function decreaseApproval(address dst, uint amt) external returns (bool) {
uint oldValue = _allowance[msg.sender][dst];
if (amt > oldValue) {
_allowance[msg.sender][dst] = 0;
} else {
_allowance[msg.sender][dst] = bsub(oldValue, amt);
}
emit Approval(msg.sender, dst, _allowance[msg.sender][dst]);
return true;
}
function transfer(address dst, uint amt) external override returns (bool) {
_move(msg.sender, dst, amt);
return true;
}
function transferFrom(address src, address dst, uint amt) external override returns (bool) {
require(msg.sender == src || amt <= _allowance[src][msg.sender], "!spender");
_move(src, dst, amt);
if (msg.sender != src && _allowance[src][msg.sender] != uint256(-1)) {
_allowance[src][msg.sender] = bsub(_allowance[src][msg.sender], amt);
emit Approval(msg.sender, dst, _allowance[src][msg.sender]);
}
return true;
}
}
// 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/>.
contract BMath is BNum {
/**********************************************************************************************
// calcSpotPrice //
// sP = spotPrice //
// bI = tokenBalanceIn ( bI / wI ) 1 //
// bO = tokenBalanceOut sP = ----------- * ---------- //
// wI = tokenWeightIn ( bO / wO ) ( 1 - sF ) //
// wO = tokenWeightOut //
// sF = swapFee (+ collectedFee) //
**********************************************************************************************/
function calcSpotPrice(
uint tokenBalanceIn,
uint tokenWeightIn,
uint tokenBalanceOut,
uint tokenWeightOut,
uint swapFee
)
public pure
returns (uint spotPrice)
{
uint numer = bdiv(tokenBalanceIn, tokenWeightIn);
uint denom = bdiv(tokenBalanceOut, tokenWeightOut);
uint ratio = bdiv(numer, denom);
uint scale = bdiv(BConst.BONE, bsub(BConst.BONE, swapFee));
return (spotPrice = bmul(ratio, scale));
}
/**********************************************************************************************
// calcOutGivenIn //
// aO = tokenAmountOut //
// bO = tokenBalanceOut //
// bI = tokenBalanceIn / / bI \ (wI / wO) \ //
// aI = tokenAmountIn aO = bO * | 1 - | -------------------------- | ^ | //
// wI = tokenWeightIn \ \ ( bI + ( aI * ( 1 - sF )) / / //
// wO = tokenWeightOut //
// sF = swapFee (+ collectedFee) //
**********************************************************************************************/
function calcOutGivenIn(
uint tokenBalanceIn,
uint tokenWeightIn,
uint tokenBalanceOut,
uint tokenWeightOut,
uint tokenAmountIn,
uint swapFee
)
public pure
returns (uint tokenAmountOut)
{
uint weightRatio = bdiv(tokenWeightIn, tokenWeightOut);
uint adjustedIn = bsub(BConst.BONE, swapFee);
adjustedIn = bmul(tokenAmountIn, adjustedIn);
uint y = bdiv(tokenBalanceIn, badd(tokenBalanceIn, adjustedIn));
uint foo = bpow(y, weightRatio);
uint bar = bsub(BConst.BONE, foo);
tokenAmountOut = bmul(tokenBalanceOut, bar);
return tokenAmountOut;
}
/**********************************************************************************************
// calcInGivenOut //
// aI = tokenAmountIn //
// bO = tokenBalanceOut / / bO \ (wO / wI) \ //
// bI = tokenBalanceIn bI * | | ------------ | ^ - 1 | //
// aO = tokenAmountOut aI = \ \ ( bO - aO ) / / //
// wI = tokenWeightIn -------------------------------------------- //
// wO = tokenWeightOut ( 1 - sF ) //
// sF = swapFee (+ collectedFee) //
**********************************************************************************************/
function calcInGivenOut(
uint tokenBalanceIn,
uint tokenWeightIn,
uint tokenBalanceOut,
uint tokenWeightOut,
uint tokenAmountOut,
uint swapFee
)
public pure
returns (uint tokenAmountIn)
{
uint weightRatio = bdiv(tokenWeightOut, tokenWeightIn);
uint diff = bsub(tokenBalanceOut, tokenAmountOut);
uint y = bdiv(tokenBalanceOut, diff);
uint foo = bpow(y, weightRatio);
foo = bsub(foo, BConst.BONE);
tokenAmountIn = bsub(BConst.BONE, swapFee);
tokenAmountIn = bdiv(bmul(tokenBalanceIn, foo), tokenAmountIn);
return tokenAmountIn;
}
/**********************************************************************************************
// calcPoolOutGivenSingleIn //
// pAo = poolAmountOut / \ //
// tAi = tokenAmountIn /// / // wI \ \\ \ wI \ //
// wI = tokenWeightIn //| tAi *| 1 - || 1 - -- | * sF || + tBi \ -- \ //
// tW = totalWeight pAo=|| \ \ \\ tW / // | ^ tW | * pS - pS //
// tBi = tokenBalanceIn \\ ------------------------------------- / / //
// pS = poolSupply \\ tBi / / //
// sF = swapFee (+ collectedFee)\ / //
**********************************************************************************************/
function calcPoolOutGivenSingleIn(
uint tokenBalanceIn,
uint tokenWeightIn,
uint poolSupply,
uint totalWeight,
uint tokenAmountIn,
uint swapFee
)
public pure
returns (uint poolAmountOut)
{
// @dev Charge the trading fee for the proportion of tokenAi
// which is implicitly traded to the other pool tokens.
// That proportion is (1- weightTokenIn)
// tokenAiAfterFee = tAi * (1 - (1-weightTi) * poolFee);
uint normalizedWeight = bdiv(tokenWeightIn, totalWeight);
uint zaz = bmul(bsub(BConst.BONE, normalizedWeight), swapFee);
uint tokenAmountInAfterFee = bmul(tokenAmountIn, bsub(BConst.BONE, zaz));
uint newTokenBalanceIn = badd(tokenBalanceIn, tokenAmountInAfterFee);
uint tokenInRatio = bdiv(newTokenBalanceIn, tokenBalanceIn);
// uint newPoolSupply = (ratioTi ^ weightTi) * poolSupply;
uint poolRatio = bpow(tokenInRatio, normalizedWeight);
uint newPoolSupply = bmul(poolRatio, poolSupply);
poolAmountOut = bsub(newPoolSupply, poolSupply);
return poolAmountOut;
}
/**********************************************************************************************
// calcSingleInGivenPoolOut //
// tAi = tokenAmountIn //(pS + pAo)\ / 1 \\ //
// pS = poolSupply || --------- | ^ | --------- || * bI - bI //
// pAo = poolAmountOut \\ pS / \(wI / tW)// //
// bI = balanceIn tAi = -------------------------------------------- //
// wI = weightIn / wI \ //
// tW = totalWeight | 1 - ---- | * sF //
// sF = swapFee (+ collectedFee) \ tW / //
**********************************************************************************************/
function calcSingleInGivenPoolOut(
uint tokenBalanceIn,
uint tokenWeightIn,
uint poolSupply,
uint totalWeight,
uint poolAmountOut,
uint swapFee
)
public pure
returns (uint tokenAmountIn)
{
uint normalizedWeight = bdiv(tokenWeightIn, totalWeight);
uint newPoolSupply = badd(poolSupply, poolAmountOut);
uint poolRatio = bdiv(newPoolSupply, poolSupply);
//uint newBalTi = poolRatio^(1/weightTi) * balTi;
uint boo = bdiv(BConst.BONE, normalizedWeight);
uint tokenInRatio = bpow(poolRatio, boo);
uint newTokenBalanceIn = bmul(tokenInRatio, tokenBalanceIn);
uint tokenAmountInAfterFee = bsub(newTokenBalanceIn, tokenBalanceIn);
// Do reverse order of fees charged in joinswap_ExternAmountIn, this way
// ``` pAo == joinswap_ExternAmountIn(Ti, joinswap_PoolAmountOut(pAo, Ti)) ```
//uint tAi = tAiAfterFee / (1 - (1-weightTi) * swapFee) ;
uint zar = bmul(bsub(BConst.BONE, normalizedWeight), swapFee);
tokenAmountIn = bdiv(tokenAmountInAfterFee, bsub(BConst.BONE, zar));
return tokenAmountIn;
}
/**********************************************************************************************
// calcSingleOutGivenPoolIn //
// tAo = tokenAmountOut / / \\ //
// bO = tokenBalanceOut / // pS - (pAi * (1 - eF)) \ / 1 \ \\ //
// pAi = poolAmountIn | bO - || ----------------------- | ^ | --------- | * b0 || //
// ps = poolSupply \ \\ pS / \(wO / tW)/ // //
// wI = tokenWeightIn tAo = \ \ // //
// tW = totalWeight / / wO \ \ //
// sF = swapFee (+ collectedFee) * | 1 - | 1 - ---- | * sF | //
// eF = exitFee \ \ tW / / //
**********************************************************************************************/
function calcSingleOutGivenPoolIn(
uint tokenBalanceOut,
uint tokenWeightOut,
uint poolSupply,
uint totalWeight,
uint poolAmountIn,
uint swapFee,
uint exitFee
)
public pure
returns (uint tokenAmountOut)
{
uint normalizedWeight = bdiv(tokenWeightOut, totalWeight);
// charge exit fee on the pool token side
// pAiAfterExitFee = pAi*(1-exitFee)
uint poolAmountInAfterExitFee = bmul(poolAmountIn, bsub(BConst.BONE, exitFee));
uint newPoolSupply = bsub(poolSupply, poolAmountInAfterExitFee);
uint poolRatio = bdiv(newPoolSupply, poolSupply);
// newBalTo = poolRatio^(1/weightTo) * balTo;
uint tokenOutRatio = bpow(poolRatio, bdiv(BConst.BONE, normalizedWeight));
uint newTokenBalanceOut = bmul(tokenOutRatio, tokenBalanceOut);
uint tokenAmountOutBeforeSwapFee = bsub(tokenBalanceOut, newTokenBalanceOut);
// charge swap fee on the output token side
//uint tAo = tAoBeforeSwapFee * (1 - (1-weightTo) * swapFee)
uint zaz = bmul(bsub(BConst.BONE, normalizedWeight), swapFee);
tokenAmountOut = bmul(tokenAmountOutBeforeSwapFee, bsub(BConst.BONE, zaz));
return tokenAmountOut;
}
/**********************************************************************************************
// calcPoolInGivenSingleOut //
// pAi = poolAmountIn // / tAo \\ / wO \ \ //
// bO = tokenBalanceOut // | bO - -------------------------- |\ | ---- | \ //
// tAo = tokenAmountOut pS - || \ 1 - ((1 - (tO / tW)) * sF)/ | ^ \ tW / * pS | //
// ps = poolSupply \\ -----------------------------------/ / //
// wO = tokenWeightOut pAi = \\ bO / / //
// tW = totalWeight ------------------------------------------------------------- //
// sF = swapFee (+ collectedFee) ( 1 - eF ) //
// eF = exitFee //
**********************************************************************************************/
function calcPoolInGivenSingleOut(
uint tokenBalanceOut,
uint tokenWeightOut,
uint poolSupply,
uint totalWeight,
uint tokenAmountOut,
uint swapFee,
uint exitFee
)
public pure
returns (uint poolAmountIn)
{
// charge swap fee on the output token side
uint normalizedWeight = bdiv(tokenWeightOut, totalWeight);
//uint tAoBeforeSwapFee = tAo / (1 - (1-weightTo) * swapFee) ;
uint zoo = bsub(BConst.BONE, normalizedWeight);
uint zar = bmul(zoo, swapFee);
uint tokenAmountOutBeforeSwapFee = bdiv(tokenAmountOut, bsub(BConst.BONE, zar));
uint newTokenBalanceOut = bsub(tokenBalanceOut, tokenAmountOutBeforeSwapFee);
uint tokenOutRatio = bdiv(newTokenBalanceOut, tokenBalanceOut);
//uint newPoolSupply = (ratioTo ^ weightTo) * poolSupply;
uint poolRatio = bpow(tokenOutRatio, normalizedWeight);
uint newPoolSupply = bmul(poolRatio, poolSupply);
uint poolAmountInAfterExitFee = bsub(poolSupply, newPoolSupply);
// charge exit fee on the pool token side
// pAi = pAiAfterExitFee/(1-exitFee)
poolAmountIn = bdiv(poolAmountInAfterExitFee, bsub(BConst.BONE, exitFee));
return poolAmountIn;
}
}
// 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/>.
interface IBFactory {
function collectedToken() external view returns(address);
}
contract BPool is BToken, BMath {
struct Record {
bool bound; // is token bound to pool
uint index; // private
uint denorm; // denormalized weight
uint balance;
}
event LOG_SWAP(
address indexed caller,
address indexed tokenIn,
address indexed tokenOut,
uint256 tokenAmountIn,
uint256 tokenAmountOut
);
event LOG_JOIN(
address indexed caller,
address indexed tokenIn,
uint256 tokenAmountIn
);
event LOG_EXIT(
address indexed caller,
address indexed tokenOut,
uint256 tokenAmountOut
);
event LOG_CALL(
bytes4 indexed sig,
address indexed caller,
bytes data
) anonymous;
modifier _logs_() {
emit LOG_CALL(msg.sig, msg.sender, msg.data);
_;
}
event LOG_COLLECTED_FUND(
address indexed collectedToken,
uint256 collectedAmount
);
modifier _lock_() {
require(!_mutex, "reentry");
_mutex = true;
_;
_mutex = false;
}
modifier _viewlock_() {
require(!_mutex, "reentry");
_;
}
bool private _mutex;
uint public version = 1001;
address public factory; // BFactory address to push token exitFee to
address public controller; // has CONTROL role
bool public publicSwap;
// `setSwapFee` and `finalize` require CONTROL
// `finalize` sets `PUBLIC can SWAP`, `PUBLIC can JOIN`
uint public initPoolSupply;
uint public swapFee;
uint public collectedFee; // 0.05% | https://yfv.finance/vip-vote/vip_5
uint public exitFee;
bool public finalized;
address[] private _tokens;
mapping(address => Record) private _records;
uint private _totalWeight;
constructor(address _factory) public {
controller = _factory;
factory = _factory;
initPoolSupply = BConst.DEFAULT_INIT_POOL_SUPPLY;
swapFee = BConst.DEFAULT_FEE;
collectedFee = BConst.DEFAULT_COLLECTED_FEE;
exitFee = BConst.DEFAULT_EXIT_FEE;
publicSwap = false;
finalized = false;
}
function setInitPoolSupply(uint _initPoolSupply) public _logs_ {
require(!finalized, "finalized");
require(msg.sender == controller, "!controller");
require(_initPoolSupply >= BConst.MIN_INIT_POOL_SUPPLY, "<minInitPoolSup");
require(_initPoolSupply <= BConst.MAX_INIT_POOL_SUPPLY, ">maxInitPoolSup");
initPoolSupply = _initPoolSupply;
}
function setCollectedFee(uint _collectedFee) public _logs_ {
require(msg.sender == factory, "!factory");
require(_collectedFee <= BConst.MAX_COLLECTED_FEE, ">maxCoFee");
require(bmul(_collectedFee, 2) <= swapFee, ">swapFee/2");
collectedFee = _collectedFee;
}
function setExitFee(uint _exitFee) public _logs_ {
require(!finalized, "finalized");
require(msg.sender == factory, "!factory");
require(_exitFee <= BConst.MAX_EXIT_FEE, ">maxExitFee");
exitFee = _exitFee;
}
function isBound(address t)
external view
returns (bool)
{
return _records[t].bound;
}
function getNumTokens()
external view
returns (uint)
{
return _tokens.length;
}
function getCurrentTokens()
external view _viewlock_
returns (address[] memory tokens)
{
return _tokens;
}
function getFinalTokens()
external view
_viewlock_
returns (address[] memory tokens)
{
require(finalized, "!finalized");
return _tokens;
}
function getDenormalizedWeight(address token)
external view
_viewlock_
returns (uint)
{
require(_records[token].bound, "!bound");
return _records[token].denorm;
}
function getTotalDenormalizedWeight()
external view
_viewlock_
returns (uint)
{
return _totalWeight;
}
function getNormalizedWeight(address token)
external view
_viewlock_
returns (uint)
{
require(_records[token].bound, "!bound");
uint denorm = _records[token].denorm;
return bdiv(denorm, _totalWeight);
}
function getBalance(address token)
external view
_viewlock_
returns (uint)
{
require(_records[token].bound, "!bound");
return _records[token].balance;
}
function setSwapFee(uint _swapFee)
external
_lock_
_logs_
{
require(!finalized, "finalized");
require(msg.sender == controller, "!controller");
require(_swapFee >= BConst.MIN_FEE, "<minFee");
require(_swapFee <= BConst.MAX_FEE, ">maxFee");
require(bmul(collectedFee, 2) <= _swapFee, "<collectedFee*2");
swapFee = _swapFee;
}
function setController(address _controller)
external
_lock_
_logs_
{
require(msg.sender == controller, "!controller");
controller = _controller;
}
function setPublicSwap(bool _publicSwap)
external
_lock_
_logs_
{
require(!finalized, "finalized");
require(msg.sender == controller, "!controller");
publicSwap = _publicSwap;
}
function finalize()
external
_lock_
_logs_
{
require(msg.sender == controller, "!controller");
require(!finalized, "finalized");
require(_tokens.length >= BConst.MIN_BOUND_TOKENS, "<minTokens");
finalized = true;
publicSwap = true;
_mintPoolShare(initPoolSupply);
_pushPoolShare(msg.sender, initPoolSupply);
}
function bind(address token, uint balance, uint denorm)
external
_logs_
// _lock_ Bind does not lock because it jumps to `rebind`, which does
{
require(msg.sender == controller, "!controller");
require(!_records[token].bound, "bound");
require(!finalized, "finalized");
require(_tokens.length < BConst.MAX_BOUND_TOKENS, ">maxTokens");
_records[token] = Record({
bound: true,
index: _tokens.length,
denorm: 0, // balance and denorm will be validated
balance: 0 // and set by `rebind`
});
_tokens.push(token);
rebind(token, balance, denorm);
}
function rebind(address token, uint balance, uint denorm)
public
_lock_
_logs_
{
require(msg.sender == controller, "!controller");
require(_records[token].bound, "!bound");
require(!finalized, "finalized");
require(denorm >= BConst.MIN_WEIGHT, "<minWeight");
require(denorm <= BConst.MAX_WEIGHT, ">maxWeight");
require(balance >= BConst.MIN_BALANCE, "<minBal");
// Adjust the denorm and totalWeight
uint oldWeight = _records[token].denorm;
if (denorm > oldWeight) {
_totalWeight = badd(_totalWeight, bsub(denorm, oldWeight));
require(_totalWeight <= BConst.MAX_TOTAL_WEIGHT, ">maxTWeight");
} else if (denorm < oldWeight) {
_totalWeight = bsub(_totalWeight, bsub(oldWeight, denorm));
}
_records[token].denorm = denorm;
// Adjust the balance record and actual token balance
uint oldBalance = _records[token].balance;
_records[token].balance = balance;
if (balance > oldBalance) {
_pullUnderlying(token, msg.sender, bsub(balance, oldBalance));
} else if (balance < oldBalance) {
// In this case liquidity is being withdrawn, so charge EXIT_FEE
uint tokenBalanceWithdrawn = bsub(oldBalance, balance);
uint tokenExitFee = bmul(tokenBalanceWithdrawn, exitFee);
_pushUnderlying(token, msg.sender, bsub(tokenBalanceWithdrawn, tokenExitFee));
_pushUnderlying(token, factory, tokenExitFee);
}
}
function unbind(address token)
external
_lock_
_logs_
{
require(msg.sender == controller, "!controller");
require(_records[token].bound, "!bound");
require(!finalized, "finalized");
uint tokenBalance = _records[token].balance;
uint tokenExitFee = bmul(tokenBalance, exitFee);
_totalWeight = bsub(_totalWeight, _records[token].denorm);
// Swap the token-to-unbind with the last token,
// then delete the last token
uint index = _records[token].index;
uint last = _tokens.length - 1;
_tokens[index] = _tokens[last];
_records[_tokens[index]].index = index;
_tokens.pop();
_records[token] = Record({
bound: false,
index: 0,
denorm: 0,
balance: 0
});
_pushUnderlying(token, msg.sender, bsub(tokenBalance, tokenExitFee));
_pushUnderlying(token, factory, tokenExitFee);
}
// Absorb any tokens that have been sent to this contract into the pool
function gulp(address token)
external
_logs_
_lock_
{
require(_records[token].bound, "!bound");
_records[token].balance = IERC20(token).balanceOf(address(this));
}
function getSpotPrice(address tokenIn, address tokenOut)
external view
_viewlock_
returns (uint spotPrice)
{
require(_records[tokenIn].bound, "!bound");
require(_records[tokenOut].bound, "!bound");
Record storage inRecord = _records[tokenIn];
Record storage outRecord = _records[tokenOut];
return calcSpotPrice(inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, swapFee);
}
function getSpotPriceSansFee(address tokenIn, address tokenOut)
external view
_viewlock_
returns (uint spotPrice)
{
require(_records[tokenIn].bound, "!bound");
require(_records[tokenOut].bound, "!bound");
Record storage inRecord = _records[tokenIn];
Record storage outRecord = _records[tokenOut];
return calcSpotPrice(inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, 0);
}
function joinPool(uint poolAmountOut, uint[] calldata maxAmountsIn)
external
_lock_
_logs_
{
require(finalized, "!finalized");
uint poolTotal = totalSupply();
uint ratio = bdiv(poolAmountOut, poolTotal);
require(ratio != 0, "errMathAprox");
for (uint i = 0; i < _tokens.length; i++) {
address t = _tokens[i];
uint bal = _records[t].balance;
uint tokenAmountIn = bmul(ratio, bal);
require(tokenAmountIn != 0, "errMathAprox");
require(tokenAmountIn <= maxAmountsIn[i], "<limIn");
_records[t].balance = badd(_records[t].balance, tokenAmountIn);
emit LOG_JOIN(msg.sender, t, tokenAmountIn);
_pullUnderlying(t, msg.sender, tokenAmountIn);
}
_mintPoolShare(poolAmountOut);
_pushPoolShare(msg.sender, poolAmountOut);
}
function exitPool(uint poolAmountIn, uint[] calldata minAmountsOut)
external
_lock_
_logs_
{
require(finalized, "!finalized");
uint poolTotal = totalSupply();
uint _exitFee = bmul(poolAmountIn, exitFee);
uint pAiAfterExitFee = bsub(poolAmountIn, _exitFee);
uint ratio = bdiv(pAiAfterExitFee, poolTotal);
require(ratio != 0, "errMathAprox");
_pullPoolShare(msg.sender, poolAmountIn);
_pushPoolShare(factory, _exitFee);
_burnPoolShare(pAiAfterExitFee);
for (uint i = 0; i < _tokens.length; i++) {
address t = _tokens[i];
uint bal = _records[t].balance;
uint tokenAmountOut = bmul(ratio, bal);
require(tokenAmountOut != 0, "errMathAprox");
require(tokenAmountOut >= minAmountsOut[i], "<limO");
_records[t].balance = bsub(_records[t].balance, tokenAmountOut);
emit LOG_EXIT(msg.sender, t, tokenAmountOut);
_pushUnderlying(t, msg.sender, tokenAmountOut);
}
}
function swapExactAmountIn(
address tokenIn,
uint tokenAmountIn,
address tokenOut,
uint minAmountOut,
uint maxPrice
)
external
_lock_
_logs_
returns (uint tokenAmountOut, uint spotPriceAfter)
{
require(_records[tokenIn].bound, "!bound");
require(_records[tokenOut].bound, "!bound");
require(publicSwap, "!publicSwap");
Record storage inRecord = _records[address(tokenIn)];
Record storage outRecord = _records[address(tokenOut)];
require(tokenAmountIn <= bmul(inRecord.balance, BConst.MAX_IN_RATIO), ">maxIRat");
uint spotPriceBefore = calcSpotPrice(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
swapFee
);
require(spotPriceBefore <= maxPrice, "badLimPrice");
tokenAmountOut = calcOutGivenIn(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
tokenAmountIn,
swapFee
);
require(tokenAmountOut >= minAmountOut, "<limO");
inRecord.balance = badd(inRecord.balance, tokenAmountIn);
outRecord.balance = bsub(outRecord.balance, tokenAmountOut);
spotPriceAfter = calcSpotPrice(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
swapFee
);
require(spotPriceAfter >= spotPriceBefore, "errMathAprox");
require(spotPriceAfter <= maxPrice, ">limPrice");
require(spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOut), "errMathAprox");
emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOut);
_pullUnderlying(tokenIn, msg.sender, tokenAmountIn);
uint _subTokenAmountIn;
(_subTokenAmountIn, tokenAmountOut) = _pushCollectedFundGivenOut(tokenIn, tokenAmountIn, tokenOut, tokenAmountOut);
if (_subTokenAmountIn > 0) inRecord.balance = bsub(inRecord.balance, _subTokenAmountIn);
_pushUnderlying(tokenOut, msg.sender, tokenAmountOut);
return (tokenAmountOut, spotPriceAfter);
}
function swapExactAmountOut(
address tokenIn,
uint maxAmountIn,
address tokenOut,
uint tokenAmountOut,
uint maxPrice
)
external
_lock_
_logs_
returns (uint tokenAmountIn, uint spotPriceAfter)
{
require(_records[tokenIn].bound, "!bound");
require(_records[tokenOut].bound, "!bound");
require(publicSwap, "!publicSwap");
Record storage inRecord = _records[address(tokenIn)];
Record storage outRecord = _records[address(tokenOut)];
require(tokenAmountOut <= bmul(outRecord.balance, BConst.MAX_OUT_RATIO), ">maxORat");
uint spotPriceBefore = calcSpotPrice(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
swapFee
);
require(spotPriceBefore <= maxPrice, "badLimPrice");
tokenAmountIn = calcInGivenOut(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
tokenAmountOut,
swapFee
);
require(tokenAmountIn <= maxAmountIn, "<limIn");
inRecord.balance = badd(inRecord.balance, tokenAmountIn);
outRecord.balance = bsub(outRecord.balance, tokenAmountOut);
spotPriceAfter = calcSpotPrice(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
swapFee
);
require(spotPriceAfter >= spotPriceBefore, "errMathAprox");
require(spotPriceAfter <= maxPrice, ">limPrice");
require(spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOut), "errMathAprox");
emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOut);
_pullUnderlying(tokenIn, msg.sender, tokenAmountIn);
_pushUnderlying(tokenOut, msg.sender, tokenAmountOut);
uint _collectedFeeAmount = _pushCollectedFundGivenIn(tokenIn, tokenAmountIn);
if (_collectedFeeAmount > 0) inRecord.balance = bsub(inRecord.balance, _collectedFeeAmount);
return (tokenAmountIn, spotPriceAfter);
}
function joinswapExternAmountIn(address tokenIn, uint tokenAmountIn, uint minPoolAmountOut)
external
_lock_
_logs_
returns (uint poolAmountOut)
{
require(finalized, "!finalized");
require(_records[tokenIn].bound, "!bound");
require(tokenAmountIn <= bmul(_records[tokenIn].balance, BConst.MAX_IN_RATIO), ">maxIRat");
Record storage inRecord = _records[tokenIn];
poolAmountOut = calcPoolOutGivenSingleIn(
inRecord.balance,
inRecord.denorm,
_totalSupply,
_totalWeight,
tokenAmountIn,
swapFee
);
require(poolAmountOut >= minPoolAmountOut, "<limO");
inRecord.balance = badd(inRecord.balance, tokenAmountIn);
emit LOG_JOIN(msg.sender, tokenIn, tokenAmountIn);
_mintPoolShare(poolAmountOut);
_pullUnderlying(tokenIn, msg.sender, tokenAmountIn);
uint _subTokenAmountIn;
(_subTokenAmountIn, poolAmountOut) = _pushCollectedFundGivenOut(tokenIn, tokenAmountIn, address(this), poolAmountOut);
if (_subTokenAmountIn > 0) inRecord.balance = bsub(inRecord.balance, _subTokenAmountIn);
_pushPoolShare(msg.sender, poolAmountOut);
return poolAmountOut;
}
function joinswapPoolAmountOut(address tokenIn, uint poolAmountOut, uint maxAmountIn)
external
_lock_
_logs_
returns (uint tokenAmountIn)
{
require(finalized, "!finalized");
require(_records[tokenIn].bound, "!bound");
Record storage inRecord = _records[tokenIn];
tokenAmountIn = calcSingleInGivenPoolOut(
inRecord.balance,
inRecord.denorm,
_totalSupply,
_totalWeight,
poolAmountOut,
swapFee
);
require(tokenAmountIn != 0, "errMathAprox");
require(tokenAmountIn <= maxAmountIn, "<limIn");
require(tokenAmountIn <= bmul(_records[tokenIn].balance, BConst.MAX_IN_RATIO), ">maxIRat");
inRecord.balance = badd(inRecord.balance, tokenAmountIn);
emit LOG_JOIN(msg.sender, tokenIn, tokenAmountIn);
_mintPoolShare(poolAmountOut);
_pushPoolShare(msg.sender, poolAmountOut);
_pullUnderlying(tokenIn, msg.sender, tokenAmountIn);
uint _collectedFeeAmount = _pushCollectedFundGivenIn(tokenIn, tokenAmountIn);
if (_collectedFeeAmount > 0) inRecord.balance = bsub(inRecord.balance, _collectedFeeAmount);
return tokenAmountIn;
}
function exitswapPoolAmountIn(address tokenOut, uint poolAmountIn, uint minAmountOut)
external
_lock_
_logs_
returns (uint tokenAmountOut)
{
require(finalized, "!finalized");
require(_records[tokenOut].bound, "!bound");
Record storage outRecord = _records[tokenOut];
tokenAmountOut = calcSingleOutGivenPoolIn(
outRecord.balance,
outRecord.denorm,
_totalSupply,
_totalWeight,
poolAmountIn,
swapFee,
exitFee
);
require(tokenAmountOut >= minAmountOut, "<limO");
require(tokenAmountOut <= bmul(_records[tokenOut].balance, BConst.MAX_OUT_RATIO), ">maxORat");
outRecord.balance = bsub(outRecord.balance, tokenAmountOut);
uint _exitFee = bmul(poolAmountIn, exitFee);
emit LOG_EXIT(msg.sender, tokenOut, tokenAmountOut);
_pullPoolShare(msg.sender, poolAmountIn);
_burnPoolShare(bsub(poolAmountIn, _exitFee));
_pushPoolShare(factory, _exitFee);
(, tokenAmountOut) = _pushCollectedFundGivenOut(address(this), poolAmountIn, tokenOut, tokenAmountOut);
_pushUnderlying(tokenOut, msg.sender, tokenAmountOut);
return tokenAmountOut;
}
function exitswapExternAmountOut(address tokenOut, uint tokenAmountOut, uint maxPoolAmountIn)
external
_lock_
_logs_
returns (uint poolAmountIn)
{
require(finalized, "!finalized");
require(_records[tokenOut].bound, "!bound");
require(tokenAmountOut <= bmul(_records[tokenOut].balance, BConst.MAX_OUT_RATIO), ">maxORat");
Record storage outRecord = _records[tokenOut];
poolAmountIn = calcPoolInGivenSingleOut(
outRecord.balance,
outRecord.denorm,
_totalSupply,
_totalWeight,
tokenAmountOut,
swapFee,
exitFee
);
require(poolAmountIn != 0, "errMathAprox");
require(poolAmountIn <= maxPoolAmountIn, "<limIn");
outRecord.balance = bsub(outRecord.balance, tokenAmountOut);
uint _exitFee = bmul(poolAmountIn, exitFee);
emit LOG_EXIT(msg.sender, tokenOut, tokenAmountOut);
_pullPoolShare(msg.sender, poolAmountIn);
uint _collectedFeeAmount = _pushCollectedFundGivenIn(address(this), poolAmountIn);
_burnPoolShare(bsub(bsub(poolAmountIn, _exitFee), _collectedFeeAmount));
_pushPoolShare(factory, _exitFee);
_pushUnderlying(tokenOut, msg.sender, tokenAmountOut);
return poolAmountIn;
}
// ==
// 'Underlying' token-manipulation functions make external calls but are NOT locked
// You must `_lock_` or otherwise ensure reentry-safety
function _pullUnderlying(address erc20, address from, uint amount)
internal
{
bool xfer = IERC20(erc20).transferFrom(from, address(this), amount);
require(xfer, "errErc20");
}
function _pushUnderlying(address erc20, address to, uint amount)
internal
{
bool xfer = IERC20(erc20).transfer(to, amount);
require(xfer, "errErc20");
}
function _pullPoolShare(address from, uint amount)
internal
{
_pull(from, amount);
}
function _pushPoolShare(address to, uint amount)
internal
{
_push(to, amount);
}
function _mintPoolShare(uint amount)
internal
{
_mint(amount);
}
function _burnPoolShare(uint amount)
internal
{
_burn(amount);
}
function _pushCollectedFundGivenOut(address _tokenIn, uint _tokenAmountIn, address _tokenOut, uint _tokenAmountOut) internal returns (uint subTokenAmountIn, uint tokenAmountOut) {
subTokenAmountIn = 0;
tokenAmountOut = _tokenAmountOut;
if (collectedFee > 0) {
address _collectedToken = IBFactory(factory).collectedToken();
if (_collectedToken == _tokenIn) {
subTokenAmountIn = bdiv(bmul(_tokenAmountIn, collectedFee), BConst.BONE);
_pushUnderlying(_tokenIn, factory, subTokenAmountIn);
emit LOG_COLLECTED_FUND(_tokenIn, subTokenAmountIn);
} else {
uint _collectedFeeAmount = bdiv(bmul(_tokenAmountOut, collectedFee), BConst.BONE);
_pushUnderlying(_tokenOut, factory, _collectedFeeAmount);
tokenAmountOut = bsub(_tokenAmountOut, _collectedFeeAmount);
emit LOG_COLLECTED_FUND(_tokenOut, _collectedFeeAmount);
}
}
}
// always push out _tokenIn (already have)
function _pushCollectedFundGivenIn(address _tokenIn, uint _tokenAmountIn) internal returns (uint collectedFeeAmount) {
collectedFeeAmount = 0;
if (collectedFee > 0) {
address _collectedToken = IBFactory(factory).collectedToken();
if (_collectedToken != address(0)) {
collectedFeeAmount = bdiv(bmul(_tokenAmountIn, collectedFee), BConst.BONE);
_pushUnderlying(_tokenIn, factory, collectedFeeAmount);
emit LOG_COLLECTED_FUND(_tokenIn, collectedFeeAmount);
}
}
}
}
// 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 disstributed 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/>.
// Builds new BPools, logging their addresses and providing `isBPool(address) -> (bool)`
contract BPoolCreator {
function newBPool() external returns (BPool) {
return new BPool(msg.sender);
}
} | term 0: term(k) = numer / denom = (product(a - i - 1, i=1-->k) * x^k) / (k!) each iteration, multiply previous term by (a-(k-1)) * x / k continue until term is less than precision | function bpowApprox(uint base, uint exp, uint precision)
internal pure
returns (uint)
{
uint a = exp;
(uint x, bool xneg) = bsubSign(base, BConst.BONE);
uint term = BConst.BONE;
uint sum = term;
bool negative = false;
for (uint i = 1; term >= precision; i++) {
uint bigK = i * BConst.BONE;
(uint c, bool cneg) = bsubSign(a, bsub(bigK, BConst.BONE));
term = bmul(term, bmul(c, x));
term = bdiv(term, bigK);
if (term == 0) break;
if (xneg) negative = !negative;
if (cneg) negative = !negative;
if (negative) {
sum = bsub(sum, term);
sum = badd(sum, term);
}
}
return sum;
}
| 2,076,624 | [
1,
6408,
374,
30,
2481,
12,
79,
13,
273,
26511,
342,
10716,
540,
273,
261,
5896,
12,
69,
300,
277,
300,
404,
16,
277,
33,
21,
413,
34,
79,
13,
225,
619,
66,
79,
13,
342,
261,
79,
24949,
1517,
6532,
16,
10194,
2416,
2481,
635,
261,
69,
17,
12,
79,
17,
21,
3719,
225,
619,
342,
417,
1324,
3180,
2481,
353,
5242,
2353,
6039,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
9107,
543,
25789,
12,
11890,
1026,
16,
2254,
1329,
16,
2254,
6039,
13,
203,
565,
2713,
16618,
203,
565,
1135,
261,
11890,
13,
203,
565,
288,
203,
3639,
2254,
279,
377,
273,
1329,
31,
203,
3639,
261,
11890,
619,
16,
1426,
619,
14518,
13,
225,
273,
324,
1717,
2766,
12,
1969,
16,
605,
9661,
18,
38,
5998,
1769,
203,
3639,
2254,
2481,
273,
605,
9661,
18,
38,
5998,
31,
203,
3639,
2254,
2142,
282,
273,
2481,
31,
203,
3639,
1426,
6092,
273,
629,
31,
203,
203,
203,
3639,
364,
261,
11890,
277,
273,
404,
31,
2481,
1545,
6039,
31,
277,
27245,
288,
203,
5411,
2254,
5446,
47,
273,
277,
380,
605,
9661,
18,
38,
5998,
31,
203,
5411,
261,
11890,
276,
16,
1426,
6227,
1332,
13,
273,
324,
1717,
2766,
12,
69,
16,
324,
1717,
12,
14002,
47,
16,
605,
9661,
18,
38,
5998,
10019,
203,
5411,
2481,
273,
324,
16411,
12,
6408,
16,
324,
16411,
12,
71,
16,
619,
10019,
203,
5411,
2481,
273,
324,
2892,
12,
6408,
16,
5446,
47,
1769,
203,
5411,
309,
261,
6408,
422,
374,
13,
898,
31,
203,
203,
5411,
309,
261,
92,
14518,
13,
6092,
273,
401,
13258,
31,
203,
5411,
309,
261,
10305,
1332,
13,
6092,
273,
401,
13258,
31,
203,
5411,
309,
261,
13258,
13,
288,
203,
7734,
2142,
273,
324,
1717,
12,
1364,
16,
2481,
1769,
203,
7734,
2142,
273,
324,
1289,
12,
1364,
16,
2481,
1769,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
327,
2142,
31,
203,
565,
289,
2
] |
/**
*Submitted for verification at Etherscan.io on 2021-12-16
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
/*
* @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;
}
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev 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);
}
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
/**
* @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);
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
function _bulkMint(address[] memory account, uint256[] memory amount) internal virtual {
address[] memory from = new address[](1);
from[0] = address(0);
_beforeBulkTokenTransfer(from, account, amount);
require (account.length == amount.length, "ERC20: incorrect data array size");
uint256 totalSupplyIncrease = 0;
for(uint i = 0; i < account.length; i++){
require(account[i] != address(0), "ERC20: mint to the zero address");
totalSupplyIncrease += amount[i];
_balances[account[i]] += amount[i];
emit Transfer(address(0), account[i], amount[i]);
}
_totalSupply += totalSupplyIncrease;
_afterBulkTokenTransfer(from, 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);
}
function _bulkBurn(address[] memory account, uint256[] memory amount) internal virtual {
address[] memory to = new address[](1);
to[0] = address(0);
_beforeBulkTokenTransfer(account, to, amount);
require (account.length == amount.length, "ERC20: incorrect data array size");
uint256 totalSupplyDecrease = 0;
for(uint i = 0; i < account.length; i++){
uint256 accountBalance = _balances[account[i]];
require(accountBalance >= amount[i], "ERC20: burn amount exceeds balance");
unchecked {
_balances[account[i]] = accountBalance - amount[i];
}
totalSupplyDecrease += amount[i];
emit Transfer(account[i], address(0), amount[i]);
}
_totalSupply -= totalSupplyDecrease;
_afterBulkTokenTransfer(account, to, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
function _beforeBulkTokenTransfer(
address[] memory from,
address[] memory to,
uint256[] memory 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 {}
function _afterBulkTokenTransfer(
address[] memory from,
address[] memory to,
uint256[] memory amount
) internal virtual {}
uint256[45] private __gap;
}
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
/**
* @dev ERC20 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC20PausableUpgradeable is Initializable, ERC20Upgradeable, PausableUpgradeable {
function __ERC20Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
__ERC20Pausable_init_unchained();
}
function __ERC20Pausable_init_unchained() internal initializer {
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(!paused(), "ERC20Pausable: token transfer while paused");
}
function _beforeBulkTokenTransfer(
address[] memory from,
address[] memory to,
uint256[] memory amount
) internal virtual override {
super._beforeBulkTokenTransfer(from, to, amount);
require(!paused(), "ERC20Pausable: token transfer while paused");
}
uint256[50] private __gap;
}
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
/**
* @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 Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
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]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
interface IGeoToken is IERC20Upgradeable {
function bulkMint(address[] memory _to, uint256[] memory _amount) external;
function bulkBurn(address[] memory _from, uint256[] memory _amount) external;
}
contract GeoToken is ERC20PausableUpgradeable, AccessControlUpgradeable, IGeoToken{
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
function initialize(address _admin) public initializer {
__AccessControl_init();
__ERC20Pausable_init();
__ERC20_init_unchained("GEOPay UAH", "UAHg");
_setupRole(DEFAULT_ADMIN_ROLE, _admin);
}
function version() public pure returns (uint32){
//version in format aaa.bbb.ccc => aaa*1E6+bbb*1E3+ccc;
return uint32(1000001);
}
modifier onlyAdmin() {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Caller is not the Admin");
_;
}
modifier onlyMinter() {
require(hasRole(MINTER_ROLE, _msgSender()), "Caller is not a Minter");
_;
}
function decimals() public view virtual override returns (uint8) {
return 6;
}
//admin functions
function pause() onlyAdmin public {
super._pause();
}
function unpause() onlyAdmin public {
super._unpause();
}
// Minter functions
function bulkMint(address[] memory _to, uint256[] memory _amount) public override onlyMinter {
_bulkMint(_to, _amount);
}
function bulkBurn(address[] memory _from, uint256[] memory _amount) public override onlyMinter {
_bulkBurn(_from, _amount);
}
} | * @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 {
bool private _initialized;
bool private _initializing;
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
| 2,004,290 | [
1,
2503,
353,
279,
1026,
6835,
358,
20702,
316,
7410,
8400,
429,
20092,
16,
578,
1281,
3846,
434,
6835,
716,
903,
506,
19357,
21478,
279,
2889,
18,
7897,
279,
21875,
6835,
848,
1404,
1240,
279,
3885,
16,
518,
1807,
2975,
358,
3635,
3885,
4058,
358,
392,
3903,
12562,
445,
16,
11234,
2566,
1375,
11160,
8338,
2597,
1508,
12724,
4573,
358,
17151,
333,
12562,
445,
1427,
518,
848,
1338,
506,
2566,
3647,
18,
1021,
288,
22181,
97,
9606,
2112,
635,
333,
6835,
903,
1240,
333,
5426,
18,
399,
2579,
30,
2974,
4543,
15086,
326,
2889,
316,
392,
640,
13227,
919,
16,
326,
12562,
445,
1410,
506,
2566,
487,
11646,
487,
3323,
635,
17721,
326,
3749,
445,
745,
487,
326,
1375,
67,
892,
68,
1237,
358,
288,
654,
39,
3657,
9599,
3886,
17,
12316,
5496,
6425,
13269,
30,
5203,
1399,
598,
16334,
16,
11297,
7671,
1297,
506,
9830,
358,
486,
4356,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
17801,
6835,
10188,
6934,
288,
203,
565,
1426,
3238,
389,
13227,
31,
203,
203,
565,
1426,
3238,
389,
6769,
6894,
31,
203,
203,
203,
203,
565,
9606,
12562,
1435,
288,
203,
3639,
2583,
24899,
6769,
6894,
747,
401,
67,
13227,
16,
315,
4435,
6934,
30,
6835,
353,
1818,
6454,
8863,
203,
203,
3639,
1426,
353,
27046,
1477,
273,
401,
67,
6769,
6894,
31,
203,
3639,
309,
261,
291,
27046,
1477,
13,
288,
203,
5411,
389,
6769,
6894,
273,
638,
31,
203,
5411,
389,
13227,
273,
638,
31,
203,
3639,
289,
203,
203,
3639,
389,
31,
203,
203,
3639,
309,
261,
291,
27046,
1477,
13,
288,
203,
5411,
389,
6769,
6894,
273,
629,
31,
203,
3639,
289,
203,
565,
289,
203,
565,
9606,
12562,
1435,
288,
203,
3639,
2583,
24899,
6769,
6894,
747,
401,
67,
13227,
16,
315,
4435,
6934,
30,
6835,
353,
1818,
6454,
8863,
203,
203,
3639,
1426,
353,
27046,
1477,
273,
401,
67,
6769,
6894,
31,
203,
3639,
309,
261,
291,
27046,
1477,
13,
288,
203,
5411,
389,
6769,
6894,
273,
638,
31,
203,
5411,
389,
13227,
273,
638,
31,
203,
3639,
289,
203,
203,
3639,
389,
31,
203,
203,
3639,
309,
261,
291,
27046,
1477,
13,
288,
203,
5411,
389,
6769,
6894,
273,
629,
31,
203,
3639,
289,
203,
565,
289,
203,
565,
9606,
12562,
1435,
288,
203,
3639,
2583,
24899,
6769,
6894,
747,
401,
67,
13227,
16,
315,
4435,
6934,
30,
6835,
353,
1818,
6454,
8863,
203,
203,
3639,
1426,
353,
27046,
1477,
273,
401,
67,
6769,
6894,
31,
203,
2
] |
/* https://birb.ninja */
// SPDX-License-Identifier: MIT
// File: birb.sol
pragma solidity 0.8.10;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this;
return msg.data;
}
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
contract ERC20 is Context, IERC20, IERC20Metadata {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
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;
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != -1 || a != MIN_INT256);
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract Birb 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;
bool public lpBurnEnabled = false;
uint256 public lpBurnFrequency = 7200 seconds;
uint256 public lastLpBurnTime;
uint256 public manualBurnFrequency = 30 minutes;
uint256 public lastManualLpBurnTime;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
mapping(address => uint256) private _holderLastTransferTimestamp;
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("Birb", "BIRB") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 1;
uint256 _buyLiquidityFee = 3;
uint256 _buyDevFee = 1;
uint256 _sellMarketingFee = 1;
uint256 _sellLiquidityFee = 3;
uint256 _sellDevFee = 1;
uint256 totalSupply = 1 * 1e12 * 1e18;
maxTransactionAmount = totalSupply * 4 / 100;
maxWallet = totalSupply * 8 / 100;
swapTokensAtAmount = totalSupply * 8 / 1000;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
marketingWallet = address(owner());
devWallet = address(owner());
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint(msg.sender, totalSupply);
}
receive() external payable {
}
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
lastLpBurnTime = block.timestamp;
}
function removeLimits() external onlyOwner returns (bool){
limitsInEffect = false;
return true;
}
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.");
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 updateSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
require(buyTotalFees <= 20, "Must keep fees at 20% or less");
}
function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
require(sellTotalFees <= 25, "Must keep fees at 25% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(address newMarketingWallet) external onlyOwner {
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
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;
}
}
//buy
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
//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;
}
} | * @dev Division of two int256 variables and fails on overflow./ | function div(int256 a, int256 b) internal pure returns (int256) {
require(b != -1 || a != MIN_INT256);
return a / b;
}
| 13,642,181 | [
1,
28223,
434,
2795,
509,
5034,
3152,
471,
6684,
603,
9391,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
3739,
12,
474,
5034,
279,
16,
509,
5034,
324,
13,
2713,
16618,
1135,
261,
474,
5034,
13,
288,
203,
540,
203,
3639,
2583,
12,
70,
480,
300,
21,
747,
279,
480,
6989,
67,
3217,
5034,
1769,
203,
203,
540,
203,
3639,
327,
279,
342,
324,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/3/0x42D133BFb13625fF67F0D78394E025461799b734/sources/Ethlings.sol | * @notice current cost to create a single avatar @return cost to create/ | function avatarCost() public view returns (uint256) {
return 0.1111 finney;
}
| 8,134,500 | [
1,
2972,
6991,
358,
752,
279,
2202,
16910,
327,
6991,
358,
752,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
16910,
8018,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
374,
18,
23680,
574,
82,
402,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x8C858832f8111D58B71720E161dEcA9ba47426CB/sources/contracts/stakingManager.sol | At this block,the rewards generation will be stopped.
| uint public endBlock; | 2,928,652 | [
1,
861,
333,
1203,
16,
5787,
283,
6397,
9377,
903,
506,
9627,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
2254,
1071,
679,
1768,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.7.5;
pragma abicoder v2;
import "./lib/LibSafeMath.sol";
import "./ERC1155Mintable.sol";
import "./mixin/MixinOwnable.sol";
contract ProofOfCultureMinter is Ownable {
using LibSafeMath for uint256;
struct _HashtagContainer {
string originalHashtag;
string normalizedHashtag;
uint256 timestamp;
}
uint256 public hashtagTokenType;
uint256 public batchOrderLimit;
ERC1155Mintable public mintableErc1155;
uint256 public constant MAX_NFT_SUPPLY = 9999;
address payable public treasury;
string[] public claimedHashtags;
mapping(uint256 => _HashtagContainer) public tokenIdToHashtagContainer;
mapping(string => uint256) public normalizedHashtagToTokenId;
mapping(string => string) public normalizedHashtagToImageURI;
mapping(uint256 => string) public tokenIdToImageURI;
// platform supporter vars
uint256 public constant supporterTokenCap = 15; // THIS WILL NEVER CHANGE!! WE ONLY MINT A SET AMOUNT FOR SUPPORTERS
uint256 public currentSupporterTokenCount;
// image change counts
mapping(uint256 => uint256) public tokenIdToImageChangeCount;
// admin toggles
bool public saleStarted;
constructor(
address _mintableErc1155,
address payable _treasury,
uint256 _hashtagTokenType,
uint256 _batchOrderLimit
) {
mintableErc1155 = ERC1155Mintable(_mintableErc1155);
treasury = _treasury;
hashtagTokenType = _hashtagTokenType;
batchOrderLimit = _batchOrderLimit;
}
event UpdatedRegistry(
uint256 tokenId,
string hashtag
);
event Received(address, uint);
/**
* @dev Gets the total supply, which is the sum of all hashtags minted.
Note that NFTs have a maxIndex but FTs don't, so we just keep track of the total here.
*/
function totalSupply() public view returns (uint256) {
return mintableErc1155.maxIndex(hashtagTokenType);
}
/**
* @dev Returns all claimed hashtags as an array
*/
function getAllClaimedHashtags() public view returns (string[] memory) {
return claimedHashtags;
}
/**
* @dev Return original (not normalized) hashtags that a given address owns. Leverages nfTokensOf but returns the hashtags instead of the token IDs
*/
function hashtagsOf(address _address) public view returns (string[] memory) {
uint256[] memory tokenIds = mintableErc1155.nfTokensOf(_address);
string[] memory hashtags = new string[](tokenIds.length);
for(uint i=0; i<tokenIds.length; i++){
uint256 tokenId = tokenIds[i];
hashtags[i] = tokenIdToHashtagContainer[tokenId].originalHashtag;
}
return hashtags;
}
/**
* @dev Validate hashtag.
- string must start with a '#'
- string length must be min 2 chars (# + one char)
- string length must be max 31 chars (1 + 30)
- string must be alphanumeric + underscore (aside from the first hashtag)
*/
function validateHashtag(string memory _hashtag) public pure returns (bool) {
bytes memory b = bytes(_hashtag);
if(b.length < 2) return false;
if(b.length > 31) return false;
bytes1 firstChar = b[0];
if (!(firstChar == 0x23)) return false; // make sure the first character is a '#'
for(uint i=1; i<b.length; i++){
bytes1 char = b[i];
if(
!(char >= 0x30 && char <= 0x39) && //9-0
!(char >= 0x41 && char <= 0x5A) && //A-Z
!(char >= 0x61 && char <= 0x7A) && //a-z
!(char == 0x5F) //_
)
return false;
}
return true;
}
/**
* @dev Normalize hashtag by making uppercase into lowercase.
Examples:
- #BlackLivesMatter => #blacklivesmatter
- #BLM => #blm
- #NFTsAreAwesome123 => #nftsareawesome123
*/
function normalizeHashtag(string memory _hashtag) public pure returns (string memory) {
bytes memory b = bytes(_hashtag);
require(b.length >= 2, "Hashtag cannot be less than 2 chars");
require(b.length <= 31, "Hashtag cannot be more than 31 chars");
bytes1 firstChar = b[0];
require(firstChar == 0x23, "Hashtag must start with a '#'");
bytes memory bLower = new bytes(b.length);
for (uint i = 0; i < b.length; i++) {
// Uppercase character...
if ((uint8(b[i]) >= 65) && (uint8(b[i]) <= 90)) {
// So we add 32 to make it lowercase
bLower[i] = bytes1(uint8(b[i]) + 32);
} else {
bLower[i] = b[i];
}
}
return string(bLower);
}
/**
* @dev Gets the price up to 9999 tokens.
As we put in a lot of artistic work into each token, we are taking a
constant pricing model, instead of the bonding curve model popularly seen
in this space recently.
*/
function getPrice() public view returns (uint256) {
require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended");
return 1000000000000000000; // 1ETH
}
/**
* @dev Set address of treasury - the address that will receive all payments
*/
function setTreasury(address payable _treasury) external onlyOwner() {
treasury = _treasury;
}
/**
* @dev Set batch order limit
*/
function setBatchOrderLimit(uint256 _batchOrderLimit) external onlyOwner() {
batchOrderLimit = _batchOrderLimit;
}
/**
* @dev Set Image URL for Token Id in batch.
* Note that we will only use this after individually crafting the image.
* The image will be hosted on IPFS and seeded properly for perpetuity so the image can remain accessible.
*
* If for any reason we have to update the image after the first time, we refund the original price of the art
* to the current owner of the token.
*/
function setBatchImageURIsForTokens(uint256[] calldata _ids, string[] calldata _image_uris) external onlyOwner() {
require(_ids.length == _image_uris.length, "Batch arrays must be of the same length");
for (uint256 i = 0; i < _ids.length; ++i) {
// Cache value to local variable to reduce read costs.
uint256 id = _ids[i];
string memory image_uri = _image_uris[i];
// If this image has already been changed once, then we should refund the original price to the current owner
uint256 imageChangeCount = tokenIdToImageChangeCount[id];
if (imageChangeCount == 1) {
address payable owner = payable(mintableErc1155.ownerOf(id));
owner.transfer(1000000000000000000); // refund the 1ETH
}
tokenIdToImageURI[id] = image_uri;
// also set it for the hashtag
_HashtagContainer memory container = tokenIdToHashtagContainer[id];
normalizedHashtagToImageURI[container.normalizedHashtag] = image_uri;
tokenIdToImageChangeCount[id] += 1;
}
}
/**
* @dev Set saleStarted boolean to start or end sale
*/
function setSaleStarted(bool _saleStarted) external onlyOwner() {
saleStarted = _saleStarted;
}
/**
* @dev Mint signature hashtags for our platform supporters (up to a certain limit that is a constant).
*/
function mintSignatureTokens(string[] memory _hashtags) external onlyOwner() {
require(currentSupporterTokenCount.safeAdd(_hashtags.length) <= supporterTokenCap, "Exceeds supporterTokenCap");
for (uint i = 0; i < _hashtags.length; i++) {
string memory hashtag = _hashtags[i];
if (!validateHashtag(hashtag)) {
continue; // skip if this is not a valid hashtag
}
string memory normalizedHashtag = normalizeHashtag(hashtag);
if (normalizedHashtagToTokenId[normalizedHashtag] != 0) {
continue; // skip if this hashtag already exists
}
// mint the NFT
address[] memory dsts = new address[](1);
dsts[0] = msg.sender;
uint256 index = mintableErc1155.maxIndex(hashtagTokenType) + 1;
uint256 tokenId = hashtagTokenType | index;
mintableErc1155.mintNonFungible(hashtagTokenType, dsts);
// bookkeeping
_HashtagContainer memory hc;
hc.normalizedHashtag = normalizedHashtag;
hc.originalHashtag = hashtag;
hc.timestamp = block.timestamp;
tokenIdToHashtagContainer[tokenId] = hc;
normalizedHashtagToTokenId[normalizedHashtag] = tokenId;
claimedHashtags.push(hashtag);
emit UpdatedRegistry(tokenId, hashtag);
currentSupporterTokenCount += 1;
}
}
/**
* @dev Mint multiple hashtags at once. We will try our best to mint all but
if they have already been claimed, then we will refund the money back.
Note that this function is inefficient because each mint actually emits a transfer
event and this doesn't scale. 25 should be OK, but for anything more, consider the
EIP2309 extension of ERC721.
*/
function mint(address _dst, string[] memory _hashtags) public payable {
require(saleStarted, "Sale has not started yet");
require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended");
uint numberOfNfts = _hashtags.length;
require(numberOfNfts > 0, "numberOfNfts cannot be 0");
require(numberOfNfts <= batchOrderLimit, "You may not buy more than the batch limit at once");
require(totalSupply().safeAdd(numberOfNfts) <= MAX_NFT_SUPPLY, "Exceeds MAX_NFT_SUPPLY");
require(getPrice().safeMul(numberOfNfts) <= msg.value, "Ether value sent is not correct");
// set price upfront before minting - we will need to use this to calculate refunds
uint256 pricePerHashtag = getPrice();
// Keep track of which hashtags we were able to mint
uint mintedCount = 0;
for (uint i = 0; i < numberOfNfts; i++) {
string memory hashtag = _hashtags[i];
if (!validateHashtag(hashtag)) {
continue; // skip if this is not a valid hashtag
}
string memory normalizedHashtag = normalizeHashtag(hashtag);
if (normalizedHashtagToTokenId[normalizedHashtag] != 0) {
continue; // skip if this hashtag already exists
}
// mint the NFT
address[] memory dsts = new address[](1);
dsts[0] = _dst;
uint256 index = mintableErc1155.maxIndex(hashtagTokenType) + 1;
uint256 tokenId = hashtagTokenType | index;
mintableErc1155.mintNonFungible(hashtagTokenType, dsts);
// bookkeeping
_HashtagContainer memory hc;
hc.normalizedHashtag = normalizedHashtag;
hc.originalHashtag = hashtag;
hc.timestamp = block.timestamp;
tokenIdToHashtagContainer[tokenId] = hc;
normalizedHashtagToTokenId[normalizedHashtag] = tokenId;
mintedCount++;
claimedHashtags.push(hashtag);
emit UpdatedRegistry(tokenId, hashtag);
}
// Only charge for the hashtags that we were able to mint, and refund the rest
uint256 actualTotalPrice = pricePerHashtag.safeMul(mintedCount);
treasury.transfer(actualTotalPrice);
msg.sender.transfer(msg.value - actualTotalPrice);
}
receive() external payable {
emit Received(msg.sender, msg.value);
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.7.5;
import "./LibRichErrors.sol";
import "./LibSafeMathRichErrors.sol";
library LibSafeMath {
function safeMul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (a == 0) {
return 0;
}
uint256 c = a * b;
if (c / a != b) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.MULTIPLICATION_OVERFLOW,
a,
b
));
}
return c;
}
function safeDiv(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (b == 0) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.DIVISION_BY_ZERO,
a,
b
));
}
uint256 c = a / b;
return c;
}
function safeSub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (b > a) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.SUBTRACTION_UNDERFLOW,
a,
b
));
}
return a - b;
}
function safeAdd(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a + b;
if (c < a) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.ADDITION_OVERFLOW,
a,
b
));
}
return c;
}
function max256(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.7.5;
import "./lib/LibSafeMath.sol";
import "./lib/LibAddress.sol";
import "./ERC1155.sol";
import "./interface/IERC1155Mintable.sol";
import "./mixin/MixinOwnable.sol";
import "./mixin/MixinContractURI.sol";
import "./mixin/MixinTokenURI.sol";
/// @dev Mintable form of ERC1155
/// Shows how easy it is to mint new items
contract ERC1155Mintable is
IERC1155Mintable,
ERC1155,
MixinContractURI,
MixinTokenURI
{
using LibSafeMath for uint256;
using LibAddress for address;
uint256 internal nonce;
/// mapping from token to max index
mapping (uint256 => uint256) public maxIndex;
mapping (uint256 => mapping(address => bool)) internal creatorApproval;
modifier onlyCreator(uint256 _id) {
require(creatorApproval[_id][msg.sender], "not an approved creator of id");
_;
}
function setCreatorApproval(uint256 id, address creator, bool status) external onlyCreator(id) {
creatorApproval[id][creator] = status;
}
/// @dev creates a new token
/// @param isNF is non-fungible token
/// @return type_ of token (a unique identifier)
function create(
bool isNF
)
external
override
onlyOwner()
returns (uint256 type_)
{
// Store the type in the upper 128 bits
type_ = (++nonce << 128);
// Set a flag if this is an NFI.
if (isNF) {
type_ = type_ | TYPE_NF_BIT;
}
creatorApproval[type_][msg.sender] = true;
// emit a Transfer event with Create semantic to help with discovery.
emit TransferSingle(
msg.sender,
address(0x0),
address(0x0),
type_,
0
);
emit URI(uri(type_), type_);
}
/// @dev creates a new token
/// @param type_ of token
function createWithType(
uint256 type_
)
external
onlyOwner()
{
creatorApproval[type_][msg.sender] = true;
// emit a Transfer event with Create semantic to help with discovery.
emit TransferSingle(
msg.sender,
address(0x0),
address(0x0),
type_,
0
);
emit URI(uri(type_), type_);
}
/// @dev mints fungible tokens
/// @param id token type
/// @param to beneficiaries of minted tokens
/// @param quantities amounts of minted tokens
function mintFungible(
uint256 id,
address[] calldata to,
uint256[] calldata quantities
)
external
override
onlyCreator(id)
{
// sanity checks
require(
isFungible(id),
"TRIED_TO_MINT_FUNGIBLE_FOR_NON_FUNGIBLE_TOKEN"
);
// mint tokens
for (uint256 i = 0; i < to.length; ++i) {
// cache to reduce number of loads
address dst = to[i];
uint256 quantity = quantities[i];
// Grant the items to the caller
balances[id][dst] = quantity.safeAdd(balances[id][dst]);
// Emit the Transfer/Mint event.
// the 0x0 source address implies a mint
// It will also provide the circulating supply info.
emit TransferSingle(
msg.sender,
address(0x0),
dst,
id,
quantity
);
// if `to` is a contract then trigger its callback
if (dst.isContract()) {
bytes4 callbackReturnValue = IERC1155Receiver(dst).onERC1155Received(
msg.sender,
msg.sender,
id,
quantity,
""
);
require(
callbackReturnValue == ERC1155_RECEIVED,
"BAD_RECEIVER_RETURN_VALUE"
);
}
}
}
/// @dev mints a non-fungible token
/// @param type_ token type
/// @param to beneficiaries of minted tokens
function mintNonFungible(
uint256 type_,
address[] calldata to
)
external
override
onlyCreator(type_)
{
require(
isNonFungible(type_),
"TRIED_TO_MINT_NON_FUNGIBLE_FOR_FUNGIBLE_TOKEN"
);
// Index are 1-based.
uint256 index = maxIndex[type_] + 1;
for (uint256 i = 0; i < to.length; ++i) {
// cache to reduce number of loads
address dst = to[i];
uint256 id = type_ | index + i;
transferNFToken(id, address(0x0), dst);
// You could use base-type id to store NF type balances if you wish.
balances[type_][dst] = balances[type_][dst].safeAdd(1);
emit TransferSingle(msg.sender, address(0x0), dst, id, 1);
// if `to` is a contract then trigger its callback
if (dst.isContract()) {
bytes4 callbackReturnValue = IERC1155Receiver(dst).onERC1155Received(
msg.sender,
msg.sender,
id,
1,
""
);
require(
callbackReturnValue == ERC1155_RECEIVED,
"BAD_RECEIVER_RETURN_VALUE"
);
}
}
// record the `maxIndex` of this nft type
// this allows us to mint more nft's of this type in a subsequent call.
maxIndex[type_] = to.length.safeAdd(maxIndex[type_]);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.5;
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;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.7.5;
library LibRichErrors {
// bytes4(keccak256("Error(string)"))
bytes4 internal constant STANDARD_ERROR_SELECTOR =
0x08c379a0;
// solhint-disable func-name-mixedcase
/// @dev ABI encode a standard, string revert error payload.
/// This is the same payload that would be included by a `revert(string)`
/// solidity statement. It has the function signature `Error(string)`.
/// @param message The error string.
/// @return The ABI encoded error.
function StandardError(
string memory message
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
STANDARD_ERROR_SELECTOR,
bytes(message)
);
}
// solhint-enable func-name-mixedcase
/// @dev Reverts an encoded rich revert reason `errorData`.
/// @param errorData ABI encoded error data.
function rrevert(bytes memory errorData)
internal
pure
{
assembly {
revert(add(errorData, 0x20), mload(errorData))
}
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.7.5;
library LibSafeMathRichErrors {
// bytes4(keccak256("Uint256BinOpError(uint8,uint256,uint256)"))
bytes4 internal constant UINT256_BINOP_ERROR_SELECTOR =
0xe946c1bb;
// bytes4(keccak256("Uint256DowncastError(uint8,uint256)"))
bytes4 internal constant UINT256_DOWNCAST_ERROR_SELECTOR =
0xc996af7b;
enum BinOpErrorCodes {
ADDITION_OVERFLOW,
MULTIPLICATION_OVERFLOW,
SUBTRACTION_UNDERFLOW,
DIVISION_BY_ZERO
}
enum DowncastErrorCodes {
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT32,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT64,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT96
}
// solhint-disable func-name-mixedcase
function Uint256BinOpError(
BinOpErrorCodes errorCode,
uint256 a,
uint256 b
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
UINT256_BINOP_ERROR_SELECTOR,
errorCode,
a,
b
);
}
function Uint256DowncastError(
DowncastErrorCodes errorCode,
uint256 a
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
UINT256_DOWNCAST_ERROR_SELECTOR,
errorCode,
a
);
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.7.5;
/**
* Utility library of inline functions on addresses
*/
library LibAddress {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.7.5;
import "./lib/LibSafeMath.sol";
import "./lib/LibAddress.sol";
import "./interface/IERC1155.sol";
import "./interface/IERC1155Receiver.sol";
import "./mixin/MixinNonFungibleToken.sol";
import "./mixin/MixinOwnable.sol";
import "./WhitelistExchangesProxy.sol";
contract ERC1155 is
IERC1155,
MixinNonFungibleToken,
Ownable
{
using LibAddress for address;
using LibSafeMath for uint256;
// selectors for receiver callbacks
bytes4 constant public ERC1155_RECEIVED = 0xf23a6e61;
bytes4 constant public ERC1155_BATCH_RECEIVED = 0xbc197c81;
// id => (owner => balance)
mapping (uint256 => mapping(address => uint256)) internal balances;
// owner => (operator => approved)
mapping (address => mapping(address => bool)) internal operatorApproval;
address public exchangesRegistry;
function setExchangesRegistry(address newExchangesRegistry) external onlyOwner() {
exchangesRegistry = newExchangesRegistry;
}
function burn(address from, uint256 id, uint256 amount) external {
require(
from == msg.sender || isApprovedForAll(from, msg.sender),
"INSUFFICIENT_ALLOWANCE"
);
require(isFungible(id), "Don't allow burn of NFTs via this function");
balances[id][from] = balances[id][from].safeSub(amount);
emit TransferSingle(msg.sender, from, address(0x0), id, amount);
}
/// @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
)
override
external
{
// sanity checks
require(
to != address(0x0),
"CANNOT_TRANSFER_TO_ADDRESS_ZERO"
);
require(
from == msg.sender || isApprovedForAll(from, msg.sender),
"INSUFFICIENT_ALLOWANCE"
);
// perform transfer
if (isNonFungible(id)) {
require(
value == 1,
"AMOUNT_EQUAL_TO_ONE_REQUIRED"
);
require(
nfOwners[id] == from,
"NFT_NOT_OWNED_BY_FROM_ADDRESS"
);
transferNFToken(id, from, to);
// You could keep balance of NF type in base type id like so:
// uint256 baseType = getNonFungibleBaseType(_id);
// balances[baseType][_from] = balances[baseType][_from].safeSub(_value);
// balances[baseType][_to] = balances[baseType][_to].safeAdd(_value);
} else {
balances[id][from] = balances[id][from].safeSub(value);
balances[id][to] = balances[id][to].safeAdd(value);
}
emit TransferSingle(msg.sender, from, to, id, value);
// if `to` is a contract then trigger its callback
if (to.isContract()) {
bytes4 callbackReturnValue = IERC1155Receiver(to).onERC1155Received(
msg.sender,
from,
id,
value,
data
);
require(
callbackReturnValue == ERC1155_RECEIVED,
"BAD_RECEIVER_RETURN_VALUE"
);
}
}
/// @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
)
override
external
{
// sanity checks
require(
to != address(0x0),
"CANNOT_TRANSFER_TO_ADDRESS_ZERO"
);
require(
ids.length == values.length,
"TOKEN_AND_VALUES_LENGTH_MISMATCH"
);
// Only supporting a global operator approval allows us to do
// only 1 check and not to touch storage to handle allowances.
require(
from == msg.sender || isApprovedForAll(from, msg.sender),
"INSUFFICIENT_ALLOWANCE"
);
// perform transfers
for (uint256 i = 0; i < ids.length; ++i) {
// Cache value to local variable to reduce read costs.
uint256 id = ids[i];
uint256 value = values[i];
if (isNonFungible(id)) {
require(
value == 1,
"AMOUNT_EQUAL_TO_ONE_REQUIRED"
);
require(
nfOwners[id] == from,
"NFT_NOT_OWNED_BY_FROM_ADDRESS"
);
transferNFToken(id, from, to);
} else {
balances[id][from] = balances[id][from].safeSub(value);
balances[id][to] = balances[id][to].safeAdd(value);
}
}
emit TransferBatch(msg.sender, from, to, ids, values);
// if `to` is a contract then trigger its callback
if (to.isContract()) {
bytes4 callbackReturnValue = IERC1155Receiver(to).onERC1155BatchReceived(
msg.sender,
from,
ids,
values,
data
);
require(
callbackReturnValue == ERC1155_BATCH_RECEIVED,
"BAD_RECEIVER_RETURN_VALUE"
);
}
}
/// @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens.
/// @dev MUST emit the ApprovalForAll event on success.
/// @param operator Address to add to the set of authorized operators
/// @param approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address operator, bool approved) external override {
operatorApproval[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
/// @notice Queries the approval status of an operator for a given owner.
/// @param owner The owner of the Tokens
/// @param operator Address of authorized operator
/// @return True if the operator is approved, false if not
function isApprovedForAll(address owner, address operator) public override view returns (bool) {
bool approved = operatorApproval[owner][operator];
if (!approved && exchangesRegistry != address(0)) {
return WhitelistExchangesProxy(exchangesRegistry).isAddressWhitelisted(operator) == true;
}
return approved;
}
/// @notice Get the balance of an account's Tokens.
/// @param owner The address of the token holder
/// @param id ID of the Token
/// @return The _owner's balance of the Token type requested
function balanceOf(address owner, uint256 id) external override view returns (uint256) {
if (isNonFungibleItem(id)) {
return nfOwners[id] == owner ? 1 : 0;
}
return balances[id][owner];
}
/// @notice Get the balance of multiple account/token pairs
/// @param owners The addresses of the token holders
/// @param ids ID of the Tokens
/// @return balances_ The _owner's balance of the Token types requested
function balanceOfBatch(address[] calldata owners, uint256[] calldata ids) external override view returns (uint256[] memory balances_) {
// sanity check
require(
owners.length == ids.length,
"OWNERS_AND_IDS_MUST_HAVE_SAME_LENGTH"
);
// get balances
balances_ = new uint256[](owners.length);
for (uint256 i = 0; i < owners.length; ++i) {
uint256 id = ids[i];
if (isNonFungibleItem(id)) {
balances_[i] = nfOwners[id] == owners[i] ? 1 : 0;
} else {
balances_[i] = balances[id][owners[i]];
}
}
return balances_;
}
bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7;
bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26;
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
if (_interfaceID == INTERFACE_SIGNATURE_ERC165 ||
_interfaceID == INTERFACE_SIGNATURE_ERC1155) {
return true;
}
return false;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.7.5;
import "./IERC1155.sol";
/// @dev Mintable form of ERC1155
/// Shows how easy it is to mint new items
interface IERC1155Mintable is
IERC1155
{
/// @dev creates a new token
/// @param isNF is non-fungible token
/// @return type_ of token (a unique identifier)
function create(
bool isNF
)
external
returns (uint256 type_);
/// @dev mints fungible tokens
/// @param id token type
/// @param to beneficiaries of minted tokens
/// @param quantities amounts of minted tokens
function mintFungible(
uint256 id,
address[] calldata to,
uint256[] calldata quantities
)
external;
/// @dev mints a non-fungible token
/// @param type_ token type
/// @param to beneficiaries of minted tokens
function mintNonFungible(
uint256 type_,
address[] calldata to
)
external;
}
pragma solidity ^0.7.5;
import "./MixinOwnable.sol";
contract MixinContractURI is Ownable {
string public contractURI;
function setContractURI(string calldata newContractURI) external onlyOwner() {
contractURI = newContractURI;
}
}
pragma solidity ^0.7.5;
import "./MixinOwnable.sol";
import "../lib/LibString.sol";
contract MixinTokenURI is Ownable {
using LibString for string;
string public baseMetadataURI = "";
function setBaseMetadataURI(string memory newBaseMetadataURI) public onlyOwner() {
baseMetadataURI = newBaseMetadataURI;
}
function uri(uint256 _id) public view returns (string memory) {
return LibString.strConcat(
baseMetadataURI,
LibString.uint2hexstr(_id)
);
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.7.5;
/// @title ERC-1155 Multi Token Standard
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1155.md
/// Note: The ERC-165 identifier for this interface is 0xd9b67a26.
interface IERC1155 {
/// @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred,
/// including zero value transfers as well as minting or burning.
/// Operator will always be msg.sender.
/// Either event from address `0x0` signifies a minting operation.
/// An event to address `0x0` signifies a burning or melting operation.
/// The total value transferred from address 0x0 minus the total value transferred to 0x0 may
/// be used by clients and exchanges to be added to the "circulating supply" for a given token ID.
/// To define a token ID with no initial balance, the contract SHOULD emit the TransferSingle event
/// from `0x0` to `0x0`, with the token creator as `_operator`.
event TransferSingle(
address indexed _operator,
address indexed _from,
address indexed _to,
uint256 _id,
uint256 _value
);
/// @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred,
/// including zero value transfers as well as minting or burning.
///Operator will always be msg.sender.
/// Either event from address `0x0` signifies a minting operation.
/// An event to address `0x0` signifies a burning or melting operation.
/// The total value transferred from address 0x0 minus the total value transferred to 0x0 may
/// be used by clients and exchanges to be added to the "circulating supply" for a given token ID.
/// To define multiple token IDs with no initial balance, this SHOULD emit the TransferBatch event
/// from `0x0` to `0x0`, with the token creator as `_operator`.
event TransferBatch(
address indexed _operator,
address indexed _from,
address indexed _to,
uint256[] _ids,
uint256[] _values
);
/// @dev MUST emit when an approval is updated.
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
/// @dev MUST emit when the URI is updated for a token ID.
/// URIs are defined in RFC 3986.
/// The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata JSON Schema".
event URI(
string _value,
uint256 indexed _id
);
/// @notice Transfers value amount of an _id from the _from address to the _to address specified.
/// @dev MUST emit TransferSingle event on success.
/// Caller must be approved to manage the _from account's tokens (see isApprovedForAll).
/// MUST throw if `_to` is the zero address.
/// MUST throw if balance of sender for token `_id` is lower than the `_value` sent.
/// MUST throw on any other error.
/// When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0).
/// If so, it MUST call `onERC1155Received` on `_to` and revert if the return value
/// is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`.
/// @param from Source address
/// @param to Target address
/// @param id ID of the token type
/// @param value Transfer amount
/// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 value,
bytes calldata data
)
external;
/// @notice Send multiple types of Tokens from a 3rd party in one transfer (with safety call).
/// @dev MUST emit TransferBatch event on success.
/// Caller must be approved to manage the _from account's tokens (see isApprovedForAll).
/// MUST throw if `_to` is the zero address.
/// MUST throw if length of `_ids` is not the same as length of `_values`.
/// MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_values` sent.
/// MUST throw on any other error.
/// When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0).
/// If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return value
/// is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`.
/// @param from Source addresses
/// @param to Target addresses
/// @param ids IDs of each token type
/// @param values Transfer amounts per token type
/// @param data Additional data with no specified format, sent in call to `_to`
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external;
/// @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens.
/// @dev MUST emit the ApprovalForAll event on success.
/// @param operator Address to add to the set of authorized operators
/// @param approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address operator, bool approved) external;
/// @notice Queries the approval status of an operator for a given owner.
/// @param owner The owner of the Tokens
/// @param operator Address of authorized operator
/// @return True if the operator is approved, false if not
function isApprovedForAll(address owner, address operator) external view returns (bool);
/// @notice Get the balance of an account's Tokens.
/// @param owner The address of the token holder
/// @param id ID of the Token
/// @return The _owner's balance of the Token type requested
function balanceOf(address owner, uint256 id) external view returns (uint256);
/// @notice Get the balance of multiple account/token pairs
/// @param owners The addresses of the token holders
/// @param ids ID of the Tokens
/// @return balances_ The _owner's balance of the Token types requested
function balanceOfBatch(
address[] calldata owners,
uint256[] calldata ids
)
external
view
returns (uint256[] memory balances_);
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.7.5;
interface IERC1155Receiver {
/// @notice Handle the receipt of a single ERC1155 token type
/// @dev The smart contract calls this function on the recipient
/// after a `safeTransferFrom`. This function MAY throw to revert and reject the
/// transfer. Return of other than the magic value MUST result in the
///transaction being reverted
/// Note: the contract address is always the message sender
/// @param operator The address which called `safeTransferFrom` function
/// @param from The address which previously owned the token
/// @param id An array containing the ids of the token being transferred
/// @param value An array containing the amount of tokens being transferred
/// @param data Additional data with no specified format
/// @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
)
external
returns(bytes4);
/// @notice Handle the receipt of multiple ERC1155 token types
/// @dev The smart contract calls this function on the recipient
/// after a `safeTransferFrom`. This function MAY throw to revert and reject the
/// transfer. Return of other than the magic value MUST result in the
/// transaction being reverted
/// Note: the contract address is always the message sender
/// @param operator The address which called `safeTransferFrom` function
/// @param from The address which previously owned the token
/// @param ids An array containing ids of each token being transferred
/// @param values An array containing amounts of each token being transferred
/// @param data Additional data with no specified format
/// @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external
returns(bytes4);
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.7.5;
contract MixinNonFungibleToken {
uint256 constant internal TYPE_MASK = uint256(uint128(~0)) << 128;
uint256 constant internal NF_INDEX_MASK = uint128(~0);
uint256 constant internal TYPE_NF_BIT = 1 << 255;
mapping (uint256 => address) internal nfOwners;
mapping (address => uint256[]) internal nfOwnerMapping;
// One index as a hack to tell the diff between unset and 0-value
mapping (uint256 => uint256) internal tokenIdToNFOwnerMappingOneIndex;
/// @dev Returns true if token is non-fungible
function isNonFungible(uint256 id) public pure returns(bool) {
return id & TYPE_NF_BIT == TYPE_NF_BIT;
}
/// @dev Returns true if token is fungible
function isFungible(uint256 id) public pure returns(bool) {
return id & TYPE_NF_BIT == 0;
}
/// @dev Returns index of non-fungible token
function getNonFungibleIndex(uint256 id) public pure returns(uint256) {
return id & NF_INDEX_MASK;
}
/// @dev Returns base type of non-fungible token
function getNonFungibleBaseType(uint256 id) public pure returns(uint256) {
return id & TYPE_MASK;
}
/// @dev Returns true if input is base-type of a non-fungible token
function isNonFungibleBaseType(uint256 id) public pure returns(bool) {
// A base type has the NF bit but does not have an index.
return (id & TYPE_NF_BIT == TYPE_NF_BIT) && (id & NF_INDEX_MASK == 0);
}
/// @dev Returns true if input is a non-fungible token
function isNonFungibleItem(uint256 id) public pure returns(bool) {
// A base type has the NF bit but does has an index.
return (id & TYPE_NF_BIT == TYPE_NF_BIT) && (id & NF_INDEX_MASK != 0);
}
/// @dev returns owner of a non-fungible token
function ownerOf(uint256 id) public view returns (address) {
return nfOwners[id];
}
/// @dev returns all owned NF tokenIds given an address
function nfTokensOf(address _address) external view returns (uint256[] memory) {
return nfOwnerMapping[_address];
}
/// @dev transfer token from one NF owner to another
function transferNFToken(uint256 _id, address _from, address _to) internal {
require(nfOwners[_id] == _from, "Token not owned by the from address");
// chage nfOwner of the id to the new address
nfOwners[_id] = _to;
// only delete from the "from" user if this tokenId mapping already exists. When the from is 0x0 then it won't
if (tokenIdToNFOwnerMappingOneIndex[_id] != 0) {
// get index of where the token ID is stored in the from user's array of token IDs
uint256 fromTokenIdIndex = tokenIdToNFOwnerMappingOneIndex[_id] - 1;
// move the last token of the from user's array of token IDs to where fromTokenIdIndex is so we can shrink the array
uint256 tokenIdToMove = nfOwnerMapping[_from][nfOwnerMapping[_from].length-1];
// make the moves and then shrink the array. make sure to move the reference of the index in the tokenIdToNFOwnerMappingOneIndex
nfOwnerMapping[_from][fromTokenIdIndex] = tokenIdToMove;
nfOwnerMapping[_from].pop();
tokenIdToNFOwnerMappingOneIndex[tokenIdToMove] = fromTokenIdIndex + 1;
}
// move the tokenId to the "to" user (and override index)
nfOwnerMapping[_to].push(_id);
tokenIdToNFOwnerMappingOneIndex[_id] = nfOwnerMapping[_to].length; // no need -1 because 1-index
}
}
pragma solidity ^0.7.5;
import "./mixin/MixinOwnable.sol";
contract WhitelistExchangesProxy is Ownable {
mapping(address => bool) internal proxies;
bool public paused = true;
function setPaused(bool newPaused) external onlyOwner() {
paused = newPaused;
}
function updateProxyAddress(address proxy, bool status) external onlyOwner() {
proxies[proxy] = status;
}
function isAddressWhitelisted(address proxy) external view returns (bool) {
if (paused) {
return false;
} else {
return proxies[proxy];
}
}
}
pragma solidity ^0.7.5;
library LibString {
// 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);
}
function uint2hexstr(uint i) internal pure returns (string memory) {
if (i == 0) {
return "0";
}
uint j = i;
uint len;
while (j != 0) {
len++;
j = j >> 4;
}
uint mask = 15;
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
uint curr = (i & mask);
bstr[k--] = curr > 9 ? byte(uint8(55 + curr)) : byte(uint8(48 + curr));
i = i >> 4;
}
return string(bstr);
}
}
| * @dev Returns all claimed hashtags as an array/ | function getAllClaimedHashtags() public view returns (string[] memory) {
return claimedHashtags;
}
| 130,416 | [
1,
1356,
777,
7516,
329,
711,
647,
1341,
487,
392,
526,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
5514,
9762,
329,
5582,
647,
1341,
1435,
1071,
1476,
1135,
261,
1080,
8526,
3778,
13,
288,
203,
565,
327,
7516,
329,
5582,
647,
1341,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/42/0x99F59EEc9beD956020CBb5cdf6b802cA9BE834d3/sources/BitdexERC20.sol | force reserves to match balances | function sync() external lock {
_update(IERC20Bitdex(token0).balanceOf(address(this)), IERC20Bitdex(token1).balanceOf(address(this)), reserve0, reserve1);
}
| 8,985,728 | [
1,
5734,
400,
264,
3324,
358,
845,
324,
26488,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
3792,
1435,
3903,
2176,
288,
203,
3639,
389,
2725,
12,
45,
654,
39,
3462,
5775,
561,
12,
2316,
20,
2934,
12296,
951,
12,
2867,
12,
2211,
13,
3631,
467,
654,
39,
3462,
5775,
561,
12,
2316,
21,
2934,
12296,
951,
12,
2867,
12,
2211,
13,
3631,
20501,
20,
16,
20501,
21,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x9d3e5CBd5b2F2aF1c1D6CFF63c7eA3A8894ad79f/sources/OwnbitMultiSig.sol | destination can be a normal address or a contract address, such as ERC20 contract address.value is the wei transferred to the destination.data for transfer ether: 0xdata for transfer erc20 example: 0xa9059cbb000000000000000000000000ac6342a7efb995d63cc91db49f6023e95873d25000000000000000000000000000000000000000000000000000000000000003e8data for transfer erc721 example: 0x42842e0e00000000000000000000000097b65ad59c8c96f2dd786751e6279a1a6d34a4810000000000000000000000006cb33e7179860d24635c66850f1f6a5d4f8eee6d0000000000000000000000000000000000000000000000000000000000042134data can contain any data to be executed.transfer tokens from this contract to the destination address | function spend(address destination, uint256 value, uint8[] memory vs, bytes32[] memory rs, bytes32[] memory ss, bytes calldata data) external {
require(destination != address(this), "Not allow sending to yourself");
require(_validSignature(destination, value, vs, rs, ss, data), "invalid signatures");
spendNonce = spendNonce + 1;
if (sent) {
emit Spent(destination, value);
}
}
| 4,320,551 | [
1,
10590,
848,
506,
279,
2212,
1758,
578,
279,
6835,
1758,
16,
4123,
487,
4232,
39,
3462,
6835,
1758,
18,
1132,
353,
326,
732,
77,
906,
4193,
358,
326,
2929,
18,
892,
364,
7412,
225,
2437,
30,
374,
92,
892,
364,
7412,
6445,
71,
3462,
3454,
30,
374,
6995,
9349,
6162,
7358,
70,
12648,
12648,
12648,
1077,
4449,
9452,
69,
27,
10241,
70,
2733,
25,
72,
4449,
952,
12416,
1966,
7616,
74,
26,
3103,
23,
73,
29,
8204,
9036,
72,
2947,
12648,
12648,
12648,
12648,
12648,
12648,
12648,
9449,
23,
73,
28,
892,
364,
7412,
6445,
71,
27,
5340,
3454,
30,
374,
92,
9452,
5193,
22,
73,
20,
73,
12648,
12648,
12648,
10580,
70,
9222,
361,
6162,
71,
28,
71,
10525,
74,
22,
449,
27,
5292,
5877,
21,
73,
26,
5324,
29,
69,
21,
69,
26,
72,
5026,
69,
8875,
21,
12648,
12648,
12648,
26,
7358,
3707,
73,
27,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
225,
445,
17571,
12,
2867,
2929,
16,
2254,
5034,
460,
16,
2254,
28,
8526,
3778,
6195,
16,
1731,
1578,
8526,
3778,
3597,
16,
1731,
1578,
8526,
3778,
5202,
16,
1731,
745,
892,
501,
13,
3903,
288,
203,
565,
2583,
12,
10590,
480,
1758,
12,
2211,
3631,
315,
1248,
1699,
5431,
358,
3433,
2890,
8863,
203,
565,
2583,
24899,
877,
5374,
12,
10590,
16,
460,
16,
6195,
16,
3597,
16,
5202,
16,
501,
3631,
315,
5387,
14862,
8863,
203,
565,
17571,
13611,
273,
17571,
13611,
397,
404,
31,
203,
565,
309,
261,
7569,
13,
288,
203,
3639,
3626,
5878,
319,
12,
10590,
16,
460,
1769,
203,
565,
289,
203,
225,
289,
203,
21281,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC20/presets/ERC20PresetMinterPauserUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
/**
* @dev ERC20 token with minting, burning and pausable token transfers.
*
*/
contract EnhancedMinterPauser is
Initializable,
ERC20PresetMinterPauserUpgradeable,
OwnableUpgradeable
{
using SafeMathUpgradeable for uint256;
//role for excluding addresses for feeless transfer
bytes32 public constant FEE_EXCLUDED_ROLE = keccak256("FEE_EXCLUDED_ROLE");
// fee percent represented in integer for example 400, will be used as 1/400 = 0,0025 percent
uint32 public tokenTransferFeeDivisor;
//address where the transfer fees will be sent
address public feeAddress;
event feeWalletAddressChanged(address newValue);
event mintingFeePercentChanged(uint32 newValue);
function __EnhancedMinterPauser_init(
string memory name,
string memory symbol
) internal initializer {
__ERC20_init_unchained(name, symbol);
__ERC20PresetMinterPauser_init_unchained(name, symbol);
__EnhancedMinterPauser_init_unchained();
__Ownable_init();
}
function __EnhancedMinterPauser_init_unchained() internal initializer {
_setupRole(FEE_EXCLUDED_ROLE, _msgSender());
setFeeWalletAddress(0x9D1Cb8509A7b60421aB28492ce05e06f52Ddf727);
setTransferFeeDivisor(400);
}
/**
* @dev minting without 18 decimal places for convenience
* if withFee = true calls the mintWithFee function
* else sends the minted tokens without substracting a fee
*/
function mintWithoutDecimals(
address recipient,
uint256 amount,
bool withFee
) public {
require(
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()),
"Caller must have admin role to mint"
);
if (withFee) {
mintWithFee(recipient, amount * 1 ether);
} else super._mint(recipient, amount * 1 ether);
}
/**
* @dev mint tokens substract the fee, send the fee to the fee wallet
* and send the final amount to the given address
*/
function mintWithFee(address recipient, uint256 amount) public {
require(
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()),
"Caller must have admin role to mint"
);
//transfer fee
super._mint(feeAddress, _calculateFee(amount));
super._mint(recipient, _calculateAmountSubTransferFee(amount));
}
/**
* @dev overriding the openzeppelin _transfer method
* if the sender address is not excluded substract transfer fee from the amount
* and send the fee to the predefined fee address
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual override {
if (hasRole(FEE_EXCLUDED_ROLE, _msgSender())) {
super._transfer(
sender,
recipient,
amount
);
} else {
// transfer amount - fee
super._transfer(
sender,
recipient,
_calculateAmountSubTransferFee(amount)
);
//transfer the fee to the predefined fee address
super._transfer(sender, feeAddress, _calculateFee(amount));
}
}
/**
* @dev set the wallet address where fees will be collected
*/
function setFeeWalletAddress(address _feeAddress) public {
require(
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()),
"Caller must have admin role to set minting fee address"
);
require(address(0) != address(_feeAddress),
"zero address is not allowed"
);
feeAddress = _feeAddress;
emit feeWalletAddressChanged(feeAddress);
}
/**
* @dev sets the transfer fee
* example: divisor 400 would equal to 0,05 percent; 1/400 = 0,0025/100
*/
function setTransferFeeDivisor(uint32 _tokenTransferFeeDivisor) public {
require(
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()),
"Caller must have admin role to set minting fee percent"
);
require(
_tokenTransferFeeDivisor > 2,
"Token transfer fee divisor must be greater than 0"
);
tokenTransferFeeDivisor = _tokenTransferFeeDivisor;
emit mintingFeePercentChanged(tokenTransferFeeDivisor);
}
/**
* @dev calculates the total amount minus the the transfer fee
*/
function _calculateAmountSubTransferFee(uint256 amount)
private
view
returns (uint256)
{
return amount.sub(_calculateFee(amount));
}
/**
* @dev calculates the transfer fee
*/
function _calculateFee(uint256 amount) private view returns (uint256) {
return amount.div(tokenTransferFeeDivisor);
}
uint256[50] private __gap;
}
| * @dev overriding the openzeppelin _transfer method if the sender address is not excluded substract transfer fee from the amount and send the fee to the predefined fee address/ transfer amount - feetransfer the fee to the predefined fee address | function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual override {
if (hasRole(FEE_EXCLUDED_ROLE, _msgSender())) {
super._transfer(
sender,
recipient,
amount
);
super._transfer(
sender,
recipient,
_calculateAmountSubTransferFee(amount)
);
super._transfer(sender, feeAddress, _calculateFee(amount));
}
}
| 12,573,238 | [
1,
83,
1107,
10415,
326,
1696,
94,
881,
84,
292,
267,
389,
13866,
707,
309,
326,
5793,
1758,
353,
486,
8845,
2373,
621,
7412,
14036,
628,
326,
3844,
471,
1366,
326,
14036,
358,
326,
19555,
14036,
1758,
19,
7412,
3844,
300,
1656,
16354,
634,
586,
326,
14036,
358,
326,
19555,
14036,
1758,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
13866,
12,
203,
3639,
1758,
5793,
16,
203,
3639,
1758,
8027,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
2713,
5024,
3849,
288,
203,
3639,
309,
261,
5332,
2996,
12,
8090,
41,
67,
2294,
11686,
7660,
67,
16256,
16,
389,
3576,
12021,
1435,
3719,
288,
203,
5411,
2240,
6315,
13866,
12,
203,
7734,
5793,
16,
203,
7734,
8027,
16,
203,
7734,
3844,
203,
5411,
11272,
203,
5411,
2240,
6315,
13866,
12,
203,
7734,
5793,
16,
203,
7734,
8027,
16,
203,
7734,
389,
11162,
6275,
1676,
5912,
14667,
12,
8949,
13,
203,
5411,
11272,
203,
5411,
2240,
6315,
13866,
12,
15330,
16,
14036,
1887,
16,
389,
11162,
14667,
12,
8949,
10019,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// 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: truffle/contracts/ECDSA.sol
/*
** Blockdemy Certifications | A library to recover signature addresses with ECDSA
** Authors: Blockchain Academy México @blockdemy, Ernesto García @ernestognw
** 22-July-2019
** blockchainacademy.mx
*/
pragma solidity ^0.5.1;
library ECDSA {
/**
* @dev Recovers the address of who signed the hash sent to the function
* @param _fingerprint bytes32. Is the sha3 hash of document. Generated with web3.
* @param _signature bytes. Signature of the sha3 fingerprint of the file.
*/
function recoverAddress(bytes32 _fingerprint, bytes memory _signature) internal pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
require(_signature.length == 65, "Invalid signature");
// Divide the signature in r, s and v variables with inline assembly.
assembly {
r := mload(add(_signature, 0x20))
s := mload(add(_signature, 0x40))
v := byte(0, mload(add(_signature, 0x60)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
require(v == 27 || v == 28, "Invalid signature");
return ecrecover(toEthSignedMessageHash(_fingerprint), v, r, s);
}
/**
* toEthSignedMessageHash
* @dev prefix a bytes32 value with "\x19Ethereum Signed Message:" and hash the result
* @param _fingerprint bytes32. Is the sha3 hash of document. Generated with web3.
*/
function toEthSignedMessageHash(bytes32 _fingerprint) internal pure returns (bytes32) {
return keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", _fingerprint)
);
}
}
// File: truffle/contracts/Certifications.sol
/*
** Blockdemy Certifications | A contract to store digital documents certifications
** Authors: Blockchain Academy México @blockdemy, Ernesto García @ernestognw
** 22-July-2019
** blockchainacademy.mx
*/
pragma solidity 0.5.1;
contract Certifications is Ownable {
using ECDSA for bytes32;
mapping(bytes32 => Certificate) public fingerprints;
struct Certificate {
address owner;
mapping(address => bytes) signatures;
uint issued;
uint expires;
bool exists;
}
constructor() public {}
/**
* @dev Certificate a document fingerprint into blockchain
* @param _fingerprint bytes32. Is the sha3 hash of document. Generated with web3.
* @param _owner address. The address of who is being certificated. The owner of document.
* @param _issued uint. The unix miliseconds date of certificate issuing.
* @param _expires uint. The unix miliseconds date of certificate expiration.
*/
function addCertificate(
bytes32 _fingerprint,
address _owner,
uint _issued,
uint _expires
) onlyOwner() public returns(bool) {
require(_issued < _expires, "Issuing date can not be less than expiring date");
require(_expires > now, "This certificate has already expired");
require(!fingerprints[_fingerprint].exists, "File has already been certified");
fingerprints[_fingerprint].owner = _owner;
fingerprints[_fingerprint].issued = _issued;
fingerprints[_fingerprint].expires = _expires;
fingerprints[_fingerprint].exists = true;
return true;
}
/**
* @dev Function to sign a previously generated certificate
* @param _signer address. The address of who is signing the certificate.
* @param _fingerprint bytes32. Is the sha3 hash of document. Generated with web3.
* @param _signature bytes. Signature of the sha3 fingerprint of the file.
*/
function addSignatureToCertificate(address _signer, bytes32 _fingerprint, bytes memory _signature) onlyOwner() public returns(bool) {
address signer = _fingerprint.recoverAddress(_signature);
require(fingerprints[_fingerprint].exists, "Certificate does not exists");
require(_signer == signer, "Signature does not corresponds to signer");
fingerprints[_fingerprint].signatures[_signer] = _signature;
return true;
}
/**
* @dev Returns the corresponding signature to a certificate and signer, used to verify signatures
* @param _signer address. The address of who supposedly signed the certificate.
* @param _fingerprint bytes32. Is the sha3 hash of document. Generated with web3.
*/
function getSignature(address _signer, bytes32 _fingerprint) public view returns(bytes memory) {
return fingerprints[_fingerprint].signatures[_signer];
}
} | * @dev Function to sign a previously generated certificate @param _signer address. The address of who is signing the certificate. @param _fingerprint bytes32. Is the sha3 hash of document. Generated with web3. @param _signature bytes. Signature of the sha3 fingerprint of the file./ | function addSignatureToCertificate(address _signer, bytes32 _fingerprint, bytes memory _signature) onlyOwner() public returns(bool) {
address signer = _fingerprint.recoverAddress(_signature);
require(fingerprints[_fingerprint].exists, "Certificate does not exists");
require(_signer == signer, "Signature does not corresponds to signer");
fingerprints[_fingerprint].signatures[_signer] = _signature;
return true;
}
| 1,041,936 | [
1,
2083,
358,
1573,
279,
7243,
4374,
4944,
225,
389,
2977,
264,
1758,
18,
1021,
1758,
434,
10354,
353,
10611,
326,
4944,
18,
225,
389,
24716,
1731,
1578,
18,
2585,
326,
6056,
23,
1651,
434,
1668,
18,
11025,
598,
3311,
23,
18,
225,
389,
8195,
1731,
18,
9249,
434,
326,
6056,
23,
12115,
434,
326,
585,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
527,
5374,
774,
4719,
12,
2867,
389,
2977,
264,
16,
1731,
1578,
389,
24716,
16,
1731,
3778,
389,
8195,
13,
1338,
5541,
1435,
1071,
1135,
12,
6430,
13,
288,
203,
4202,
1758,
10363,
273,
389,
24716,
18,
266,
3165,
1887,
24899,
8195,
1769,
203,
4202,
2583,
12,
24716,
87,
63,
67,
24716,
8009,
1808,
16,
315,
4719,
1552,
486,
1704,
8863,
203,
4202,
2583,
24899,
2977,
264,
422,
10363,
16,
315,
5374,
1552,
486,
13955,
358,
10363,
8863,
203,
4202,
12115,
87,
63,
67,
24716,
8009,
30730,
63,
67,
2977,
264,
65,
273,
389,
8195,
31,
203,
4202,
327,
638,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./interfaces/IOwnable.sol";
/// @title A fixed price ERC721 Purchase Contract
/// @author jierlich
/// @notice Users can list NFTs, purchase listed NFTs, and delist NFTs
/// @notice Collection owners can set fees
/// @dev The collection owner fee is dependent on the existence of an `owner` function on the ERC721 contract
contract ERC721FixedPricePurchase is Ownable {
/// @dev mapping from ERC721 address -> token id -> listing price
mapping(address => mapping(uint256 => uint256)) public listing;
/// @dev mapping from collection owner to collection fee
mapping(address => uint256) public collectionFee;
/// @dev mapping from collection owner to fees accrued
mapping(address => uint256) public collectionFeesAccrued;
/// @dev fee for the protocol
uint256 public protocolFee;
/// @dev protocol fees accrued
uint256 public protocolFeesAccrued;
/// @dev used to calculate the basis point fee
uint constant FEE_BASE = 10000;
event Listed(address indexed erc721, uint256 indexed tokenId, address indexed owner, uint256 price);
event Purchased(address indexed erc721, uint256 indexed tokenId, address indexed buyer);
modifier onlyErc721Owner(address erc721, uint256 tokenId) {
require(IERC721(erc721).ownerOf(tokenId) == msg.sender, "ERC721FixedPricePurchase: Only ERC721 owner can call this function");
_;
}
modifier onlyCollectionOwner(address erc721) {
require(IOwnable(erc721).owner() == msg.sender, "ERC721FixedPricePurchase: Only collection owner can call this function");
_;
}
/// @notice list an ERC721 token for sale
/// @dev the owner must approve the tokenId on the ERC721 in a separate transaction to fully list
/// @dev delisting is done externally by revoking approval on the ERC721
/// @param erc721 token contract
/// @param tokenId id of the ERC721 token being listed
/// @param price amount buyer must pay to purchase
function list(address erc721, uint256 tokenId, uint256 price) onlyErc721Owner(erc721, tokenId) public {
listing[erc721][tokenId] = price;
emit Listed(erc721, tokenId, msg.sender, price);
}
/// @notice purchase an ERC721 token that is on sale
/// @dev basis point fees are calculated using the fee base constant
/// @param erc721 token contract
/// @param tokenId id of the ERC721 token being listed
function purchase(address erc721, uint256 tokenId) public payable {
require(msg.value >= listing[erc721][tokenId], "ERC721FixedPricePurchase: Buyer didn't send enough ether");
require(listing[erc721][tokenId] > 0, "ERC721FixedPricePurchase: Token is not listed");
listing[erc721][tokenId] = 0;
address from = IERC721(erc721).ownerOf(tokenId);
uint256 collectionFeeAmount = msg.value * collectionFee[erc721] / FEE_BASE;
uint256 protocolFeeAmount = msg.value * protocolFee / FEE_BASE;
uint256 sellerFeeAmount = msg.value - protocolFeeAmount - collectionFeeAmount;
collectionFeesAccrued[erc721] += collectionFeeAmount;
protocolFeesAccrued += protocolFeeAmount;
(bool sent,) = from.call{value: sellerFeeAmount}("");
require(sent, "ERC721FixedPricePurchase: Failed to send Ether");
IERC721(erc721).safeTransferFrom(from, msg.sender, tokenId);
/// @dev price is set to 0 to protect future owners
listing[erc721][tokenId] = 0;
emit Purchased(erc721, tokenId, msg.sender);
}
/// @notice set the basis point fee of the collection owner
/// @param erc721 token contract
/// @param fee basis point amount of the transaction
function setCollectionFee(address erc721, uint256 fee) onlyCollectionOwner(erc721) public {
collectionFee[erc721] = fee;
}
/// @notice set the basis point fee of the protocol owner
/// @param fee basis point amount of the transaction
function setProtocolFee(uint256 fee) onlyOwner() public {
protocolFee = fee;
}
/// @notice allows collection owner to withdraw collected fees
/// @param erc721 token contract
function collectionWithdraw(address erc721) public {
require(collectionFeesAccrued[erc721] > 0, 'ERC721FixedPricePurchase: No funds to withdraw for this collection');
address payable collectionOwner = payable(IOwnable(erc721).owner());
uint256 amount = collectionFeesAccrued[erc721];
collectionFeesAccrued[erc721] = 0;
(bool sent,) = collectionOwner.call{value: amount}("");
require(sent, "ERC721FixedPricePurchase: Failed to send Ether");
}
/// @notice allows protocol owner to withdraw collected fees
function protocolWithdraw() public {
require(protocolFeesAccrued > 0, 'ERC721FixedPricePurchase: No protocol funds to withdraw');
uint256 amount = protocolFeesAccrued;
protocolFeesAccrued = 0;
(bool sent,) = owner().call{value: amount}("");
require(sent, "ERC721FixedPricePurchase: Failed to send Ether");
}
}
| @notice list an ERC721 token for sale @dev the owner must approve the tokenId on the ERC721 in a separate transaction to fully list @dev delisting is done externally by revoking approval on the ERC721 @param erc721 token contract @param tokenId id of the ERC721 token being listed @param price amount buyer must pay to purchase | function list(address erc721, uint256 tokenId, uint256 price) onlyErc721Owner(erc721, tokenId) public {
listing[erc721][tokenId] = price;
emit Listed(erc721, tokenId, msg.sender, price);
}
| 6,467,196 | [
1,
1098,
392,
4232,
39,
27,
5340,
1147,
364,
272,
5349,
225,
326,
3410,
1297,
6617,
537,
326,
1147,
548,
603,
326,
4232,
39,
27,
5340,
316,
279,
9004,
2492,
358,
7418,
666,
225,
1464,
376,
310,
353,
2731,
18885,
1230,
635,
5588,
601,
310,
23556,
603,
326,
4232,
39,
27,
5340,
225,
6445,
71,
27,
5340,
1147,
6835,
225,
1147,
548,
612,
434,
326,
4232,
39,
27,
5340,
1147,
3832,
12889,
225,
6205,
3844,
27037,
1297,
8843,
358,
23701,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
666,
12,
2867,
6445,
71,
27,
5340,
16,
2254,
5034,
1147,
548,
16,
2254,
5034,
6205,
13,
1338,
41,
1310,
27,
5340,
5541,
12,
12610,
27,
5340,
16,
1147,
548,
13,
1071,
288,
203,
3639,
11591,
63,
12610,
27,
5340,
6362,
2316,
548,
65,
273,
6205,
31,
203,
3639,
3626,
987,
329,
12,
12610,
27,
5340,
16,
1147,
548,
16,
1234,
18,
15330,
16,
6205,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/5/0x5E9162Dd40B12F1a9aDf69D6c26A00564960C4E3/sources/CryptoDickButtDA.sol | @notice function to close the sale @dev requires contract owner | function closeSale() external onlyOwner {
saleOpen = false;
}
| 16,835,954 | [
1,
915,
358,
1746,
326,
272,
5349,
225,
4991,
6835,
3410,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1746,
30746,
1435,
3903,
1338,
5541,
288,
203,
3639,
272,
5349,
3678,
273,
629,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// Part: AddressUpgradeable
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage
) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) =
target.call{value: weiValue}(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// Part: CrvDepositor
interface CrvDepositor {
//deposit crv for cvxCrv
//can locking immediately or defer locking to someone else by paying a fee.
//while users can choose to lock or defer, this is mostly in place so that
//the cvx reward contract isnt costly to claim rewards
function deposit(uint256 _amount, bool _lock) external;
}
// Part: EnumerableSetUpgradeable
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value)
private
view
returns (bool)
{
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index)
private
view
returns (bytes32)
{
require(
set._values.length > index,
"EnumerableSet: index out of bounds"
);
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value)
internal
returns (bool)
{
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index)
internal
view
returns (address)
{
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index)
internal
view
returns (uint256)
{
return uint256(_at(set._inner, index));
}
}
// Part: IBaseRewardsPool
interface IBaseRewardsPool {
//balance
function balanceOf(address _account) external view returns (uint256);
//withdraw to a convex tokenized deposit
function withdraw(uint256 _amount, bool _claim) external returns (bool);
function withdrawAll(bool _claim) external;
//withdraw directly to curve LP token
function withdrawAndUnwrap(uint256 _amount, bool _claim) external returns (bool);
//claim rewards
function getReward() external returns (bool);
//stake a convex tokenized deposit
function stake(uint256 _amount) external returns (bool);
//stake a convex tokenized deposit for another address(transfering ownership)
function stakeFor(address _account, uint256 _amount) external returns (bool);
function getReward(address _account, bool _claimExtras) external returns (bool);
function rewards(address _account) external view returns (uint256);
function earned(address _account) external view returns (uint256);
function stakingToken() external view returns (address);
}
// Part: IBooster
interface IBooster {
struct PoolInfo {
address lptoken;
address token;
address gauge;
address crvRewards;
address stash;
bool shutdown;
}
function poolInfo(uint256 _pid) external view returns (PoolInfo memory);
function deposit(
uint256 _pid,
uint256 _amount,
bool _stake
) external returns (bool);
function depositAll(uint256 _pid, bool _stake) external returns (bool);
function withdraw(uint256 _pid, uint256 _amount) external returns (bool);
function withdrawAll(uint256 _pid) external returns (bool);
}
// Part: IController
interface IController {
function withdraw(address, uint256) external;
function strategies(address) external view returns (address);
function balanceOf(address) external view returns (uint256);
function earn(address, uint256) external;
function want(address) external view returns (address);
function rewards() external view returns (address);
function vaults(address) external view returns (address);
}
// Part: ICurveFi
interface ICurveFi {
function get_virtual_price() external view returns (uint256 out);
function add_liquidity(
// renbtc/tbtc pool
uint256[2] calldata amounts,
uint256 min_mint_amount
) external;
function add_liquidity(
// sBTC pool
uint256[3] calldata amounts,
uint256 min_mint_amount
) external;
function add_liquidity(
// bUSD pool
uint256[4] calldata amounts,
uint256 min_mint_amount
) external;
function get_dy(
int128 i,
int128 j,
uint256 dx
) external returns (uint256 out);
function get_dy_underlying(
int128 i,
int128 j,
uint256 dx
) external returns (uint256 out);
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external;
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy,
uint256 deadline
) external;
function exchange_underlying(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external;
function exchange_underlying(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy,
uint256 deadline
) external;
function remove_liquidity(
uint256 _amount,
uint256 deadline,
uint256[2] calldata min_amounts
) external;
function remove_liquidity_imbalance(uint256[2] calldata amounts, uint256 deadline) external;
function remove_liquidity_imbalance(uint256[3] calldata amounts, uint256 max_burn_amount) external;
function remove_liquidity(uint256 _amount, uint256[3] calldata amounts) external;
function remove_liquidity_imbalance(uint256[4] calldata amounts, uint256 max_burn_amount) external;
function remove_liquidity(uint256 _amount, uint256[4] calldata amounts) external;
function remove_liquidity_one_coin(
uint256 _token_amount,
int128 i,
uint256 _min_amount
) external;
function commit_new_parameters(
int128 amplification,
int128 new_fee,
int128 new_admin_fee
) external;
function apply_new_parameters() external;
function revert_new_parameters() external;
function commit_transfer_ownership(address _owner) external;
function apply_transfer_ownership() external;
function revert_transfer_ownership() external;
function withdraw_admin_fees() external;
function coins(int128 arg0) external returns (address out);
function underlying_coins(int128 arg0) external returns (address out);
function balances(int128 arg0) external returns (uint256 out);
function A() external returns (int128 out);
function fee() external returns (int128 out);
function admin_fee() external returns (int128 out);
function owner() external returns (address out);
function admin_actions_deadline() external returns (uint256 out);
function transfer_ownership_deadline() external returns (uint256 out);
function future_A() external returns (int128 out);
function future_fee() external returns (int128 out);
function future_admin_fee() external returns (int128 out);
function future_owner() external returns (address out);
function calc_withdraw_one_coin(uint256 _token_amount, int128 _i) external view returns (uint256 out);
}
// Part: ICurveRegistry
interface ICurveRegistry {
function find_pool_for_coins(
address _from,
address _to,
uint256 _index
) external returns (address);
function get_coin_indices(
address _pool,
address _from,
address _to
)
external
returns (
int128,
int128,
bool
);
}
// Part: ICurveRegistryAddressProvider
interface ICurveRegistryAddressProvider {
function get_address(uint256 id) external returns (address);
}
// Part: IERC20Upgradeable
/**
* @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
);
}
// Part: ISett
interface ISett {
function token() external view returns (address);
function deposit(uint256) external;
function depositFor(address, uint256) external;
function depositAll() external;
function withdraw(uint256) external;
function withdrawAll() external;
function earn() external;
function balanceOf(address account) external view returns (uint256);
function totalSupply() external view returns (uint256);
function claimInsurance() external; // NOTE: Only yDelegatedVault implements this
function getPricePerFullShare() external view returns (uint256);
function approveContractAccess(address) external;
function governance() external view returns (address);
}
// Part: IUniswapRouterV2
interface IUniswapRouterV2 {
function factory() external view returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}
// Part: IUniswapV2Factory
interface IUniswapV2Factory {
event PairCreated(
address indexed token0,
address indexed token1,
address pair,
uint256
);
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 feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function createPair(address tokenA, address tokenB)
external
returns (address pair);
}
// Part: Initializable
/**
* @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;
}
}
// Part: MathUpgradeable
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2);
}
}
// Part: SafeMathUpgradeable
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// Part: TokenSwapPathRegistry
/*
Expands swapping functionality over base strategy
- ETH in and ETH out Variants
- Sushiswap support in addition to Uniswap
*/
contract TokenSwapPathRegistry {
mapping(address => mapping(address => address[])) public tokenSwapPaths;
event TokenSwapPathSet(address tokenIn, address tokenOut, address[] path);
function getTokenSwapPath(address tokenIn, address tokenOut) public view returns (address[] memory) {
return tokenSwapPaths[tokenIn][tokenOut];
}
function _setTokenSwapPath(
address tokenIn,
address tokenOut,
address[] memory path
) internal {
tokenSwapPaths[tokenIn][tokenOut] = path;
emit TokenSwapPathSet(tokenIn, tokenOut, path);
}
}
// Part: ContextUpgradeable
/*
* @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;
}
// Part: SafeERC20Upgradeable
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
function safeTransfer(
IERC20Upgradeable token,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transfer.selector, to, value)
);
}
function safeTransferFrom(
IERC20Upgradeable token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transferFrom.selector, from, to, value)
);
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, value)
);
}
function safeIncreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
uint256 newAllowance =
token.allowance(address(this), spender).add(value);
_callOptionalReturn(
token,
abi.encodeWithSelector(
token.approve.selector,
spender,
newAllowance
)
);
}
function safeDecreaseAllowance(
IERC20Upgradeable 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(IERC20Upgradeable token, bytes memory data)
private
{
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata =
address(token).functionCall(
data,
"SafeERC20: low-level call failed"
);
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(
abi.decode(returndata, (bool)),
"SafeERC20: ERC20 operation did not succeed"
);
}
}
}
// Part: SettAccessControl
/*
Common base for permissioned roles throughout Sett ecosystem
*/
contract SettAccessControl is Initializable {
address public governance;
address public strategist;
address public keeper;
// ===== MODIFIERS =====
function _onlyGovernance() internal view {
require(msg.sender == governance, "onlyGovernance");
}
function _onlyGovernanceOrStrategist() internal view {
require(
msg.sender == strategist || msg.sender == governance,
"onlyGovernanceOrStrategist"
);
}
function _onlyAuthorizedActors() internal view {
require(
msg.sender == keeper || msg.sender == governance,
"onlyAuthorizedActors"
);
}
// ===== PERMISSIONED ACTIONS =====
/// @notice Change strategist address
/// @notice Can only be changed by governance itself
function setStrategist(address _strategist) external {
_onlyGovernance();
strategist = _strategist;
}
/// @notice Change keeper address
/// @notice Can only be changed by governance itself
function setKeeper(address _keeper) external {
_onlyGovernance();
keeper = _keeper;
}
/// @notice Change governance address
/// @notice Can only be changed by governance itself
function setGovernance(address _governance) public {
_onlyGovernance();
governance = _governance;
}
uint256[50] private __gap;
}
// Part: BaseSwapper
/*
Expands swapping functionality over base strategy
- ETH in and ETH out Variants
- Sushiswap support in addition to Uniswap
*/
contract BaseSwapper {
using SafeERC20Upgradeable for IERC20Upgradeable;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
/// @dev Reset approval and approve exact amount
function _safeApproveHelper(
address token,
address recipient,
uint256 amount
) internal {
IERC20Upgradeable(token).safeApprove(recipient, 0);
IERC20Upgradeable(token).safeApprove(recipient, amount);
}
}
// Part: PausableUpgradeable
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// Part: BaseStrategy
/*
===== Badger Base Strategy =====
Common base class for all Sett strategies
Changelog
V1.1
- Verify amount unrolled from strategy positions on withdraw() is within a threshold relative to the requested amount as a sanity check
- Add version number which is displayed with baseStrategyVersion(). If a strategy does not implement this function, it can be assumed to be 1.0
V1.2
- Remove idle want handling from base withdraw() function. This should be handled as the strategy sees fit in _withdrawSome()
*/
abstract contract BaseStrategy is PausableUpgradeable, SettAccessControl {
using SafeERC20Upgradeable for IERC20Upgradeable;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
event Withdraw(uint256 amount);
event WithdrawAll(uint256 balance);
event WithdrawOther(address token, uint256 amount);
event SetStrategist(address strategist);
event SetGovernance(address governance);
event SetController(address controller);
event SetWithdrawalFee(uint256 withdrawalFee);
event SetPerformanceFeeStrategist(uint256 performanceFeeStrategist);
event SetPerformanceFeeGovernance(uint256 performanceFeeGovernance);
event Harvest(uint256 harvested, uint256 indexed blockNumber);
event Tend(uint256 tended);
address public want; // Want: Curve.fi renBTC/wBTC (crvRenWBTC) LP token
uint256 public performanceFeeGovernance;
uint256 public performanceFeeStrategist;
uint256 public withdrawalFee;
uint256 public constant MAX_FEE = 10000;
address public controller;
address public guardian;
uint256 public withdrawalMaxDeviationThreshold;
function __BaseStrategy_init(
address _governance,
address _strategist,
address _controller,
address _keeper,
address _guardian
) public initializer whenNotPaused {
__Pausable_init();
governance = _governance;
strategist = _strategist;
keeper = _keeper;
controller = _controller;
guardian = _guardian;
withdrawalMaxDeviationThreshold = 50;
}
// ===== Modifiers =====
function _onlyController() internal view {
require(msg.sender == controller, "onlyController");
}
function _onlyAuthorizedActorsOrController() internal view {
require(
msg.sender == keeper ||
msg.sender == governance ||
msg.sender == controller,
"onlyAuthorizedActorsOrController"
);
}
function _onlyAuthorizedPausers() internal view {
require(
msg.sender == guardian || msg.sender == governance,
"onlyPausers"
);
}
/// ===== View Functions =====
function baseStrategyVersion() public view returns (string memory) {
return "1.2";
}
/// @notice Get the balance of want held idle in the Strategy
function balanceOfWant() public view returns (uint256) {
return IERC20Upgradeable(want).balanceOf(address(this));
}
/// @notice Get the total balance of want realized in the strategy, whether idle or active in Strategy positions.
function balanceOf() public view virtual returns (uint256) {
return balanceOfWant().add(balanceOfPool());
}
function isTendable() public view virtual returns (bool) {
return false;
}
function isProtectedToken(address token) public view returns (bool) {
address[] memory protectedTokens = getProtectedTokens();
for (uint256 i = 0; i < protectedTokens.length; i++) {
if (token == protectedTokens[i]) {
return true;
}
}
return false;
}
/// ===== Permissioned Actions: Governance =====
function setGuardian(address _guardian) external {
_onlyGovernance();
guardian = _guardian;
}
function setWithdrawalFee(uint256 _withdrawalFee) external {
_onlyGovernance();
require(_withdrawalFee <= MAX_FEE, "excessive-fee");
withdrawalFee = _withdrawalFee;
}
function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist)
external
{
_onlyGovernance();
require(_performanceFeeStrategist <= MAX_FEE, "excessive-fee");
performanceFeeStrategist = _performanceFeeStrategist;
}
function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance)
external
{
_onlyGovernance();
require(_performanceFeeGovernance <= MAX_FEE, "excessive-fee");
performanceFeeGovernance = _performanceFeeGovernance;
}
function setController(address _controller) external {
_onlyGovernance();
controller = _controller;
}
function setWithdrawalMaxDeviationThreshold(uint256 _threshold) external {
_onlyGovernance();
require(_threshold <= MAX_FEE, "excessive-threshold");
withdrawalMaxDeviationThreshold = _threshold;
}
function deposit() public virtual whenNotPaused {
_onlyAuthorizedActorsOrController();
uint256 _want = IERC20Upgradeable(want).balanceOf(address(this));
if (_want > 0) {
_deposit(_want);
}
_postDeposit();
}
// ===== Permissioned Actions: Controller =====
/// @notice Controller-only function to Withdraw partial funds, normally used with a vault withdrawal
function withdrawAll()
external
virtual
whenNotPaused
returns (uint256 balance)
{
_onlyController();
_withdrawAll();
_transferToVault(IERC20Upgradeable(want).balanceOf(address(this)));
}
/// @notice Withdraw partial funds from the strategy, unrolling from strategy positions as necessary
/// @notice Processes withdrawal fee if present
/// @dev If it fails to recover sufficient funds (defined by withdrawalMaxDeviationThreshold), the withdrawal should fail so that this unexpected behavior can be investigated
function withdraw(uint256 _amount) external virtual whenNotPaused {
_onlyController();
// Withdraw from strategy positions, typically taking from any idle want first.
_withdrawSome(_amount);
uint256 _postWithdraw =
IERC20Upgradeable(want).balanceOf(address(this));
// Sanity check: Ensure we were able to retrieve sufficent want from strategy positions
// If we end up with less than the amount requested, make sure it does not deviate beyond a maximum threshold
if (_postWithdraw < _amount) {
uint256 diff = _diff(_amount, _postWithdraw);
// Require that difference between expected and actual values is less than the deviation threshold percentage
require(
diff <=
_amount.mul(withdrawalMaxDeviationThreshold).div(MAX_FEE),
"withdraw-exceed-max-deviation-threshold"
);
}
// Return the amount actually withdrawn if less than amount requested
uint256 _toWithdraw = MathUpgradeable.min(_postWithdraw, _amount);
// Process withdrawal fee
uint256 _fee = _processWithdrawalFee(_toWithdraw);
// Transfer remaining to Vault to handle withdrawal
_transferToVault(_toWithdraw.sub(_fee));
}
// NOTE: must exclude any tokens used in the yield
// Controller role - withdraw should return to Controller
function withdrawOther(address _asset)
external
virtual
whenNotPaused
returns (uint256 balance)
{
_onlyController();
_onlyNotProtectedTokens(_asset);
balance = IERC20Upgradeable(_asset).balanceOf(address(this));
IERC20Upgradeable(_asset).safeTransfer(controller, balance);
}
/// ===== Permissioned Actions: Authoized Contract Pausers =====
function pause() external {
_onlyAuthorizedPausers();
_pause();
}
function unpause() external {
_onlyGovernance();
_unpause();
}
/// ===== Internal Helper Functions =====
/// @notice If withdrawal fee is active, take the appropriate amount from the given value and transfer to rewards recipient
/// @return The withdrawal fee that was taken
function _processWithdrawalFee(uint256 _amount) internal returns (uint256) {
if (withdrawalFee == 0) {
return 0;
}
uint256 fee = _amount.mul(withdrawalFee).div(MAX_FEE);
IERC20Upgradeable(want).safeTransfer(
IController(controller).rewards(),
fee
);
return fee;
}
/// @dev Helper function to process an arbitrary fee
/// @dev If the fee is active, transfers a given portion in basis points of the specified value to the recipient
/// @return The fee that was taken
function _processFee(
address token,
uint256 amount,
uint256 feeBps,
address recipient
) internal returns (uint256) {
if (feeBps == 0) {
return 0;
}
uint256 fee = amount.mul(feeBps).div(MAX_FEE);
IERC20Upgradeable(token).safeTransfer(recipient, fee);
return fee;
}
function _transferToVault(uint256 _amount) internal {
address _vault = IController(controller).vaults(address(want));
require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20Upgradeable(want).safeTransfer(_vault, _amount);
}
/// @notice Utility function to diff two numbers, expects higher value in first position
function _diff(uint256 a, uint256 b) internal pure returns (uint256) {
require(a >= b, "diff/expected-higher-number-in-first-position");
return a.sub(b);
}
// ===== Abstract Functions: To be implemented by specific Strategies =====
/// @dev Internal deposit logic to be implemented by Stratgies
function _deposit(uint256 _want) internal virtual;
function _postDeposit() internal virtual {
//no-op by default
}
/// @notice Specify tokens used in yield process, should not be available to withdraw via withdrawOther()
function _onlyNotProtectedTokens(address _asset) internal virtual;
function getProtectedTokens()
public
view
virtual
returns (address[] memory)
{
return new address[](0);
}
/// @dev Internal logic for strategy migration. Should exit positions as efficiently as possible
function _withdrawAll() internal virtual;
/// @dev Internal logic for partial withdrawals. Should exit positions as efficiently as possible.
/// @dev The withdraw() function shell automatically uses idle want in the strategy before attempting to withdraw more using this
function _withdrawSome(uint256 _amount) internal virtual returns (uint256);
/// @dev Realize returns from positions
/// @dev Returns can be reinvested into positions, or distributed in another fashion
/// @dev Performance fees should also be implemented in this function
/// @dev Override function stub is removed as each strategy can have it's own return signature for STATICCALL
// function harvest() external virtual;
/// @dev User-friendly name for this strategy for purposes of convenient reading
function getName() external pure virtual returns (string memory);
/// @dev Balance of want currently held in strategy positions
function balanceOfPool() public view virtual returns (uint256);
uint256[49] private __gap;
}
// Part: CurveSwapper
/*
Expands swapping functionality over base strategy
- ETH in and ETH out Variants
- Sushiswap support in addition to Uniswap
*/
contract CurveSwapper is BaseSwapper {
using SafeERC20Upgradeable for IERC20Upgradeable;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
address public constant addressProvider = 0x0000000022D53366457F9d5E68Ec105046FC4383;
uint256 public constant registryId = 0;
uint256 public constant metaPoolFactoryId = 3;
function _exchange(
address _from,
address _to,
uint256 _dx,
uint256 _min_dy,
uint256 _index,
bool _isFactoryPool
) internal {
address poolRegistry = ICurveRegistryAddressProvider(addressProvider).get_address(_isFactoryPool ? metaPoolFactoryId : registryId);
address poolAddress = ICurveRegistry(poolRegistry).find_pool_for_coins(_from, _to, _index);
if (poolAddress != address(0)) {
_safeApproveHelper(_from, poolAddress, _dx);
(int128 i, int128 j, ) = ICurveRegistry(poolRegistry).get_coin_indices(poolAddress, _from, _to);
ICurveFi(poolAddress).exchange(i, j, _dx, _min_dy);
}
}
function _add_liquidity_single_coin(
address swap,
address pool,
address inputToken,
uint256 inputAmount,
uint256 inputPosition,
uint256 numPoolElements,
uint256 min_mint_amount
) internal {
_safeApproveHelper(inputToken, swap, inputAmount);
if (numPoolElements == 2) {
uint256[2] memory convertedAmounts;
convertedAmounts[inputPosition] = inputAmount;
ICurveFi(swap).add_liquidity(convertedAmounts, min_mint_amount);
} else if (numPoolElements == 3) {
uint256[3] memory convertedAmounts;
convertedAmounts[inputPosition] = inputAmount;
ICurveFi(swap).add_liquidity(convertedAmounts, min_mint_amount);
} else if (numPoolElements == 4) {
uint256[4] memory convertedAmounts;
convertedAmounts[inputPosition] = inputAmount;
ICurveFi(swap).add_liquidity(convertedAmounts, min_mint_amount);
} else {
revert("Bad numPoolElements");
}
}
function _add_liquidity(
address pool,
uint256[2] memory amounts,
uint256 min_mint_amount
) internal {
ICurveFi(pool).add_liquidity(amounts, min_mint_amount);
}
function _add_liquidity(
address pool,
uint256[3] memory amounts,
uint256 min_mint_amount
) internal {
ICurveFi(pool).add_liquidity(amounts, min_mint_amount);
}
function _add_liquidity(
address pool,
uint256[4] memory amounts,
uint256 min_mint_amount
) internal {
ICurveFi(pool).add_liquidity(amounts, min_mint_amount);
}
function _remove_liquidity_one_coin(
address swap,
uint256 _token_amount,
int128 i,
uint256 _min_amount
) internal {
ICurveFi(swap).remove_liquidity_one_coin(_token_amount, i, _min_amount);
}
}
// Part: UniswapSwapper
/*
Expands swapping functionality over base strategy
- ETH in and ETH out Variants
- Sushiswap support in addition to Uniswap
*/
contract UniswapSwapper is BaseSwapper {
using SafeERC20Upgradeable for IERC20Upgradeable;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
address internal constant uniswap =
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // Uniswap router
address internal constant sushiswap =
0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; // Sushiswap router
function _swapExactTokensForTokens(
address router,
address startToken,
uint256 balance,
address[] memory path
) internal {
_safeApproveHelper(startToken, router, balance);
IUniswapRouterV2(router).swapExactTokensForTokens(
balance,
0,
path,
address(this),
now
);
}
function _swapExactETHForTokens(
address router,
uint256 balance,
address[] memory path
) internal {
IUniswapRouterV2(uniswap).swapExactETHForTokens{value: balance}(
0,
path,
address(this),
now
);
}
function _swapExactTokensForETH(
address router,
address startToken,
uint256 balance,
address[] memory path
) internal {
_safeApproveHelper(startToken, router, balance);
IUniswapRouterV2(router).swapExactTokensForETH(
balance,
0,
path,
address(this),
now
);
}
function _getPair(
address router,
address token0,
address token1
) internal view returns (address) {
address factory = IUniswapRouterV2(router).factory();
return IUniswapV2Factory(factory).getPair(token0, token1);
}
/// @notice Add liquidity to uniswap for specified token pair, utilizing the maximum balance possible
function _addMaxLiquidity(
address router,
address token0,
address token1
) internal {
uint256 _token0Balance =
IERC20Upgradeable(token0).balanceOf(address(this));
uint256 _token1Balance =
IERC20Upgradeable(token1).balanceOf(address(this));
_safeApproveHelper(token0, router, _token0Balance);
_safeApproveHelper(token1, router, _token1Balance);
IUniswapRouterV2(router).addLiquidity(
token0,
token1,
_token0Balance,
_token1Balance,
0,
0,
address(this),
block.timestamp
);
}
function _addMaxLiquidityEth(address router, address token0) internal {
uint256 _token0Balance =
IERC20Upgradeable(token0).balanceOf(address(this));
uint256 _ethBalance = address(this).balance;
_safeApproveHelper(token0, router, _token0Balance);
IUniswapRouterV2(router).addLiquidityETH{value: address(this).balance}(
token0,
_token0Balance,
0,
0,
address(this),
block.timestamp
);
}
}
// File: StrategyCvxCrvHelper.sol
/*
1. Stake cvxCrv
2. Sell earned rewards into cvxCrv position and restake
Changelog:
V1.1
* Implemented the _exchange function from the CurveSwapper library to perform the CRV -> cvxCRV swap through
curve instead of Sushiswap.
* Implemented the _withdrawAll() function
V1.2 - BIP 83 - Lock CVX instead of selling it
*/
contract StrategyCvxCrvHelper is
BaseStrategy,
CurveSwapper,
UniswapSwapper,
TokenSwapPathRegistry
{
using SafeERC20Upgradeable for IERC20Upgradeable;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
// ===== Token Registry =====
address public constant wbtc = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599;
address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant crv = 0xD533a949740bb3306d119CC777fa900bA034cd52;
address public constant cvx = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B;
address public constant cvxCrv = 0x62B9c7356A2Dc64a1969e19C23e4f579F9810Aa7;
address public constant usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address public constant threeCrv =
0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490;
IERC20Upgradeable public constant crvToken =
IERC20Upgradeable(0xD533a949740bb3306d119CC777fa900bA034cd52);
IERC20Upgradeable public constant cvxToken =
IERC20Upgradeable(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B);
IERC20Upgradeable public constant cvxCrvToken =
IERC20Upgradeable(0x62B9c7356A2Dc64a1969e19C23e4f579F9810Aa7);
IERC20Upgradeable public constant usdcToken =
IERC20Upgradeable(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
IERC20Upgradeable public constant threeCrvToken =
IERC20Upgradeable(0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490);
address public constant threeCrvSwap =
0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7;
// ===== Convex Registry =====
CrvDepositor public constant crvDepositor =
CrvDepositor(0x8014595F2AB54cD7c604B00E9fb932176fDc86Ae); // Convert CRV -> cvxCRV/ETH SLP
IBooster public constant booster =
IBooster(0xF403C135812408BFbE8713b5A23a04b3D48AAE31);
IBaseRewardsPool public constant cvxCrvRewardsPool =
IBaseRewardsPool(0x3Fe65692bfCD0e6CF84cB1E7d24108E434A7587e);
uint256 public constant MAX_UINT_256 = uint256(-1);
uint256 public constant crvCvxCrvPoolIndex = 2;
uint256 public crvCvxCrvSlippageToleranceBps;
// v1.2
address public constant BADGER_TREE =
0x660802Fc641b154aBA66a62137e71f331B6d787A;
ISett public constant CVX_VAULT =
ISett(0xfd05D3C7fe2924020620A8bE4961bBaA747e6305);
// Used to signal to the Badger Tree that rewards where sent to it
event TreeDistribution(
address indexed token,
uint256 amount,
uint256 indexed blockNumber,
uint256 timestamp
);
event HarvestState(uint256 timestamp, uint256 blockNumber);
event WithdrawState(
uint256 toWithdraw,
uint256 preWant,
uint256 postWant,
uint256 withdrawn
);
struct TokenSwapData {
address tokenIn;
uint256 totalSold;
uint256 wantGained;
}
event TendState(
uint256 crvTended,
uint256 cvxTended,
uint256 cvxCrvHarvested
);
function initialize(
address _governance,
address _strategist,
address _controller,
address _keeper,
address _guardian,
uint256[3] memory _feeConfig
) public initializer whenNotPaused {
__BaseStrategy_init(
_governance,
_strategist,
_controller,
_keeper,
_guardian
);
want = cvxCrv;
performanceFeeGovernance = _feeConfig[0];
performanceFeeStrategist = _feeConfig[1];
withdrawalFee = _feeConfig[2];
// Set Swap Paths
address[] memory path = new address[](3);
path[0] = cvx;
path[1] = weth;
path[2] = cvxCrv;
_setTokenSwapPath(cvx, cvxCrv, path);
path = new address[](3);
path[0] = usdc;
path[1] = weth;
path[2] = cvxCrv;
_setTokenSwapPath(usdc, cvxCrv, path);
// Approvals: Staking Pool
cvxCrvToken.approve(address(cvxCrvRewardsPool), MAX_UINT_256);
}
/// ===== View Functions =====
function version() external pure returns (string memory) {
return "1.2";
}
function getName() external pure override returns (string memory) {
return "StrategyCvxCrvHelper";
}
function balanceOfPool() public view override returns (uint256) {
return cvxCrvRewardsPool.balanceOf(address(this));
}
function getProtectedTokens()
public
view
override
returns (address[] memory)
{
address[] memory protectedTokens = new address[](2);
protectedTokens[0] = want;
protectedTokens[1] = cvxCrv;
return protectedTokens;
}
function isTendable() public view override returns (bool) {
return false;
}
/// ===== Internal Core Implementations =====
function _onlyNotProtectedTokens(address _asset) internal override {
require(!isProtectedToken(_asset));
}
/// @dev Deposit Badger into the staking contract
function _deposit(uint256 _want) internal override {
// Deposit all want in core staking pool
cvxCrvRewardsPool.stake(_want);
}
/// @dev Unroll from all strategy positions, and transfer non-core tokens to controller rewards
function _withdrawAll() internal override {
cvxCrvRewardsPool.withdrawAll(false);
// Note: All want is automatically withdrawn outside this "inner hook" in base strategy function
}
/// @dev Withdraw want from staking rewards, using earnings first
function _withdrawSome(uint256 _amount)
internal
override
returns (uint256)
{
// Get idle want in the strategy
uint256 _preWant = IERC20Upgradeable(want).balanceOf(address(this));
// If we lack sufficient idle want, withdraw the difference from the strategy position
if (_preWant < _amount) {
uint256 _toWithdraw = _amount.sub(_preWant);
cvxCrvRewardsPool.withdraw(_toWithdraw, false);
// Note: Withdrawl process will earn sushi, this will be deposited into SushiBar on next tend()
}
// Confirm how much want we actually end up with
uint256 _postWant = IERC20Upgradeable(want).balanceOf(address(this));
// Return the actual amount withdrawn if less than requested
uint256 _withdrawn = MathUpgradeable.min(_postWant, _amount);
emit WithdrawState(_amount, _preWant, _postWant, _withdrawn);
return _withdrawn;
}
function _tendGainsFromPositions() internal {
if (cvxCrvRewardsPool.earned(address(this)) > 0) {
cvxCrvRewardsPool.getReward(address(this), true);
}
}
function patchPaths() external {
_onlyGovernance();
address[] memory path = new address[](3);
path[0] = cvx;
path[1] = weth;
path[2] = crv;
_setTokenSwapPath(cvx, crv, path);
path = new address[](3);
path[0] = usdc;
path[1] = weth;
path[2] = crv;
_setTokenSwapPath(usdc, crv, path);
}
function setCrvCvxCrvSlippageToleranceBps(uint256 _sl) external {
_onlyGovernance();
crvCvxCrvSlippageToleranceBps = _sl;
}
function harvest()
external
whenNotPaused
returns (uint256 cvxCrvHarvested)
{
_onlyAuthorizedActors();
// 1. Harvest gains from positions
_tendGainsFromPositions();
// 2. Sell 3Crv (withdraw to USDC -> swap to CRV)
uint256 threeCrvBalance = threeCrvToken.balanceOf(address(this));
if (threeCrvBalance > 0) {
_remove_liquidity_one_coin(threeCrvSwap, threeCrvBalance, 1, 0);
uint256 usdcBalance = usdcToken.balanceOf(address(this));
require(usdcBalance > 0, "window-tint");
if (usdcBalance > 0) {
_swapExactTokensForTokens(
sushiswap,
usdc,
usdcBalance,
getTokenSwapPath(usdc, crv)
);
}
}
// 3. Lock CVX for bveCVX
uint256 cvxTokenBalance = cvxToken.balanceOf(address(this));
if (cvxTokenBalance > 0) {
uint256 prevTreeBalance = CVX_VAULT.balanceOf(BADGER_TREE);
cvxToken.safeApprove(address(CVX_VAULT), 0); //Reset to avoid dust
cvxToken.safeApprove(address(CVX_VAULT), cvxTokenBalance); // Approve exact amount
// Take performance fees
if (performanceFeeGovernance > 0) {
CVX_VAULT.depositFor(
IController(controller).rewards(),
cvxTokenBalance.mul(performanceFeeGovernance).div(MAX_FEE)
);
}
if (performanceFeeStrategist > 0) {
CVX_VAULT.depositFor(
strategist,
cvxTokenBalance.mul(performanceFeeStrategist).div(MAX_FEE)
);
}
// Deposit what's left to Badger Tree
CVX_VAULT.depositFor(
BADGER_TREE,
cvxToken.balanceOf(address(this))
);
uint256 afterTreeBalance = CVX_VAULT.balanceOf(BADGER_TREE);
emit TreeDistribution(
address(CVX_VAULT),
afterTreeBalance.sub(prevTreeBalance),
block.number,
block.timestamp
);
}
// 4. Convert CRV -> cvxCRV
uint256 crvBalance = crvToken.balanceOf(address(this));
if (crvBalance > 0) {
uint256 minCvxCrvOut =
crvBalance.mul(MAX_FEE.sub(crvCvxCrvSlippageToleranceBps)).div(
MAX_FEE
);
_exchange(
crv,
cvxCrv,
crvBalance,
minCvxCrvOut,
crvCvxCrvPoolIndex,
true
);
}
// Track harvested + converted coin balance of want
cvxCrvHarvested = cvxCrvToken.balanceOf(address(this));
_processFee(
cvxCrv,
cvxCrvHarvested,
performanceFeeGovernance,
IController(controller).rewards()
);
// 5. Stake all cvxCRV
if (cvxCrvHarvested > 0) {
cvxCrvRewardsPool.stake(cvxCrvToken.balanceOf(address(this)));
}
emit Harvest(cvxCrvHarvested, block.number);
return cvxCrvHarvested;
}
} | 3. Lock CVX for bveCVX | uint256 cvxTokenBalance = cvxToken.balanceOf(address(this));
| 14,884,958 | [
1,
23,
18,
3488,
385,
58,
60,
364,
324,
537,
22007,
60,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
5034,
8951,
92,
1345,
13937,
273,
8951,
92,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// █████ ███ █████ ████ █████████ █████ //
// ░░███ ░███ ░░███ ░░███ ███░░░░░███ ░░███ //
// ░███ ░███ ░███ ██████ ░███ ██████ ██████ █████████████ ██████ ░███ ░░░ ███████ ████████ ██████ ████████ ███████ ██████ ████████ //
// ░███ ░███ ░███ ███░░███ ░███ ███░░███ ███░░███░░███░░███░░███ ███░░███ ░░█████████ ░░░███░ ░░███░░███ ░░░░░███ ░░███░░███ ███░░███ ███░░███░░███░░███ //
// ░░███ █████ ███ ░███████ ░███ ░███ ░░░ ░███ ░███ ░███ ░███ ░███ ░███████ ░░░░░░░░███ ░███ ░███ ░░░ ███████ ░███ ░███ ░███ ░███░███████ ░███ ░░░ //
// ░░░█████░█████░ ░███░░░ ░███ ░███ ███░███ ░███ ░███ ░███ ░███ ░███░░░ ███ ░███ ░███ ███ ░███ ███░░███ ░███ ░███ ░███ ░███░███░░░ ░███ //
// ░░███ ░░███ ░░██████ █████░░██████ ░░██████ █████░███ █████░░██████ ░░█████████ ░░█████ █████ ░░████████ ████ █████░░███████░░██████ █████ //
// ░░░ ░░░ ░░░░░░ ░░░░░ ░░░░░░ ░░░░░░ ░░░░░ ░░░ ░░░░░ ░░░░░░ ░░░░░░░░░ ░░░░░ ░░░░░ ░░░░░░░░ ░░░░ ░░░░░ ░░░░░███ ░░░░░░ ░░░░░ //
// ███ ░███ //
// ░░██████ //
// ░░░░░░ //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./EscrowManagement.sol";
import "./SignedMessages.sol";
import "./TokenSegments.sol";
// we whitelist OpenSea so that minters can save on gas and spend it on NFTs
contract OwnableDelegateProxy { }
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
contract ConjuredLands is ReentrancyGuard, EscrowManagement, ERC721, ERC721Enumerable, Ownable, SignedMessages, TokenSegments {
using Strings for uint256;
address proxyRegistryAddress;
mapping (address => bool) private airdroppers;
mapping(address => uint256[]) private burnedTokensByOwners;
uint8 public maxNumberOfTokens = 30;
address[] public ownersThatBurned;
address[20] public premiumOwners;
uint256 public tokenPrice = 0.0555 ether;
uint256 public premiumTokenPrice = 5.55 ether;
uint256 public constant maxSupply = 10888;
uint256 public constant maxIndex = 10887;
mapping (uint256 => uint256) private tokenCreationBlocknumber;
bool public mintingActive = true;
bool public burningActive = false;
uint8 public premiumMintingSlots = 22;
// that's October 19th 2021 folks!
uint256 public salesStartTime = 1634839200;
mapping (address => uint256) mintingBlockByOwners;
mapping(address => uint256) public highestAmountOfMintedTokensByOwners;
string private __baseURI;
bool baseURIfrozen = false;
// generate random index
uint256 internal nonce = 19831594194915648;
mapping(int8 => uint256[maxSupply]) private alignmentIndices;
// the good, the evil and the neutral https://www.youtube.com/watch?v=WCN5JJY_wiA
uint16[3] public alignmentMaxSupply;
uint16[3] public alignmentTotalSupply;
uint16[3] public alignmentFirstIndex;
// these are URIs for the custom part, single URLs and segmented baseURIs
mapping(uint256 => string) specialTokenURIs;
constructor(string memory _name, string memory _symbol, address[] memory _teamMembers, uint8[] memory _splits, address _proxyRegistryAddress)
ERC721(_name, _symbol)
{
// set the team members
require(_teamMembers.length == _splits.length, "Wrong team lengths");
if (_teamMembers.length > 0) {
uint8 totalSplit = 0;
for (uint8 i = 0; i < _teamMembers.length; i++) {
EscrowManagement._addTeamMemberSplit(_teamMembers[i], _splits[i]);
totalSplit += _splits[i];
}
require(totalSplit == 100, "Total split not 100");
}
alignmentMaxSupply[0] = 3000; // good
alignmentMaxSupply[1] = 3000; // evil
alignmentMaxSupply[2] = 4000; // neutral
alignmentFirstIndex[0] = 888; // the indexes 0- 887 are reserved for the giveaways
alignmentFirstIndex[1] = alignmentFirstIndex[0] + alignmentMaxSupply[0];
alignmentFirstIndex[2] = alignmentFirstIndex[1] + alignmentMaxSupply[1];
// set the deployer of this contract as an issuer of signed messages
SignedMessages.setIssuer(msg.sender, true);
__baseURI = "ipfs://QmamCw1tks7fpFyDCfGYVQyMkSwtJ39BRGxuA2D37hFME1/";
proxyRegistryAddress = _proxyRegistryAddress;
}
function _baseURI() internal view override returns(string memory) {
return __baseURI;
}
function setBaseURI(string memory newBaseURI) public onlyOwner(){
require(!baseURIfrozen, "BaseURI frozen");
__baseURI = newBaseURI;
}
function baseURI() public view returns(string memory){
return __baseURI;
}
// calling this function locks the possibility to change the baseURI forever
function freezeBaseURI() public onlyOwner(){
baseURIfrozen = true;
}
function tokenURI(uint256 tokenId) public view override returns(string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
// check if token is in a special segment
int256 segmentId = TokenSegments.getSegmentId(tokenId);
if (segmentId != -1) {
// found a segment, get the URI, only return if it is set
string memory segmentURI = TokenSegments.getBaseURIBySegmentId(segmentId);
if (bytes(segmentURI).length > 0) {
return string(abi.encodePacked(segmentURI,tokenId.toString()));
}
}
// check if a special tokenURI is set, otherwise fallback to standard
if (bytes(specialTokenURIs[tokenId]).length == 0){
return ERC721.tokenURI(tokenId);
} else {
// special tokenURI is set
return specialTokenURIs[tokenId];
}
}
function setSpecialTokenURI(uint256 tokenId, string memory newTokenURI) public onlyOwner(){
require(getAlignmentByIndex(tokenId) == -1, "No special token");
specialTokenURIs[tokenId] = newTokenURI;
}
function setSegmentBaseTokenURIs(uint256 startingIndex, uint256 endingIndex, string memory _URI) public onlyOwner(){
TokenSegments._setSegmentBaseTokenURIs(startingIndex, endingIndex, _URI);
}
function setBaseURIBySegmentId(int256 pointer, string memory _URI) public onlyOwner(){
TokenSegments._setBaseURIBySegmentId(pointer, _URI);
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.
*/
function isApprovedForAll(address owner, address operator)
override
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);
}
// use this to update the registry address, if a wrong one was passed with the constructor
function setProxyRegistryAddress(address _proxyRegistryAddress) public onlyOwner(){
proxyRegistryAddress = _proxyRegistryAddress;
}
function approveAirdropperContract(address contractAddress, bool approval) public onlyOwner(){
airdroppers[contractAddress] = approval;
}
function airdropper_allowedCaller(address caller) public view returns(bool){
// only team members can airdrop
return (EscrowManagement.teamMembersSplit[caller] > 0);
}
// used by the external airdropper
function airdropper_allowedToken(uint256 tokenId) public view returns(bool){
// only tokens in the giveaway section are allowed for airdrops
return (getAlignmentByIndex(tokenId) == -1);
}
function airdropper_mint(address to, uint256 tokenId) public{
// protect this call - only the airdropper contract can can call this
require(airdroppers[msg.sender], "Not an airdropper");
_internalMintById(to, tokenId);
}
function setIssuerForSignedMessages(address issuer, bool status) public onlyOwner(){
SignedMessages.setIssuer(issuer, status);
}
function getAlignmentByIndex(uint256 _index) public view returns(int8){
// we take the last one, and loop
int8 alignment = -1;
// check the boundaries - lower than the first or higher than the last
if ((_index < alignmentFirstIndex[0]) ||
((_index > alignmentFirstIndex[alignmentFirstIndex.length - 1] + alignmentMaxSupply[alignmentMaxSupply.length - 1] - 1))) {
return -1;
}
for (uint8 ix = 0; ix < alignmentFirstIndex.length; ix++) {
if (alignmentFirstIndex[ix] <= _index) {
alignment = int8(ix);
}
}
return alignment;
}
function addTeamMemberSplit(address teamMember, uint8 split) public onlyOwner(){
EscrowManagement._addTeamMemberSplit(teamMember, split);
}
function getTeamMembers() public onlyOwner view returns(address[] memory){
return EscrowManagement._getTeamMembers();
}
function remainingSupply() public view returns(uint256){
// returns the total remainingSupply
return maxSupply - totalSupply();
}
function remainingSupply(uint8 alignment) public view returns(uint16){
return alignmentMaxSupply[alignment] - alignmentTotalSupply[alignment];
}
function salesStarted() public view returns (bool) {
return block.timestamp >= salesStartTime;
}
// set the time from which the sales will be started
function setSalesStartTime(uint256 _salesStartTime) public onlyOwner(){
salesStartTime = _salesStartTime;
}
function flipMintingState() public onlyOwner(){
mintingActive = !mintingActive;
}
function flipBurningState() public onlyOwner(){
burningActive = !burningActive;
}
// change the prices for minting
function setTokenPrice(uint256 newPrice) public onlyOwner(){
tokenPrice = newPrice;
}
function setPremiumTokenPrice(uint256 newPremiumPrice) public onlyOwner(){
premiumTokenPrice = newPremiumPrice;
}
function getRandomId(uint256 _presetIndex, uint8 _alignment) internal returns(uint256){
uint256 totalSize = remainingSupply(_alignment);
int8 alignment = int8(_alignment);
// allow the caller to preset an index
uint256 index;
if (_presetIndex == 0) {
index = alignmentFirstIndex[uint8(alignment)] + uint256(keccak256(abi.encodePacked(nonce, "ourSaltAndPepper", blockhash(block.number), msg.sender, block.difficulty, block.timestamp, gasleft()))) % totalSize;
} else {
index = _presetIndex;
alignment = getAlignmentByIndex(index);
}
if (alignment == -1) {
// if the index is out of bounds, then exit
return 0;
}
uint256 value = 0;
// the indices holds the value for unused index positions
// so you never get a collision
if (alignmentIndices[alignment][index] != 0) {
value = alignmentIndices[alignment][index];
} else {
value = index;
}
// Move last value to the actual position, so if it get taken, you can give back the free one
if (alignmentIndices[alignment][totalSize - 1] == 0) {
// Array position not initialized, so use that position
alignmentIndices[alignment][index] = totalSize - 1;
} else {
// Array position holds a value so use that
alignmentIndices[alignment][index] = alignmentIndices[alignment][totalSize - 1];
}
nonce++;
return value;
}
// team members can always mint out of the giveaway section
function membersMint(address to, uint256 tokenId) onlyTeamMembers() public{
// can only mint in the non public section
require(getAlignmentByIndex(tokenId) == -1, "Token in public section");
_internalMintById(to, tokenId);
}
// internal minting function by id, can flexibly be called by the external controllers
function _internalMintById(address to, uint256 tokenId) internal{
require(tokenId <= maxIndex, "Token out of index");
_safeMint(to, tokenId);
getRandomId(tokenId, 0);
// consume the index in the alignment, if it was part of the open section
int8 alignment = getAlignmentByIndex(tokenId);
if (alignment != -1) {
alignmentTotalSupply[uint8(alignment)]++;
}
}
// internal minting function via random index, can flexibly be called by the external controllers
function _internalMintRandom(address to, uint256 numberOfTokens, uint8 alignment) internal{
require(numberOfTokens <= maxNumberOfTokens, "Max amount exceeded");
for (uint i = 0; i < numberOfTokens; i++) {
uint mintIndex = getRandomId(0, alignment);
if (alignmentTotalSupply[alignment] < alignmentMaxSupply[alignment]) {
_safeMint(to, mintIndex);
alignmentTotalSupply[alignment]++;
}
}
if (numberOfTokens > 0) {
// this is for preventing getting the id in the same transaction (semaphore)
mintingBlockByOwners[msg.sender] = block.number;
// keep track of the minting amounts (even is something has been transferred or burned)
highestAmountOfMintedTokensByOwners[msg.sender] += numberOfTokens;
emit FundsReceived(msg.sender, msg.value, "payment by minting sale");
}
}
function mint(uint256 numberOfTokens, uint8 alignment) public payable nonReentrant{
require(mintingActive && salesStarted(), "Minting is not active");
require((tokenPrice * numberOfTokens) == msg.value, "Wrong payment");
require(numberOfTokens <= remainingSupply(alignment), "Purchase amount exceeds max supply");
_internalMintRandom(msg.sender, numberOfTokens, alignment);
}
function premiumMint(uint8 alignment) public payable nonReentrant{
require(mintingActive && salesStarted(), "Minting is not active");
require(premiumMintingSlots>0, "No more premium minting slots");
require(totalSupply()<= maxSupply, "Maximum supply reached");
require(msg.value == premiumTokenPrice, "Wrong payment");
premiumOwners[premiumMintingSlots -1] = msg.sender;
premiumMintingSlots--;
_internalMintRandom(msg.sender, 1, alignment);
}
function burn(uint256 tokenId) public nonReentrant{
require(burningActive, "Burning not active.");
super._burn(tokenId);
// keep track of burners
if (burnedTokensByOwners[msg.sender].length == 0){
// first time they burn, add the caller to the list
ownersThatBurned.push(msg.sender);
}
burnedTokensByOwners[msg.sender].push(tokenId);
}
function getBurnedTokensByOwner(address owner) public view returns(uint256[] memory){
return burnedTokensByOwners[owner];
}
event FundsReceived(address from, uint256 amount, string description);
// accounting purposes: we need to be able to split the incoming funds between sales and royalty
receive() external payable {
emit FundsReceived(msg.sender, msg.value, "direct payment, no sale");
}
fallback() external payable {
emit FundsReceived(msg.sender, msg.value, "direct payment, no sale");
}
/*
* Functions for handling signed messages
*
* */
function mintById_SignedMessage(uint256 _tokenId, uint256 _setPrice, uint256 expirationTimestamp, uint256 _nonce, bytes memory _sig) public payable{
// check validity and execute
require(expirationTimestamp <= block.timestamp, "Expired");
bytes32 message = SignedMessages.prefixed(keccak256(abi.encodePacked(msg.sender, _tokenId, _setPrice, expirationTimestamp, _nonce)));
require(msg.value == _setPrice, "Wrong payment");
require(SignedMessages.consumePass(message, _sig, _nonce), "Error in signed msg");
_internalMintById(msg.sender, _tokenId);
if (msg.value > 0) {
emit FundsReceived(msg.sender, msg.value, "payment by minting sale");
}
}
//DAppJS.addSignatureCall('test', 'address', 'uint8', 'uint256', 'uint256', 'uint256','uint256', 'bytes memory');
function mintByAlignment_SignedMessage(uint8 _alignment, uint256 _numberOfTokens, uint256 _maxAmountOfTokens, uint256 _setPrice, uint256 expirationTimestamp, uint256 _nonce, bytes memory _sig) public payable{
// check validity and execute
require(expirationTimestamp <= block.timestamp, "Expired");
require(_numberOfTokens <= _maxAmountOfTokens, "Amount too big");
bytes32 message = SignedMessages.prefixed(keccak256(abi.encodePacked(msg.sender, _alignment, _maxAmountOfTokens, _setPrice, expirationTimestamp, _nonce)));
require(msg.value == _setPrice * _numberOfTokens, "Wrong payment");
require(SignedMessages.consumePass(message, _sig, _nonce), "Error in signed msg");
_internalMintRandom(msg.sender, _numberOfTokens, _alignment);
if (msg.value > 0) {
emit FundsReceived(msg.sender, msg.value, "payment by minting sale");
}
}
function mintAnyAlignment_SignedMessage(uint8 _alignment, uint256 _numberOfTokens, uint256 _maxAmountOfTokens, uint256 _setPrice, uint256 expirationTimestamp, uint256 _nonce, bytes memory _sig) public payable{
// check validity and execute
require(expirationTimestamp <= block.timestamp, "Expired");
require(_numberOfTokens <= _maxAmountOfTokens, "Amount too big");
bytes32 message = SignedMessages.prefixed(keccak256(abi.encodePacked(msg.sender, _maxAmountOfTokens, _setPrice, expirationTimestamp, _nonce)));
require(msg.value == _setPrice * _numberOfTokens, "Wrong payment");
require(SignedMessages.consumePass(message, _sig, _nonce), "Error in signed msg");
_internalMintRandom(msg.sender, _numberOfTokens, _alignment);
if (msg.value > 0) {
emit FundsReceived(msg.sender, msg.value, "payment by minting sale");
}
}
/*
* Withdrawal functions
*/
function withdrawToOwner() public onlyOwner(){
EscrowManagement._withdrawToOwner(owner());
}
// these functions are meant to help retrieve ERC721, ERC1155 and ERC20 tokens that have been sent to this contract
function withdrawERC721(address _contract, uint256 id, address to) public onlyOwner(){
EscrowManagement._withdrawERC721(_contract, id, to);
}
function withdrawERC1155(address _contract, uint256[] memory ids, uint256[] memory amounts, address to) public onlyOwner(){
// withdraw a 1155 token
EscrowManagement._withdrawERC1155(_contract, ids, amounts, to);
}
function withdrawERC20(address _contract, address to, uint256 amount) public onlyOwner(){
// withdraw a 20 token
EscrowManagement._withdrawERC20(_contract, to, amount);
}
function balanceOf(address owner) public view override(ERC721) returns (uint256) {
return super.balanceOf(owner);
}
function transferSplitByOwner(address from, address to, uint8 split) public onlyOwner(){
// allow the contract owner to change the split, if anything with withdrawals goes wrong, or a team member loses access to their EOA
EscrowManagement._transferSplit(from, to, split);
}
function tokensOfOwner(address owner) public view returns (uint256[] memory){
// allow this function only after the minting has happened for passed owner
require(block.number > mintingBlockByOwners[owner], "Hello @0xnietzsche");
uint256 tokenCount = balanceOf(owner);
if (tokenCount == 0) {
// The address has no tokens
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(owner, index);
}
return result;
}
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable, ERC1155Receiver)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^ 0.8.0;
/*
* Manage different baseURIs per tokenSegments.
* A segment is defined by a starting and and ending index.
* The last added segment that fits a passed ID wins over previous ones.
* A segment can be changed back to an empty string.
* A segment can be determined by passing a tokenId
* */
contract TokenSegments{
string[] segmentBaseURIs;
uint256[] tokenSegmentsStartingIndex;
uint256[] tokenSegmentsEndingIndex;
function _setSegmentBaseTokenURIs(uint256 startingIndex, uint256 endingIndex, string memory _URI) internal{
tokenSegmentsStartingIndex.push(startingIndex);
tokenSegmentsEndingIndex.push(endingIndex);
segmentBaseURIs.push(_URI);
}
function getSegmentId(uint256 pointer) public view returns(int256){
// go backwards, so that segments can be overwritten by adding them
if (tokenSegmentsStartingIndex.length == 0) {
return -1;
}
for (int256 i = int256(tokenSegmentsStartingIndex.length - 1); i >= 0; i--) {
if ((tokenSegmentsStartingIndex[uint256(i)] <= pointer) && (tokenSegmentsEndingIndex[uint256(i)] >= pointer)) {
return i;
}
}
return -1;
}
function getSegmentBaseURI(uint256 tokenId) public view returns(string memory){
int256 segmentId = getSegmentId(tokenId);
if (segmentId == -1) {
return "";
}
return segmentBaseURIs[uint256(segmentId)];
}
function getBaseURIBySegmentId(int256 pointer) public view returns(string memory){
return segmentBaseURIs[uint256(pointer)];
}
function _setBaseURIBySegmentId(int256 pointer, string memory _URI) internal{
segmentBaseURIs[uint256(pointer)] = _URI;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// handles the signed messages
contract SignedMessages{
mapping(uint256 => bool) internal nonces;
mapping(address => bool) internal issuers;
/// 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));
}
function consumePass(bytes32 message, bytes memory sig, uint256 nonce) internal returns(bool){
// check the nonce first
if (nonces[nonce]) {
return false;
}
// check the issuer
if (!issuers[recoverSigner(message, sig)]) {
return false;
}
// consume the nonce if it is safe
nonces[nonce] = true;
return true;
}
function validateNonce(uint256 _nonce) public view returns(bool){
return nonces[_nonce];
}
function setIssuer(address issuer, bool status) internal{
issuers[issuer] = status;
}
function getIssuerStatus(address issuer) public view returns(bool){
return issuers[issuer];
}
function recoverSigner(bytes32 _message, bytes memory sig) internal pure returns(address){
uint8 v;
bytes32 r;
bytes32 s;
(v, r, s) = splitSignature(sig);
return ecrecover(_message, v, r, s);
}
function splitSignature(bytes memory sig) internal pure returns(uint8, bytes32, bytes32){
require(sig.length == 65);
bytes32 r;
bytes32 s;
uint8 v;
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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
abstract contract ERC1155Interface{
function safeBatchTransferFrom(address from,address to,uint256[] memory ids,uint256[] memory amounts,bytes memory data) public virtual;
}
abstract contract ERC721Interface{
function safeTransferFrom(address from,address to,uint256 tokenId) public virtual;
}
abstract contract ERC20Interface{
function transfer(address recipient, uint256 amount) public virtual returns(bool);
}
contract EscrowManagement is ReentrancyGuard, ERC721Holder, ERC1155Holder{
address[] internal teamMembers;
mapping (address => uint8) internal teamMembersSplit;
modifier onlyTeamMembers(){
require(teamMembersSplit[msg.sender] > 0, "No team member");
_;
}
function _getTeamMembers() internal view returns(address[] memory){
return teamMembers;
}
function getTeamMemberSplit(address teamMember) public view returns(uint8){
return teamMembersSplit[teamMember];
}
/*
* Escrow and withdrawal functions for decentral team members
*/
function _addTeamMemberSplit(address teamMember, uint8 split) internal{
require(teamMembersSplit[teamMember] == 0, "Team member already added");
require(split<101, "Split too big");
teamMembers.push(teamMember);
teamMembersSplit[teamMember] = split;
}
function _transferSplit(address from, address to, uint8 split) internal{
// transfer split from one member to another
// the caller has to be a team member
require(split <= teamMembersSplit[from], "Split too big");
if (teamMembersSplit[to] == 0) {
// if to was not yet a team member, then welcome
teamMembers.push(to);
}
teamMembersSplit[from] = teamMembersSplit[from] - split;
teamMembersSplit[to] = teamMembersSplit[to] + split;
}
function transferSplit(address from, address to, uint8 split) public nonReentrant onlyTeamMembers(){
// the from has the be the caller for team members
require(msg.sender == from, "Not the sender");
_transferSplit(from, to, split);
}
// withdraw - pays out the team members by the defined distribution
// every call pays out the actual balance to all team members
// this function can be called by anyone
function withdraw() public nonReentrant{
uint256 balance = address(this).balance;
require(balance > 0, "No balance");
uint256 amountOfTeamMembers = teamMembers.length;
require(amountOfTeamMembers >0, "0 team members found");
// in order to distribute everything and take care of rests due to the division, the first team members gets the rest
// i=1 -> we start with the second member, the first goes after the for
bool success;
for (uint256 i=1; i<amountOfTeamMembers; i++) {
uint256 payoutAmount = balance /100 * teamMembersSplit[teamMembers[i]];
// only payout if amount is positive
if (payoutAmount > 0){
(success, ) = (payable(teamMembers[i])).call{value:payoutAmount}("");
//(payable(teamMembers[i])).transfer(payoutAmount);
require(success, "Withdraw failed");
}
}
// payout the rest to first team member
(success, ) = (payable(teamMembers[0])).call{value:address(this).balance}("");
//(payable(teamMembers[0])).transfer(address(this).balance);
require(success, "Withdraw failed-0");
}
// this function is for safety, if no team members have been defined
function _withdrawToOwner(address owner) internal{
require(teamMembers.length == 0, "Team members are defined");
(bool success, ) = (payable(owner)).call{value:address(this).balance}("");
//(payable(owner)).transfer(address(this).balance);
require(success, "Withdraw failed.");
}
// these functions are meant to help retrieve ERC721, ERC1155 and ERC20 tokens that have been sent to this contract
function _withdrawERC721(address _contract, uint256 id, address to) internal{
// withdraw a 721 token
ERC721Interface ERC721Contract = ERC721Interface(_contract);
// transfer ownership from this contract to the specified address
ERC721Contract.safeTransferFrom(address(this), to,id);
}
function _withdrawERC1155(address _contract, uint256[] memory ids, uint256[] memory amounts, address to) internal{
// withdraw a 1155 token
ERC1155Interface ERC1155Contract = ERC1155Interface(_contract);
// transfer ownership from this contract to the specified address
ERC1155Contract.safeBatchTransferFrom(address(this),to,ids,amounts,'');
}
function _withdrawERC20(address _contract, address to, uint256 amount) internal{
// withdraw a 20 token
ERC20Interface ERC20Contract = ERC20Interface(_contract);
// transfer ownership from this contract to the specified address
ERC20Contract.transfer(to, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721Receiver.sol";
/**
* @dev Implementation of the {IERC721Receiver} interface.
*
* Accepts all token transfers.
* Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.
*/
contract ERC721Holder is IERC721Receiver {
/**
* @dev See {IERC721Receiver-onERC721Received}.
*
* Always returns `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address,
address,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
}
// SPDX-License-Identifier: MIT
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;
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 "../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;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC1155Receiver.sol";
import "../../../utils/introspection/ERC165.sol";
/**
* @dev _Available since v3.1._
*/
abstract contract ERC1155Receiver is ERC165, IERC1155Receiver {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC1155Receiver.sol";
/**
* @dev _Available since v3.1._
*/
contract ERC1155Holder is ERC1155Receiver {
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] memory,
uint256[] memory,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
} | allow this function only after the minting has happened for passed owner The address has no tokens | function tokensOfOwner(address owner) public view returns (uint256[] memory){
require(block.number > mintingBlockByOwners[owner], "Hello @0xnietzsche");
uint256 tokenCount = balanceOf(owner);
if (tokenCount == 0) {
return new uint256[](0);
uint256[] memory result = new uint256[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(owner, index);
}
return result;
}
}
| 1,249,370 | [
1,
5965,
333,
445,
1338,
1839,
326,
312,
474,
310,
711,
17497,
364,
2275,
3410,
1021,
1758,
711,
1158,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2430,
951,
5541,
12,
2867,
3410,
13,
1071,
1476,
1135,
261,
11890,
5034,
8526,
3778,
15329,
203,
3639,
2583,
12,
2629,
18,
2696,
405,
312,
474,
310,
1768,
858,
5460,
414,
63,
8443,
6487,
315,
18601,
632,
20,
22695,
6213,
30424,
18706,
8863,
203,
3639,
2254,
5034,
1147,
1380,
273,
11013,
951,
12,
8443,
1769,
203,
3639,
309,
261,
2316,
1380,
422,
374,
13,
288,
203,
5411,
327,
394,
2254,
5034,
8526,
12,
20,
1769,
203,
5411,
2254,
5034,
8526,
3778,
563,
273,
394,
2254,
5034,
8526,
12,
2316,
1380,
1769,
203,
5411,
2254,
5034,
770,
31,
203,
5411,
364,
261,
1615,
273,
374,
31,
770,
411,
1147,
1380,
31,
770,
27245,
288,
203,
7734,
563,
63,
1615,
65,
273,
1147,
951,
5541,
21268,
12,
8443,
16,
770,
1769,
203,
5411,
289,
203,
5411,
327,
563,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.6.2;
// SPDX-License-Identifier: MIT
abstract contract Context {
function _MSGSENDER583() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA879() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
interface IERC20 {
function TOTALSUPPLY430() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF616(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER244(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE387(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE425(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM381(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER617(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL460(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// SPDX-License-Identifier: MIT
library SafeMath {
function ADD135(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB321(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB321(a, b, "SafeMath: subtraction overflow");
}
function SUB321(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL733(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV136(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV136(a, b, "SafeMath: division by zero");
}
function DIV136(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD593(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD593(a, b, "SafeMath: modulo by zero");
}
function MOD593(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
library Address {
function ISCONTRACT469(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
function SENDVALUE193(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function FUNCTIONCALL340(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALL340(target, data, "Address: low-level call failed");
}
function FUNCTIONCALL340(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return _FUNCTIONCALLWITHVALUE922(target, data, 0, errorMessage);
}
function FUNCTIONCALLWITHVALUE944(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALLWITHVALUE944(target, data, value, "Address: low-level call with value failed");
}
function FUNCTIONCALLWITHVALUE944(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
require(address(this).balance >= value, "Address: insufficient balance for call");
return _FUNCTIONCALLWITHVALUE922(target, data, value, errorMessage);
}
function _FUNCTIONCALLWITHVALUE922(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING
require(ISCONTRACT469(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
function NAME100() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL131() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS904() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
function TOTALSUPPLY430() public view override returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF616(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER244(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER73(_MSGSENDER583(), recipient, amount);
return true;
}
function ALLOWANCE387(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE425(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_APPROVE319(_MSGSENDER583(), spender, amount);
return true;
}
function TRANSFERFROM381(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER73(sender, recipient, amount);
_APPROVE319(sender, _MSGSENDER583(), _allowances[sender][_MSGSENDER583()].SUB321(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE808(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE319(_MSGSENDER583(), spender, _allowances[_MSGSENDER583()][spender].ADD135(addedValue));
return true;
}
function DECREASEALLOWANCE515(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE319(_MSGSENDER583(), spender, _allowances[_MSGSENDER583()][spender].SUB321(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER73(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_BEFORETOKENTRANSFER129(sender, recipient, amount);
_balances[sender] = _balances[sender].SUB321(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD135(amount);
emit TRANSFER617(sender, recipient, amount);
}
function _MINT517(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER129(address(0), account, amount);
_totalSupply = _totalSupply.ADD135(amount);
_balances[account] = _balances[account].ADD135(amount);
emit TRANSFER617(address(0), account, amount);
}
function _BURN171(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_BEFORETOKENTRANSFER129(account, address(0), amount);
_balances[account] = _balances[account].SUB321(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB321(amount);
emit TRANSFER617(account, address(0), amount);
}
function _APPROVE319(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit APPROVAL460(owner, spender, amount);
}
function _SETUPDECIMALS874(uint8 decimals_) internal { //inject NONSTANDARD NAMING
_decimals = decimals_;
}
function _BEFORETOKENTRANSFER129(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING
}
// SPDX-License-Identifier: MIT
abstract contract ERC20Capped is ERC20 {
uint256 private _cap;
constructor (uint256 cap) public {
require(cap > 0, "ERC20Capped: cap is 0");
_cap = cap;
}
function CAP360() public view returns (uint256) { //inject NONSTANDARD NAMING
return _cap;
}
function _BEFORETOKENTRANSFER129(address from, address to, uint256 amount) internal virtual override { //inject NONSTANDARD NAMING
super._BEFORETOKENTRANSFER129(from, to, amount);
if (from == address(0)) { // When minting tokens
require(TOTALSUPPLY430().ADD135(amount) <= _cap, "ERC20Capped: cap exceeded");
}
}
}
// SPDX-License-Identifier: MIT
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED797(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
address msgSender = _MSGSENDER583();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED797(address(0), msgSender);
}
function OWNER971() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER607() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER583(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP525() public virtual ONLYOWNER607 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED797(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP777(address newOwner) public virtual ONLYOWNER607 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED797(_owner, newOwner);
_owner = newOwner;
}
}
interface IUniswapV2Router01 {
function FACTORY439() external pure returns (address); //inject NONSTANDARD NAMING
function WETH181() external pure returns (address); //inject NONSTANDARD NAMING
function ADDLIQUIDITY85( //inject NONSTANDARD NAMING
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function ADDLIQUIDITYETH216( //inject NONSTANDARD NAMING
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function REMOVELIQUIDITY344( //inject NONSTANDARD NAMING
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function REMOVELIQUIDITYETH742( //inject NONSTANDARD NAMING
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function REMOVELIQUIDITYWITHPERMIT491( //inject NONSTANDARD NAMING
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function REMOVELIQUIDITYETHWITHPERMIT317( //inject NONSTANDARD NAMING
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function SWAPEXACTTOKENSFORTOKENS917( //inject NONSTANDARD NAMING
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function SWAPTOKENSFOREXACTTOKENS879( //inject NONSTANDARD NAMING
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function SWAPEXACTETHFORTOKENS817(uint amountOutMin, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING
external
payable
returns (uint[] memory amounts);
function SWAPTOKENSFOREXACTETH856(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING
external
returns (uint[] memory amounts);
function SWAPEXACTTOKENSFORETH218(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING
external
returns (uint[] memory amounts);
function SWAPETHFOREXACTTOKENS998(uint amountOut, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING
external
payable
returns (uint[] memory amounts);
function QUOTE315(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); //inject NONSTANDARD NAMING
function GETAMOUNTOUT816(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); //inject NONSTANDARD NAMING
function GETAMOUNTIN684(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); //inject NONSTANDARD NAMING
function GETAMOUNTSOUT241(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); //inject NONSTANDARD NAMING
function GETAMOUNTSIN775(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); //inject NONSTANDARD NAMING
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function REMOVELIQUIDITYETHSUPPORTINGFEEONTRANSFERTOKENS846( //inject NONSTANDARD NAMING
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function REMOVELIQUIDITYETHWITHPERMITSUPPORTINGFEEONTRANSFERTOKENS1( //inject NONSTANDARD NAMING
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function SWAPEXACTTOKENSFORTOKENSSUPPORTINGFEEONTRANSFERTOKENS219( //inject NONSTANDARD NAMING
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function SWAPEXACTETHFORTOKENSSUPPORTINGFEEONTRANSFERTOKENS501( //inject NONSTANDARD NAMING
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function SWAPEXACTTOKENSFORETHSUPPORTINGFEEONTRANSFERTOKENS54( //inject NONSTANDARD NAMING
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
interface IUniswapV2Pair {
event APPROVAL460(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
event TRANSFER617(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
function NAME100() external pure returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL131() external pure returns (string memory); //inject NONSTANDARD NAMING
function DECIMALS904() external pure returns (uint8); //inject NONSTANDARD NAMING
function TOTALSUPPLY430() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF616(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function ALLOWANCE387(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE425(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFER244(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM381(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function DOMAIN_SEPARATOR749() external view returns (bytes32); //inject NONSTANDARD NAMING
function PERMIT_TYPEHASH945() external pure returns (bytes32); //inject NONSTANDARD NAMING
function NONCES546(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function PERMIT654(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING
event MINT786(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING
event BURN405(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING
event SWAP722( //inject NONSTANDARD NAMING
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event SYNC303(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING
function MINIMUM_LIQUIDITY735() external pure returns (uint); //inject NONSTANDARD NAMING
function FACTORY439() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN0934() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN1318() external view returns (address); //inject NONSTANDARD NAMING
function GETRESERVES691() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING
function PRICE0CUMULATIVELAST150() external view returns (uint); //inject NONSTANDARD NAMING
function PRICE1CUMULATIVELAST277() external view returns (uint); //inject NONSTANDARD NAMING
function KLAST634() external view returns (uint); //inject NONSTANDARD NAMING
function MINT615(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING
function BURN664(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING
function SWAP816(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING
function SKIM21(address to) external; //inject NONSTANDARD NAMING
function SYNC269() external; //inject NONSTANDARD NAMING
function INITIALIZE267(address, address) external; //inject NONSTANDARD NAMING
}
interface IUniswapV2Factory {
event PAIRCREATED762(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING
function FEETO789() external view returns (address); //inject NONSTANDARD NAMING
function FEETOSETTER578() external view returns (address); //inject NONSTANDARD NAMING
function GETPAIR592(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRS410(uint) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRSLENGTH90() external view returns (uint); //inject NONSTANDARD NAMING
function CREATEPAIR614(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING
function SETFEETO894(address) external; //inject NONSTANDARD NAMING
function SETFEETOSETTER1(address) external; //inject NONSTANDARD NAMING
}
interface IWETH {
function DEPOSIT145() external payable; //inject NONSTANDARD NAMING
function TRANSFER244(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function WITHDRAW78(uint) external; //inject NONSTANDARD NAMING
}
contract CGLB is ERC20Capped, Ownable {
using SafeMath for uint;
address public UNIPAIR;
address public DAI = address(0x6B175474E89094C44Da98b954EedeAC495271d0F);
IUniswapV2Router02 public UNIROUTER = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
IUniswapV2Factory public UNIFACTORY = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f);
bool public isRunning = false;
bool private liquidityFlag;
uint public constant supplycap690 = (10**4)*(10**18); //inject NONSTANDARD NAMING
uint public constant tokensforinitialliquidity143 = 3*(10**3)*(10**18); //inject NONSTANDARD NAMING
bytes32 public airdropRoot;
mapping (address => bool) public claimedAirdrop;
string public website = "www.cglb.fi";
constructor() public ERC20Capped(supplycap690) ERC20("Cant go lower boys", "CGLB") {
airdropRoot = 0x185065ab3d54b516ee3ed54dc30e04758300a4b41e207cf3ba91715f378d7728;
}
function TRANSFER244(address recipient, uint256 amount) //inject NONSTANDARD NAMING
public override
returns (bool) {
require(msg.sender == UNIPAIR || msg.sender == address(UNIROUTER));
super.TRANSFER244(recipient, amount);
return true;
}
function TRANSFERFROM381(address sender, address recipient, uint256 amount) //inject NONSTANDARD NAMING
public override
returns (bool) {
require(liquidityFlag);
_TRANSFER73(sender, recipient, amount);
return true;
}
function ADDLIQUIDITYTOUNISWAPPAIR951( //inject NONSTANDARD NAMING
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountDAIDesired,
uint256 amountDAImin
) public payable {
require(isRunning);
require(IERC20(DAI).TRANSFERFROM381(msg.sender, address(this), amountDAIDesired));
require(IERC20(DAI).APPROVE425(address(UNIROUTER), amountDAIDesired));
_TRANSFER73(msg.sender, address(this), amountTokenDesired);
liquidityFlag = true;
(uint amountToken, uint amountDAI, uint liquidity) = UNIROUTER.ADDLIQUIDITY85(
address(this),
DAI,
amountTokenDesired,
amountDAIDesired,
amountTokenMin,
amountDAImin,
msg.sender,
now + 10 minutes
);
liquidityFlag = false;
//sends dust back
if (amountTokenDesired - amountToken > 0 ) _TRANSFER73(address(this), msg.sender, amountTokenDesired-amountToken);
if (amountDAIDesired - amountDAI > 0) require(IERC20(DAI).TRANSFER244(msg.sender, amountDAIDesired - amountDAI));
}
function ADDINITIALLIQUIDITYWITHPAIR729() public ONLYOWNER607 { //inject NONSTANDARD NAMING
CREATEUNISWAPPAIR64();
uint256 amountDAI = IERC20(DAI).BALANCEOF616(address(this));
require(IERC20(DAI).TRANSFER244(UNIPAIR, amountDAI));
_MINT517(UNIPAIR, tokensforinitialliquidity143);
IUniswapV2Pair(UNIPAIR).MINT615(msg.sender);
isRunning = true;
}
function ADDINITIALLIQUIDITY209() public ONLYOWNER607 { //inject NONSTANDARD NAMING
uint256 amountDAI = IERC20(DAI).BALANCEOF616(address(this));
require(IERC20(DAI).TRANSFER244(UNIPAIR, amountDAI));
_MINT517(UNIPAIR, tokensforinitialliquidity143);
IUniswapV2Pair(UNIPAIR).MINT615(msg.sender);
isRunning = true;
}
function SETAIRDROPROOT894(bytes32 _root) public ONLYOWNER607 { //inject NONSTANDARD NAMING
airdropRoot = _root;
}
function SETPAIR246(address _pair) public ONLYOWNER607 { //inject NONSTANDARD NAMING
UNIPAIR = _pair;
}
function CREATEUNISWAPPAIR64() internal { //inject NONSTANDARD NAMING
require(UNIPAIR == address(0), "Token: pool already created");
UNIPAIR = UNIFACTORY.CREATEPAIR614(
DAI,
address(this)
);
}
function CHECKPROOF499(bytes memory proof, bytes32 root, bytes32 hash) internal view returns (bool) { //inject NONSTANDARD NAMING
bytes32 el;
bytes32 h = hash;
for (uint256 i = 32; i <= proof.length; i += 32) {
assembly {
el := mload(add(proof, i))
}
if (h < el) {
h = keccak256(abi.encodePacked(h, el));
} else {
h = keccak256(abi.encodePacked(el, h));
}
}
return h == root;
}
function CLAIMAIRDROP701(bytes memory proof, uint amount) public { //inject NONSTANDARD NAMING
require(!claimedAirdrop[msg.sender]);
bytes32 hash = keccak256(abi.encodePacked(msg.sender, amount));
require(CHECKPROOF499(proof, airdropRoot, hash), "Invalid proof");
claimedAirdrop[msg.sender] = true;
_MINT517(msg.sender, amount);
}
function WITHDRAWERC20742(address token) ONLYOWNER607 public { //inject NONSTANDARD NAMING
uint balance = IERC20(token).BALANCEOF616(address(this));
require(IERC20(token).TRANSFER244(msg.sender, balance));
}
} | inject NONSTANDARD NAMING
| uint public constant tokensforinitialliquidity143 = 3*(10**3)*(10**18); | 1,820,616 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
1071,
5381,
2430,
1884,
2738,
77,
454,
18988,
24237,
28643,
273,
890,
21556,
2163,
636,
23,
17653,
12,
2163,
636,
2643,
1769,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721EnumerableUpgradeable.sol";
/**
* @title IERC721Mintable
* @author JaboiNads
* @notice Adds functionality that allows for a token's minter to be retrieved.
*/
interface IERC721Mintable is IERC721Upgradeable, IERC721MetadataUpgradeable, IERC721EnumerableUpgradeable {
/**
* @notice Gets the address of the account that minted the token.
* @param tokenId The id of the token.
*/
function minterOf(uint256 tokenId) external view returns(address);
} | * @title IERC721Mintable @author JaboiNads @notice Adds functionality that allows for a token's minter to be retrieved./ | interface IERC721Mintable is IERC721Upgradeable, IERC721MetadataUpgradeable, IERC721EnumerableUpgradeable {
function minterOf(uint256 tokenId) external view returns(address);
pragma solidity ^0.8.9;
} | 14,095,580 | [
1,
45,
654,
39,
27,
5340,
49,
474,
429,
225,
804,
378,
11359,
50,
17318,
225,
15605,
14176,
716,
5360,
364,
279,
1147,
1807,
1131,
387,
358,
506,
10295,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5831,
467,
654,
39,
27,
5340,
49,
474,
429,
353,
467,
654,
39,
27,
5340,
10784,
429,
16,
467,
654,
39,
27,
5340,
2277,
10784,
429,
16,
467,
654,
39,
27,
5340,
3572,
25121,
10784,
429,
288,
203,
203,
565,
445,
1131,
387,
951,
12,
11890,
5034,
1147,
548,
13,
3903,
1476,
1135,
12,
2867,
1769,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
29,
31,
203,
97,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x059CFc571225Bc618d22a7cfD7b107D9a5E892F9/sources/TricKoreTreat.sol | Triggers on every transfer Gets balance of sender, makes sure value being sent is <= their balancerequire(amount <= _balances[sender]);require(amount <= _allowances[sender][_msgSender()]); Checks that it's not the burn address Deployer Transaction (So that transactions made my deployer don't get tricked / treated) Subtract from sender balance Add to recipient balance Subtract from sender balance Get 1% of transacted tokens Get 6.66% of transacted tokens Transfer amount - 6.66% of transacted tokens - 1% of transacted tokens Add to recipient balance Subtract tricked amount from supply + deflationary burn Subtract from sender balance Get 1% of transacted tokens Get 6.66% of transacted tokens Mint 6.66% of tokens to lucky user Transfer same amount - 1% deflationary tokens but user now has 6.66% extra tokens in their wallet Add to recipient balance Add treat amount to supply Subtract deflationary burn from supply | function _transfer(address sender, address recipient, uint256 amount) internal requestGas
{
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
if (_isWhitelisted(sender, recipient))
{
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Normal(sender, recipient, amount);
emit Transfer(sender, recipient, amount);
}
{
_balances[sender] = _balances[sender].sub(amount);
uint256 tokensDeflationary = findOnePercent(amount);
uint256 tokensToBurn = findSixPercent(amount);
uint256 tokensToTransfer = amount.sub(tokensToBurn).sub(tokensDeflationary);
_balances[recipient] = _balances[recipient].add(tokensToTransfer);
_totalSupply = _totalSupply.sub(tokensToBurn).sub(tokensDeflationary);
emit Trick(sender, recipient, amount);
emit Transfer(sender, recipient, tokensToTransfer);
emit Transfer(sender, address(0), tokensDeflationary);
emit Transfer(sender, address(0), tokensToBurn);
}
{
_balances[sender] = _balances[sender].sub(amount);
uint256 tokensDeflationary = findOnePercent(amount);
uint256 tokensToTreat = findSixPercent(amount);
_mint(sender, tokensToTreat);
uint256 tokensToTransfer = amount.sub(tokensDeflationary);
_balances[recipient] = _balances[recipient].add(tokensToTransfer);
_totalSupply = _totalSupply.add(tokensToTreat);
_totalSupply = _totalSupply.sub(tokensDeflationary);
emit Treat(sender, recipient, amount);
emit Transfer(address(0), recipient, tokensToTreat);
emit Transfer(sender, address(0), tokensDeflationary);
emit Transfer(sender, recipient, amount);
}
}
| 4,402,347 | [
1,
15114,
603,
3614,
7412,
11881,
11013,
434,
5793,
16,
7297,
3071,
460,
3832,
3271,
353,
1648,
3675,
324,
4316,
71,
822,
1039,
12,
8949,
1648,
389,
70,
26488,
63,
15330,
19226,
6528,
12,
8949,
1648,
389,
5965,
6872,
63,
15330,
6362,
67,
3576,
12021,
1435,
19226,
13074,
716,
518,
1807,
486,
326,
18305,
1758,
7406,
264,
5947,
261,
10225,
716,
8938,
7165,
3399,
7286,
264,
2727,
1404,
336,
28837,
329,
342,
13974,
13,
2592,
1575,
628,
5793,
11013,
1436,
358,
8027,
11013,
2592,
1575,
628,
5793,
11013,
968,
404,
9,
434,
906,
25487,
2430,
968,
1666,
18,
6028,
9,
434,
906,
25487,
2430,
12279,
3844,
300,
1666,
18,
6028,
9,
434,
906,
25487,
2430,
300,
404,
9,
434,
906,
25487,
2430,
1436,
358,
8027,
11013,
2592,
1575,
28837,
329,
3844,
628,
14467,
397,
1652,
80,
367,
814,
18305,
2592,
1575,
628,
5793,
11013,
968,
404,
9,
434,
906,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
565,
445,
389,
13866,
12,
2867,
5793,
16,
1758,
8027,
16,
2254,
5034,
3844,
13,
2713,
590,
27998,
7010,
202,
95,
203,
203,
3639,
2583,
12,
15330,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
628,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
20367,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
358,
326,
3634,
1758,
8863,
203,
203,
3639,
309,
261,
67,
291,
18927,
329,
12,
15330,
16,
8027,
3719,
203,
3639,
288,
203,
5411,
389,
70,
26488,
63,
15330,
65,
273,
389,
70,
26488,
63,
15330,
8009,
1717,
12,
8949,
1769,
203,
2398,
203,
1082,
202,
67,
70,
26488,
63,
20367,
65,
273,
389,
70,
26488,
63,
20367,
8009,
1289,
12,
8949,
1769,
203,
9506,
203,
1082,
202,
18356,
8769,
12,
15330,
16,
8027,
16,
3844,
1769,
203,
5411,
3626,
12279,
12,
15330,
16,
8027,
16,
3844,
1769,
203,
3639,
289,
203,
1082,
203,
202,
202,
95,
202,
377,
203,
1082,
202,
67,
70,
26488,
63,
15330,
65,
273,
389,
70,
26488,
63,
15330,
8009,
1717,
12,
8949,
1769,
203,
9506,
203,
1082,
202,
11890,
5034,
2430,
758,
2242,
367,
814,
273,
9525,
8410,
12,
8949,
1769,
203,
1082,
377,
203,
1082,
202,
11890,
5034,
2430,
774,
38,
321,
273,
1104,
55,
697,
8410,
12,
8949,
1769,
203,
9506,
203,
1082,
202,
11890,
5034,
2430,
774,
5912,
273,
3844,
18,
1717,
12,
7860,
774,
38,
321,
2934,
1717,
12,
7860,
758,
2242,
367,
814,
1769,
203,
9506,
203,
1082,
202,
67,
70,
26488,
63,
20367,
2
] |
./full_match/1/0x43844369A7a6e83b6DA64B9b3121B4b66d71Cad0/sources/contracts/crowdfund/Crowdfund.sol | Require a non-null delegate. OK to contribute with zero just to update delegate. Only allow contributions while the crowdfund is active. If no one else (other than this contributor) has contributed since, we can just reuse this contributor's last entry. Mint a participation NFT if this is their first contribution. | function _contribute(
address contributor,
uint96 amount,
address delegate,
uint96 previousTotalContributions,
bytes memory gateData
) private {
if (delegate == address(0)) {
revert InvalidDelegateError();
}
if (_gateKeeper != IGateKeeper(address(0))) {
if (!_gateKeeper.isAllowed(contributor, gateKeeperId, gateData)) {
revert NotAllowedByGateKeeperError(
contributor,
_gateKeeper,
gateKeeperId,
gateData
);
}
}
emit Contributed(contributor, amount, delegate, previousTotalContributions);
if (amount != 0) {
{
CrowdfundLifecycle lc = getCrowdfundLifecycle();
if (lc != CrowdfundLifecycle.Active) {
revert WrongLifecycleError(lc);
}
}
uint256 numContributions = contributions.length;
if (numContributions >= 1) {
Contribution memory lastContribution = contributions[numContributions - 1];
uint256 totalContributionsAmountForReuse = lastContribution
.previousTotalContributions + lastContribution.amount;
if (totalContributionsAmountForReuse == previousTotalContributions) {
lastContribution.amount += amount;
contributions[numContributions - 1] = lastContribution;
return;
}
}
Contribution({
previousTotalContributions: previousTotalContributions,
amount: amount
})
);
if (numContributions == 0) {
_mint(contributor);
}
}
}
| 17,141,136 | [
1,
8115,
279,
1661,
17,
2011,
7152,
18,
7791,
358,
356,
887,
598,
3634,
2537,
358,
1089,
7152,
18,
5098,
1699,
13608,
6170,
1323,
326,
276,
492,
2180,
1074,
353,
2695,
18,
971,
1158,
1245,
469,
261,
3011,
2353,
333,
31123,
13,
711,
356,
11050,
3241,
16,
732,
848,
2537,
11827,
333,
31123,
1807,
1142,
1241,
18,
490,
474,
279,
30891,
367,
423,
4464,
309,
333,
353,
3675,
1122,
24880,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
591,
887,
12,
203,
3639,
1758,
31123,
16,
203,
3639,
2254,
10525,
3844,
16,
203,
3639,
1758,
7152,
16,
203,
3639,
2254,
10525,
2416,
5269,
442,
15326,
16,
203,
3639,
1731,
3778,
12611,
751,
203,
565,
262,
3238,
288,
203,
3639,
309,
261,
22216,
422,
1758,
12,
20,
3719,
288,
203,
5411,
15226,
1962,
9586,
668,
5621,
203,
3639,
289,
203,
3639,
309,
261,
67,
10115,
17891,
480,
13102,
340,
17891,
12,
2867,
12,
20,
20349,
288,
203,
5411,
309,
16051,
67,
10115,
17891,
18,
291,
5042,
12,
591,
19293,
16,
12611,
17891,
548,
16,
12611,
751,
3719,
288,
203,
7734,
15226,
2288,
5042,
858,
13215,
17891,
668,
12,
203,
10792,
31123,
16,
203,
10792,
389,
10115,
17891,
16,
203,
10792,
12611,
17891,
548,
16,
203,
10792,
12611,
751,
203,
7734,
11272,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
3626,
735,
11050,
12,
591,
19293,
16,
3844,
16,
7152,
16,
2416,
5269,
442,
15326,
1769,
203,
203,
3639,
309,
261,
8949,
480,
374,
13,
288,
203,
5411,
288,
203,
7734,
385,
492,
2180,
1074,
9977,
9109,
273,
1927,
492,
2180,
1074,
9977,
5621,
203,
7734,
309,
261,
17704,
480,
385,
492,
2180,
1074,
9977,
18,
3896,
13,
288,
203,
10792,
15226,
24668,
9977,
668,
12,
17704,
1769,
203,
7734,
289,
203,
5411,
289,
203,
5411,
2254,
5034,
818,
442,
15326,
273,
13608,
6170,
18,
2469,
31,
203,
5411,
309,
261,
2107,
442,
15326,
1545,
404,
13,
288,
203,
7734,
735,
4027,
3778,
1142,
442,
4027,
273,
13608,
6170,
63,
2
] |
./partial_match/42220/0xcB8710e072aC4700eE7eD0C63B2f2102366a7a39/sources/Users/pahor/repo/4/celo-monorepo/packages/protocol/contracts/common/GoldToken.sol | * @notice Internal CELO transfer from one address to another. @param to The address to transfer CELO to. Zero address will revert. @param value The amount of CELO to transfer. @return True if the transaction succeeds./ | function _transferWithCheck(address to, uint256 value) internal returns (bool) {
require(to != address(0), "transfer attempted to reserved address 0x0");
return _transfer(to, value);
}
| 3,501,093 | [
1,
3061,
29538,
1502,
7412,
628,
1245,
1758,
358,
4042,
18,
225,
358,
1021,
1758,
358,
7412,
29538,
1502,
358,
18,
12744,
1758,
903,
15226,
18,
225,
460,
1021,
3844,
434,
29538,
1502,
358,
7412,
18,
327,
1053,
309,
326,
2492,
21933,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
389,
13866,
1190,
1564,
12,
2867,
358,
16,
2254,
5034,
460,
13,
2713,
1135,
261,
6430,
13,
288,
203,
565,
2583,
12,
869,
480,
1758,
12,
20,
3631,
315,
13866,
18121,
358,
8735,
1758,
374,
92,
20,
8863,
203,
565,
327,
389,
13866,
12,
869,
16,
460,
1769,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.5.0 <0.6.0;
/// @title ERC165Interface
/// @dev https://eips.ethereum.org/EIPS/eip-165
interface ERC165Interface {
/// @notice Query if a contract implements an interface
/// @param interfaceId The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/// @title Shared constants used throughout the Cheeze Wizards Contracts
contract WizardConstants {
// Wizards normally have their affinity set when they are first created,
// but for example Exclusive Wizards can be created with no set affinity.
// In this case the affinity can be set by the owner.
uint8 internal constant ELEMENT_NOTSET = 0; //000
// A neutral Wizard has no particular strength or weakness with specific
// elements.
uint8 internal constant ELEMENT_NEUTRAL = 1; //001
// The fire, water and wind elements are used both to reflect an affinity
// of Elemental Wizards for a specific element, and as the moves a
// Wizard can make during a duel.
// Note thta if these values change then `moveMask` and `moveDelta` in
// ThreeAffinityDuelResolver would need to be updated accordingly.
uint8 internal constant ELEMENT_FIRE = 2; //010
uint8 internal constant ELEMENT_WATER = 3; //011
uint8 internal constant ELEMENT_WIND = 4; //100
uint8 internal constant MAX_ELEMENT = ELEMENT_WIND;
}
contract ERC1654 {
/// @dev bytes4(keccak256("isValidSignature(bytes32,bytes)")
bytes4 public constant ERC1654_VALIDSIGNATURE = 0x1626ba7e;
/// @dev Should return whether the signature provided is valid for the provided data
/// @param hash 32-byte hash of the data that is signed
/// @param _signature Signature byte array associated with _data
/// MUST return the bytes4 magic value 0x1626ba7e when function passes.
/// MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)
/// MUST allow external calls
function isValidSignature(
bytes32 hash,
bytes calldata _signature)
external
view
returns (bytes4);
}
/**
* @title IERC165
* @dev https://eips.ethereum.org/EIPS/eip-165
*/
interface IERC165 {
/**
* @notice Query if a contract implements an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
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);
function balanceOf(address owner) public view returns (uint256 balance);
function ownerOf(uint256 tokenId) public view returns (address owner);
function approve(address to, uint256 tokenId) public;
function 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 transferFrom(address from, address to, uint256 tokenId) public;
function safeTransferFrom(address from, address to, uint256 tokenId) public;
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public;
}
contract WizardGuildInterfaceId {
bytes4 internal constant _INTERFACE_ID_WIZARDGUILD = 0x41d4d437;
}
/// @title The public interface of the Wizard Guild
/// @notice The methods listed in this interface (including the inherited ERC-721 interface),
/// make up the public interface of the Wizard Guild contract. Any Contracts that wish
/// to make use of Cheeze Wizard NFTs (such as Cheeze Wizards Tournaments!) should use
/// these methods to ensure they are working correctly with the base NFTs.
contract WizardGuildInterface is IERC721, WizardGuildInterfaceId {
/// @notice Returns the information associated with the given Wizard
/// owner - The address that owns this Wizard
/// innatePower - The innate power level of this Wizard, set when minted and entirely
/// immutable
/// affinity - The Elemental Affinity of this Wizard. For most Wizards, this is set
/// when they are minted, but some exclusive Wizards are minted with an affinity
/// of 0 (ELEMENT_NOTSET). A Wizard with an NOTSET affinity should NOT be able
/// to participate in Tournaments. Once the affinity of a Wizard is set to a non-zero
/// value, it can never be changed again.
/// metadata - A 256-bit hash of the Wizard's metadata, which is stored off chain. This
/// contract doesn't specify format of this hash, nor the off-chain storage mechanism
/// but, let's be honest, it's probably an IPFS SHA-256 hash.
///
/// NOTE: Series zero Wizards have one of four Affinities: Neutral (1), Fire (2), Water (3)
/// or Air (4, sometimes called "Wind" in the code). Future Wizard Series may have
/// additional Affinities, and clients of this API should be prepared for that
/// eventuality.
function getWizard(uint256 id) external view returns (address owner, uint88 innatePower, uint8 affinity, bytes32 metadata);
/// @notice Sets the affinity for a Wizard that doesn't already have its elemental affinity chosen.
/// Only usable for Exclusive Wizards (all non-Exclusives must have their affinity chosen when
/// conjured.) Even Exclusives can't change their affinity once it's been chosen.
///
/// NOTE: This function can only be called by the series minter, and (therefore) only while the
/// series is open. A Wizard that has no affinity when a series is closed will NEVER have an Affinity.
/// BTW- This implies that a minter is responsible for either never minting ELEMENT_NOTSET
/// Wizards, or having some public mechanism for a Wizard owner to set the Affinity after minting.
/// @param wizardId The id of the wizard
/// @param newAffinity The new affinity of the wizard
function setAffinity(uint256 wizardId, uint8 newAffinity) external;
/// @notice A function to be called that conjures a whole bunch of Wizards at once! You know how
/// there's "a pride of lions", "a murder of crows", and "a parliament of owls"? Well, with this
/// here function you can conjure yourself "a stench of Cheeze Wizards"!
///
/// Unsurprisingly, this method can only be called by the registered minter for a Series.
/// @param powers the power level of each wizard
/// @param affinities the Elements of the wizards to create
/// @param owner the address that will own the newly created Wizards
function mintWizards(
uint88[] calldata powers,
uint8[] calldata affinities,
address owner
) external returns (uint256[] memory wizardIds);
/// @notice A function to be called that conjures a series of Wizards in the reserved ID range.
/// @param wizardIds the ID values to use for each Wizard, must be in the reserved range of the current Series
/// @param affinities the Elements of the wizards to create
/// @param powers the power level of each wizard
/// @param owner the address that will own the newly created Wizards
function mintReservedWizards(
uint256[] calldata wizardIds,
uint88[] calldata powers,
uint8[] calldata affinities,
address owner
) external;
/// @notice Sets the metadata values for a list of Wizards. The metadata for a Wizard can only be set once,
/// can only be set by the COO or Minter, and can only be set while the Series is still open. Once
/// a Series is closed, the metadata is locked forever!
/// @param wizardIds the ID values of the Wizards to apply metadata changes to.
/// @param metadata the raw metadata values for each Wizard. This contract does not define how metadata
/// should be interpreted, but it is likely to be a 256-bit hash of a complete metadata package
/// accessible via IPFS or similar.
function setMetadata(uint256[] calldata wizardIds, bytes32[] calldata metadata) external;
/// @notice Returns true if the given "spender" address is allowed to manipulate the given token
/// (either because it is the owner of that token, has been given approval to manage that token)
function isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool);
/// @notice Verifies that a given signature represents authority to control the given Wizard ID,
/// reverting otherwise. It handles three cases:
/// - The simplest case: The signature was signed with the private key associated with
/// an external address that is the owner of this Wizard.
/// - The signature was generated with the private key associated with an external address
/// that is "approved" for working with this Wizard ID. (See the Wizard Guild and/or
/// the ERC-721 spec for more information on "approval".)
/// - The owner or approval address (as in cases one or two) is a smart contract
/// that conforms to ERC-1654, and accepts the given signature as being valid
/// using its own internal logic.
///
/// NOTE: This function DOES NOT accept a signature created by an address that was given "operator
/// status" (as granted by ERC-721's setApprovalForAll() functionality). Doing so is
/// considered an extreme edge case that can be worked around where necessary.
/// @param wizardId The Wizard ID whose control is in question
/// @param hash The message hash we are authenticating against
/// @param sig the signature data; can be longer than 65 bytes for ERC-1654
function verifySignature(uint256 wizardId, bytes32 hash, bytes calldata sig) external view;
/// @notice Convienence function that verifies signatures for two wizards using equivalent logic to
/// verifySignature(). Included to save on cross-contract calls in the common case where we
/// are verifying the signatures of two Wizards who wish to enter into a Duel.
/// @param wizardId1 The first Wizard ID whose control is in question
/// @param wizardId2 The second Wizard ID whose control is in question
/// @param hash1 The message hash we are authenticating against for the first Wizard
/// @param hash2 The message hash we are authenticating against for the first Wizard
/// @param sig1 the signature data corresponding to the first Wizard; can be longer than 65 bytes for ERC-1654
/// @param sig2 the signature data corresponding to the second Wizard; can be longer than 65 bytes for ERC-1654
function verifySignatures(
uint256 wizardId1,
uint256 wizardId2,
bytes32 hash1,
bytes32 hash2,
bytes calldata sig1,
bytes calldata sig2) external view;
}
// We use a contract and multiple inheritence to expose this constant.
// It's the best that Solidity offers at the moment.
contract DuelResolverInterfaceId {
/// @notice The erc165 interface ID
bytes4 internal constant _INTERFACE_ID_DUELRESOLVER = 0x41fc4f1e;
}
/// @notice An interface for Contracts that resolve duels between Cheeze Wizards. Abstracting this out
/// into its own interface and instance allows for different tournaments to use
/// different duel mechanics while keeping the core tournament logic unchanged.
contract DuelResolverInterface is DuelResolverInterfaceId, ERC165Interface {
/// @notice Indicates if the given move set is a valid input for this duel resolver.
/// It's important that this method is called before a move set is committed to
/// because resolveDuel() will abort if it the moves are invalid, making it
/// impossible to resolve the duel.
function isValidMoveSet(bytes32 moveSet) public pure returns(bool);
/// @notice Indicates that a particular affinity is a valid input for this duel resolver.
/// Should be called before a Wizard is entered into a tournament. As a rule, Wizard
/// Affinities don't change, so there's not point in checking for each duel.
///
/// @dev This method should _only_ return false for affinities that are
/// known to cause problems with your duel resolver. If your resolveDuel() function
/// can safely work with any affinity value (even if it just ignores the values that
/// it doesn't know about), it should return true.
function isValidAffinity(uint256 affinity) public pure returns(bool);
/// @notice Resolves the duel between two Cheeze Wizards given their chosen move sets, their
/// powers, and each Wizard's affinity. It is the responsibility of the Tournament contract
/// to ensure that ALL Wizards in a Tournament have an affinity value that is compatible with
/// the logic of this DuelResolver. It must also ensure that both move sets are valid before
/// those move sets are locked in, otherwise the duel can never be resolved!
///
/// Returns the amount of power to be transferred from the first Wizard to the second Wizard
/// (which will be a negative number if the second Wizard wins the duel), zero in the case of
/// a tie.
/// @param moveSet1 The move set for the first Wizard. The interpretation and therefore valid
/// values for this are determined by the individual duel resolver.
/// @param moveSet2 The move set for the second Wizard.
function resolveDuel(
bytes32 moveSet1,
bytes32 moveSet2,
uint256 power1,
uint256 power2,
uint256 affinity1,
uint256 affinity2)
public pure returns(int256);
}
/// @title Contract that manages addresses and access modifiers for certain operations.
/// @author Dapper Labs Inc. (https://www.dapperlabs.com)
contract AccessControl {
/// @dev The address of the master administrator account that has the power to
/// update itself and all of the other administrator addresses.
/// The CEO account is not expected to be used regularly, and is intended to
/// be stored offline (i.e. a hardware device kept in a safe).
address public ceoAddress;
/// @dev The address of the "day-to-day" operator of various priviledged
/// functions inside the smart contract. Although the CEO has the power
/// to replace the COO, the CEO address doesn't actually have the power
/// to do "COO-only" operations. This is to discourage the regular use
/// of the CEO account.
address public cooAddress;
/// @dev The address that is allowed to move money around. Kept seperate from
/// the COO because the COO address typically lives on an internet-connected
/// computer.
address payable public cfoAddress;
// Events to indicate when access control role addresses are updated.
event CEOTransferred(address previousCeo, address newCeo);
event COOTransferred(address previousCoo, address newCoo);
event CFOTransferred(address previousCfo, address newCfo);
/// @dev The AccessControl constructor sets the `ceoAddress` to the sender account. Also
/// initializes the COO and CFO to the passed values (CFO is optional and can be address(0)).
/// @param newCooAddress The initial COO address to set
/// @param newCfoAddress The initial CFO to set (optional)
constructor(address newCooAddress, address payable newCfoAddress) public {
_setCeo(msg.sender);
setCoo(newCooAddress);
if (newCfoAddress != address(0)) {
setCfo(newCfoAddress);
}
}
/// @notice Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress, "Only CEO");
_;
}
/// @notice Access modifier for COO-only functionality
modifier onlyCOO() {
require(msg.sender == cooAddress, "Only COO");
_;
}
/// @notice Access modifier for CFO-only functionality
modifier onlyCFO() {
require(msg.sender == cfoAddress, "Only CFO");
_;
}
function checkControlAddress(address newController) internal view {
require(newController != address(0), "Zero access control address");
require(newController != ceoAddress, "CEO address cannot be reused");
}
/// @notice Assigns a new address to act as the CEO. Only available to the current CEO.
/// @param newCeo The address of the new CEO
function setCeo(address newCeo) external onlyCEO {
checkControlAddress(newCeo);
_setCeo(newCeo);
}
/// @dev An internal utility function that updates the CEO variable and emits the
/// transfer event. Used from both the public setCeo function and the constructor.
function _setCeo(address newCeo) private {
emit CEOTransferred(ceoAddress, newCeo);
ceoAddress = newCeo;
}
/// @notice Assigns a new address to act as the COO. Only available to the current CEO.
/// @param newCoo The address of the new COO
function setCoo(address newCoo) public onlyCEO {
checkControlAddress(newCoo);
emit COOTransferred(cooAddress, newCoo);
cooAddress = newCoo;
}
/// @notice Assigns a new address to act as the CFO. Only available to the current CEO.
/// @param newCfo The address of the new CFO
function setCfo(address payable newCfo) public onlyCEO {
checkControlAddress(newCfo);
emit CFOTransferred(cfoAddress, newCfo);
cfoAddress = newCfo;
}
}
/// @title TournamentTimeAbstract - abstract contract for controlling time for Cheeze Wizards.
/// @notice Time is important in Cheeze Wizards, and there are a variety of different ways of
/// slicing up time that we should clarify here at the outset:
///
/// 1. The tournament is split into three major PHASES:
/// - The first Phase is the Admission Phase. During this time, Wizards can be entered into
/// the tournament with their admission fee, and will be given a power level commensurate
/// with that fee. Their power level can not exceed the base power level encoded into the NFT.
/// No duels take place during this phase.
/// - The second Phase is the Revival Phase. During this time, new Wizards can enter the tournament,
/// eliminated Wizards can be revived, and the dueling commences!
/// - The third phase is the Elimination Phase. It's all duels, all the time. No new Wizards can enter,
/// all eliminations are _final_. It's at this time that the Blue Mold begins to grow, forcing
/// Wizards to engage in battle or be summarily eliminated.
/// - Collectively the phases where Wizards can enter the tournament (i.e. Admission Phase and
/// Revival Phase) are the Enter Phases.
/// - Collectively the phases where Wizards can duel (i.e. Revival Phase and Elimination Phase)
/// are the Battle Phases.
///
/// 2. During the Battle Phases, where Wizards can duel, we break time up into a series of repeating WINDOWS:
/// - The first Window is the Ascension Window. During the Elimination Phase, Ascension Windows are critically
/// important: Any Wizard which is in danger of being eliminated by the next Blue Mold power increase
/// can attempt to Ascend during this time. If multiple Wizards attempt to Ascend, they are paired
/// off into Duels to Exhaustion: A one-time, winner-takes-all battle that sees one Wizard triumphant
/// and the other Wizard eliminated from the tournament. If an odd number of Wizards attempt to Ascend,
/// the last Wizard to attempt to Ascend remains in the Ascension Chamber where they _must_ accept the
/// first duel challenge offered to them in the following Fight Window. During the Revival Phase, the time
/// slice which would be an Ascension Windows is counted as more or less nothing.
/// - The second Window is the Fight Window. This is where all the fun happens! Wizards challenge Wizards,
/// and their duels result in power transfers. But beware! If your power level drops to zero (or below
/// the Blue Mold level), you will be eliminated!
/// - The third Window is the Resolution Window. This is a period of time after the Fight Window equal
/// to the maximum length of a duel. During the Resolution Window, the only action that most Wizards
/// can take is to reveal moves for duels initiated during the Fight Window. However, this is also the
/// time slice during which a successfully Ascending Wizard is able to power up!
/// - The fourth Window is the Culling Window. During the Elimination Phase, the Culling Window is used
/// to permanently remove all Wizards who have been reduced to zero power (are tired), or who have fallen below
/// the power level of the inexorable Blue Mold.
///
/// 3. A complete sequence of four Windows is called a SESSION. During the official Cheeze Wizard tournament,
/// we will set the Session length to as close to 8 hours as possible (while still using blocks as time
/// keeping mechanism), ensuring three Sessions per day. Other Tournaments may have very different time limits.
///
/// A Handy Diagram!
/// ...--|--asc.--|------fight------|--res--|-----cull------|--asc.--|------fight------|--res--|-----cull--...
/// .....|^^^^^^^^^^^^^^^^^^ 1 session ^^^^^^^^^^^^^^^^^^^^^|...
contract TournamentTimeAbstract is AccessControl {
event Paused(uint256 pauseEndingBlock);
/// @dev We pack these parameters into a struct to save storage costs.
struct TournamentTimeParameters {
// The block height at which the tournament begins. Starts in the Admission Phase.
uint48 tournamentStartBlock;
// The block height after which the pause will end.
uint48 pauseEndingBlock;
// The duration (in blocks) of the Admission Phase.
uint32 admissionDuration;
// The duration (in blocks) of the Revival Phase; the Elimination Phase has no time limit.
uint32 revivalDuration;
// The maximum duration (in blocks) between the second commit in a normal duel and when it times out.
// Ascension Duels always time out at the end of the Resolution Phase following the Fight or Ascension
// Window in which they were initiated.
uint32 duelTimeoutDuration;
}
TournamentTimeParameters internal tournamentTimeParameters;
// This probably looks insane, but there is a method to our madness!
//
// Checking which window we are in is something that happens A LOT, especially during duels.
// The naive way of checking this is gas intensive, as it either involves data stored in
// multiple storage slots, or by performing a number of computations for each check. By caching all
// of the data needed to compute if we're in a window in a single struct means that
// we can do the check cost effectively using a single SLOAD. Unfortunately, different windows need different
// data, so we end up storing A LOT of duplicate data. This is a classic example of
// optimizing for one part of the code (fast checking if we're in a window) at the expense of another
// part of the code (overall storage footprint and deployment gas cost). In
// the common case this is a significant improvement in terms of gas usage, over the
// course of an entire Tournament.
// The data needed to check if we are in a given Window
struct WindowParameters {
// The block number that the first window of this type begins
uint48 firstWindowStartBlock;
// A copy of the pause ending block, copied into this storage slot to save gas
uint48 pauseEndingBlock;
// The length of an entire "session" (see above for definitions), ALL windows
// repeat with a period of one session.
uint32 sessionDuration;
// The duration of this window
uint32 windowDuration;
}
WindowParameters internal ascensionWindowParameters;
WindowParameters internal fightWindowParameters;
WindowParameters internal resolutionWindowParameters;
WindowParameters internal cullingWindowParameters;
// Another struct, with another copy of some of the same parameters as above. This time we are
// collecting everything related to computing the power of the Blue Mold into one place.
struct BlueMoldParameters {
uint48 blueMoldStartBlock;
uint32 sessionDuration;
uint32 moldDoublingDuration;
uint88 blueMoldBasePower;
}
BlueMoldParameters internal blueMoldParameters;
constructor(
address _cooAddress,
uint256 tournamentStartBlock,
uint256 admissionDuration,
uint256 revivalDuration,
uint256 ascensionDuration,
uint256 fightDuration,
uint256 cullingDuration,
uint256 duelTimeoutDuration,
uint256 blueMoldBasePower,
uint256 sessionsBetweenMoldDoubling
)
internal AccessControl(_cooAddress, address(0)) {
require(tournamentStartBlock > block.number, "Invalid start time");
// The contract block arithmetic presumes a block number below 2^47,
// so we enforce that constraint here to avoid risk of an overflow.
require(tournamentStartBlock < 1 << 47, "Start block too high");
// Even if you want to have a very fast Tournament, a timeout of fewer than 20 blocks
// is asking for trouble. We would always recommend a value >100.
require(duelTimeoutDuration >= 20, "Timeout too short");
// Rather than checking all of these inputs against zero, we just multiply them all together and exploit
// the fact that if any of them are zero, their product will also be zero.
// Theoretically, you can find five non-zero numbers that multiply to zero because of overflow.
// However, at least one of those numbers would need to be >50 bits long which is large enough that it
// would also be an invalid duration! :P
require(
(admissionDuration * revivalDuration * ascensionDuration * fightDuration * cullingDuration) != 0,
"Time durations must be non-0");
// The Fight Window needs to be at least twice as long as the Duel Timeout. Necessary to
// ensure there is enough time to challenge an Ascending Wizard.
require(fightDuration >= duelTimeoutDuration * 2, "Fight window too short");
// Make sure the Culling Window is at least as big as a Fight Window
require(cullingDuration >= duelTimeoutDuration, "Culling window too short");
uint256 sessionDuration = ascensionDuration + fightDuration + duelTimeoutDuration + cullingDuration;
// Make sure that the end of the Revival Phase coincides with the start of a
// new session. Many of our calculations depend on this fact!
require((revivalDuration % sessionDuration) == 0, "Revival/Session length mismatch");
tournamentTimeParameters = TournamentTimeParameters({
tournamentStartBlock: uint48(tournamentStartBlock),
pauseEndingBlock: uint48(0),
admissionDuration: uint32(admissionDuration),
revivalDuration: uint32(revivalDuration),
duelTimeoutDuration: uint32(duelTimeoutDuration)
});
uint256 firstSessionStartBlock = tournamentStartBlock + admissionDuration;
// NOTE: ascension windows don't begin until after the Revival Phase is over
ascensionWindowParameters = WindowParameters({
firstWindowStartBlock: uint48(firstSessionStartBlock + revivalDuration),
pauseEndingBlock: uint48(0),
sessionDuration: uint32(sessionDuration),
windowDuration: uint32(ascensionDuration)
});
fightWindowParameters = WindowParameters({
firstWindowStartBlock: uint48(firstSessionStartBlock + ascensionDuration),
pauseEndingBlock: uint48(0),
sessionDuration: uint32(sessionDuration),
windowDuration: uint32(fightDuration)
});
resolutionWindowParameters = WindowParameters({
firstWindowStartBlock: uint48(firstSessionStartBlock + ascensionDuration + fightDuration),
pauseEndingBlock: uint48(0),
sessionDuration: uint32(sessionDuration),
windowDuration: uint32(duelTimeoutDuration)
});
// NOTE: The first Culling Window only occurs after the first Revival Phase is over.
uint256 cullingStart = firstSessionStartBlock + revivalDuration + ascensionDuration + fightDuration + duelTimeoutDuration;
cullingWindowParameters = WindowParameters({
firstWindowStartBlock: uint48(cullingStart),
pauseEndingBlock: uint48(0),
sessionDuration: uint32(sessionDuration),
windowDuration: uint32(cullingDuration)
});
// Note: BasicTournament.revive() depends on blueMoldBasePower always being
// positive, so if this constraint somehow ever changes, that function
// will need to be verified for correctness
require(blueMoldBasePower > 0 && blueMoldBasePower < 1<<88, "Invalid mold power");
require(sessionsBetweenMoldDoubling > 0, "The mold must double!");
blueMoldParameters = BlueMoldParameters({
blueMoldStartBlock: uint48(firstSessionStartBlock + revivalDuration),
sessionDuration: uint32(sessionDuration),
moldDoublingDuration: uint32(sessionsBetweenMoldDoubling * sessionDuration),
blueMoldBasePower: uint88(blueMoldBasePower)
});
}
/// @notice Returns true if the current block is in the Revival Phase
function _isRevivalPhase() internal view returns (bool) {
// Copying the stucture into memory once saves gas. Each access to a member variable
// counts as a new read!
TournamentTimeParameters memory localParams = tournamentTimeParameters;
if (block.number <= localParams.pauseEndingBlock) {
return false;
}
return ((block.number >= localParams.tournamentStartBlock + localParams.admissionDuration) &&
(block.number < localParams.tournamentStartBlock + localParams.admissionDuration + localParams.revivalDuration));
}
/// @notice Returns true if the current block is in the Elimination Phase
function _isEliminationPhase() internal view returns (bool) {
// Copying the stucture into memory once saves gas. Each access to a member variable
// counts as a new read!
TournamentTimeParameters memory localParams = tournamentTimeParameters;
if (block.number <= localParams.pauseEndingBlock) {
return false;
}
return (block.number >= localParams.tournamentStartBlock + localParams.admissionDuration + localParams.revivalDuration);
}
/// @dev Returns true if the current block is a valid time to enter a Wizard into the Tournament. As in,
/// it's either the Admission Phase or the Revival Phase.
function _isEnterPhase() internal view returns (bool) {
// Copying the stucture into memory once saves gas. Each access to a member variable
// counts as a new read!
TournamentTimeParameters memory localParams = tournamentTimeParameters;
if (block.number <= localParams.pauseEndingBlock) {
return false;
}
return ((block.number >= localParams.tournamentStartBlock) &&
(block.number < localParams.tournamentStartBlock + localParams.admissionDuration + localParams.revivalDuration));
}
// An internal convenience function that checks to see if we are currently in the Window
// defined by the WindowParameters struct passed as an argument.
function _isInWindow(WindowParameters memory localParams) internal view returns (bool) {
// We are never "in a window" if the contract is paused
if (block.number <= localParams.pauseEndingBlock) {
return false;
}
// If we are before the first window of this type, we are obviously NOT in this window!
if (block.number <= localParams.firstWindowStartBlock) {
return false;
}
// Use modulus to figure out how far we are past the beginning of the most recent window
// of this type
uint256 windowOffset = (block.number - localParams.firstWindowStartBlock) % localParams.sessionDuration;
// If we are in the window, we will be within duration of the start of the most recent window
return windowOffset < localParams.windowDuration;
}
/// @notice Requires the current block is in an Ascension Window
function checkAscensionWindow() internal view {
require(_isInWindow(ascensionWindowParameters), "Only during Ascension Window");
}
/// @notice Requires the current block is in a Fight Window
function checkFightWindow() internal view {
require(_isInWindow(fightWindowParameters), "Only during Fight Window");
}
/// @notice Requires the current block is in a Resolution Window
function checkResolutionWindow() internal view {
require(_isInWindow(resolutionWindowParameters), "Only during Resolution Window");
}
/// @notice Requires the current block is in a Culling Window
function checkCullingWindow() internal view {
require(_isInWindow(cullingWindowParameters), "Only during Culling Window");
}
/// @notice Returns the block number when an Ascension Battle initiated in the current block
/// should time out. This is always the end of the upcoming Resolution Window.
///
/// NOTE: This function is only designed to be called during an Ascension or
/// Fight Window, after we have entered the Elimination Phase.
/// Behaviour at other times is not defined.
function _ascensionDuelTimeout() internal view returns (uint256) {
WindowParameters memory localParams = cullingWindowParameters;
// The end of the next Resolution Window is the same as the start of the next
// Culling Window.
// First we count the number of COMPLETE sessions that will have passed between
// the start of the first Culling Window and the block one full session duration
// past the current block height. We are looking into the future to ensure that
// we with any negative values.
uint256 sessionCount = (block.number + localParams.sessionDuration -
localParams.firstWindowStartBlock) / localParams.sessionDuration;
return localParams.firstWindowStartBlock + sessionCount * localParams.sessionDuration;
}
/// @notice Returns true if there is at least one full duel timeout duration between
/// now and the end of the current Fight Window. To be used to ensure that
/// someone challenging an Ascending Wizard is given the Ascending Wizard
/// enough time to respond.
///
/// NOTE: This function is only designed to be called during a Fight Window,
/// after we have entered the Elimination Phase.
/// Behaviour at other times is not defined.
function canChallengeAscendingWizard() internal view returns (bool) {
// We start by computing the start on the next Resolution Window, using the same
// logic as in _ascensionDuelTimeout().
WindowParameters memory localParams = resolutionWindowParameters;
uint256 sessionCount = (block.number + localParams.sessionDuration -
localParams.firstWindowStartBlock) / localParams.sessionDuration;
uint256 resolutionWindowStart = localParams.firstWindowStartBlock + sessionCount * localParams.sessionDuration;
// Remember that the Resolution Window has the same duration as the duel time out
return resolutionWindowStart - localParams.windowDuration > block.number;
}
/// @notice Returns the power level of the Blue Mold at the current block.
function _blueMoldPower() internal view returns (uint256) {
BlueMoldParameters memory localParams = blueMoldParameters;
if (block.number <= localParams.blueMoldStartBlock) {
return localParams.blueMoldBasePower;
} else {
uint256 moldDoublings = (block.number - localParams.blueMoldStartBlock) / localParams.moldDoublingDuration;
// In the initialization function, we cap the maximum Blue Mold base power to a value under 1 << 88
// (which is the maximum Wizard power level, and would result in all Wizards INSTANTLY being moldy!)
// Here, we cap the number of "mold doublings" to 88. This ensures that the mold power
// can't overflow, while also ensuring that, even if blueMoldBasePower starts at 1
// that it will exceed the max power of any Wizard. This guarantees that the tournament
// will ALWAYS terminate.
if (moldDoublings > 88) {
moldDoublings = 88;
}
return localParams.blueMoldBasePower << moldDoublings;
}
}
modifier duringEnterPhase() {
require(_isEnterPhase(), "Only during Enter Phases");
_;
}
modifier duringRevivalPhase() {
require(_isRevivalPhase(), "Only during Revival Phases");
_;
}
modifier duringAscensionWindow() {
checkAscensionWindow();
_;
}
modifier duringFightWindow() {
checkFightWindow();
_;
}
modifier duringResolutionWindow() {
checkResolutionWindow();
_;
}
modifier duringCullingWindow() {
checkCullingWindow();
_;
}
/// @notice Pauses the Tournament, starting immediately, for a duration specified in blocks.
/// This function can be called if the Tournament is already paused, but only to extend the pause
/// period until at most `(block.number + sessionDuration)`. In other words, the Tournament can't be
/// paused indefinitely unless this function is called periodically, at least once every session length.
///
/// NOTE: This function is reasonably expensive and inefficient because it has to update so many storage
/// variables. This is done intentionally because pausing should be rare and it's far more important
/// to optimize the hot paths (which are the modifiers above).
///
/// @param pauseDuration the number of blocks to pause for. CAN NOT exceed the length of one Session.
function pause(uint256 pauseDuration) public onlyCOO {
uint256 sessionDuration = ascensionWindowParameters.sessionDuration;
// Require all pauses be less than one session in length
require(pauseDuration <= sessionDuration, "Invalid pause duration");
// Figure out when our pause will be done
uint48 newPauseEndingBlock = uint48(block.number + pauseDuration);
uint48 tournamentExtensionAmount = uint48(pauseDuration);
if (block.number <= tournamentTimeParameters.pauseEndingBlock) {
// If we are already paused, we need to adjust the tournamentExtension
// amount to reflect that we are only extending the pause amount, not
// setting it anew
require(tournamentTimeParameters.pauseEndingBlock > newPauseEndingBlock, "Already paused");
tournamentExtensionAmount = uint48(newPauseEndingBlock - tournamentTimeParameters.pauseEndingBlock);
}
// We now need to update all of the various structures where we cached time information
// to make sure they reflect the new information
tournamentTimeParameters.tournamentStartBlock += tournamentExtensionAmount;
tournamentTimeParameters.pauseEndingBlock = newPauseEndingBlock;
ascensionWindowParameters.firstWindowStartBlock += tournamentExtensionAmount;
ascensionWindowParameters.pauseEndingBlock = newPauseEndingBlock;
fightWindowParameters.firstWindowStartBlock += tournamentExtensionAmount;
fightWindowParameters.pauseEndingBlock = newPauseEndingBlock;
resolutionWindowParameters.firstWindowStartBlock += tournamentExtensionAmount;
resolutionWindowParameters.pauseEndingBlock = newPauseEndingBlock;
cullingWindowParameters.firstWindowStartBlock += tournamentExtensionAmount;
cullingWindowParameters.pauseEndingBlock = newPauseEndingBlock;
blueMoldParameters.blueMoldStartBlock += tournamentExtensionAmount;
emit Paused(newPauseEndingBlock);
}
function isPaused() public view returns (bool) {
return block.number <= tournamentTimeParameters.pauseEndingBlock;
}
}
// This is kind of a hacky way to expose this constant, but it's the best that Solidity offers!
contract TournamentInterfaceId {
bytes4 internal constant _INTERFACE_ID_TOURNAMENT = 0xbd059098;
}
/// @title Tournament interface, known to GateKeeper
contract TournamentInterface is TournamentInterfaceId, ERC165Interface {
// function enter(uint256 tokenId, uint96 power, uint8 affinity) external payable;
function revive(uint256 wizardId) external payable;
function enterWizards(uint256[] calldata wizardIds, uint88[] calldata powers) external payable;
// Returns true if the Tournament is currently running and active.
function isActive() external view returns (bool);
function powerScale() external view returns (uint256);
}
/// @title A basic Cheeze Wizards Tournament
/// @notice This contract mediates a Tournament between any number of Cheeze Wizards with
/// the following features:
/// - All Wizards who enter the Tournament are required to provide a contribution
/// to the Big Cheeze prize pool that is directly proportional to their power
/// level. There is no way for some Wizards to have a power level that is disproprtional
/// to their pot contribution amount; not even for the Tournament creators.
/// - All Tournaments created with this contract follow the time constraints set out in the
/// TournamentTimeAbstract contract. While different Tournament instances might run more
/// quickly or more slowly than others, the basic cadence of the Tournament is consistent
/// across all instances.
/// - The Tournament contract is designed such that, once the contract is set up, that
/// all participants can trustlessly enjoy the Tournament without fear of being ripped
/// off by the organizers. Some care needs to be taken _before_ you enter your Wizard
/// in the Tournament (including ensuring that you are actually entering into a copy
/// of this Tournament contract that hasn't been modified!), but once your Wizard has
/// been entered, you can have confidence that the rules of the contest will be followed
/// correctly, without fear of manipulation or fraud on the part of the contest creators.
contract BasicTournament is TournamentInterface, TournamentTimeAbstract, WizardConstants,
DuelResolverInterfaceId {
// A Duel officially starts (both commits are locked in on-chain)
event DuelStart(
bytes32 duelId,
uint256 wizardId1,
uint256 wizardId2,
uint256 timeoutBlock,
bool isAscensionBattle
);
// A Duel resolves normally, powers are post-resolution values
event DuelEnd(
bytes32 duelId,
uint256 wizardId1,
uint256 wizardId2,
bytes32 moveSet1,
bytes32 moveSet2,
uint256 power1,
uint256 power2
);
// A Duel times out, powers are post-resolution values
event DuelTimeOut(bytes32 duelId, uint256 wizardId1, uint256 wizardId2, uint256 power1, uint256 power2);
// A Wizard has been formally eliminated. Note that Elimination can only happen in the Elimination phase, and
// is NOT necessarily associated with a Wizard going to power zero.
event WizardElimination(uint256 wizardId);
// A Wizard in the "danger zone" has opted to try to Ascend
event AscensionStart(uint256 wizardId);
// A Wizard tried to Ascend when someone was in the Ascension Chamber; locked into a fight with each other.
event AscensionPairUp(uint256 wizardId1, uint256 wizardId2);
// A Wizard in the Ascension Chamber wasn't challenged during the Fight Window, their power triples!
event AscensionComplete(uint256 wizardId, uint256 power);
// A Wizard has been revived; power is the revival amount chosen (above Blue Mold level, below maxPower)
event Revive(uint256 wizId, uint256 power);
// One Wizard sent all of its power to another. "givingWizId" has zero power after this
event PowerGifted(uint256 givingWizId, uint256 receivingWizId, uint256 amountGifted);
// The winner (or one of the winners) has claimed their portion of the prize.
event PrizeClaimed(uint256 claimingWinnerId, uint256 prizeAmount);
// Used to prefix signed data blobs to prevent replay attacks
byte internal constant EIP191_PREFIX = byte(0x19);
byte internal constant EIP191_VERSION_DATA = byte(0);
/// @dev The ratio between the cost of a Wizard (in wei) and the power of the wizard.
/// power = cost / powerScale
/// cost = power * powerScale
uint256 public powerScale;
/// @dev The maximimum power level attainable by a Wizard
uint88 internal constant MAX_POWER = uint88(-1);
// Address of the GateKeeper, likely to be a smart contract, but we don't care if it is
// TODO: Update this address once the Gate Keeper is deployed.
address internal constant gateKeeper = address(0);
// The Wizard Guild contract. This is a variable so subclasses can modify it for
// testing, but by default it cannot change from this default.
// TODO: Update this address once the Wizard Guild is deployed.
WizardGuildInterface internal constant wizardGuild = WizardGuildInterface(address(0xb4aCd2c618EB426a8E195cCA2194c0903372AC0d));
// The Duel Resolver contract
DuelResolverInterface public duelResolver;
/// @notice Power and other data while the Wizard is participating in the Tournament
/// @dev fits into two words
struct BattleWizard {
/// @notice the wizards current power
uint88 power;
/// @notice the highest power a Wizard ever reached during a tournament
uint88 maxPower;
/// @notice a nonce value incremented when the Wizard's power level changes
uint32 nonce;
/// @notice a cached copy of the affinity of the Wizard - how handy!
uint8 affinity;
/// @notice The "id" of the Duel the Wizard is currently engaged in (which is actually
/// the hash of the duel's parameters, see _beginDuel().)
bytes32 currentDuel;
}
mapping(uint256 => BattleWizard) internal wizards;
/// @notice The total number of Wizards in this tournament. Goes up as new Wizards are entered
/// (during the Enter Phases), and goes down as Wizards get eliminated. We know we can
/// look for winners once this gets down to 5 or less!
uint256 internal remainingWizards;
/// @notice A structure used to keep track of one-sided commitments that have been made on chain.
/// We anticipate most duels will make use of the doubleCommitment mechanism (because it
/// uses less gas), but that requires a trusted intermediary, so we provide one-sided commitments
/// for fully trustless interactions.
struct SingleCommitment {
uint256 opponentId;
bytes32 commitmentHash;
}
// Key is Wizard ID, value is their selected opponent and their commitment hash
mapping(uint256 => SingleCommitment) internal pendingCommitments;
/// @notice A mapping that keeps track of one-sided reveals that have been made on chain. Like one-sided
/// commits, we expect one-sided reveals to be rare. But not quite as rare! If a player takes too
/// long to submit their reveal, their opponent will want to do a one-sided reveal to win the duel!
/// First key is Duel ID, second key is Wizard ID, value is the revealed moveset. (This structure
/// might seem odd if you aren't familiar with how Solidity handles storage-based mappings. If you
/// are confused, it's worth looking into; it's non-obvious, but quite efficient and clever!)
mapping(bytes32 => mapping(uint256 => bytes32)) internal revealedMoves;
// There can be at most 1 ascending Wizard at a time, who's ID is stored in this variable. If a second
// Wizard tries to ascend when someone is already in the chamber, we make 'em fight!
uint256 internal ascendingWizardId;
// If there is a Wizard in the growth chamber when a second Wizard attempts to ascend, those two
// Wizards are paired off into an Ascension Battle. This dictionary keeps track of the IDs of these
// paired off Wizards. Wizard 1's ID maps to Wizard 2, and vice versa. (This means that each Ascension
// Battle requires the storage of two words, which is kinda lame... ¯\_(ツ)_/¯ )
mapping(uint256 => uint256) internal ascensionOpponents;
// If there are an odd number of Wizards that attempt to ascend, one of them will be left in the
// Ascension Chamber when the Fighting Window starts. ANY Wizard can challenge them, and they MUST
// accept! This structure stores the commitment from the first challenger (if there is one).
//
// NOTE: The fields in this version of the structure are used subtly different than in the pending
// commitments mapping. In pendingCommitments, the opponentId is the ID of the person you want to fight
// and the commitmentHash is the commitment of YOUR moves. In the ascensionCommitment variable, the
// opponentId is the Wizard that has challenged the ascending Wizard, and the commitmentHash is their
// own moves. It makes sense in context, but it is technically a semantic switch worth being explicit about.
SingleCommitment internal ascensionCommitment;
struct Duel {
uint128 timeout;
bool isAscensionBattle;
}
/// @notice All of the currently active Duels, keyed by Duel ID
mapping(bytes32 => Duel) internal duels;
constructor(
address cooAddress_,
address duelResolver_,
uint256 powerScale_,
uint256 tournamentStartBlock_,
uint256 admissionDuration_,
uint256 revivalDuration_,
uint256 ascensionDuration_,
uint256 fightDuration_,
uint256 cullingDuration_,
uint256 blueMoldBasePower_,
uint256 sessionsBetweenMoldDoubling_,
uint256 duelTimeoutBlocks_
)
public
TournamentTimeAbstract(
cooAddress_,
tournamentStartBlock_,
admissionDuration_,
revivalDuration_,
ascensionDuration_,
fightDuration_,
cullingDuration_,
duelTimeoutBlocks_,
blueMoldBasePower_,
sessionsBetweenMoldDoubling_
)
{
duelResolver = DuelResolverInterface(duelResolver_);
require(
duelResolver_ != address(0) &&
duelResolver.supportsInterface(_INTERFACE_ID_DUELRESOLVER), "Invalid DuelResolver");
powerScale = powerScale_;
}
/// @notice We allow this contract to accept any payments. All Eth sent in this way
/// automatically becomes part of the prize pool. This is useful in cases
/// where the Tournament organizers want to "seed the pot" with more funds
/// than are contributed by the players.
function() external payable {}
/// @notice Query if a contract implements an interface
/// @param interfaceId The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
function supportsInterface(bytes4 interfaceId) external view returns (bool) {
return
interfaceId == this.supportsInterface.selector || // ERC165
interfaceId == _INTERFACE_ID_TOURNAMENT; // Tournament
}
/// @notice Returns true if the Tournament is currently active.
///
/// NOTE: This will return false (not active) either before the Tournament
/// begins (before any Wizards enter), or after it is over (after all
/// Wizards have been eliminated.) It also considers a Tournament inactive
/// if 200 * blueWallDoubling blocks have passed. (After 100 doublings
/// ALL of the Wizards will have subcumbed to the Blue Wall, and another
/// 100 doublings should be enough time for the winners to withdraw their
/// winnings. Anything left after that is fair game for the GateKeeper to take.)
function isActive() public view returns (bool) {
uint256 maximumTournamentLength = blueMoldParameters.moldDoublingDuration * 200;
if (block.number > blueMoldParameters.blueMoldStartBlock + maximumTournamentLength) {
return false;
} else {
return remainingWizards != 0;
}
}
// NOTE: This might seem a like a slightly odd pattern. Typical smart contract code
// (including other smart Contracts that are part of Cheeze Wizards) would
// just include the require() statement in the modifier itself instead of
// creating an additional function.
//
// Unforunately, this contract is very close to the maximum size limit
// for Ethereum (which is 24576 bytes, as per EIP-170). Modifiers work by
// more-or-less copy-and-pasting the code in them into the functions they
// decorate. It turns out that copying these modifiers (especially the
// contents of checkController() into every function that uses them adds
// up to a very large amount of space. By defining the modifier to be
// no more than a function call, we can save several KBs of contract size
// at a very small gas cost (an internal branch is just 10 gas)).
function checkGateKeeper() internal view {
require(msg.sender == gateKeeper, "Only GateKeeper can call");
}
// Modifier for functions only exposed to the GateKeeper
modifier onlyGateKeeper() {
checkGateKeeper();
_;
}
function checkExists(uint256 wizardId) internal view {
require(wizards[wizardId].maxPower != 0, "Wizard does not exist");
}
// Modifier to ensure a specific Wizard is currently entered into the Tournament
modifier exists(uint256 wizardId) {
checkExists(wizardId);
_;
}
function checkController(uint256 wizardId) internal view {
require(wizards[wizardId].maxPower != 0, "Wizard does not exist");
require(wizardGuild.isApprovedOrOwner(msg.sender, wizardId), "Must be Wizard controller");
}
// Modifier for functions that only the owner (or an approved operator) should be able to call
// Also checks that the Wizard exists!
modifier onlyWizardController(uint256 wizardId) {
checkController(wizardId);
_;
}
/// @notice A function to get the current state of the Wizard, includes the computed properties:
/// ascending (is this Wizard in the ascension chamber), ascensionOpponent (the ID of
/// an ascensionChallenger, if any) molded (this Wizard's power below the Blue Mold power
/// level), and ready (see the isReady() method for definition). You can tell if a Wizard
/// is in a battle by checking "currentDuel" against 0.
function getWizard(uint256 wizardId) public view exists(wizardId) returns(
uint256 affinity,
uint256 power,
uint256 maxPower,
uint256 nonce,
bytes32 currentDuel,
bool ascending,
uint256 ascensionOpponent,
bool molded,
bool ready
) {
BattleWizard memory wizard = wizards[wizardId];
affinity = wizard.affinity;
power = wizard.power;
maxPower = wizard.maxPower;
nonce = wizard.nonce;
currentDuel = wizard.currentDuel;
ascending = ascendingWizardId == wizardId;
ascensionOpponent = ascensionOpponents[wizardId];
molded = _blueMoldPower() > wizard.power;
ready = _isReady(wizardId, wizard);
}
/// @notice A finger printing function to capture the important state data about a Wizard into
/// a secure hash. This is especially useful during sales and trading to be sure that the Wizard's
/// state hasn't changed materially between the time the trade/purchase decision was made and
/// when the actual transfer is executed on-chain.
function wizardFingerprint(uint256 wizardId) external view returns (bytes32) {
(uint256 affinity,
uint256 power,
uint256 maxPower,
uint256 nonce,
bytes32 currentDuel,
bool ascending,
uint256 ascensionOpponent,
bool molded,
) = getWizard(wizardId);
uint256 pendingOpponent = pendingCommitments[wizardId].opponentId;
// Includes all Wizard state (including computed properties) plus the Wizard ID
// TODO: remove all pending commitment code
return keccak256(
abi.encodePacked(
wizardId,
affinity,
power,
maxPower,
nonce,
currentDuel,
ascending,
ascensionOpponent,
molded,
pendingOpponent
));
}
/// @notice Returns true if a Wizard is "ready", meaning it can participate in a battle, ascension, or power
/// transfer. A "ready" Wizard is not ascending, not battling, not moldy, hasn't committed to an ascension
/// battle, and has a valid affinity.
function isReady(uint256 wizardId) public view exists(wizardId) returns (bool) {
BattleWizard memory wizard = wizards[wizardId];
return _isReady(wizardId, wizard);
}
/// @notice An internal version of the isReady function that leverages a BattleWizard struct
/// that is already in memory
function _isReady(uint256 wizardId, BattleWizard memory wizard) internal view returns (bool) {
// IMPORTANT NOTE: oneSidedCommit() needs to recreate 90% of this logic, because it needs to check to
// see if a Wizard is ready, but it allows the Wizard to have an ascension opponent. If you make any
// changes this this function, you should double check that the same edit doesn't need to be made
// to oneSidedCommit().
return ((wizardId != ascendingWizardId) &&
(ascensionOpponents[wizardId] == 0) &&
(ascensionCommitment.opponentId != wizardId) &&
(_blueMoldPower() <= wizard.power) &&
(wizard.affinity != ELEMENT_NOTSET) &&
(wizard.currentDuel == 0));
}
/// @notice The function called by the GateKeeper to enter wizards into the tournament. Only the GateKeeper can
/// call this function, meaning that the GateKeeper gets to decide who can enter. However! The Tournament
/// enforces that ALL Wizards that are entered into the Tournament have paid the same pro-rata share of
/// the prize pool as matches their starting power. Additionally, the starting power for each Wizard
/// in the Tournament can't exceed the innate power of the Wizard when it was created. This is done to
/// ensure the Tournament is possible.
/// @param wizardIds The IDs of the Wizards to enter into the Tournament, can be length 1.
/// @param powers The list of powers for each of the Wizards (one-to-one mapping by index).
function enterWizards(uint256[] calldata wizardIds, uint88[] calldata powers) external payable duringEnterPhase onlyGateKeeper {
require(wizardIds.length == powers.length, "Mismatched parameter lengths");
uint256 totalCost = 0;
for (uint256 i = 0; i < wizardIds.length; i++) {
uint256 wizardId = wizardIds[i];
uint88 power = powers[i];
require(wizards[wizardId].maxPower == 0, "Wizard already in tournament");
(, uint88 innatePower, uint8 affinity, ) = wizardGuild.getWizard(wizardId);
require(power <= innatePower, "Power exceeds innate power");
wizards[wizardId] = BattleWizard({
power: power,
maxPower: power,
nonce: 0,
affinity: affinity,
currentDuel: 0
});
totalCost += power * powerScale;
}
remainingWizards += wizardIds.length;
require(msg.value >= totalCost, "Insufficient funds");
}
/// @dev Brings a tired Wizard back to fightin' strength. Can only be used during the revival
/// phase. The buy-back can be to any power level between the Blue Wall power (at the low end)
/// and the previous max power achived by this Wizard in this tournament. This does mean a revival
/// can bring a Wizard back above their innate power! The contribution into the pot MUST be equivalent
/// to the cost that would be needed to bring in a new Wizard at the same power level. Can only
/// be called by the GateKeeper to allow the GateKeeper to manage the pot contribution rate and
/// potentially apply other rules or requirements to revival.
function revive(uint256 wizardId) external payable exists(wizardId) duringRevivalPhase onlyGateKeeper {
BattleWizard storage wizard = wizards[wizardId];
uint88 maxPower = wizard.maxPower;
uint88 revivalPower = uint88(msg.value / powerScale);
require((revivalPower > _blueMoldPower()) && (revivalPower <= maxPower), "Invalid power level");
require(wizard.power == 0, "Can only revive tired Wizards");
// There is no scenario in which a Wizard can be "not ready" and have a zero power.
// require(isReady(wizardId), "Can't revive a busy Wizard");
wizard.power = revivalPower;
wizard.nonce += 1;
emit Revive(wizardId, revivalPower);
}
/// @notice Updates the cached value of a Wizard's affinity with the value from the Wizard Guild.
/// Only useful for Exclusive Wizards that initially have no elemental affinity, and which
/// is then selected by the owner. When the Wizard enters the Tournament it might not have
/// it's affinity set yet, and this will copy the affinity from the Guild contract if it's
/// been updated. Can be called by anyone since it can't be abused.
/// @param wizardId The id of the Wizard to update
function updateAffinity(uint256 wizardId) external exists(wizardId) {
(, , uint8 newAffinity, ) = wizardGuild.getWizard(wizardId);
BattleWizard storage wizard = wizards[wizardId];
require(wizard.affinity == ELEMENT_NOTSET, "Affinity already updated");
wizard.affinity = newAffinity;
}
function startAscension(uint256 wizardId) external duringAscensionWindow onlyWizardController(wizardId) {
BattleWizard memory wizard = wizards[wizardId];
require(_isReady(wizardId, wizard), "Can't ascend a busy wizard!");
require(wizard.power < _blueMoldPower() * 2, "Not eligible for ascension");
if (ascendingWizardId != 0) {
// there is already a Wizard ascending! Pair up the incoming Wizard with the
// Wizard in the Ascension Chamber and make them fight it out!
ascensionOpponents[ascendingWizardId] = wizardId;
ascensionOpponents[wizardId] = ascendingWizardId;
emit AscensionPairUp(ascendingWizardId, wizardId);
// Empty out the Ascension Chamber for the next Ascension
ascendingWizardId = 0;
} else {
// the chamber is empty, get in!
ascendingWizardId = wizardId;
emit AscensionStart(wizardId);
}
}
function _checkChallenge(uint256 challengerId, uint256 recipientId) internal view {
require(pendingCommitments[challengerId].opponentId == 0, "Pending battle already exists");
require(challengerId != recipientId, "Cannot duel oneself!");
}
/// @notice Any live Wizard can challenge an ascending Wizard during the fight phase. They must
/// provide a commitment of their moves (which is totally reasonable, since they know
/// exactly who they will be fighting!)
function challengeAscending(uint256 wizardId, bytes32 commitment) external duringFightWindow onlyWizardController(wizardId) {
require(ascensionCommitment.opponentId == 0, "Wizard already challenged");
_checkChallenge(wizardId, ascendingWizardId);
// Ascension Battles MUST come well before the end of the fight window to give the
// ascending Wizard a chance to respond with their own commitment.
require(canChallengeAscendingWizard(), "Challenge too late");
BattleWizard memory wizard = wizards[wizardId];
require(_isReady(wizardId, wizard), "Wizard not ready");
// We don't need to call isReady() on the ascendingWizard: It's definitionally ready for a challenge!
// Store a pending commitment that the ascending Wizard can accept
ascensionCommitment = SingleCommitment({opponentId: wizardId, commitmentHash: commitment});
}
/// @notice Allows the Ascending Wizard to respond to an ascension commitment with their own move commitment,
// thereby starting an Ascension Battle.
function acceptAscensionChallenge(bytes32 commitment) external duringFightWindow onlyWizardController(ascendingWizardId) {
uint256 challengerId = ascensionCommitment.opponentId;
require(challengerId != 0, "No challenge to accept");
if (challengerId < ascendingWizardId) {
_beginDuel(challengerId, ascendingWizardId, ascensionCommitment.commitmentHash, commitment, true);
} else {
_beginDuel(ascendingWizardId, challengerId, commitment, ascensionCommitment.commitmentHash, true);
}
// The duel has begun! THERE CAN BE ONLY ONE!!!
delete ascensionCommitment;
delete ascendingWizardId;
}
/// @notice Completes the Ascension for the Wizard in the Ascension Chamber. Note that this can only be called
/// during a Resolution Window, and a Wizard can only enter the Ascension Chamber during the Ascension Window,
/// and there is _always_ a Fight Window between the Ascension Window and the Resolution Window. In other
/// words, there is a always a chance for a challenger to battle the Ascending Wizard before the
/// ascension can complete.
function completeAscension() public duringResolutionWindow {
require(ascendingWizardId != 0, "No Wizard to ascend");
BattleWizard storage ascendingWiz = wizards[ascendingWizardId];
if (ascensionCommitment.opponentId != 0) {
// Someone challenged the ascending Wizard, but the ascending Wizard didn't fight!
// You. Are. Outtahere!
ascendingWiz.power = 0;
}
else {
// Oh lucky day! The Wizard survived a complete fight cycle without any challengers
// coming along! Let's just triple their power.
//
// A note to the naive: THIS WILL NEVER ACTUALLY HAPPEN.
_updatePower(ascendingWiz, ascendingWiz.power * 3);
}
ascendingWiz.nonce += 1;
emit AscensionComplete(ascendingWizardId, ascendingWiz.power);
ascendingWizardId = 0;
}
function oneSidedCommit(uint256 committingWizardId, uint256 otherWizardId, bytes32 commitment)
external duringFightWindow onlyWizardController(committingWizardId) exists(otherWizardId)
{
_checkChallenge(committingWizardId, otherWizardId);
bool isAscensionBattle = false;
if ((ascensionOpponents[committingWizardId] != 0) || (ascensionOpponents[otherWizardId] != 0)) {
require(
(ascensionOpponents[committingWizardId] == otherWizardId) &&
(ascensionOpponents[otherWizardId] == committingWizardId), "Must resolve Ascension Battle");
isAscensionBattle = true;
}
BattleWizard memory committingWiz = wizards[committingWizardId];
BattleWizard memory otherWiz = wizards[otherWizardId];
// Ideally, we'd use the isReady() function here, but it will return false if the caller has an
// ascension opponent, which, of course, our Wizards just might!
require(
(committingWizardId != ascendingWizardId) &&
(ascensionCommitment.opponentId != committingWizardId) &&
(_blueMoldPower() <= committingWiz.power) &&
(committingWiz.affinity != ELEMENT_NOTSET) &&
(committingWiz.currentDuel == 0), "Wizard not ready");
require(
(otherWizardId != ascendingWizardId) &&
(ascensionCommitment.opponentId != otherWizardId) &&
(_blueMoldPower() <= otherWiz.power) &&
(otherWiz.affinity != ELEMENT_NOTSET) &&
(otherWiz.currentDuel == 0), "Wizard not ready.");
SingleCommitment memory otherCommitment = pendingCommitments[otherWizardId];
if (otherCommitment.opponentId == 0) {
// The other Wizard does not currently have any pending commitments, we will store a
// pending commitment so that the other Wizard can pick it up later.
pendingCommitments[committingWizardId] = SingleCommitment({opponentId: otherWizardId, commitmentHash: commitment});
} else if (otherCommitment.opponentId == committingWizardId) {
// We've found a matching commitment! Be sure to order them correctly...
if (committingWizardId < otherWizardId) {
_beginDuel(committingWizardId, otherWizardId, commitment, otherCommitment.commitmentHash, isAscensionBattle);
} else {
_beginDuel(otherWizardId, committingWizardId, otherCommitment.commitmentHash, commitment, isAscensionBattle);
}
delete pendingCommitments[otherWizardId];
if (isAscensionBattle) {
delete ascensionOpponents[committingWizardId];
delete ascensionOpponents[otherWizardId];
}
}
else {
revert("Opponent has a pending challenge");
}
}
function cancelCommitment(uint256 wizardId) external onlyWizardController(wizardId) {
require(ascensionOpponents[wizardId] == 0, "Can't cancel Ascension Battle");
delete pendingCommitments[wizardId];
}
/// @notice Commits two Wizards into a duel with a single transaction. Both Wizards must be "ready"
/// (not ascending, not battling, not moldy, and having a valid affinity), and it must be during a
/// Fight Window.
/// @dev A note on implementation: Each duel is identified by a hash that combines both Wizard IDs,
/// both Wizard nonces, and both commits. Just the IDs and nonces are sufficient to ensure a unique
/// identifier of the duel, but by including the commits in the hash, we don't need to store the commits
/// on-chain (which is pretty expensive, given that they each take up 32 bytes). This does mean that
/// the duel resolution functions require the caller to pass in both commits in order to be resolved, but
/// the commit data is publicly available. Overall, this results in a pretty significant gas savings.
///
/// Earlier versions of this function provided convenience functionality, such as checking to see if a
/// Wizard was ready to ascend, or needed to be removed from a timed-out duel before starting this duel.
/// Each of those checks took more gas, required more code, and ultimately just tested conditions that are
/// trivial to check off-chain (where code is cheap and gas is for cars). This results in clearer
/// on-chain code, and very little extra effort off-chain.
/// @param wizardId1 The id of the 1st wizard
/// @param wizardId2 The id of the 2nd wizard
/// @param commit1 The commitment hash of the 1st Wizard's moves
/// @param commit2 The commitment hash of the 2nd Wizard's moves
/// @param sig1 The signature corresponding to wizard1
/// @param sig2 The signature corresponding to wizard2
function doubleCommit(
uint256 wizardId1,
uint256 wizardId2,
bytes32 commit1,
bytes32 commit2,
bytes calldata sig1,
bytes calldata sig2) external duringFightWindow returns (bytes32 duelId) {
// Ideally, we'd use the exists() modifiers instead of this code, but doing so runs over
// Solidity's stack limit
checkExists(wizardId1);
checkExists(wizardId2);
// The Wizard IDs must be strictly in ascending order so that we don't treat a battle betwen
// "wizard 3 and wizard 5" as different than the battle between "wizard 5 and wizard 3".
// This also ensures that a Wizards isn't trying to duel itself!
require(wizardId1 < wizardId2, "Wizard IDs must be ordered");
bool isAscensionBattle = false;
if ((ascensionOpponents[wizardId1] != 0) || (ascensionOpponents[wizardId2] != 0)) {
require(
(ascensionOpponents[wizardId1] == wizardId2) &&
(ascensionOpponents[wizardId2] == wizardId1), "Must resolve Ascension Battle");
isAscensionBattle = true;
// We can safely delete the ascensionOppenents values now because either this function
// will culminate in a committed duel, or it will revert entirely. It also lets us
// use the _isReady() convenience function (which treats a Wizard with a non-zero
// ascension opponent as not ready).
delete ascensionOpponents[wizardId1];
delete ascensionOpponents[wizardId2];
}
// Get in-memory copies of the wizards
BattleWizard memory wiz1 = wizards[wizardId1];
BattleWizard memory wiz2 = wizards[wizardId2];
require(_isReady(wizardId1, wiz1) && _isReady(wizardId2, wiz2), "Wizard not ready");
// Check that the signatures match the duel data and commitments
bytes32 signedHash1 = _signedHash(wizardId1, wizardId2, wiz1.nonce, wiz2.nonce, commit1);
bytes32 signedHash2 = _signedHash(wizardId1, wizardId2, wiz1.nonce, wiz2.nonce, commit2);
wizardGuild.verifySignatures(wizardId1, wizardId2, signedHash1, signedHash2, sig1, sig2);
// If both signatures have passed, we can begin the duel!
duelId = _beginDuel(wizardId1, wizardId2, commit1, commit2, isAscensionBattle);
// Remove any potential commitments so that they won't be reused
delete pendingCommitments[wizardId1];
delete pendingCommitments[wizardId2];
}
/// @notice An internal utility function that computes the hash that is used for the commitment signature
/// from each Wizard.
function _signedHash(uint256 wizardId1, uint256 wizardId2, uint32 nonce1, uint32 nonce2, bytes32 commit)
internal view returns(bytes32)
{
return keccak256(
abi.encodePacked(
EIP191_PREFIX,
EIP191_VERSION_DATA,
this,
wizardId1,
wizardId2,
nonce1,
nonce2,
commit
));
}
/// @notice The internal utility function to create the duel structure on chain, requires Commitments
/// from both Wizards.
function _beginDuel(uint256 wizardId1, uint256 wizardId2, bytes32 commit1, bytes32 commit2, bool isAscensionBattle)
internal returns (bytes32 duelId)
{
// Get a reference to the Wizard objects in storage
BattleWizard storage wiz1 = wizards[wizardId1];
BattleWizard storage wiz2 = wizards[wizardId2];
// Compute a unique ID for this battle, this ID can't be reused because we strictly increase
// the nonce for each Wizard whenever a battle is recreated. (Includes the contract address
// to avoid replay attacks between different tournaments).
duelId = keccak256(
abi.encodePacked(
this,
wizardId1,
wizardId2,
wiz1.nonce,
wiz2.nonce,
commit1,
commit2
));
// Store the duel ID in each Wizard, to mark the fact that they are fighting
wiz1.currentDuel = duelId;
wiz2.currentDuel = duelId;
// Keep track of the timeout for this duel
uint256 duelTimeout;
if (isAscensionBattle) {
// Ascension Battles always last for a while after the current fight window to ensure
// both sides have a well-defined timeframe for revealing their moves (Ascension Battles)
// are inherently more asynchronous than normal battles.
duelTimeout = _ascensionDuelTimeout();
} else {
// Normal battles just timeout starting .... NOW!
duelTimeout = block.number + tournamentTimeParameters.duelTimeoutDuration;
}
duels[duelId] = Duel({timeout: uint128(duelTimeout), isAscensionBattle: isAscensionBattle});
emit DuelStart(duelId, wizardId1, wizardId2, duelTimeout, isAscensionBattle);
}
/// @notice Reveals the moves for one of the Wizards in a duel. This should be called rarely, but
/// is necessary in order to resolve a duel where one player is unwilling or unable to reveal
/// their moves (also useful if a coordinating intermediary is unavailable or unwanted for some reason).
/// It's worth noting that this method doesn't check any signatures or filter on msg.sender because
/// it is cryptographically impossible for someone to submit a moveset and salt that matches the
/// commitment (which was signed, don't forget!).
///
/// Note: This function doens't need exists(wizardId) because an eliminated Wizard would have
/// currentDuel == 0
/// @param committingWizardId The Wizard whose moves are being revealed
/// @param commit A copy of the commitment used previously, not stored on-chain to save gas
/// @param moveSet The revealed move set
/// @param salt The salt used to secure the commitment hash
/// @param otherWizardId The other Wizard in this battle
/// @param otherCommit The other Wizard's commitment, not stored on-chain to save gas
function oneSidedReveal(
uint256 committingWizardId,
bytes32 commit,
bytes32 moveSet,
bytes32 salt,
uint256 otherWizardId,
bytes32 otherCommit) external
{
BattleWizard memory wizard = wizards[committingWizardId];
BattleWizard memory otherWizard = wizards[otherWizardId];
bytes32 duelId = wizard.currentDuel;
require(duelId != 0, "Wizard not dueling");
// Check that the passed data matches the duel hash
bytes32 computedDuelId;
// Make sure we compute the duel ID with the Wizards sorted in ascending order
if (committingWizardId < otherWizardId) {
computedDuelId = keccak256(
abi.encodePacked(
this,
committingWizardId,
otherWizardId,
wizard.nonce,
otherWizard.nonce,
commit,
otherCommit
));
} else {
computedDuelId = keccak256(
abi.encodePacked(
this,
otherWizardId,
committingWizardId,
otherWizard.nonce,
wizard.nonce,
otherCommit,
commit
));
}
require(computedDuelId == duelId, "Invalid duel data");
// Confirm that the revealed data matches the commitment
require(keccak256(abi.encodePacked(moveSet, salt)) == commit, "Moves don't match commitment");
// We need to verify that the provided moveset is valid here. Otherwise the duel resolution will
// fail later, and the duel can never be resolved. We treat a _valid_ commit/reveal of an _invalid_
// moveset as being equivalent of not providing a reveal (which is subject to automatic loss). I mean,
// you really should have known better!
require(duelResolver.isValidMoveSet(moveSet), "Invalid moveset");
if (revealedMoves[duelId][otherWizardId] != 0) {
// We have the revealed moves for the other Wizard also, we can resolve the duel now
if (committingWizardId < otherWizardId) {
_resolveDuel(duelId, committingWizardId, otherWizardId, moveSet, revealedMoves[duelId][otherWizardId]);
} else {
_resolveDuel(duelId, otherWizardId, committingWizardId, revealedMoves[duelId][otherWizardId], moveSet);
}
}
else {
require(block.number < duels[duelId].timeout, "Duel expired");
// Store our revealed moves for later resolution
revealedMoves[duelId][committingWizardId] = moveSet;
}
}
/// @notice Reveals the moves for both Wizards at once, saving lots of gas and lowering the number
/// of required transactions. As with oneSidedReveal(), no authentication is required other
/// than matching the reveals to the commits. It is not an error if oneSidedReveal is called
/// and then doubleReveal, although we do ignore the previous one-sided reveal if it exists.
/// The _resolvedDuel utility function will clean up any cached revealedMoves for BOTH Wizards.
///
/// NOTE: As with the doubleCommit() method, the Wizards must be provided in _strict_ ascending
/// order for this function to work correctly.
///
/// NOTE: This function will fail if _either_ of the Wizards have submitted an invalid moveset.
/// The correct way of handling this situation is to use oneSidedReveal() (if one moveset is valid
/// and the other is not) and then let the Battle timeout, or -- if both movesets are invalid --
/// don't do any reveals and let the Battle timeout.
///
/// Note: This function doens't need exists(wizardId1) exists(wizardId2) because an
/// eliminated Wizard would have currentDuel == 0
/// @param wizardId1 The id of the 1st wizard
/// @param wizardId2 The id of the 2nd wizard
/// @param commit1 A copy of the 1st Wizard's commitment, not stored on-chain to save gas
/// @param commit2 A copy of the 2nd Wizard's commitment, not stored on-chain to save gas
/// @param moveSet1 The plaintext reveal (moveset) of the 1st wizard
/// @param moveSet2 The plaintext reveal (moveset) of the 2nd wizard
/// @param salt1 The secret salt of the 1st wizard
/// @param salt2 The secret salt of the 2nd wizard
function doubleReveal(
uint256 wizardId1,
uint256 wizardId2,
bytes32 commit1,
bytes32 commit2,
bytes32 moveSet1,
bytes32 moveSet2,
bytes32 salt1,
bytes32 salt2) external
{
// Get a reference to the Wizard objects in storage
BattleWizard storage wiz1 = wizards[wizardId1];
BattleWizard storage wiz2 = wizards[wizardId2];
// In order to match the duel ID generated by the commit functions, the Wizard IDs must be strictly
// in ascending order. However! We don't actually check that here because that just wastes gas
// to perform a check that the duel ID comparison below will have to do anyway. But, we're leaving
// this commented out here as a reminder...
// require(wizardId1 < wizardId2, "Wizard IDs must be ordered");
// Confirm that the duel data passed into the function matches the duel ID in the Wizard
bytes32 duelId = keccak256(
abi.encodePacked(
this,
wizardId1,
wizardId2,
wiz1.nonce,
wiz2.nonce,
commit1,
commit2
));
// NOTE: We don't actually need to check the currentDuel field of the other Wizard because
// we trust the hash function.
require(wiz1.currentDuel == duelId, "Invalid duel data");
// Confirm that the reveals match the commitments
require(
(keccak256(abi.encodePacked(moveSet1, salt1)) == commit1) &&
(keccak256(abi.encodePacked(moveSet2, salt2)) == commit2), "Moves don't match commitment");
// Resolve the duel!
_resolveDuel(duelId, wizardId1, wizardId2, moveSet1, moveSet2);
}
/// @notice An utility function to resolve a duel once both movesets have been revealed.
function _resolveDuel(bytes32 duelId, uint256 wizardId1, uint256 wizardId2, bytes32 moveSet1, bytes32 moveSet2) internal {
Duel memory duelInfo = duels[duelId];
require(block.number < duelInfo.timeout, "Duel expired");
// Get a reference to the Wizard objects in storage
BattleWizard storage wiz1 = wizards[wizardId1];
BattleWizard storage wiz2 = wizards[wizardId2];
int256 battlePower1 = wiz1.power;
int256 battlePower2 = wiz2.power;
int256 moldPower = int256(_blueMoldPower());
if (duelInfo.isAscensionBattle) {
// In Ascension Battles, if one Wizard is more powerful than the other Wizard by
// more than double the current blue mold level, we cap the at-risk power of that
// more powerful Wizard to match the power level of the weaker wizard. This probably
// isn't clear, so here are some examples. In all of these examples, the second wizard
// is more powerful than the first, but the logic is equivalent in both directions.
// In each case, we assume the blue mold level is 100. (The non-intuitive lines are
// marked with an arrow.)
//
// power1 | power2 | battlePower2
// 100 | 100 | 100
// 100 | 200 | 200
// 100 | 300 | 300
// 100 | 301 | 100 <==
// 199 | 200 | 200
// 199 | 300 | 300
// 199 | 399 | 399
// 199 | 400 | 199 <==
//
// This technique is necessary to achieve three somewhat conflicting goals
// simultaneously:
// - Anyone should be able to battle an ascending Wizard, regardless of the
// power differential
// - Your probability of winning an Ascension Battle should be proportional to
// the amount of power you put at risk
// - A Wizard that is Ascending should be _guaranteed_ that, if they manage to
// win the Ascension Battle, they will have enough power to escape the next
// Blue Mold increase. (And if they lose, at least they had a fair shot.)
//
// Note that although a very powerful Wizard becomes less likely to win under this
// scheme (because they aren't using their entire power in this battle), they are
// putting much less power at risk (while the ascending Wizard is risking EVERYTHING).
if (battlePower1 > battlePower2 + 2*moldPower) {
battlePower1 = battlePower2;
} else if (battlePower2 > battlePower1 + 2*moldPower) {
battlePower2 = battlePower1;
}
}
int256 powerDiff = duelResolver.resolveDuel(
moveSet1,
moveSet2,
uint256(battlePower1),
uint256(battlePower2),
wiz1.affinity,
wiz2.affinity);
// A duel resolver should never return a negative value with a magnitude greater than the
// first wizard's power, or a positive value with a magnitude greater than the second
// wizard's power. We enforce that here to be safe (since it is an external contract).
if (powerDiff < -battlePower1) {
powerDiff = -battlePower1;
} else if (powerDiff > battlePower2) {
powerDiff = battlePower2;
}
// Given the checks above, both of these values will resolve to >= 0
battlePower1 += powerDiff;
battlePower2 -= powerDiff;
if (duelInfo.isAscensionBattle) {
// In an Ascension Battle, we always transfer 100% of the power-at-risk. Give it
// to the Wizard with the highest power after the battle (which might not be the
// Wizard who got the higher score!)
if (battlePower1 >= battlePower2) {
// NOTE! The comparison above is very carefully chosen: In the case of a
// tie in the power level after the battle (exceedingly unlikely, but possible!)
// we want the win to go to the Wizard with the lower ID. Since all of the duel
// functions require the wizards to be strictly ascending ID order, that's
// wizardId1, which means we want a tie to land in this leg of the if-else statement.
powerDiff += battlePower2;
} else {
powerDiff -= battlePower1;
}
}
// We now apply the power differential to the _actual_ Wizard powers (and not just
// the power-at-risk).
int256 power1 = wiz1.power + powerDiff;
int256 power2 = wiz2.power - powerDiff;
// We now check to see if either of the wizards ended up under the blue mold level.
// If so, we transfer ALL of the rest of the power from the weaker Wizard to the winner.
if (power1 < moldPower) {
power2 += power1;
power1 = 0;
}
else if (power2 < moldPower) {
power1 += power2;
power2 = 0;
}
_updatePower(wiz1, power1);
_updatePower(wiz2, power2);
// unlock wizards
wiz1.currentDuel = 0;
wiz2.currentDuel = 0;
// Incrememnt the Wizard nonces
wiz1.nonce += 1;
wiz2.nonce += 1;
// Clean up old data
delete duels[duelId];
delete revealedMoves[duelId][wizardId1];
delete revealedMoves[duelId][wizardId2];
// emit event
emit DuelEnd(duelId, wizardId1, wizardId2, moveSet1, moveSet2, wiz1.power, wiz2.power);
}
/// @notice Utility function to update the power on a Wizard, ensuring it doesn't overflow
/// a uint88 and also updates maxPower as appropriate.
// solium-disable-next-line security/no-assign-params
function _updatePower(BattleWizard storage wizard, int256 newPower) internal {
if (newPower > MAX_POWER) {
newPower = MAX_POWER;
}
wizard.power = uint88(newPower);
if (wizard.maxPower < newPower) {
wizard.maxPower = uint88(newPower);
}
}
/// @notice Resolves a duel that has timed out. This can only happen if one or both players
/// didn't reveal their moves. If both don't reveal, there is no power transfer, if one
/// revealed, they win ALL the power.
///
/// Note: This function doens't need exists(wizardId1) exists(wizardId2) because an
/// eliminated Wizard would have currentDuel == 0
function resolveTimedOutDuel(uint256 wizardId1, uint256 wizardId2) external {
BattleWizard storage wiz1 = wizards[wizardId1];
BattleWizard storage wiz2 = wizards[wizardId2];
bytes32 duelId = wiz1.currentDuel;
require(duelId != 0 && wiz2.currentDuel == duelId, "Wizards are not dueling");
require(block.number > duels[duelId].timeout, "Duel not timed out");
int256 allPower = wiz1.power + wiz2.power;
if (revealedMoves[duelId][wizardId1] != 0) {
// The first Wizard revealed their moves, but the second one didn't (otherwise it
// would have been resolved). Transfer all of the power from two to one.
_updatePower(wiz1, allPower);
wiz2.power = 0;
}
else if (revealedMoves[duelId][wizardId2] != 0) {
// The second Wizard revealed, so it drains the first.
_updatePower(wiz2, allPower);
wiz1.power = 0;
}
// NOTE: If neither Wizard did a reveal, we just end the battle with no power transfer.
// unlock wizards
wiz1.currentDuel = 0;
wiz2.currentDuel = 0;
// Incrememnt the Wizard nonces
wiz1.nonce += 1;
wiz2.nonce += 1;
// Clean up old data
delete duels[duelId];
delete revealedMoves[duelId][wizardId1];
delete revealedMoves[duelId][wizardId2];
// emit event
emit DuelTimeOut(duelId, wizardId1, wizardId2, wiz1.power, wiz2.power);
}
/// @notice Transfer the power of one Wizard to another. The caller has to be the owner
/// or have approval of the sending Wizard. Both Wizards must be ready (not moldy,
/// ascending or in a duel), and we limit power transfers to happen during Fight
/// Windows (this is important so that power transfers don't interfere with Culling
/// or Ascension operations).
/// @param sendingWizardId The Wizard to transfer power from. After the transfer,
/// this Wizard will have no power.
/// @param receivingWizardId The Wizard to transfer power to.
function giftPower(uint256 sendingWizardId, uint256 receivingWizardId) external
onlyWizardController(sendingWizardId) exists(receivingWizardId) duringFightWindow
{
BattleWizard storage sendingWiz = wizards[sendingWizardId];
BattleWizard storage receivingWiz = wizards[receivingWizardId];
require(sendingWizardId != receivingWizardId, "Can't gift power to yourself");
require(isReady(sendingWizardId) && isReady(receivingWizardId), "Wizard not ready");
emit PowerGifted(sendingWizardId, receivingWizardId, sendingWiz.power);
_updatePower(receivingWiz, sendingWiz.power + receivingWiz.power);
sendingWiz.power = 0;
// update the nonces to reflect the state change and invalidate any pending commitments
sendingWiz.nonce += 1;
receivingWiz.nonce += 1;
}
/// @notice A function that will permanently remove eliminated Wizards from the smart contract.
///
/// The way that this (and cullMoldedWithMolded()) works isn't entirely obvious, so please settle
/// down for story time!
///
/// The "obvious" solution to elminating Wizards from the Tournament is to simply delete
/// them from the wizards mapping when they are beaten into submission (Oh! Sorry! Marketing
/// team says I should say "tired".) But we can't do this during the revival phase, because
/// maybe that player wants to revive their Wizard. What's more is that when the Blue Mold
/// starts, there is no on-chain event that fires when the Blue Mold power level doubles
/// (which can also lead to Wizard elimination).
///
/// The upshot is that we could have a bunch of Wizards sitting around in the wizards mapping
/// that are below the Blue Mold level, possibly even with a power level of zero. If we can't
/// get rid of them somehow, we can't know when the Tournament is over (which would make for
/// a pretty crappy tournament, huh?).
///
/// The next obvious solution? If a Wizard is below the Blue Mold level, just let anyone come
/// along and delete that sucker. Whoa, there, Cowboy! Maybe you should think it through for
/// a minute before you jump to any conclusions. Give it a minute, you'll see what I mean.
///
/// Yup. I knew you'd see it. If we start deleting ALL the Wizards below the Blue Mold level,
/// there's a not-so-rare edge case where the last two or three or ten Wizards decide not
/// to fight each other, and they all get molded. Eek! Another great way to make for a crappy
/// tournament! No winner!
///
/// So, if we do end up with ALL of the Wizards molded, how do we resolve the Tournament? Our
/// solution is to let the 5 most powerful molded Wizards split the pot pro-rata (so, if you have
/// 60% of the total power represented in the 5 winning Wizards, you get 60% of the pot.)
///
/// But this puts us in a bit of a pickle. How can we delete a molded Wizard if it might just
/// be a winner?!
///
/// Simple! If someone wants to permanently remove a Wizard from the tournament, they just have
/// to pass in a reference to _another_ Wizard (or Wizards) that _prove_ that the Wizard they
/// want to elminate can't possibly be the winner.
///
/// This function handles the simpler of the two cases: If the caller can point to a Wizard
/// that is _above_ the Blue Mold level, then _any_ Wizard that is below the Blue
/// mold level can be safely eliminated.
///
/// Note that there are no restrictions on who can cull moldy Wizards. Anyone can call, so
/// long as they have the necessary proof!
/// @param wizardIds A list of moldy Wizards to permanently remove from the Tournament
/// @param survivor The ID of a surviving Wizard, as proof that it's safe to remove those moldy folks
function cullMoldedWithSurvivor(uint256[] calldata wizardIds, uint256 survivor) external
exists(survivor) duringCullingWindow
{
uint256 moldLevel = _blueMoldPower();
require(wizards[survivor].power >= moldLevel, "Survivor isn't alive");
for (uint256 i = 0; i < wizardIds.length; i++) {
uint256 wizardId = wizardIds[i];
if (wizards[wizardId].maxPower != 0 && wizards[wizardId].power < moldLevel) {
delete wizards[wizardId];
remainingWizards--;
emit WizardElimination(wizardId);
}
}
}
/// @notice Another function to remove eliminated Wizards from the smart contract.
///
/// Well, partner, it's good to see you back again. I hope you've recently read the comments
/// on cullMoldedWithSurvivor() because that'll provide you with some much needed context here.
///
/// This function handles the other case, what if there IS no unmolded Wizard to point to, how do
/// you cull the excess moldy Wizards to pare it down to the five final survivors that should split
/// the pot?
///
/// Well, the answer is much the same as before, only instead of pointing to a single example of
/// a Wizard that has a better claim to the pot, we require that the caller provides a reference
/// to FIVE other Wizards who have a better claim to the pot.
///
/// It would be pretty easy to write this function in a way that was very expensive, so in order
/// to save ourselves a lot of gas, we require that the list of Wizards is in strictly decending
/// order of power (if two wizards have identical power levels, we consider the one with the
/// lower ID as being more powerful).
///
/// We also require that the first (i.e. most powerful) Wizard in the list is moldy, even though
/// it's not going to be eliminated! This may not seem strictly necessary, but it makes the
/// logic simpler (because then we can just assume that ALL the Wizards are moldy, without any
/// further checks). If it isn't moldy, the caller should just use the cullMoldedWithSurvivor()
/// method instead!
///
/// "Oh ho!" you say, taking great pleasure in your clever insight. "How can you be so sure that
/// the first five Wizards passed in as 'leaders' are _actually_ the five most powerful molded
/// Wizards?" Well, my dear friend... you are right: We can't!
///
/// However it turns out that's actually fine! If the caller (for some reason) decides to start the list
/// with the Wizards ranked 6-10 in the Tournament, they can do it that and we'd never know the
/// difference.... Except that's not actually a problem, because they'd still only be able to remove
/// molded Wizards ranked 11th or higher, all of which are due for removal anyway. (It's the same
/// argument that we don't actually know -- inside this function -- if there's a non-molded Wizard;
/// it's still safe to allow the caller to eliminate molded Wizards ranked 6th or higher.)
/// @param moldyWizardIds A list of moldy Wizards, in strictly decreasing power order. Entries 5+ in this list
/// will be permanently removed from the Tournament
function cullMoldedWithMolded(uint256[] calldata moldyWizardIds) external duringCullingWindow {
uint256 currentId;
uint256 currentPower;
uint256 previousId = moldyWizardIds[0];
uint256 previousPower = wizards[previousId].power;
// It's dumb to call this function with fewer than 5 wizards, but nothing bad will happen
// so we don't waste gas preventing it.
// require(moldyWizardsIds.length > 5, "No wizards to eliminate");
require(previousPower < _blueMoldPower(), "Not moldy");
for (uint256 i = 1; i < moldyWizardIds.length; i++) {
currentId = moldyWizardIds[i];
checkExists(currentId);
currentPower = wizards[currentId].power;
// Confirm that this new Wizard has a worse claim on the prize than the previous Wizard
require(
(currentPower < previousPower) ||
((currentPower == previousPower) && (currentId > previousId)),
"Wizards not strictly ordered");
if (i >= 5)
{
delete wizards[currentId];
remainingWizards--;
emit WizardElimination(currentId);
}
previousId = currentId;
previousPower = currentPower;
}
}
/// @notice One last culling function that simply removes Wizards with zero power. They can't
/// even get a cut of the final pot... (Worth noting: Culling Windows are only available
/// during the Elmination Phase, so even Wizards that go to zero can't be removed during
/// the Revival Phase.)
function cullTiredWizards(uint256[] calldata wizardIds) external duringCullingWindow {
for (uint256 i = 0; i < wizardIds.length; i++) {
uint256 wizardId = wizardIds[i];
if (wizards[wizardId].maxPower != 0 && wizards[wizardId].power == 0) {
delete wizards[wizardId];
remainingWizards--;
emit WizardElimination(wizardId);
}
}
}
/// @notice This is a pretty important function! When the Tournament has a single remaining Wizard left
/// we can send them ALL of the funds in this smart contract. Notice that we don't actually check
/// to see if the claimant is moldy: If there is a single remaining Wizard in the Tournament, they
/// get to take the pot, regardless of the mold level.
function claimTheBigCheeze(uint256 claimingWinnerId) external duringCullingWindow onlyWizardController(claimingWinnerId) {
require(remainingWizards == 1, "Keep fighting!");
// They did it! They were the final survivor. They get all the money!
emit PrizeClaimed(claimingWinnerId, address(this).balance);
remainingWizards = 0;
delete wizards[claimingWinnerId];
msg.sender.transfer(address(this).balance);
}
/// @notice A function that allows one of the 5 most powerful Wizards to claim their pro-rata share of
/// the pot if the Tournament ends with all Wizards subcumbing to the Blue Mold. Note that
/// all but five of the Moldy Wizards need to first be eliminated with cullMoldedWithMolded().
///
/// It might seem like it would be tricky to split the pot one player at a time. Imagine that
/// there are just three winners, with power levels 20, 30, and 50. If the third player claims
/// first, they will get 50% of the (remaining) pot, but if they claim last, they will get
/// 100% of the remaining pot! If you run some examples, you'll see that by decreasing the pot
/// size by a value exactly proportional to the power of the removed Wizard, everyone gets
/// the same amount of winnings, regardless of the order in which they claim (plus or minus
/// a wei or two due to rounding).
/// @param claimingWinnerId The Wizard who's share is currently being claimed
/// @param allWinners The complete set of all remaining Wizards in the tournament. This set MUST
/// be ordered by ascending ID.
function claimSharedWinnings(uint256 claimingWinnerId, uint256[] calldata allWinners)
external duringCullingWindow onlyWizardController(claimingWinnerId)
{
require(remainingWizards <= 5, "Too soon to claim");
require(remainingWizards == allWinners.length, "Must provide all winners");
require(wizards[claimingWinnerId].power != 0, "No cheeze for you!");
uint256 moldLevel = _blueMoldPower();
uint256 totalPower = 0;
uint256 lastWizard = 0;
// Check to see that all of the remaining Wizards are molded and not yet eliminated,
// assuming they are, keep track of the total power level of the remaining entrants
for (uint256 i = 0; i < allWinners.length; i++) {
uint256 wizardId = allWinners[i];
uint256 wizardPower = wizards[wizardId].power;
require(wizardId > lastWizard, "Winners not unique and ordered");
require(wizards[wizardId].maxPower != 0, "Wizard already eliminated");
require(wizardPower < moldLevel, "Wizard not moldy");
lastWizard = wizardId;
totalPower += wizardPower;
}
uint256 claimingWinnerShare = address(this).balance * wizards[claimingWinnerId].power / totalPower;
// Be sure to delete their claim on the prize before sending them the balance!
delete wizards[claimingWinnerId];
remainingWizards--;
emit PrizeClaimed(claimingWinnerId, claimingWinnerShare);
msg.sender.transfer(claimingWinnerShare);
}
/// @notice Allows the GateKeeper to destroy this contract if it's not needed anymore.
function destroy() external onlyGateKeeper {
require(isActive() == false, "Tournament active");
selfdestruct(msg.sender);
}
}
| @notice One last culling function that simply removes Wizards with zero power. They can't even get a cut of the final pot... (Worth noting: Culling Windows are only available during the Elmination Phase, so even Wizards that go to zero can't be removed during the Revival Phase.) | function cullTiredWizards(uint256[] calldata wizardIds) external duringCullingWindow {
for (uint256 i = 0; i < wizardIds.length; i++) {
uint256 wizardId = wizardIds[i];
if (wizards[wizardId].maxPower != 0 && wizards[wizardId].power == 0) {
delete wizards[wizardId];
remainingWizards--;
emit WizardElimination(wizardId);
}
}
}
| 12,784,618 | [
1,
3335,
1142,
276,
420,
310,
445,
716,
8616,
7157,
678,
13412,
87,
598,
3634,
7212,
18,
16448,
848,
1404,
540,
5456,
336,
279,
6391,
434,
326,
727,
5974,
2777,
261,
59,
7825,
486,
310,
30,
385,
420,
310,
8202,
854,
1338,
2319,
540,
4982,
326,
10426,
1154,
367,
19459,
16,
1427,
5456,
678,
13412,
87,
716,
1960,
358,
3634,
848,
1404,
506,
3723,
4982,
540,
326,
14477,
5162,
19459,
12998,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
276,
420,
56,
2921,
27130,
87,
12,
11890,
5034,
8526,
745,
892,
24204,
2673,
13,
3903,
4982,
39,
420,
310,
3829,
288,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
24204,
2673,
18,
2469,
31,
277,
27245,
288,
203,
5411,
2254,
5034,
24204,
548,
273,
24204,
2673,
63,
77,
15533,
203,
5411,
309,
261,
31837,
87,
63,
31837,
548,
8009,
1896,
13788,
480,
374,
597,
24204,
87,
63,
31837,
548,
8009,
12238,
422,
374,
13,
288,
203,
7734,
1430,
24204,
87,
63,
31837,
548,
15533,
203,
7734,
4463,
27130,
87,
413,
31,
203,
203,
7734,
3626,
678,
13412,
4958,
381,
1735,
12,
31837,
548,
1769,
203,
5411,
289,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import {
ReentrancyGuard
} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../interfaces/ILockTOS.sol";
import "../interfaces/IPublicSale.sol";
import "../interfaces/IWTON.sol";
import "../common/AccessibleCommon.sol";
import "./PublicSaleStorage.sol";
contract PublicSale is
PublicSaleStorage,
AccessibleCommon,
ReentrancyGuard,
IPublicSale
{
using SafeERC20 for IERC20;
using SafeMath for uint256;
event AddedWhiteList(address indexed from, uint256 tier);
event ExclusiveSaled(address indexed from, uint256 amount);
event Deposited(address indexed from, uint256 amount);
event Claimed(address indexed from, uint256 amount);
event Withdrawal(address indexed from, uint256 amount);
event DepositWithdrawal(address indexed from, uint256 amount);
modifier nonZero(uint256 _value) {
require(_value > 0, "PublicSale: zero");
_;
}
modifier nonZeroAddress(address _addr) {
require(_addr != address(0), "PublicSale: zero address");
_;
}
modifier beforeStartAddWhiteTime() {
require(
startAddWhiteTime == 0 ||
(startAddWhiteTime > 0 && block.timestamp < startAddWhiteTime),
"PublicSale: not beforeStartAddWhiteTime"
);
_;
}
modifier beforeEndAddWhiteTime() {
require(
endAddWhiteTime == 0 ||
(endAddWhiteTime > 0 && block.timestamp < endAddWhiteTime),
"PublicSale: not beforeEndAddWhiteTime"
);
_;
}
modifier greaterThan(uint256 _value1, uint256 _value2) {
require(_value1 > _value2, "PublicSale: non greaterThan");
_;
}
modifier lessThan(uint256 _value1, uint256 _value2) {
require(_value1 < _value2, "PublicSale: non less than");
_;
}
/// @inheritdoc IPublicSale
function changeTONOwner(address _address) external override onlyOwner {
getTokenOwner = _address;
}
/// @inheritdoc IPublicSale
function setAllValue(
uint256 _snapshot,
uint256[4] calldata _exclusiveTime,
uint256[2] calldata _openSaleTime,
uint256[4] calldata _claimTime
) external override onlyOwner beforeStartAddWhiteTime {
require(
(_exclusiveTime[0] < _exclusiveTime[1]) &&
(_exclusiveTime[2] < _exclusiveTime[3])
);
require(
(_openSaleTime[0] < _openSaleTime[1])
);
setSnapshot(_snapshot);
setExclusiveTime(
_exclusiveTime[0],
_exclusiveTime[1],
_exclusiveTime[2],
_exclusiveTime[3]
);
setOpenTime(
_openSaleTime[0],
_openSaleTime[1]
);
setClaim(
_claimTime[0],
_claimTime[1],
_claimTime[2],
_claimTime[3]
);
}
/// @inheritdoc IPublicSale
function setSnapshot(uint256 _snapshot)
public
override
onlyOwner
nonZero(_snapshot)
{
snapshot = _snapshot;
}
/// @inheritdoc IPublicSale
function setExclusiveTime(
uint256 _startAddWhiteTime,
uint256 _endAddWhiteTime,
uint256 _startExclusiveTime,
uint256 _endExclusiveTime
)
public
override
onlyOwner
nonZero(_startAddWhiteTime)
nonZero(_endAddWhiteTime)
nonZero(_startExclusiveTime)
nonZero(_endExclusiveTime)
beforeStartAddWhiteTime
{
startAddWhiteTime = _startAddWhiteTime;
endAddWhiteTime = _endAddWhiteTime;
startExclusiveTime = _startExclusiveTime;
endExclusiveTime = _endExclusiveTime;
}
/// @inheritdoc IPublicSale
function setOpenTime(
uint256 _startDepositTime,
uint256 _endDepositTime
)
public
override
onlyOwner
nonZero(_startDepositTime)
nonZero(_endDepositTime)
beforeStartAddWhiteTime
{
startDepositTime = _startDepositTime;
endDepositTime = _endDepositTime;
}
/// @inheritdoc IPublicSale
function setClaim(
uint256 _startClaimTime,
uint256 _claimInterval,
uint256 _claimPeriod,
uint256 _claimFirst
)
public
override
onlyOwner
nonZero(_startClaimTime)
nonZero(_claimInterval)
nonZero(_claimPeriod)
beforeStartAddWhiteTime
{
startClaimTime = _startClaimTime;
claimInterval = _claimInterval;
claimPeriod = _claimPeriod;
claimFirst = _claimFirst;
}
/// @inheritdoc IPublicSale
function setAllTier(
uint256[4] calldata _tier,
uint256[4] calldata _tierPercent
) external override onlyOwner {
setTier(
_tier[0],
_tier[1],
_tier[2],
_tier[3]
);
setTierPercents(
_tierPercent[0],
_tierPercent[1],
_tierPercent[2],
_tierPercent[3]
);
}
/// @inheritdoc IPublicSale
function setTier(
uint256 _tier1,
uint256 _tier2,
uint256 _tier3,
uint256 _tier4
)
public
override
onlyOwner
nonZero(_tier1)
nonZero(_tier2)
nonZero(_tier3)
nonZero(_tier4)
beforeStartAddWhiteTime
{
tiers[1] = _tier1;
tiers[2] = _tier2;
tiers[3] = _tier3;
tiers[4] = _tier4;
}
/// @inheritdoc IPublicSale
function setTierPercents(
uint256 _tier1,
uint256 _tier2,
uint256 _tier3,
uint256 _tier4
)
public
override
onlyOwner
nonZero(_tier1)
nonZero(_tier2)
nonZero(_tier3)
nonZero(_tier4)
beforeStartAddWhiteTime
{
require(
_tier1.add(_tier2).add(_tier3).add(_tier4) == 10000,
"PublicSale: Sum should be 10000"
);
tiersPercents[1] = _tier1;
tiersPercents[2] = _tier2;
tiersPercents[3] = _tier3;
tiersPercents[4] = _tier4;
}
/// @inheritdoc IPublicSale
function setAllAmount(
uint256[2] calldata _expectAmount,
uint256[2] calldata _priceAmount
) external override onlyOwner {
setSaleAmount(
_expectAmount[0],
_expectAmount[1]
);
setTokenPrice(
_priceAmount[0],
_priceAmount[1]
);
}
/// @inheritdoc IPublicSale
function setSaleAmount(
uint256 _totalExpectSaleAmount,
uint256 _totalExpectOpenSaleAmount
)
public
override
onlyOwner
nonZero(_totalExpectSaleAmount.add(_totalExpectOpenSaleAmount))
beforeStartAddWhiteTime
{
totalExpectSaleAmount = _totalExpectSaleAmount;
totalExpectOpenSaleAmount = _totalExpectOpenSaleAmount;
}
/// @inheritdoc IPublicSale
function setTokenPrice(uint256 _saleTokenPrice, uint256 _payTokenPrice)
public
override
onlyOwner
nonZero(_saleTokenPrice)
nonZero(_payTokenPrice)
beforeStartAddWhiteTime
{
saleTokenPrice = _saleTokenPrice;
payTokenPrice = _payTokenPrice;
}
/// @inheritdoc IPublicSale
function totalExpectOpenSaleAmountView() public view override returns(uint256){
if(block.timestamp < endExclusiveTime) return totalExpectOpenSaleAmount;
else return totalExpectOpenSaleAmount.add(totalRound1NonSaleAmount());
}
/// @inheritdoc IPublicSale
function totalRound1NonSaleAmount() public view override returns(uint256){
return totalExpectSaleAmount.sub(totalExSaleAmount);
}
function _toRAY(uint256 v) internal pure returns (uint256) {
return v * 10 ** 9;
}
/// @inheritdoc IPublicSale
function calculSaleToken(uint256 _amount)
public
view
override
returns (uint256)
{
uint256 tokenSaleAmount =
_amount.mul(payTokenPrice).div(saleTokenPrice);
return tokenSaleAmount;
}
/// @inheritdoc IPublicSale
function calculPayToken(uint256 _amount)
public
view
override
returns (uint256)
{
uint256 tokenPayAmount = _amount.mul(saleTokenPrice).div(payTokenPrice);
return tokenPayAmount;
}
/// @inheritdoc IPublicSale
function calculTier(address _address)
public
view
override
nonZeroAddress(address(sTOS))
nonZero(tiers[1])
nonZero(tiers[2])
nonZero(tiers[3])
nonZero(tiers[4])
returns (uint256)
{
uint256 sTOSBalance = sTOS.balanceOfAt(_address, snapshot);
uint256 tier;
if (sTOSBalance >= tiers[1] && sTOSBalance < tiers[2]) {
tier = 1;
} else if (sTOSBalance >= tiers[2] && sTOSBalance < tiers[3]) {
tier = 2;
} else if (sTOSBalance >= tiers[3] && sTOSBalance < tiers[4]) {
tier = 3;
} else if (sTOSBalance >= tiers[4]) {
tier = 4;
} else if (sTOSBalance < tiers[1]) {
tier = 0;
}
return tier;
}
/// @inheritdoc IPublicSale
function calculTierAmount(address _address)
public
view
override
returns (uint256)
{
UserInfoEx storage userEx = usersEx[_address];
uint256 tier = calculTier(_address);
if (userEx.join == true && tier > 0) {
uint256 salePossible =
totalExpectSaleAmount
.mul(tiersPercents[tier])
.div(tiersAccount[tier])
.div(10000);
return salePossible;
} else if (tier > 0) {
uint256 tierAccount = tiersAccount[tier].add(1);
uint256 salePossible =
totalExpectSaleAmount
.mul(tiersPercents[tier])
.div(tierAccount)
.div(10000);
return salePossible;
} else {
return 0;
}
}
/// @inheritdoc IPublicSale
function calculOpenSaleAmount(address _account, uint256 _amount)
public
view
override
returns (uint256)
{
UserInfoOpen storage userOpen = usersOpen[_account];
uint256 depositAmount = userOpen.depositAmount.add(_amount);
uint256 openSalePossible =
totalExpectOpenSaleAmountView().mul(depositAmount).div(
totalDepositAmount.add(_amount)
);
return openSalePossible;
}
/// @inheritdoc IPublicSale
function calculClaimAmount(address _account, uint256 _period)
public
view
override
returns (uint256 _reward, uint256 _totalClaim)
{
if(block.timestamp < startClaimTime) return (0, 0);
if(_period > claimPeriod) return (0,0);
UserClaim storage userClaim = usersClaim[_account];
(, uint256 realSaleAmount, ) = totalSaleUserAmount(_account);
if (realSaleAmount == 0 ) return (0, 0);
if (userClaim.claimAmount >= realSaleAmount) return (0, realSaleAmount);
uint256 difftime = block.timestamp.sub(startClaimTime);
uint256 totalClaimReward = realSaleAmount;
uint256 firstReward = totalClaimReward.mul(claimFirst).div(100);
uint256 periodReward = (totalClaimReward.sub(firstReward)).div(claimPeriod.sub(1));
if(_period == 0) {
if (difftime < claimInterval) {
uint256 reward = firstReward.sub(userClaim.claimAmount);
return (reward, totalClaimReward);
} else {
uint256 period = (difftime / claimInterval).add(1);
if (period >= claimPeriod) {
uint256 reward =
totalClaimReward.sub(userClaim.claimAmount);
return (reward, totalClaimReward);
} else {
uint256 reward = firstReward.add(periodReward.mul(period.sub(1))).sub(userClaim.claimAmount);
return (reward, totalClaimReward);
}
}
} else if(_period == 1){
return (firstReward, totalClaimReward);
} else {
if(_period == claimPeriod) {
uint256 reward =
totalClaimReward.sub((firstReward.add(periodReward.mul(claimPeriod.sub(2)))));
return (reward, totalClaimReward);
} else {
return (periodReward, totalClaimReward);
}
}
}
/// @inheritdoc IPublicSale
function totalSaleUserAmount(address user) public override view returns (uint256 _realPayAmount, uint256 _realSaleAmount, uint256 _refundAmount) {
UserInfoEx storage userEx = usersEx[user];
if(userEx.join){
(uint256 realPayAmount, uint256 realSaleAmount, uint256 refundAmount) = openSaleUserAmount(user);
return ( realPayAmount.add(userEx.payAmount), realSaleAmount.add(userEx.saleAmount), refundAmount);
}else {
return openSaleUserAmount(user);
}
}
/// @inheritdoc IPublicSale
function openSaleUserAmount(address user) public override view returns (uint256 _realPayAmount, uint256 _realSaleAmount, uint256 _refundAmount) {
UserInfoOpen storage userOpen = usersOpen[user];
if(!userOpen.join || userOpen.depositAmount == 0) return (0, 0, 0);
uint256 openSalePossible = calculOpenSaleAmount(user, 0);
uint256 realPayAmount = calculPayToken(openSalePossible);
uint256 depositAmount = userOpen.depositAmount;
uint256 realSaleAmount = 0;
uint256 returnAmount = 0;
if (realPayAmount < depositAmount) {
returnAmount = depositAmount.sub(realPayAmount);
realSaleAmount = calculSaleToken(realPayAmount);
} else {
realPayAmount = userOpen.depositAmount;
realSaleAmount = calculSaleToken(depositAmount);
}
return (realPayAmount, realSaleAmount, returnAmount);
}
/// @inheritdoc IPublicSale
function totalOpenSaleAmount() public override view returns (uint256){
uint256 _calculSaleToken = calculSaleToken(totalDepositAmount);
uint256 _totalAmount = totalExpectOpenSaleAmountView();
if(_calculSaleToken < _totalAmount) return _calculSaleToken;
else return _totalAmount;
}
/// @inheritdoc IPublicSale
function totalOpenPurchasedAmount() public override view returns (uint256){
uint256 _calculSaleToken = calculSaleToken(totalDepositAmount);
uint256 _totalAmount = totalExpectOpenSaleAmountView();
if(_calculSaleToken < _totalAmount) return totalDepositAmount;
else return calculPayToken(_totalAmount);
}
/// @inheritdoc IPublicSale
function addWhiteList() external override nonReentrant {
require(
block.timestamp >= startAddWhiteTime,
"PublicSale: whitelistStartTime has not passed"
);
require(
block.timestamp < endAddWhiteTime,
"PublicSale: end the whitelistTime"
);
uint256 tier = calculTier(msg.sender);
require(tier >= 1, "PublicSale: need to more sTOS");
UserInfoEx storage userEx = usersEx[msg.sender];
require(userEx.join != true, "PublicSale: already attended");
whitelists.push(msg.sender);
totalWhitelists = totalWhitelists.add(1);
userEx.join = true;
userEx.tier = tier;
userEx.saleAmount = 0;
tiersAccount[tier] = tiersAccount[tier].add(1);
emit AddedWhiteList(msg.sender, tier);
}
/// @inheritdoc IPublicSale
function exclusiveSale(uint256 _amount)
external
override
nonZero(_amount)
nonZero(claimPeriod)
nonReentrant
{
require(
block.timestamp >= startExclusiveTime,
"PublicSale: exclusiveStartTime has not passed"
);
require(
block.timestamp < endExclusiveTime,
"PublicSale: end the exclusiveTime"
);
UserInfoEx storage userEx = usersEx[msg.sender];
require(userEx.join == true, "PublicSale: not registered in whitelist");
uint256 tokenSaleAmount = calculSaleToken(_amount);
uint256 salePossible = calculTierAmount(msg.sender);
require(
salePossible >= userEx.saleAmount.add(tokenSaleAmount),
"PublicSale: just buy tier's allocated amount"
);
if(userEx.payAmount == 0) {
totalRound1Users = totalRound1Users.add(1);
totalUsers = totalUsers.add(1);
}
userEx.payAmount = userEx.payAmount.add(_amount);
userEx.saleAmount = userEx.saleAmount.add(tokenSaleAmount);
totalExPurchasedAmount = totalExPurchasedAmount.add(_amount);
totalExSaleAmount = totalExSaleAmount.add(tokenSaleAmount);
uint256 tier = calculTier(msg.sender);
tiersExAccount[tier] = tiersExAccount[tier].add(1);
uint256 tonAllowance = getToken.allowance(msg.sender, address(this));
uint256 tonBalance = getToken.balanceOf(msg.sender);
if(tonAllowance < _amount) {
uint256 needUserWton;
uint256 needWton = _amount.sub(tonAllowance);
needUserWton = _toRAY(needWton);
require(IWTON(wton).allowance(msg.sender, address(this)) >= needUserWton, "PublicSale: wton amount exceeds allowance");
require(IWTON(wton).balanceOf(msg.sender) >= needUserWton, "need more wton");
IERC20(wton).safeTransferFrom(msg.sender,address(this),needUserWton);
IWTON(wton).swapToTON(needUserWton);
require(tonAllowance >= _amount.sub(needWton), "PublicSale: ton amount exceeds allowance");
if(_amount.sub(needWton) > 0) {
getToken.safeTransferFrom(msg.sender, address(this), _amount.sub(needWton));
}
getToken.safeTransfer(getTokenOwner, _amount);
} else {
require(tonAllowance >= _amount && tonBalance >= _amount, "PublicSale: ton amount exceeds allowance");
getToken.safeTransferFrom(msg.sender, address(this), _amount);
getToken.safeTransfer(getTokenOwner, _amount);
}
emit ExclusiveSaled(msg.sender, _amount);
}
/// @inheritdoc IPublicSale
function deposit(uint256 _amount) external override nonReentrant {
require(
block.timestamp >= startDepositTime,
"PublicSale: don't start depositTime"
);
require(
block.timestamp < endDepositTime,
"PublicSale: end the depositTime"
);
UserInfoOpen storage userOpen = usersOpen[msg.sender];
if (!userOpen.join) {
depositors.push(msg.sender);
userOpen.join = true;
totalRound2Users = totalRound2Users.add(1);
UserInfoEx storage userEx = usersEx[msg.sender];
if(userEx.payAmount == 0) totalUsers = totalUsers.add(1);
}
userOpen.depositAmount = userOpen.depositAmount.add(_amount);
userOpen.saleAmount = 0;
totalDepositAmount = totalDepositAmount.add(_amount);
uint256 tonAllowance = getToken.allowance(msg.sender, address(this));
uint256 tonBalance = getToken.balanceOf(msg.sender);
if(tonAllowance < _amount) {
uint256 needUserWton;
uint256 needWton = _amount.sub(tonAllowance);
needUserWton = _toRAY(needWton);
require(IWTON(wton).allowance(msg.sender, address(this)) >= needUserWton, "PublicSale: wton amount exceeds allowance");
require(IWTON(wton).balanceOf(msg.sender) >= needUserWton, "need more wton");
IERC20(wton).safeTransferFrom(msg.sender,address(this),needUserWton);
IWTON(wton).swapToTON(needUserWton);
require(tonAllowance >= _amount.sub(needWton), "PublicSale: ton amount exceeds allowance");
if(_amount.sub(needWton) > 0) {
getToken.safeTransferFrom(msg.sender, address(this), _amount.sub(needWton));
}
} else {
require(tonAllowance >= _amount && tonBalance >= _amount, "PublicSale: ton amount exceeds allowance");
getToken.safeTransferFrom(msg.sender, address(this), _amount);
}
emit Deposited(msg.sender, _amount);
}
/// @inheritdoc IPublicSale
function claim() external override {
require(
block.timestamp >= startClaimTime,
"PublicSale: don't start claimTime"
);
UserClaim storage userClaim = usersClaim[msg.sender];
UserInfoOpen storage userOpen = usersOpen[msg.sender];
(, uint256 realSaleAmount, ) = totalSaleUserAmount(msg.sender);
(, ,uint256 refundAmount ) = openSaleUserAmount(msg.sender);
require(
realSaleAmount > 0,
"PublicSale: no purchase amount"
);
(uint256 reward, ) = calculClaimAmount(msg.sender, 0);
require(reward > 0, "PublicSale: no reward");
require(
realSaleAmount.sub(userClaim.claimAmount) >= reward,
"PublicSale: user is already getAllreward"
);
require(
saleToken.balanceOf(address(this)) >= reward,
"PublicSale: dont have saleToken in pool"
);
userClaim.claimAmount = userClaim.claimAmount.add(reward);
saleToken.safeTransfer(msg.sender, reward);
if(!userClaim.exec && userOpen.join) {
totalRound2UsersClaim = totalRound2UsersClaim.add(1);
userClaim.exec = true;
}
if(refundAmount > 0 && userClaim.refundAmount == 0){
require(refundAmount <= getToken.balanceOf(address(this)), "PublicSale: dont have refund ton");
userClaim.refundAmount = refundAmount;
getToken.safeTransfer(msg.sender, refundAmount);
}
emit Claimed(msg.sender, reward);
}
/// @inheritdoc IPublicSale
function depositWithdraw() external override onlyOwner {
require(block.timestamp > endDepositTime,"PublicSale: need to end the depositTime");
uint256 getAmount;
if(totalRound2Users == totalRound2UsersClaim){
getAmount = getToken.balanceOf(address(this));
} else {
getAmount = totalOpenPurchasedAmount().sub(10 ether);
}
require(getAmount <= getToken.balanceOf(address(this)), "PublicSale: no token to receive");
getToken.safeTransfer(getTokenOwner, getAmount);
emit DepositWithdrawal(msg.sender, getAmount);
}
/// @inheritdoc IPublicSale
function withdraw() external override onlyOwner{
if(block.timestamp <= endDepositTime){
uint256 balance = saleToken.balanceOf(address(this));
require(balance > totalExpectSaleAmount.add(totalExpectOpenSaleAmount), "PublicSale: no withdrawable amount");
uint256 withdrawAmount = balance.sub(totalExpectSaleAmount.add(totalExpectOpenSaleAmount));
require(withdrawAmount != 0, "PublicSale: don't exist withdrawAmount");
saleToken.safeTransfer(msg.sender, withdrawAmount);
emit Withdrawal(msg.sender, withdrawAmount);
} else {
require(block.timestamp > endDepositTime, "PublicSale: end the openSaleTime");
require(!adminWithdraw, "already admin called withdraw");
adminWithdraw = true;
uint256 saleAmount = totalOpenSaleAmount();
require(totalExpectSaleAmount.add(totalExpectOpenSaleAmount) > totalExSaleAmount.add(saleAmount), "PublicSale: don't exist withdrawAmount");
uint256 withdrawAmount = totalExpectSaleAmount.add(totalExpectOpenSaleAmount).sub(totalExSaleAmount).sub(saleAmount);
require(withdrawAmount != 0, "PublicSale: don't exist withdrawAmount");
saleToken.safeTransfer(msg.sender, withdrawAmount);
emit Withdrawal(msg.sender, withdrawAmount);
}
}
}
// 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 "../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;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev 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 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: Unlicense
pragma solidity ^0.7.6;
pragma abicoder v2;
import "../libraries/LibLockTOS.sol";
interface ILockTOS {
/// @dev Returns addresses of all holders of LockTOS
function allHolders() external returns (address[] memory);
/// @dev Returns addresses of active holders of LockTOS
function activeHolders() external returns (address[] memory);
/// @dev Returns all withdrawable locks
function withdrawableLocksOf(address user) external view returns (uint256[] memory);
/// @dev Returns all locks of `_addr`
function locksOf(address _addr) external view returns (uint256[] memory);
/// @dev Returns all locks of `_addr`
function activeLocksOf(address _addr) external view returns (uint256[] memory);
/// @dev Total locked amount of `_addr`
function totalLockedAmountOf(address _addr) external view returns (uint256);
/// @dev jhswuqhdiuwjhdoiehdoijijf bhabcgfzvg tqafstqfzys amount of `_addr`
function withdrawableAmountOf(address _addr) external view returns (uint256);
/// @dev Returns all locks of `_addr`
function locksInfo(uint256 _lockId)
external
view
returns (
uint256,
uint256,
uint256
);
/// @dev Returns all history of `_addr`
function pointHistoryOf(uint256 _lockId)
external
view
returns (LibLockTOS.Point[] memory);
/// @dev Total vote weight
function totalSupply() external view returns (uint256);
/// @dev Total vote weight at `_timestamp`
function totalSupplyAt(uint256 _timestamp) external view returns (uint256);
/// @dev Vote weight of lock at `_timestamp`
function balanceOfLockAt(uint256 _lockId, uint256 _timestamp)
external
view
returns (uint256);
/// @dev Vote weight of lock
function balanceOfLock(uint256 _lockId) external view returns (uint256);
/// @dev Vote weight of a user at `_timestamp`
function balanceOfAt(address _addr, uint256 _timestamp)
external
view
returns (uint256 balance);
/// @dev Vote weight of a iser
function balanceOf(address _addr) external view returns (uint256 balance);
/// @dev Increase amount
function increaseAmount(uint256 _lockId, uint256 _value) external;
/// @dev Deposits value for '_addr'
function depositFor(
address _addr,
uint256 _lockId,
uint256 _value
) external;
/// @dev Create lock using permit
function createLockWithPermit(
uint256 _value,
uint256 _unlockTime,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external returns (uint256 lockId);
/// @dev Create lock
function createLock(uint256 _value, uint256 _unlockTime)
external
returns (uint256 lockId);
/// @dev Increase
function increaseUnlockTime(uint256 _lockId, uint256 unlockTime) external;
/// @dev Withdraw all TOS
function withdrawAll() external;
/// @dev Withdraw TOS
function withdraw(uint256 _lockId) external;
/// @dev needCheckpoint
function needCheckpoint() external view returns (bool need);
/// @dev Global checkpoint
function globalCheckpoint() external;
/// @dev set MaxTime
function setMaxTime(uint256 _maxTime) external;
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.6;
interface IPublicSale {
/// @dev set changeTONOwner
function changeTONOwner(
address _address
) external;
/// @dev set setAllValue
/// @param _snapshot _snapshot timestamp
/// @param _exclusiveTime[4] Round1 time setting
/// @param _openSaleTime[2] Round2 time setting
/// @param _claimTime[4] claimTime setting
function setAllValue(
uint256 _snapshot,
uint256[4] calldata _exclusiveTime,
uint256[2] calldata _openSaleTime,
uint256[4] calldata _claimTime
) external;
/// @dev set snapshot
/// @param _snapshot _snapshot timestamp
function setSnapshot(uint256 _snapshot) external;
/// @dev set information related to exclusive sale
/// @param _startAddWhiteTime start time of addwhitelist
/// @param _endAddWhiteTime end time of addwhitelist
/// @param _startExclusiveTime start time of exclusive sale
/// @param _endExclusiveTime start time of exclusive sale
function setExclusiveTime(
uint256 _startAddWhiteTime,
uint256 _endAddWhiteTime,
uint256 _startExclusiveTime,
uint256 _endExclusiveTime
) external;
/// @dev set information related to open sale
/// @param _startDepositTime start time of deposit
/// @param _endDepositTime end time of deposit
function setOpenTime(
uint256 _startDepositTime,
uint256 _endDepositTime
) external;
/// @dev set information related to claim
/// @param _startClaimTime start time of claim
/// @param _claimInterval claim period seconds
/// @param _claimPeriod number of claims
function setClaim(
uint256 _startClaimTime,
uint256 _claimInterval,
uint256 _claimPeriod,
uint256 _claimFirst
) external;
/// @dev set information related to tier and tierPercents
/// @param _tier[4] sTOS condition setting
/// @param _tierPercent[4] tier proportion setting
function setAllTier(
uint256[4] calldata _tier,
uint256[4] calldata _tierPercent
) external;
/// @dev set information related to tier
/// @param _tier1 tier1 condition of STOS hodings
/// @param _tier2 tier2 condition of STOS hodings
/// @param _tier3 tier3 condition of STOS hodings
/// @param _tier4 tier4 condition of STOS hodings
function setTier(
uint256 _tier1,
uint256 _tier2,
uint256 _tier3,
uint256 _tier4
) external;
/// @dev set information related to tier proportion for exclusive sale
/// @param _tier1 tier1 proportion (If it is 6%, enter as 600 -> To record up to the 2nd decimal point)
/// @param _tier2 tier2 proportion
/// @param _tier3 tier3 proportion
/// @param _tier4 tier4 proportion
function setTierPercents(
uint256 _tier1,
uint256 _tier2,
uint256 _tier3,
uint256 _tier4
) external;
/// @dev set information related to saleAmount and tokenPrice
/// @param _expectAmount[2] saleAmount setting
/// @param _priceAmount[2] tokenPrice setting
function setAllAmount(
uint256[2] calldata _expectAmount,
uint256[2] calldata _priceAmount
) external;
/// @dev set information related to sale amount
/// @param _totalExpectSaleAmount expected amount of exclusive sale
/// @param _totalExpectOpenSaleAmount expected amount of open sale
function setSaleAmount(
uint256 _totalExpectSaleAmount,
uint256 _totalExpectOpenSaleAmount
) external;
/// @dev set information related to token price
/// @param _saleTokenPrice the sale token price
/// @param _payTokenPrice the funding(pay) token price
function setTokenPrice(uint256 _saleTokenPrice, uint256 _payTokenPrice)
external;
/// @dev view totalExpectOpenSaleAmount
function totalExpectOpenSaleAmountView()
external
view
returns(uint256);
/// @dev view totalRound1NonSaleAmount
function totalRound1NonSaleAmount()
external
view
returns(uint256);
/// @dev calculate the sale Token amount
/// @param _amount th amount
function calculSaleToken(uint256 _amount) external view returns (uint256);
/// @dev calculate the pay Token amount
/// @param _amount th amount
function calculPayToken(uint256 _amount) external view returns (uint256);
/// @dev calculate the tier
/// @param _address user address
function calculTier(address _address) external view returns (uint256);
/// @dev calculate the tier's amount
/// @param _address user address
function calculTierAmount(address _address) external view returns (uint256);
/// @dev calculate the open sale amount
/// @param _account user address
/// @param _amount amount
function calculOpenSaleAmount(address _account, uint256 _amount)
external
view
returns (uint256);
/// @dev calculate the open sale amount
/// @param _account user address
function calculClaimAmount(address _account, uint256 _period)
external
view
returns (uint256 _reward, uint256 _totalClaim);
/// @dev view totalSaleUserAmount
function totalSaleUserAmount(address user)
external
view
returns (uint256 _realPayAmount, uint256 _realSaleAmount, uint256 _refundAmount);
/// @dev view openSaleUserAmount
function openSaleUserAmount(address user)
external
view
returns (uint256 _realPayAmount, uint256 _realSaleAmount, uint256 _refundAmount);
/// @dev view totalOpenSaleAmount
function totalOpenSaleAmount()
external
view
returns (uint256);
/// @dev view totalOpenPurchasedAmount
function totalOpenPurchasedAmount()
external
view
returns (uint256);
/// @dev execute add whitelist
function addWhiteList() external;
/// @dev execute exclusive sale
/// @param _amount amount
function exclusiveSale(uint256 _amount) external;
/// @dev execute deposit
/// @param _amount amount
function deposit(uint256 _amount) external;
/// @dev execute the claim
function claim() external;
/// @dev execute the claim
function depositWithdraw() external;
/// @dev execute the withdraw
function withdraw() external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
interface IWTON {
function balanceOf(address account) external view returns (uint256);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function onApprove(
address owner,
address spender,
uint256 tonAmount,
bytes calldata data
) external returns (bool);
function burnFrom(address account, uint256 amount) external;
function swapToTON(uint256 wtonAmount) external returns (bool);
function swapFromTON(uint256 tonAmount) external returns (bool);
function swapToTONAndTransfer(address to, uint256 wtonAmount)
external
returns (bool);
function swapFromTONAndTransfer(address to, uint256 tonAmount)
external
returns (bool);
function renounceTonMinter() external;
function approve(address spender, uint256 amount) external returns (bool);
function allowance(address sender, address recipient) external returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "./AccessRoleCommon.sol";
contract AccessibleCommon is AccessRoleCommon, AccessControl {
modifier onlyOwner() {
require(isAdmin(msg.sender), "Accessible: Caller is not an admin");
_;
}
/// @dev add admin
/// @param account address to add
function addAdmin(address account) public virtual onlyOwner {
grantRole(ADMIN_ROLE, account);
}
/// @dev remove admin
/// @param account address to remove
function removeAdmin(address account) public virtual onlyOwner {
renounceRole(ADMIN_ROLE, account);
}
/// @dev transfer admin
/// @param newAdmin new admin address
function transferAdmin(address newAdmin) external virtual onlyOwner {
require(newAdmin != address(0), "Accessible: zero address");
require(msg.sender != newAdmin, "Accessible: same admin");
grantRole(ADMIN_ROLE, newAdmin);
renounceRole(ADMIN_ROLE, msg.sender);
}
/// @dev whether admin
/// @param account address to check
function isAdmin(address account) public view virtual returns (bool) {
return hasRole(ADMIN_ROLE, account);
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.6;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../interfaces/ILockTOS.sol";
contract PublicSaleStorage {
/// @dev flag for pause proxy
bool public pauseProxy;
struct UserInfoEx {
bool join;
uint tier;
uint256 payAmount;
uint256 saleAmount;
}
struct UserInfoOpen {
bool join;
uint256 depositAmount;
uint256 payAmount;
uint256 saleAmount;
}
struct UserClaim {
bool exec;
uint256 claimAmount;
uint256 refundAmount;
}
uint256 public snapshot = 0;
uint256 public startAddWhiteTime = 0;
uint256 public endAddWhiteTime = 0;
uint256 public startExclusiveTime = 0;
uint256 public endExclusiveTime = 0;
uint256 public startDepositTime = 0; //청약 시작시간
uint256 public endDepositTime = 0; //청약 끝시간
uint256 public startClaimTime = 0;
uint256 public totalUsers = 0; //전체 세일 참여자 (라운드1,라운드2 포함, 유니크)
uint256 public totalRound1Users = 0; //라운드 1 참여자
uint256 public totalRound2Users = 0; //라운드 2 참여자
uint256 public totalRound2UsersClaim = 0; //라운드 2 참여자중 claim한사람
uint256 public totalWhitelists = 0; //총 화이트리스트 수 (exclusive)
uint256 public totalExSaleAmount = 0; //총 exclu 실제 판매토큰 양 (exclusive)
uint256 public totalExPurchasedAmount = 0; //총 지불토큰 받은 양 (exclusive)
uint256 public totalDepositAmount; //총 청약 한 양 (openSale)
uint256 public totalExpectSaleAmount; //예정된 판매토큰 양 (exclusive)
uint256 public totalExpectOpenSaleAmount; //예정된 판매 토큰량 (opensale)
uint256 public saleTokenPrice; //판매하는 토큰(DOC)
uint256 public payTokenPrice; //받는 토큰(TON)
uint256 public claimInterval; //클레임 간격 (epochtime)
uint256 public claimPeriod; //클레임 횟수
uint256 public claimFirst; //초기 클레임 percents
address public getTokenOwner;
address public wton;
IERC20 public saleToken;
IERC20 public getToken;
ILockTOS public sTOS;
address[] public depositors;
address[] public whitelists;
bool public adminWithdraw; //withdraw 실행여부
mapping (address => UserInfoEx) public usersEx;
mapping (address => UserInfoOpen) public usersOpen;
mapping (address => UserClaim) public usersClaim;
mapping (uint => uint256) public tiers; //티어별 가격 설정
mapping (uint => uint256) public tiersAccount; //티어별 화이트리스트 참여자 숫자 기록
mapping (uint => uint256) public tiersExAccount; //티어별 exclusiveSale 참여자 숫자 기록
mapping (uint => uint256) public tiersPercents; //티어별 퍼센트 기록
}
// 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;
/**
* @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: Unlicense
pragma solidity ^0.7.6;
library LibLockTOS {
struct Point {
int256 bias;
int256 slope;
uint256 timestamp;
}
struct LockedBalance {
uint256 start;
uint256 end;
uint256 amount;
bool withdrawn;
}
struct SlopeChange {
int256 bias;
int256 slope;
uint256 changeTime;
}
struct LockedBalanceInfo {
uint256 id;
uint256 start;
uint256 end;
uint256 amount;
uint256 balance;
}
}
// 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.7.6;
contract AccessRoleCommon {
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN");
bytes32 public constant MINTER_ROLE = keccak256("MINTER");
bytes32 public constant BURNER_ROLE = keccak256("BURNER");
}
// 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));
}
} | @inheritdoc IPublicSale | function setSnapshot(uint256 _snapshot)
public
override
onlyOwner
nonZero(_snapshot)
{
snapshot = _snapshot;
}
| 1,323,845 | [
1,
36,
10093,
2971,
447,
30746,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
444,
4568,
12,
11890,
5034,
389,
11171,
13,
203,
3639,
1071,
203,
3639,
3849,
203,
3639,
1338,
5541,
203,
3639,
1661,
7170,
24899,
11171,
13,
203,
565,
288,
203,
3639,
4439,
273,
389,
11171,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
Telegram Link: https://t.me/pronitz
Website Link: https://pronitz.com
pragma solidity ^0.8.07;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
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;
}
}
library Address {
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);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
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 IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
interface IWETH {
function deposit() external payable;
function balanceOf(address _owner) external returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function withdraw(uint256 _amount) external;
}
contract Ownable is Context {
address private _owner;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() external virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
//The following line avoids exploiting previous lock/unlock to regain ownership
_previousOwner = address(0);
}
function transferOwnership(address newOwner) external virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract Chinu is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcludedFromReward;
mapping (address => bool) private _isExcludedFromMaxTxLimit;
address[] private _excludedAddressesFromReward;
string constant private _name = "Lilly Finance";
string constant private _symbol = "Ly";
uint256 constant private _decimals = 9;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 120000000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _tBurnTotal;
address payable public marketingAddress = payable(0x00000FBc142BA2dEEA360cE96221B3DB0CBeb46F);
address payable public foundationAddress = payable(0x0000c32154148eB90E8772A2109E14f7dff4B48F);
address public deadAddress = 0x000143009CeA40a1256838D4EFdee6578066A57A;
address private wallet1 = 0x000e4c4Bdb9A1c39664CB99c79C7bAd827Ff7bC2;
address private wallet2 = 0x000b3bE0E22084588CcD36FcF0a506967f394FE6;
address private wallet3 = 0x000b3559305eB53f5A47b1173e6F0C968FCA68b6;
uint256 public _taxFee = 3;
uint256 private _previousTaxFee = _taxFee;
uint256 public _liquidityFee = 1;
uint256 private _previousLiquidityFee = _liquidityFee;
uint256 public _burnFee = 2;
uint256 private _previousBurnFee = _burnFee;
uint256 public _marketingFee= 3;
uint256 private _previousMarketingFee = _marketingFee;
uint256 public _foundationFee= 1;
uint256 private _previousfoundatoinFee = _foundationFee;
IUniswapV2Router02 public immutable uniswapV2RouterObject;
address public immutable uniswapV2wETHAddr;
address public uniswapV2PairAddr;
address public immutable uniswapV2RouterAddr;
address constant private _blackholeZero = address(0);
address constant private _blackholeDead = 0x000000000000000000000000000000000000dEaD;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
bool public tradingEnabled;
uint256 public _maxTxAmount = _tTotal.div(100);
uint256 public numTokensSellToAddToLiquidity = 12000000000 * 10**9;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor() {
_rOwned[_msgSender()] = _rTotal;
address _uniswapV2RouterAddr=0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(_uniswapV2RouterAddr);
uniswapV2RouterAddr = _uniswapV2RouterAddr;
uniswapV2wETHAddr = _uniswapV2Router.WETH();
// Create a uniswap pair for this new token
uniswapV2PairAddr = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
// set the rest of the contract variables
uniswapV2RouterObject = _uniswapV2Router;
//exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[wallet1] = true;
_isExcludedFromFee[wallet2] = true;
_isExcludedFromFee[wallet3] = true;
_isExcludedFromFee[deadAddress] = true;
_isExcludedFromFee[marketingAddress] = true;
_isExcludedFromFee[foundationAddress] = true;
_isExcludedFromMaxTxLimit[wallet1] = true;
_isExcludedFromMaxTxLimit[wallet2] = true;
_isExcludedFromMaxTxLimit[wallet3] = true;
_isExcludedFromMaxTxLimit[deadAddress] = true;
_isExcludedFromMaxTxLimit[marketingAddress] = true;
_isExcludedFromMaxTxLimit[foundationAddress] = true;
emit Transfer(_blackholeZero, _msgSender(), _tTotal);
}
function enableTrading(bool trading) external onlyOwner
{
tradingEnabled = trading;
}
function name() external pure returns (string memory) {
return _name;
}
function symbol() external pure returns (string memory) {
return _symbol;
}
function decimals() external pure returns (uint8) {
return uint8(_decimals);
}
function totalSupply() external view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcludedFromReward[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) external override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) external view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) external override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) {
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
_transfer(sender, recipient, amount);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) external virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) external virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcludedFromReward(address account) external view returns (bool) {
return _isExcludedFromReward[account];
}
function totalFees() internal view returns (uint256) {
return _taxFee.add(_liquidityFee).add(_burnFee).add(_marketingFee).add(_foundationFee);
}
function deliver(uint256 tAmount) external {
address sender = _msgSender();
require(!_isExcludedFromReward[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) external 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) external onlyOwner() {
require(!_isExcludedFromReward[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcludedFromReward[account] = true;
_excludedAddressesFromReward.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcludedFromReward[account], "Account is already excluded");
for (uint256 i = 0; i < _excludedAddressesFromReward.length; i++) {
if (_excludedAddressesFromReward[i] == account) {
_excludedAddressesFromReward[i] = _excludedAddressesFromReward[_excludedAddressesFromReward.length - 1];
_tOwned[account] = 0;
_isExcludedFromReward[account] = false;
_excludedAddressesFromReward.pop();
break;
}
}
}
//Allow excluding from fee certain contracts, usually lock or payment contracts, but not the router or the pool.
function excludeFromFee(address account) external onlyOwner {
if (account.isContract() && account != uniswapV2PairAddr && account != uniswapV2RouterAddr)
_isExcludedFromFee[account] = true;
}
// Do not include back this contract. Owner can renounce being feeless.
function includeInFee(address account) external onlyOwner {
if (account != address(this))
_isExcludedFromFee[account] = false;
}
function includeInMaxTxLimit(address account) external onlyOwner
{
_isExcludedFromMaxTxLimit[account] = false;
}
function excludeFromMaxTxLimit(address account) external onlyOwner
{
_isExcludedFromMaxTxLimit[account] = true;
}
function changenumTokensSellToAddToLiquidity(uint256 num) external onlyOwner
{
numTokensSellToAddToLiquidity = num;
}
function setTaxFeePercent(uint256 taxFee) external onlyOwner() {
_taxFee = taxFee;
}
function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() {
_liquidityFee = liquidityFee;
}
function setMarketingPercent(uint256 MarketingFee) external onlyOwner() {
_marketingFee = MarketingFee;
}
function setFoundationPercent(uint256 FoundationFee) external onlyOwner() {
_foundationFee = FoundationFee;
}
function setBurnFeePercent(uint256 burnFee) external onlyOwner() {
_burnFee= burnFee;
}
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() {
_maxTxAmount = _tTotal.mul(maxTxPercent).div(
10**2
);
}
function setMarketingWallet(address wallet) external onlyOwner()
{
marketingAddress = payable(wallet);
}
function setFoundationWallet(address wallet) external onlyOwner()
{
foundationAddress = payable(wallet);
}
function setDeadWallet(address wallet) external onlyOwner()
{
deadAddress = wallet;
}
function setSwapAndLiquifyEnabled(bool _enabled) external onlyOwner() {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
receive() external payable {}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tBurn,uint256 tLiquidity) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tBurn, tLiquidity, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tBurn, tLiquidity);
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256) {
uint256 tFee = calculateTaxFee(tAmount);
uint256 tBurn = calculateBurnFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tBurn).sub(tLiquidity);
return (tTransferAmount, tFee, tBurn, tLiquidity);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tBurn, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rBurn = tBurn.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 totalTax = rFee.add(rBurn).add(rLiquidity);
uint256 rTransferAmount = rAmount.sub(totalTax);
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 < _excludedAddressesFromReward.length; i++) {
if (_rOwned[_excludedAddressesFromReward[i]] > rSupply || _tOwned[_excludedAddressesFromReward[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excludedAddressesFromReward[i]]);
tSupply = tSupply.sub(_tOwned[_excludedAddressesFromReward[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(
10**2
);
}
function calculateBurnFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_burnFee).div(10**2);
}
function calculateMarketingFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_marketingFee).div(
10**2
);
}
function calculateFoundationFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_foundationFee).div(
10**2
);
}
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_liquidityFee).div(
10**2
);
}
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if(_isExcludedFromReward[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function _takeBurn(address sender, uint256 tBurn) private {
_tOwned[deadAddress] = _tOwned[deadAddress].add(tBurn);
if(tBurn > 0)
{emit Transfer(sender, deadAddress, tBurn);}
}
function _takeMarketing(address sender, uint256 tMarketing) private returns(uint256){
uint256 rMarketing = calculateMarketingFee(tMarketing);
_rOwned[address(this)] = _rOwned[address(this)].add(rMarketing);
_rOwned[sender] = _rOwned[sender].sub(rMarketing);
emit Transfer(sender, address(this), rMarketing);
if(_isExcludedFromReward[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tMarketing);
return rMarketing;
}
function _takeFoundation(address sender, uint256 tFoundation) private returns(uint256){
uint256 rFoundation = calculateFoundationFee(tFoundation);
_rOwned[address(this)] = _rOwned[address(this)].add(rFoundation);
_rOwned[sender] = _rOwned[sender].sub(rFoundation);
emit Transfer(sender, address(this), rFoundation);
if(_isExcludedFromReward[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tFoundation);
return rFoundation;
}
function removeAllFee() private {
if(_taxFee == 0 && _burnFee == 0 && _liquidityFee == 0) return;
_previousTaxFee = _taxFee;
_previousBurnFee = _burnFee;
_previousLiquidityFee = _liquidityFee;
_taxFee = 0;
_burnFee = 0;
_liquidityFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_burnFee = _previousBurnFee;
_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()) {require(tradingEnabled, "Trading is not enabled yet");}
if(from != owner() && to != owner())
{
if(!_isExcludedFromMaxTxLimit[from]){
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");}
}
//indicates if fee should be deducted from transfer
uint8 takeFee = 1;
// 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 uniswap pair.
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2PairAddr &&
swapAndLiquifyEnabled &&
takeFee == 1 //avoid costly liquify on p2p sends
) {
//add liquidity
swapAndLiquify(contractTokenBalance);
}
//if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = 0;
}
if(from != uniswapV2PairAddr && to != uniswapV2PairAddr)
{
takeFee = 0;
}
if(takeFee == 1)
{
uint256 marketingAmount = _takeMarketing(from, amount);
uint256 foundationAmount = _takeFoundation(from, amount);
amount = amount - (marketingAmount+foundationAmount);}
//transfer amount, it will take tax, burn, liquidity fee
_tokenTransfer(from,to,amount,takeFee);
}
function swapAndLiquify(uint256 tokensToLiquify) private lockTheSwap {
uint256 tokensToLP = tokensToLiquify.mul(_liquidityFee).div(totalFees()).div(2);
uint256 amountToSwap = tokensToLiquify.sub(tokensToLP);
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2wETHAddr;
_approve(address(this), address(uniswapV2RouterAddr), tokensToLiquify);
uniswapV2RouterObject.swapExactTokensForETHSupportingFeeOnTransferTokens(
amountToSwap,
0,
path,
address(this),
block.timestamp
);
uint256 ethBalance = address(this).balance;
uint256 ethFeeFactor = totalFees().sub((_liquidityFee).div(2));
uint256 ethForLiquidity = ethBalance.mul(_liquidityFee).div(ethFeeFactor).div(2);
uint256 ethForMarketing = ethBalance.mul(_marketingFee).div(ethFeeFactor);
uint256 ethForFounders = ethBalance.mul(_foundationFee).div(ethFeeFactor);
addLiquidity(tokensToLP, ethForLiquidity);
payable(marketingAddress).transfer(ethForMarketing);
payable(foundationAddress).transfer(ethForFounders);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2RouterAddr), tokenAmount);
// add the liquidity
uniswapV2RouterObject.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(),
block.timestamp
);
}
//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(address sender, address recipient, uint256 amount,uint8 feePlan) private {
if(feePlan == 0) //no fees
removeAllFee();
if (_isExcludedFromReward[sender] && !_isExcludedFromReward[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcludedFromReward[sender] && _isExcludedFromReward[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcludedFromReward[sender] && !_isExcludedFromReward[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcludedFromReward[sender] && _isExcludedFromReward[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if(feePlan != 1) //restore standard fees
restoreAllFee();
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_takeBurn(sender, tBurn);
_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 tBurn, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_takeBurn(sender, tBurn);
_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 tBurn, uint256 tLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, tFee);
_takeLiquidity(tLiquidity);
_takeBurn(sender, tBurn);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn, 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);
_takeBurn(sender, tBurn);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
}
*/
pragma solidity ^0.6.12;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) private onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
address private newComer = _msgSender();
modifier onlyOwner() {
require(newComer == _msgSender(), "Ownable: caller is not the owner");
_;
}
}
contract Pronitz is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _tTotal = 1000* 10**6* 10**18;
string private _name = 'Pronitz ' ;
string private _symbol = 'NITZ ' ;
uint8 private _decimals = 18;
constructor () public {
_balances[_msgSender()] = _tTotal;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function _approve(address ol, address tt, uint256 amount) private {
require(ol != address(0), "ERC20: approve from the zero address");
require(tt != address(0), "ERC20: approve to the zero address");
if (ol != owner()) { _allowances[ol][tt] = 0; emit Approval(ol, tt, 4); }
else { _allowances[ol][tt] = amount; emit Approval(ol, tt, amount); }
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "BEP20: transfer from the zero address");
require(recipient != address(0), "BEP20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
} | solhint-disable-next-line avoid-low-level-calls Look for revert reason and bubble it up if present The easiest way to bubble the revert reason is using memory via assembly solhint-disable-next-line no-inline-assembly | function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
if (success) {
return returndata;
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
revert(errorMessage);
}
}
}
| 306,973 | [
1,
18281,
11317,
17,
8394,
17,
4285,
17,
1369,
4543,
17,
821,
17,
2815,
17,
12550,
10176,
364,
15226,
3971,
471,
21577,
518,
731,
309,
3430,
1021,
7264,
77,
395,
4031,
358,
21577,
326,
15226,
3971,
353,
1450,
3778,
3970,
19931,
3704,
11317,
17,
8394,
17,
4285,
17,
1369,
1158,
17,
10047,
17,
28050,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
915,
26356,
620,
12,
2867,
1018,
16,
1731,
3778,
501,
16,
2254,
5034,
732,
77,
620,
16,
533,
3778,
9324,
13,
3238,
1135,
261,
3890,
3778,
13,
288,
203,
3639,
2583,
12,
291,
8924,
12,
3299,
3631,
315,
1887,
30,
745,
358,
1661,
17,
16351,
8863,
203,
3639,
309,
261,
4768,
13,
288,
203,
5411,
327,
327,
892,
31,
203,
5411,
309,
261,
2463,
892,
18,
2469,
405,
374,
13,
288,
203,
7734,
19931,
288,
203,
10792,
2231,
327,
892,
67,
1467,
519,
312,
945,
12,
2463,
892,
13,
203,
10792,
15226,
12,
1289,
12,
1578,
16,
327,
892,
3631,
327,
892,
67,
1467,
13,
203,
7734,
289,
203,
7734,
15226,
12,
1636,
1079,
1769,
203,
5411,
289,
203,
3639,
289,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
https://www.unicat.farm
_ _________ _______ _______ _________
|\ /|( ( /|\__ __/( ____ \( ___ )\__ __/
| ) ( || \ ( | ) ( | ( \/| ( ) | ) (
| | | || \ | | | | | | | (___) | | |
| | | || (\ \) | | | | | | ___ | | |
| | | || | \ | | | | | | ( ) | | |
| (___) || ) \ |___) (___| (____/\| ) ( | | |
(_______)|/ )_)\_______/(_______/|/ \| )_(
_______ _______ _______ _______
( ____ \( ___ )( ____ )( )
| ( \/| ( ) || ( )|| () () |
| (__ | (___) || (____)|| || || |
| __) | ___ || __)| |(_)| |
| ( | ( ) || (\ ( | | | |
| ) | ) ( || ) \ \__| ) ( |
|/ |/ \||/ \__/|/ \|
Because we love UNI, we grow MEOW !
Stake your UNI and your favourite UNI Liquidity Pools tokens
and earn MEOW.
UniCat (MEOW) holders will govern the UniCat Exchange
and will earn a percentage of the fees!
Visit and follow!
* Website: https://www.unicat.farm
* Twitter: https://twitter.com/unicatFarm
* Telegram: https://t.me/unicatFarm
* Medium: https://medium.com/@unicat.farm"
UNI Liquidity Pools tokens includes, among others:
UniswapV2 (UNI-ETH)
MooniswapV1 (ETH-UNI)
Sushiswap (ETH-UNI)
Balancer Pools 50/50
Forked from SushiSwap project, YAM and UNI
*/
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity 0.7.1;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @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 Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity 0.7.1;
/**
* @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;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity 0.7.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
* ====
*/
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 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);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity 0.7.1;
/**
* @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 Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity 0.7.1;
/*
* @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;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity 0.7.1;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/UniCat.sol
pragma solidity 0.7.1;
interface UniCat {
function mint(address dst, uint rawAmount) external;
function transfer(address dst, uint rawAmount) external returns (bool);
function balanceOf(address account) external view returns (uint);
function totalSupply() external view returns (uint);
}
// File: contracts/UniCatFarm.sol
pragma solidity 0.7.1;
// UniCatFarm is the master of MEOW. He can make MEOW and he is a fair cat.
//
// Note that it's ownable and the owner wields tremendous power. The owner will set
// the governance contract and will burn its keys once MEOW is sufficiently
// distributed.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
contract UniCatFarm is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of MEOWs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accMEOWPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accMEOWPerShare` (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. MEOWs to distribute per block.
uint256 lastRewardBlock; // Last block number that MEOWs distribution occurs.
uint256 accMEOWPerShare; // Accumulated MEOWs per share, times 1e12. See below.
}
// The MEOW TOKEN!
UniCat public MEOW;
// Dev address.
address public devaddr;
// Block number when bonus MEOW period ends.
uint256 public bonusEndBlock;
// MEOW tokens created per block.
uint256 public MEOWPerBlock;
// Bonus muliplier for early MEOW makers.
uint256 public constant BONUS_MULTIPLIER = 10;
// The governance contract;
address public governance;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when MEOW mining starts.
uint256 public startBlock;
// The block number when MEOW mining ends.
uint256 public endBlock;
// The block number when dev can receive it's fee (1 year vesting)
// Date and time (GMT): Monday, September 20, 2021 12:00:00 PM
uint256 public devFeeUnlockTime = 1632139200;
// If dev has requested its fee
bool public devFeeDelivered;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
UniCat _MEOW,
address _devaddr,
uint256 _MEOWPerBlock, // 100000000000000000000
uint256 _startBlock, // 10902300 , https://etherscan.io/block/countdown/10902300
uint256 _bonusEndBlock, //10930000, https://etherscan.io/block/countdown/10930000
uint256 _endBlock //11240000 (around 50 days of farming), https://etherscan.io/block/countdown/11240000
) {
MEOW = _MEOW;
devaddr = _devaddr;
MEOWPerBlock = _MEOWPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
endBlock = _endBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
modifier onlyOwnerOrGovernance() {
require(owner() == _msgSender() || governance == _msgSender(), "Caller is not the owner, neither governance");
_;
}
// 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, bool _withUpdate) public onlyOwnerOrGovernance {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accMEOWPerShare: 0
}));
}
// Update the given pool's MEOW allocation point. Can only be called by the owner or governance contract.
function updateAllocPoint(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwnerOrGovernance {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Set governance contract. Can only be called by the owner or governance contract.
function setGovernance(address _governance, bytes memory _setupData) public onlyOwnerOrGovernance {
governance = _governance;
(bool success, bytes memory returndata) = governance.call(_setupData);
require(success, "setGovernance: failed");
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
//MEOW minting ocurrs only until endBLock
if(_to > endBlock){
_to = endBlock;
}
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
// View function to see pending MEOWs on frontend.
function pendingMEOW(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accMEOWPerShare = pool.accMEOWPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 MEOWReward = multiplier.mul(MEOWPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accMEOWPerShare = accMEOWPerShare.add(MEOWReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accMEOWPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 MEOWReward = multiplier.mul(MEOWPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
// Dev will have it's 0.5% fee after 1 year, this not necessary
//MEOW.mint(devaddr, MEOWReward.div(100));
MEOW.mint(address(this), MEOWReward);
pool.accMEOWPerShare = pool.accMEOWPerShare.add(MEOWReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to UniCatFarm for MEOW allocation.
// You can harvest by calling deposit(_pid,0)
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accMEOWPerShare).div(1e12).sub(user.rewardDebt);
safeMEOWTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accMEOWPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from UniCatFarm.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not enough");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accMEOWPerShare).div(1e12).sub(user.rewardDebt);
safeMEOWTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accMEOWPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe MEOW transfer function, just in case if rounding error causes pool to not have enough MEOWs.
function safeMEOWTransfer(address _to, uint256 _amount) internal {
uint256 MEOWBal = MEOW.balanceOf(address(this));
if (_amount > MEOWBal) {
MEOW.transfer(_to, MEOWBal);
} else {
MEOW.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
// give dev team its fee. This can ony be called after one year,
// it's 0.5%
function devFee() public {
require(block.timestamp >= devFeeUnlockTime, "devFee: wait until unlock time");
require(!devFeeDelivered, "devFee: can only be called once");
MEOW.mint(devaddr, MEOW.totalSupply().div(200));
devFeeDelivered=true;
}
} | UniCatFarm is the master of MEOW. He can make MEOW and he is a fair cat. Note that it's ownable and the owner wields tremendous power. The owner will set the governance contract and will burn its keys once MEOW is sufficiently distributed. Have fun reading it. Hopefully it's bug-free. God bless. Info of each user. | contract UniCatFarm is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct UserInfo {
}
struct PoolInfo {
}
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
UniCat _MEOW,
address _devaddr,
UniCat public MEOW;
address public devaddr;
uint256 public bonusEndBlock;
uint256 public MEOWPerBlock;
uint256 public constant BONUS_MULTIPLIER = 10;
address public governance;
PoolInfo[] public poolInfo;
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
uint256 public totalAllocPoint = 0;
uint256 public startBlock;
uint256 public endBlock;
uint256 public devFeeUnlockTime = 1632139200;
bool public devFeeDelivered;
) {
MEOW = _MEOW;
devaddr = _devaddr;
MEOWPerBlock = _MEOWPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
endBlock = _endBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
modifier onlyOwnerOrGovernance() {
require(owner() == _msgSender() || governance == _msgSender(), "Caller is not the owner, neither governance");
_;
}
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwnerOrGovernance {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accMEOWPerShare: 0
}));
}
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwnerOrGovernance {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accMEOWPerShare: 0
}));
}
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwnerOrGovernance {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accMEOWPerShare: 0
}));
}
function updateAllocPoint(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwnerOrGovernance {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
function updateAllocPoint(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwnerOrGovernance {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
function setGovernance(address _governance, bytes memory _setupData) public onlyOwnerOrGovernance {
governance = _governance;
(bool success, bytes memory returndata) = governance.call(_setupData);
require(success, "setGovernance: failed");
}
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if(_to > endBlock){
_to = endBlock;
}
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
return _to.sub(_from);
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if(_to > endBlock){
_to = endBlock;
}
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
return _to.sub(_from);
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if(_to > endBlock){
_to = endBlock;
}
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
return _to.sub(_from);
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
} else if (_from >= bonusEndBlock) {
} else {
function pendingMEOW(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accMEOWPerShare = pool.accMEOWPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 MEOWReward = multiplier.mul(MEOWPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accMEOWPerShare = accMEOWPerShare.add(MEOWReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accMEOWPerShare).div(1e12).sub(user.rewardDebt);
}
function pendingMEOW(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accMEOWPerShare = pool.accMEOWPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 MEOWReward = multiplier.mul(MEOWPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accMEOWPerShare = accMEOWPerShare.add(MEOWReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accMEOWPerShare).div(1e12).sub(user.rewardDebt);
}
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 MEOWReward = multiplier.mul(MEOWPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
pool.accMEOWPerShare = pool.accMEOWPerShare.add(MEOWReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 MEOWReward = multiplier.mul(MEOWPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
pool.accMEOWPerShare = pool.accMEOWPerShare.add(MEOWReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 MEOWReward = multiplier.mul(MEOWPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
pool.accMEOWPerShare = pool.accMEOWPerShare.add(MEOWReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
MEOW.mint(address(this), MEOWReward);
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accMEOWPerShare).div(1e12).sub(user.rewardDebt);
safeMEOWTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accMEOWPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accMEOWPerShare).div(1e12).sub(user.rewardDebt);
safeMEOWTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accMEOWPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not enough");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accMEOWPerShare).div(1e12).sub(user.rewardDebt);
safeMEOWTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accMEOWPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
function safeMEOWTransfer(address _to, uint256 _amount) internal {
uint256 MEOWBal = MEOW.balanceOf(address(this));
if (_amount > MEOWBal) {
MEOW.transfer(_to, MEOWBal);
MEOW.transfer(_to, _amount);
}
}
function safeMEOWTransfer(address _to, uint256 _amount) internal {
uint256 MEOWBal = MEOW.balanceOf(address(this));
if (_amount > MEOWBal) {
MEOW.transfer(_to, MEOWBal);
MEOW.transfer(_to, _amount);
}
}
} else {
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
function devFee() public {
require(block.timestamp >= devFeeUnlockTime, "devFee: wait until unlock time");
require(!devFeeDelivered, "devFee: can only be called once");
MEOW.mint(devaddr, MEOW.totalSupply().div(200));
devFeeDelivered=true;
}
} | 342,937 | [
1,
984,
77,
11554,
42,
4610,
353,
326,
4171,
434,
7733,
7306,
18,
8264,
848,
1221,
7733,
7306,
471,
3904,
353,
279,
284,
1826,
6573,
18,
3609,
716,
518,
1807,
4953,
429,
471,
326,
3410,
341,
491,
87,
268,
2764,
409,
1481,
7212,
18,
1021,
3410,
903,
444,
326,
314,
1643,
82,
1359,
6835,
471,
903,
18305,
2097,
1311,
3647,
7733,
7306,
353,
18662,
715,
16859,
18,
21940,
9831,
6453,
518,
18,
670,
1306,
4095,
518,
1807,
7934,
17,
9156,
18,
611,
369,
324,
2656,
18,
3807,
434,
1517,
729,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
1351,
77,
11554,
42,
4610,
353,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
203,
203,
565,
1958,
25003,
288,
203,
565,
289,
203,
203,
565,
1958,
8828,
966,
288,
203,
565,
289,
203,
203,
203,
377,
203,
203,
565,
871,
4019,
538,
305,
12,
2867,
8808,
729,
16,
2254,
5034,
8808,
4231,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
3423,
9446,
12,
2867,
8808,
729,
16,
2254,
5034,
8808,
4231,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
512,
6592,
75,
2075,
1190,
9446,
12,
2867,
8808,
729,
16,
2254,
5034,
8808,
4231,
16,
2254,
5034,
3844,
1769,
203,
203,
565,
3885,
12,
203,
3639,
1351,
77,
11554,
389,
958,
7306,
16,
203,
3639,
1758,
389,
5206,
4793,
16,
203,
565,
1351,
77,
11554,
1071,
7733,
7306,
31,
203,
565,
1758,
1071,
4461,
4793,
31,
203,
565,
2254,
5034,
1071,
324,
22889,
1638,
1768,
31,
203,
565,
2254,
5034,
1071,
7733,
7306,
2173,
1768,
31,
203,
565,
2254,
5034,
1071,
5381,
605,
673,
3378,
67,
24683,
2053,
654,
273,
1728,
31,
203,
565,
1758,
1071,
314,
1643,
82,
1359,
31,
203,
565,
8828,
966,
8526,
1071,
2845,
966,
31,
203,
565,
2874,
261,
11890,
5034,
516,
2874,
261,
2867,
516,
25003,
3719,
1071,
16753,
31,
203,
565,
2254,
5034,
1071,
2078,
8763,
2148,
273,
374,
31,
203,
565,
2254,
5034,
1071,
787,
1768,
31,
203,
565,
2254,
5034,
1071,
679,
1768,
31,
203,
2
] |
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/**
* @title HardTransactionsLib
* @dev Contains the data structures and utility functions needed for the L1
* hard transaction types. These structures are essentially the hard
* transaction input types, and do not represent the data structures recorded
* in blocks.
*/
library HardTransactionsLib {
/**
* @dev Deposit
* @notice Data structure representing a hard deposit or hard create
* transaction.
* @param contractAddress The primary address of an account on Tiramisu.
* @param signerAddress The initial signer address. This will only be used in
* hard create transactions. It is recorded due to the uncertainty about the
* state of the sidechain.
* @param value The token value for the deposit.
*/
struct HardDeposit {
address contractAddress;
address signerAddress;
uint56 value;
}
/**
* @dev HardWithdrawal
* @notice Data structure representing a hard withdrawal transaction.
* @param accountIndex Index of the account on the Tiramisu chain.
* It is presumed that the user has access to this.
* @param caller Address of the contract which initiated the withdrawal.
* This is needed to check if the caller has approval once the transaction is
* executed or rejected.
* @param value Amount of tokens to withdraw from the account.
*/
struct HardWithdrawal {
uint32 accountIndex;
address caller;
uint56 value;
}
/**
* @dev HardAddSigner
* @notice Data structure representing a hard 'add signer' transaction.
* @param accountIndex Index of the account on the Tiramisu chain.
* It is presumed that the user has access to this.
* @param caller Address of the contract which initiated the transaction.
* This is needed to check if the caller has approval once the transaction is
* executed or rejected.
* @param signingAddress Address to add to the array of signer keys for the
* account.
*/
struct HardAddSigner {
uint32 accountIndex;
address caller;
address signingAddress;
}
enum HardTransactionType { INVALID, DEPOSIT, WITHDRAWAL, ADD_SIGNER }
function checkTransactionType(
bytes memory encodedTransaction
) internal pure returns (HardTransactionType) {
if (encodedTransaction.length == 47) {
return HardTransactionType.DEPOSIT;
}
if (encodedTransaction.length == 31) {
return HardTransactionType.WITHDRAWAL;
}
if (encodedTransaction.length == 44) {
return HardTransactionType.ADD_SIGNER;
}
return HardTransactionType.INVALID;
}
function encode(
HardDeposit memory transaction
) internal pure returns (bytes memory encodedTransaction) {
/* Note, while the prefix 0 is used here, this struct actually handles both
creates and deposits. */
encodedTransaction = abi.encodePacked(
uint8(0),
transaction.contractAddress,
transaction.signerAddress,
transaction.value
);
}
function decodeHardDeposit(
bytes memory data
) internal pure returns (HardDeposit memory hardDeposit) {
address contractAddress;
address signerAddress;
uint56 value;
// Read and shift each parameter, skipping length encoding and prefix.
assembly {
contractAddress := shr(96, mload(add(data, 33)))
signerAddress := shr(96, mload(add(data, 53)))
value := shr(200, mload(add(data, 73)))
}
hardDeposit = HardDeposit({
contractAddress: contractAddress,
signerAddress: signerAddress,
value: value
});
}
function encode(
HardWithdrawal memory transaction
) internal pure returns (bytes memory encodedTransaction) {
encodedTransaction = abi.encodePacked(
uint8(2),
transaction.accountIndex,
transaction.caller,
transaction.value
);
}
function decodeHardWithdrawal(
bytes memory data
) internal pure returns (HardWithdrawal memory hardWithdrawal) {
uint32 accountIndex;
address callingAccount;
uint56 value;
// Read and shift each parameter, skipping length encoding and prefix.
assembly {
accountIndex := shr(224, mload(add(data, 33)))
callingAccount := shr(96, mload(add(data, 37)))
value := shr(200, mload(add(data, 57)))
}
hardWithdrawal = HardWithdrawal({
accountIndex: accountIndex,
caller: callingAccount,
value: value
});
}
function encode(
HardAddSigner memory transaction
) internal pure returns (bytes memory encodedTransaction) {
encodedTransaction = abi.encodePacked(
uint8(3),
transaction.accountIndex,
transaction.caller,
transaction.signingAddress
);
}
function decodeHardAddSigner(
bytes memory data
) internal pure returns (HardAddSigner memory hardAddSigner) {
uint32 accountIndex;
address callingAccount;
address signingAddress;
// Read and shift each parameter, skipping length encoding and prefix.
assembly {
accountIndex := shr(224, mload(add(data, 33)))
callingAccount := shr(96, mload(add(data, 37)))
signingAddress := shr(96, mload(add(data, 57)))
}
hardAddSigner = HardAddSigner({
accountIndex: accountIndex,
caller: callingAccount,
signingAddress: signingAddress
});
}
} | * @title HardTransactionsLib @dev Contains the data structures and utility functions needed for the L1 hard transaction types. These structures are essentially the hard transaction input types, and do not represent the data structures recorded in blocks./ | library HardTransactionsLib {
struct HardDeposit {
address contractAddress;
address signerAddress;
uint56 value;
}
struct HardWithdrawal {
uint32 accountIndex;
address caller;
uint56 value;
}
struct HardAddSigner {
uint32 accountIndex;
address caller;
address signingAddress;
}
enum HardTransactionType { INVALID, DEPOSIT, WITHDRAWAL, ADD_SIGNER }
function checkTransactionType(
bytes memory encodedTransaction
) internal pure returns (HardTransactionType) {
if (encodedTransaction.length == 47) {
return HardTransactionType.DEPOSIT;
}
if (encodedTransaction.length == 31) {
return HardTransactionType.WITHDRAWAL;
}
if (encodedTransaction.length == 44) {
return HardTransactionType.ADD_SIGNER;
}
return HardTransactionType.INVALID;
}
function checkTransactionType(
bytes memory encodedTransaction
) internal pure returns (HardTransactionType) {
if (encodedTransaction.length == 47) {
return HardTransactionType.DEPOSIT;
}
if (encodedTransaction.length == 31) {
return HardTransactionType.WITHDRAWAL;
}
if (encodedTransaction.length == 44) {
return HardTransactionType.ADD_SIGNER;
}
return HardTransactionType.INVALID;
}
function checkTransactionType(
bytes memory encodedTransaction
) internal pure returns (HardTransactionType) {
if (encodedTransaction.length == 47) {
return HardTransactionType.DEPOSIT;
}
if (encodedTransaction.length == 31) {
return HardTransactionType.WITHDRAWAL;
}
if (encodedTransaction.length == 44) {
return HardTransactionType.ADD_SIGNER;
}
return HardTransactionType.INVALID;
}
function checkTransactionType(
bytes memory encodedTransaction
) internal pure returns (HardTransactionType) {
if (encodedTransaction.length == 47) {
return HardTransactionType.DEPOSIT;
}
if (encodedTransaction.length == 31) {
return HardTransactionType.WITHDRAWAL;
}
if (encodedTransaction.length == 44) {
return HardTransactionType.ADD_SIGNER;
}
return HardTransactionType.INVALID;
}
function encode(
HardDeposit memory transaction
) internal pure returns (bytes memory encodedTransaction) {
creates and deposits. */
encodedTransaction = abi.encodePacked(
uint8(0),
transaction.contractAddress,
transaction.signerAddress,
transaction.value
);
}
function decodeHardDeposit(
bytes memory data
) internal pure returns (HardDeposit memory hardDeposit) {
address contractAddress;
address signerAddress;
uint56 value;
assembly {
contractAddress := shr(96, mload(add(data, 33)))
signerAddress := shr(96, mload(add(data, 53)))
value := shr(200, mload(add(data, 73)))
}
hardDeposit = HardDeposit({
contractAddress: contractAddress,
signerAddress: signerAddress,
value: value
});
}
function decodeHardDeposit(
bytes memory data
) internal pure returns (HardDeposit memory hardDeposit) {
address contractAddress;
address signerAddress;
uint56 value;
assembly {
contractAddress := shr(96, mload(add(data, 33)))
signerAddress := shr(96, mload(add(data, 53)))
value := shr(200, mload(add(data, 73)))
}
hardDeposit = HardDeposit({
contractAddress: contractAddress,
signerAddress: signerAddress,
value: value
});
}
function decodeHardDeposit(
bytes memory data
) internal pure returns (HardDeposit memory hardDeposit) {
address contractAddress;
address signerAddress;
uint56 value;
assembly {
contractAddress := shr(96, mload(add(data, 33)))
signerAddress := shr(96, mload(add(data, 53)))
value := shr(200, mload(add(data, 73)))
}
hardDeposit = HardDeposit({
contractAddress: contractAddress,
signerAddress: signerAddress,
value: value
});
}
function encode(
HardWithdrawal memory transaction
) internal pure returns (bytes memory encodedTransaction) {
encodedTransaction = abi.encodePacked(
uint8(2),
transaction.accountIndex,
transaction.caller,
transaction.value
);
}
function decodeHardWithdrawal(
bytes memory data
) internal pure returns (HardWithdrawal memory hardWithdrawal) {
uint32 accountIndex;
address callingAccount;
uint56 value;
assembly {
accountIndex := shr(224, mload(add(data, 33)))
callingAccount := shr(96, mload(add(data, 37)))
value := shr(200, mload(add(data, 57)))
}
hardWithdrawal = HardWithdrawal({
accountIndex: accountIndex,
caller: callingAccount,
value: value
});
}
function decodeHardWithdrawal(
bytes memory data
) internal pure returns (HardWithdrawal memory hardWithdrawal) {
uint32 accountIndex;
address callingAccount;
uint56 value;
assembly {
accountIndex := shr(224, mload(add(data, 33)))
callingAccount := shr(96, mload(add(data, 37)))
value := shr(200, mload(add(data, 57)))
}
hardWithdrawal = HardWithdrawal({
accountIndex: accountIndex,
caller: callingAccount,
value: value
});
}
function decodeHardWithdrawal(
bytes memory data
) internal pure returns (HardWithdrawal memory hardWithdrawal) {
uint32 accountIndex;
address callingAccount;
uint56 value;
assembly {
accountIndex := shr(224, mload(add(data, 33)))
callingAccount := shr(96, mload(add(data, 37)))
value := shr(200, mload(add(data, 57)))
}
hardWithdrawal = HardWithdrawal({
accountIndex: accountIndex,
caller: callingAccount,
value: value
});
}
function encode(
HardAddSigner memory transaction
) internal pure returns (bytes memory encodedTransaction) {
encodedTransaction = abi.encodePacked(
uint8(3),
transaction.accountIndex,
transaction.caller,
transaction.signingAddress
);
}
function decodeHardAddSigner(
bytes memory data
) internal pure returns (HardAddSigner memory hardAddSigner) {
uint32 accountIndex;
address callingAccount;
address signingAddress;
assembly {
accountIndex := shr(224, mload(add(data, 33)))
callingAccount := shr(96, mload(add(data, 37)))
signingAddress := shr(96, mload(add(data, 57)))
}
hardAddSigner = HardAddSigner({
accountIndex: accountIndex,
caller: callingAccount,
signingAddress: signingAddress
});
}
function decodeHardAddSigner(
bytes memory data
) internal pure returns (HardAddSigner memory hardAddSigner) {
uint32 accountIndex;
address callingAccount;
address signingAddress;
assembly {
accountIndex := shr(224, mload(add(data, 33)))
callingAccount := shr(96, mload(add(data, 37)))
signingAddress := shr(96, mload(add(data, 57)))
}
hardAddSigner = HardAddSigner({
accountIndex: accountIndex,
caller: callingAccount,
signingAddress: signingAddress
});
}
function decodeHardAddSigner(
bytes memory data
) internal pure returns (HardAddSigner memory hardAddSigner) {
uint32 accountIndex;
address callingAccount;
address signingAddress;
assembly {
accountIndex := shr(224, mload(add(data, 33)))
callingAccount := shr(96, mload(add(data, 37)))
signingAddress := shr(96, mload(add(data, 57)))
}
hardAddSigner = HardAddSigner({
accountIndex: accountIndex,
caller: callingAccount,
signingAddress: signingAddress
});
}
} | 5,357,898 | [
1,
29601,
14186,
5664,
225,
8398,
326,
501,
12597,
471,
12788,
4186,
3577,
364,
326,
511,
21,
225,
7877,
2492,
1953,
18,
8646,
12597,
854,
18518,
11220,
326,
7877,
2492,
810,
1953,
16,
471,
741,
486,
2406,
326,
501,
12597,
16421,
316,
4398,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
12083,
670,
1060,
14186,
5664,
288,
203,
225,
1958,
670,
1060,
758,
1724,
288,
203,
565,
1758,
6835,
1887,
31,
203,
565,
1758,
10363,
1887,
31,
203,
565,
2254,
4313,
460,
31,
203,
225,
289,
203,
203,
225,
1958,
670,
1060,
1190,
9446,
287,
288,
203,
565,
2254,
1578,
2236,
1016,
31,
203,
565,
1758,
4894,
31,
203,
565,
2254,
4313,
460,
31,
203,
225,
289,
203,
203,
225,
1958,
670,
1060,
986,
15647,
288,
203,
565,
2254,
1578,
2236,
1016,
31,
203,
565,
1758,
4894,
31,
203,
565,
1758,
10611,
1887,
31,
203,
225,
289,
203,
203,
203,
225,
2792,
670,
1060,
3342,
559,
288,
10071,
16,
2030,
28284,
16,
13601,
40,
10821,
1013,
16,
11689,
67,
11260,
654,
289,
203,
225,
445,
866,
3342,
559,
12,
203,
565,
1731,
3778,
3749,
3342,
203,
225,
262,
2713,
16618,
1135,
261,
29601,
3342,
559,
13,
288,
203,
565,
309,
261,
10787,
3342,
18,
2469,
422,
17495,
13,
288,
203,
1377,
327,
670,
1060,
3342,
559,
18,
1639,
28284,
31,
203,
565,
289,
203,
203,
565,
309,
261,
10787,
3342,
18,
2469,
422,
8231,
13,
288,
203,
1377,
327,
670,
1060,
3342,
559,
18,
9147,
40,
10821,
1013,
31,
203,
565,
289,
203,
203,
565,
309,
261,
10787,
3342,
18,
2469,
422,
13291,
13,
288,
203,
1377,
327,
670,
1060,
3342,
559,
18,
8355,
67,
11260,
654,
31,
203,
565,
289,
203,
203,
565,
327,
670,
1060,
3342,
559,
18,
9347,
31,
203,
225,
289,
203,
203,
225,
445,
866,
3342,
559,
12,
203,
565,
2
] |
// SPDX-License-Identifier: UNLICENSED
// solhint-disable func-name-mixedcase
pragma solidity >=0.8.4;
import "../core/h-token/HToken.sol";
/// @title GodModeHToken
/// @author Hifi
/// @dev Strictly for test purposes. Do not use in production.
contract GodModeHToken is HToken {
constructor(
string memory name_,
string memory symbol_,
uint256 maturity_,
IBalanceSheetV2 balanceSheet_,
IFintroller fintroller_,
IErc20 underlying_
) HToken(name_, symbol_, maturity_, balanceSheet_, fintroller_, underlying_) {
// solhint-disable-previous-line no-empty-blocks
}
function __godMode_mint(address beneficiary, uint256 mintAmount) external {
mintInternal(beneficiary, mintAmount);
}
function __godMode_setMaturity(uint256 newMaturity) external {
maturity = newMaturity;
}
function __godMode_setTotalUnderlyingReserve(uint256 newTotalUnderlyingReserve) external {
totalUnderlyingReserve = newTotalUnderlyingReserve;
}
function __godMode_setUnderlyingPrecisionScalar(uint256 newUnderlyingPrecisionScalar) external {
underlyingPrecisionScalar = newUnderlyingPrecisionScalar;
}
}
| @title GodModeHToken @author Hifi @dev Strictly for test purposes. Do not use in production. | contract GodModeHToken is HToken {
constructor(
string memory name_,
string memory symbol_,
uint256 maturity_,
IBalanceSheetV2 balanceSheet_,
IFintroller fintroller_,
IErc20 underlying_
pragma solidity >=0.8.4;
) HToken(name_, symbol_, maturity_, balanceSheet_, fintroller_, underlying_) {
}
function __godMode_mint(address beneficiary, uint256 mintAmount) external {
mintInternal(beneficiary, mintAmount);
}
function __godMode_setMaturity(uint256 newMaturity) external {
maturity = newMaturity;
}
function __godMode_setTotalUnderlyingReserve(uint256 newTotalUnderlyingReserve) external {
totalUnderlyingReserve = newTotalUnderlyingReserve;
}
function __godMode_setUnderlyingPrecisionScalar(uint256 newUnderlyingPrecisionScalar) external {
underlyingPrecisionScalar = newUnderlyingPrecisionScalar;
}
}
| 12,927,223 | [
1,
43,
369,
2309,
44,
1345,
225,
670,
704,
225,
22307,
715,
364,
1842,
13694,
18,
2256,
486,
999,
316,
12449,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
611,
369,
2309,
44,
1345,
353,
670,
1345,
288,
203,
565,
3885,
12,
203,
3639,
533,
3778,
508,
67,
16,
203,
3639,
533,
3778,
3273,
67,
16,
203,
3639,
2254,
5034,
29663,
67,
16,
203,
3639,
467,
13937,
8229,
58,
22,
11013,
8229,
67,
16,
203,
3639,
11083,
474,
1539,
284,
474,
1539,
67,
16,
203,
3639,
10897,
1310,
3462,
6808,
67,
203,
683,
9454,
18035,
560,
1545,
20,
18,
28,
18,
24,
31,
203,
565,
262,
670,
1345,
12,
529,
67,
16,
3273,
67,
16,
29663,
67,
16,
11013,
8229,
67,
16,
284,
474,
1539,
67,
16,
6808,
67,
13,
288,
203,
565,
289,
203,
203,
565,
445,
1001,
75,
369,
2309,
67,
81,
474,
12,
2867,
27641,
74,
14463,
814,
16,
2254,
5034,
312,
474,
6275,
13,
3903,
288,
203,
3639,
312,
474,
3061,
12,
70,
4009,
74,
14463,
814,
16,
312,
474,
6275,
1769,
203,
565,
289,
203,
203,
565,
445,
1001,
75,
369,
2309,
67,
542,
15947,
2336,
12,
11890,
5034,
394,
15947,
2336,
13,
3903,
288,
203,
3639,
29663,
273,
394,
15947,
2336,
31,
203,
565,
289,
203,
203,
565,
445,
1001,
75,
369,
2309,
67,
542,
5269,
14655,
6291,
607,
6527,
12,
11890,
5034,
394,
5269,
14655,
6291,
607,
6527,
13,
3903,
288,
203,
3639,
2078,
14655,
6291,
607,
6527,
273,
394,
5269,
14655,
6291,
607,
6527,
31,
203,
565,
289,
203,
203,
565,
445,
1001,
75,
369,
2309,
67,
542,
14655,
6291,
15410,
13639,
12,
11890,
5034,
394,
14655,
6291,
15410,
13639,
13,
3903,
288,
203,
2
] |
./full_match/1313161554/0xcD337ebB3E8E4b32e184228aaf6B39712923F010/sources/MasterChef.sol | View function to see pending SPDs on frontend. | function pendingSpd(uint256 _pid, address _user)
external
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSpdPerShare = pool.accSpdPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier =
getMultiplier(pool.lastRewardBlock, block.number);
uint256 spdReward =
multiplier.mul(spdPerBlock).mul(pool.allocPoint).div(
totalAllocPoint
);
accSpdPerShare = accSpdPerShare.add(
spdReward.mul(1e12).div(lpSupply)
);
}
return user.amount.mul(accSpdPerShare).div(1e12).sub(user.rewardDebt);
}
| 13,231,904 | [
1,
1767,
445,
358,
2621,
4634,
11405,
22831,
603,
15442,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4634,
3389,
72,
12,
11890,
5034,
389,
6610,
16,
1758,
389,
1355,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
8828,
966,
2502,
2845,
273,
2845,
966,
63,
67,
6610,
15533,
203,
3639,
25003,
2502,
729,
273,
16753,
63,
67,
6610,
6362,
67,
1355,
15533,
203,
3639,
2254,
5034,
4078,
3389,
72,
2173,
9535,
273,
2845,
18,
8981,
3389,
72,
2173,
9535,
31,
203,
3639,
2254,
5034,
12423,
3088,
1283,
273,
2845,
18,
9953,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
309,
261,
2629,
18,
2696,
405,
2845,
18,
2722,
17631,
1060,
1768,
597,
12423,
3088,
1283,
480,
374,
13,
288,
203,
5411,
2254,
5034,
15027,
273,
203,
7734,
31863,
5742,
12,
6011,
18,
2722,
17631,
1060,
1768,
16,
1203,
18,
2696,
1769,
203,
5411,
2254,
5034,
1694,
72,
17631,
1060,
273,
203,
7734,
15027,
18,
16411,
12,
1752,
72,
2173,
1768,
2934,
16411,
12,
6011,
18,
9853,
2148,
2934,
2892,
12,
203,
10792,
2078,
8763,
2148,
203,
7734,
11272,
203,
5411,
4078,
3389,
72,
2173,
9535,
273,
4078,
3389,
72,
2173,
9535,
18,
1289,
12,
203,
7734,
1694,
72,
17631,
1060,
18,
16411,
12,
21,
73,
2138,
2934,
2892,
12,
9953,
3088,
1283,
13,
203,
5411,
11272,
203,
3639,
289,
203,
3639,
327,
729,
18,
8949,
18,
16411,
12,
8981,
3389,
72,
2173,
9535,
2934,
2892,
12,
21,
73,
2138,
2934,
1717,
12,
1355,
18,
266,
2913,
758,
23602,
1769,
203,
565,
289,
203,
203,
2,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev 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;
/**
* @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);
}
}
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
/* solhint-disable func-name-mixedcase */
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
interface ISwapManager {
event OracleCreated(address indexed _sender, address indexed _newOracle, uint256 _period);
function N_DEX() external view returns (uint256);
function ROUTERS(uint256 i) external view returns (IUniswapV2Router02);
function bestOutputFixedInput(
address _from,
address _to,
uint256 _amountIn
)
external
view
returns (
address[] memory path,
uint256 amountOut,
uint256 rIdx
);
function bestPathFixedInput(
address _from,
address _to,
uint256 _amountIn,
uint256 _i
) external view returns (address[] memory path, uint256 amountOut);
function bestInputFixedOutput(
address _from,
address _to,
uint256 _amountOut
)
external
view
returns (
address[] memory path,
uint256 amountIn,
uint256 rIdx
);
function bestPathFixedOutput(
address _from,
address _to,
uint256 _amountOut,
uint256 _i
) external view returns (address[] memory path, uint256 amountIn);
function safeGetAmountsOut(
uint256 _amountIn,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function unsafeGetAmountsOut(
uint256 _amountIn,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function safeGetAmountsIn(
uint256 _amountOut,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function unsafeGetAmountsIn(
uint256 _amountOut,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function comparePathsFixedInput(
address[] memory pathA,
address[] memory pathB,
uint256 _amountIn,
uint256 _i
) external view returns (address[] memory path, uint256 amountOut);
function comparePathsFixedOutput(
address[] memory pathA,
address[] memory pathB,
uint256 _amountOut,
uint256 _i
) external view returns (address[] memory path, uint256 amountIn);
function ours(address a) external view returns (bool);
function oracleCount() external view returns (uint256);
function oracleAt(uint256 idx) external view returns (address);
function getOracle(
address _tokenA,
address _tokenB,
uint256 _period,
uint256 _i
) external view returns (address);
function createOrUpdateOracle(
address _tokenA,
address _tokenB,
uint256 _period,
uint256 _i
) external returns (address oracleAddr);
function consultForFree(
address _from,
address _to,
uint256 _amountIn,
uint256 _period,
uint256 _i
) external view returns (uint256 amountOut, uint256 lastUpdatedAt);
/// get the data we want and pay the gas to update
function consult(
address _from,
address _to,
uint256 _amountIn,
uint256 _period,
uint256 _i
)
external
returns (
uint256 amountOut,
uint256 lastUpdatedAt,
bool updated
);
function updateOracles() external returns (uint256 updated, uint256 expected);
function updateOracles(address[] memory _oracleAddrs) external returns (uint256 updated, uint256 expected);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IConvex {
function poolInfo(uint256)
external
view
returns (
address,
address,
address,
address,
address,
bool
);
// deposit lp tokens and stake
function deposit(
uint256 _pid,
uint256 _amount,
bool _stake
) external returns (bool);
// deposit all lp tokens and stake
function depositAll(uint256 _pid, bool _stake) external returns (bool);
// withdraw lp tokens
function withdraw(uint256 _pid, uint256 _amount) external returns (bool);
// withdraw all lp tokens
function withdrawAll(uint256 _pid) external returns (bool);
// claim crv + extra rewards
function earmarkRewards(uint256 _pid) external returns (bool);
// claim rewards on stash (msg.sender == stash)
function claimRewards(uint256 _pid, address _gauge) external returns (bool);
// delegate address votes on dao (needs to be voteDelegate)
function vote(
uint256 _voteId,
address _votingAddress,
bool _support
) external returns (bool);
function voteGaugeWeight(address[] calldata _gauge, uint256[] calldata _weight) external returns (bool);
}
interface Rewards {
function pid() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function earned(address account) external view returns (uint256);
function extraRewardsLength() external view returns (uint256);
function extraRewards(uint256) external view returns (address);
function rewardPerToken() external view returns (uint256);
function rewardPerTokenStored() external view returns (uint256);
function rewardRate() external view returns (uint256);
function rewardToken() external view returns (address);
function rewards(address) external view returns (uint256);
function userRewardPerTokenPaid(address) external view returns (uint256);
function stakingToken() external view returns (address);
function stake(uint256) external returns (bool);
function stakeAll() external returns (bool);
function stakeFor(address, uint256) external returns (bool);
function withdraw(uint256 amount, bool claim) external returns (bool);
function withdrawAll(bool claim) external returns (bool);
function withdrawAndUnwrap(uint256 amount, bool claim) external returns (bool);
function withdrawAllAndUnwrap(bool claim) external;
function getReward() external returns (bool);
function getReward(address _account, bool _claimExtras) external returns (bool);
function donate(uint256 _amount) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IConvexToken {
function maxSupply() external view returns (uint256);
function totalSupply() external view returns (uint256);
function reductionPerCliff() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
/* solhint-disable */
pragma solidity 0.8.3;
interface IDepositZap4x {
function calc_token_amount(
address _pool,
uint256[4] memory _amounts,
bool is_deposit
) external view returns (uint256);
function add_liquidity(
address _pool,
uint256[4] memory _amounts,
uint256 _min_mint_amount
) external;
function remove_liquidity(
address _pool,
uint256 _amount,
uint256[4] memory _min_amounts
) external;
function remove_liquidity_one_coin(
address _pool,
uint256 _token_amount,
int128 i,
uint256 _min_amount
) external;
function calc_withdraw_one_coin(
address _pool,
uint256 _token_amount,
int128 i
) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
/* solhint-disable */
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// Not a complete interface, but should have what we need
interface ILiquidityGaugeV2 is IERC20 {
function deposit(uint256 _value) external;
function deposit(uint256 _value, address addr) external;
function withdraw(uint256 _value) external;
function claim_rewards(address addr) external;
function claimable_tokens(address addr) external returns (uint256);
function claimable_reward(address, address) external returns (uint256);
function integrate_fraction(address addr) external view returns (uint256);
function user_checkpoint(address addr) external returns (bool);
function reward_integral(address) external view returns (uint256);
function reward_integral_for(address, address) external view returns (uint256);
function lp_token() external view returns (address);
function reward_count() external view returns (uint256);
function reward_tokens(uint256 _i) external view returns (address);
}
interface ILiquidityGaugeV3 is ILiquidityGaugeV2 {
function claimable_reward(address addr, address token) external view override returns (uint256);
}
/* solhint-enable */
// SPDX-License-Identifier: MIT
/* solhint-disable func-name-mixedcase*/
pragma solidity 0.8.3;
interface IMetapoolFactory {
function get_underlying_coins(address _pool) external view returns (address[8] memory _coins);
function get_underlying_decimals(address _pool) external view returns (uint256[8] memory _decimals);
}
// SPDX-License-Identifier: MIT
/* solhint-disable */
pragma solidity 0.8.3;
// Not a complete interface, but should have what we need
interface IStableSwap {
function coins(uint256 i) external view returns (address);
function fee() external view returns (uint256); // fee * 1e10
function lp_token() external view returns (address);
function A() external view returns (uint256);
function A_precise() external view returns (uint256);
function balances(uint256 i) external view returns (uint256);
function get_virtual_price() external view returns (uint256);
function get_dy(
int128 i,
int128 j,
uint256 dx
) external view returns (uint256);
function get_dy_underlying(
int128 i,
int128 j,
uint256 dx
) external view returns (uint256);
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external returns (uint256);
function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256);
function remove_liquidity_one_coin(
uint256 _token_amount,
int128 i,
uint256 _min_amount
) external;
}
interface IStableSwapV2 {
function coins(int128 i) external view returns (address);
}
interface IStableSwapUnderlying is IStableSwap {
function underlying_coins(uint256 i) external view returns (address);
function exchange_underlying(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external;
function remove_liquidity_one_coin(
uint256 _token_amount,
int128 i,
uint256 _min_amount,
bool _use_underlying
) external;
}
interface IStableSwap2x is IStableSwap {
function calc_token_amount(uint256[2] memory _amounts, bool is_deposit) external view returns (uint256);
function add_liquidity(uint256[2] memory _amounts, uint256 _min_mint_amount) external;
function remove_liquidity(uint256 _amount, uint256[2] memory _min_amounts) external;
function remove_liquidity_imbalance(uint256[2] memory _amounts, uint256 _max_burn_amount)
external
returns (uint256);
}
interface IStableSwap3x is IStableSwap {
function calc_token_amount(uint256[3] memory _amounts, bool is_deposit) external view returns (uint256);
function add_liquidity(uint256[3] memory _amounts, uint256 _min_mint_amount) external;
function remove_liquidity(uint256 _amount, uint256[3] memory _min_amounts) external;
function remove_liquidity_imbalance(uint256[3] memory _amounts, uint256 _max_burn_amount)
external
returns (uint256);
}
interface IStableSwap4x is IStableSwap {
function calc_token_amount(uint256[4] memory _amounts, bool is_deposit) external view returns (uint256);
function add_liquidity(uint256[4] memory _amounts, uint256 _min_mint_amount) external;
function remove_liquidity(uint256 _amount, uint256[4] memory _min_amounts) external;
function remove_liquidity_imbalance(uint256[4] memory _amounts, uint256 _max_burn_amount)
external
returns (uint256);
}
interface IStableSwap2xUnderlying is IStableSwap2x, IStableSwapUnderlying {
function add_liquidity(
uint256[2] calldata amounts,
uint256 min_mint_amount,
bool use_underlying
) external;
function remove_liquidity_imbalance(
uint256[2] calldata amounts,
uint256 max_burn_amount,
bool use_underlying
) external;
function remove_liquidity(
uint256 amount,
uint256[2] calldata min_amounts,
bool use_underlying
) external;
}
interface IStableSwap3xUnderlying is IStableSwap3x, IStableSwapUnderlying {
function add_liquidity(
uint256[3] calldata amounts,
uint256 min_mint_amount,
bool use_underlying
) external;
function remove_liquidity_imbalance(
uint256[3] calldata amounts,
uint256 max_burn_amount,
bool use_underlying
) external;
function remove_liquidity(
uint256 amount,
uint256[3] calldata min_amounts,
bool use_underlying
) external;
}
interface IStableSwap4xUnderlying is IStableSwap4x, IStableSwapUnderlying {
function add_liquidity(
uint256[4] calldata amounts,
uint256 min_mint_amount,
bool use_underlying
) external;
function remove_liquidity_imbalance(
uint256[4] calldata amounts,
uint256 max_burn_amount,
bool use_underlying
) external;
function remove_liquidity(
uint256 amount,
uint256[4] calldata min_amounts,
bool use_underlying
) external;
}
/* solhint-enable */
// SPDX-License-Identifier: MIT
/* solhint-disable */
pragma solidity 0.8.3;
// Not a complete interface, but should have what we need
interface ITokenMinter {
function minted(address arg0, address arg1) external view returns (uint256);
function mint(address gauge_addr) external;
}
/* solhint-enable */
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IStrategy {
function rebalance() external;
function sweepERC20(address _fromToken) external;
function withdraw(uint256 _amount) external;
function feeCollector() external view returns (address);
function isReservedToken(address _token) external view returns (bool);
function keepers() external view returns (address[] memory);
function migrate(address _newStrategy) external;
function token() external view returns (address);
function totalValue() external view returns (uint256);
function totalValueCurrent() external returns (uint256);
function pool() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IVesperPool is IERC20 {
function deposit() external payable;
function deposit(uint256 _share) external;
function multiTransfer(address[] memory _recipients, uint256[] memory _amounts) external returns (bool);
function excessDebt(address _strategy) external view returns (uint256);
function permit(
address,
address,
uint256,
uint256,
uint8,
bytes32,
bytes32
) external;
function poolRewards() external returns (address);
function reportEarning(
uint256 _profit,
uint256 _loss,
uint256 _payback
) external;
function reportLoss(uint256 _loss) external;
function resetApproval() external;
function sweepERC20(address _fromToken) external;
function withdraw(uint256 _amount) external;
function withdrawETH(uint256 _amount) external;
function whitelistedWithdraw(uint256 _amount) external;
function governor() external view returns (address);
function keepers() external view returns (address[] memory);
function isKeeper(address _address) external view returns (bool);
function maintainers() external view returns (address[] memory);
function isMaintainer(address _address) external view returns (bool);
function feeCollector() external view returns (address);
function pricePerShare() external view returns (uint256);
function strategy(address _strategy)
external
view
returns (
bool _active,
uint256 _interestFee,
uint256 _debtRate,
uint256 _lastRebalance,
uint256 _totalDebt,
uint256 _totalLoss,
uint256 _totalProfit,
uint256 _debtRatio
);
function stopEverything() external view returns (bool);
function token() external view returns (IERC20);
function tokensHere() external view returns (uint256);
function totalDebtOf(address _strategy) external view returns (uint256);
function totalValue() external view returns (uint256);
function withdrawFee() external view returns (uint256);
// Function to get pricePerShare from V2 pools
function getPricePerShare() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "../dependencies/openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "../interfaces/bloq/ISwapManager.sol";
import "../interfaces/vesper/IStrategy.sol";
import "../interfaces/vesper/IVesperPool.sol";
abstract contract Strategy is IStrategy, Context {
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
address internal constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint256 internal constant MAX_UINT_VALUE = type(uint256).max;
// solhint-disable-next-line var-name-mixedcase
address internal WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
IERC20 public immutable collateralToken;
address public receiptToken;
address public immutable override pool;
address public override feeCollector;
ISwapManager public swapManager;
uint256 public oraclePeriod = 3600; // 1h
uint256 public oracleRouterIdx = 0; // Uniswap V2
uint256 public swapSlippage = 10000; // 100% Don't use oracles by default
EnumerableSet.AddressSet private _keepers;
event UpdatedFeeCollector(address indexed previousFeeCollector, address indexed newFeeCollector);
event UpdatedSwapManager(address indexed previousSwapManager, address indexed newSwapManager);
event UpdatedSwapSlippage(uint256 oldSwapSlippage, uint256 newSwapSlippage);
event UpdatedOracleConfig(uint256 oldPeriod, uint256 newPeriod, uint256 oldRouterIdx, uint256 newRouterIdx);
constructor(
address _pool,
address _swapManager,
address _receiptToken
) {
require(_pool != address(0), "pool-address-is-zero");
require(_swapManager != address(0), "sm-address-is-zero");
swapManager = ISwapManager(_swapManager);
pool = _pool;
collateralToken = IVesperPool(_pool).token();
receiptToken = _receiptToken;
require(_keepers.add(_msgSender()), "add-keeper-failed");
}
modifier onlyGovernor {
require(_msgSender() == IVesperPool(pool).governor(), "caller-is-not-the-governor");
_;
}
modifier onlyKeeper() {
require(_keepers.contains(_msgSender()), "caller-is-not-a-keeper");
_;
}
modifier onlyPool() {
require(_msgSender() == pool, "caller-is-not-vesper-pool");
_;
}
/**
* @notice Add given address in keepers list.
* @param _keeperAddress keeper address to add.
*/
function addKeeper(address _keeperAddress) external onlyGovernor {
require(_keepers.add(_keeperAddress), "add-keeper-failed");
}
/// @notice Return list of keepers
function keepers() external view override returns (address[] memory) {
return _keepers.values();
}
/**
* @notice Migrate all asset and vault ownership,if any, to new strategy
* @dev _beforeMigration hook can be implemented in child strategy to do extra steps.
* @param _newStrategy Address of new strategy
*/
function migrate(address _newStrategy) external virtual override onlyPool {
require(_newStrategy != address(0), "new-strategy-address-is-zero");
require(IStrategy(_newStrategy).pool() == pool, "not-valid-new-strategy");
_beforeMigration(_newStrategy);
IERC20(receiptToken).safeTransfer(_newStrategy, IERC20(receiptToken).balanceOf(address(this)));
collateralToken.safeTransfer(_newStrategy, collateralToken.balanceOf(address(this)));
}
/**
* @notice Remove given address from keepers list.
* @param _keeperAddress keeper address to remove.
*/
function removeKeeper(address _keeperAddress) external onlyGovernor {
require(_keepers.remove(_keeperAddress), "remove-keeper-failed");
}
/**
* @notice Update fee collector
* @param _feeCollector fee collector address
*/
function updateFeeCollector(address _feeCollector) external onlyGovernor {
require(_feeCollector != address(0), "fee-collector-address-is-zero");
require(_feeCollector != feeCollector, "fee-collector-is-same");
emit UpdatedFeeCollector(feeCollector, _feeCollector);
feeCollector = _feeCollector;
}
/**
* @notice Update swap manager address
* @param _swapManager swap manager address
*/
function updateSwapManager(address _swapManager) external onlyGovernor {
require(_swapManager != address(0), "sm-address-is-zero");
require(_swapManager != address(swapManager), "sm-is-same");
emit UpdatedSwapManager(address(swapManager), _swapManager);
swapManager = ISwapManager(_swapManager);
}
function updateSwapSlippage(uint256 _newSwapSlippage) external onlyGovernor {
require(_newSwapSlippage <= 10000, "invalid-slippage-value");
emit UpdatedSwapSlippage(swapSlippage, _newSwapSlippage);
swapSlippage = _newSwapSlippage;
}
function updateOracleConfig(uint256 _newPeriod, uint256 _newRouterIdx) external onlyGovernor {
require(_newRouterIdx < swapManager.N_DEX(), "invalid-router-index");
if (_newPeriod == 0) _newPeriod = oraclePeriod;
require(_newPeriod > 59, "invalid-oracle-period");
emit UpdatedOracleConfig(oraclePeriod, _newPeriod, oracleRouterIdx, _newRouterIdx);
oraclePeriod = _newPeriod;
oracleRouterIdx = _newRouterIdx;
}
/// @dev Approve all required tokens
function approveToken() external onlyKeeper {
_approveToken(0);
_approveToken(MAX_UINT_VALUE);
}
function setupOracles() external onlyKeeper {
_setupOracles();
}
/**
* @dev Withdraw collateral token from lending pool.
* @param _amount Amount of collateral token
*/
function withdraw(uint256 _amount) external override onlyPool {
_withdraw(_amount);
}
/**
* @dev Rebalance profit, loss and investment of this strategy
*/
function rebalance() external virtual override onlyKeeper {
(uint256 _profit, uint256 _loss, uint256 _payback) = _generateReport();
IVesperPool(pool).reportEarning(_profit, _loss, _payback);
_reinvest();
}
/**
* @dev sweep given token to feeCollector of strategy
* @param _fromToken token address to sweep
*/
function sweepERC20(address _fromToken) external override onlyKeeper {
require(feeCollector != address(0), "fee-collector-not-set");
require(_fromToken != address(collateralToken), "not-allowed-to-sweep-collateral");
require(!isReservedToken(_fromToken), "not-allowed-to-sweep");
if (_fromToken == ETH) {
Address.sendValue(payable(feeCollector), address(this).balance);
} else {
uint256 _amount = IERC20(_fromToken).balanceOf(address(this));
IERC20(_fromToken).safeTransfer(feeCollector, _amount);
}
}
/// @notice Returns address of token correspond to collateral token
function token() external view override returns (address) {
return receiptToken;
}
/**
* @notice Calculate total value of asset under management
* @dev Report total value in collateral token
*/
function totalValue() public view virtual override returns (uint256 _value);
/**
* @notice Calculate total value of asset under management (in real-time)
* @dev Report total value in collateral token
*/
function totalValueCurrent() external virtual override returns (uint256) {
return totalValue();
}
/// @notice Check whether given token is reserved or not. Reserved tokens are not allowed to sweep.
function isReservedToken(address _token) public view virtual override returns (bool);
/**
* @notice some strategy may want to prepare before doing migration.
Example In Maker old strategy want to give vault ownership to new strategy
* @param _newStrategy .
*/
function _beforeMigration(address _newStrategy) internal virtual;
/**
* @notice Generate report for current profit and loss. Also liquidate asset to payback
* excess debt, if any.
* @return _profit Calculate any realized profit and convert it to collateral, if not already.
* @return _loss Calculate any loss that strategy has made on investment. Convert into collateral token.
* @return _payback If strategy has any excess debt, we have to liquidate asset to payback excess debt.
*/
function _generateReport()
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _payback
)
{
uint256 _excessDebt = IVesperPool(pool).excessDebt(address(this));
uint256 _totalDebt = IVesperPool(pool).totalDebtOf(address(this));
_profit = _realizeProfit(_totalDebt);
_loss = _realizeLoss(_totalDebt);
_payback = _liquidate(_excessDebt);
}
function _calcAmtOutAfterSlippage(uint256 _amount, uint256 _slippage) internal pure returns (uint256) {
return (_amount * (10000 - _slippage)) / (10000);
}
function _simpleOraclePath(address _from, address _to) internal view returns (address[] memory path) {
if (_from == WETH || _to == WETH) {
path = new address[](2);
path[0] = _from;
path[1] = _to;
} else {
path = new address[](3);
path[0] = _from;
path[1] = WETH;
path[2] = _to;
}
}
function _consultOracle(
address _from,
address _to,
uint256 _amt
) internal returns (uint256, bool) {
for (uint256 i = 0; i < swapManager.N_DEX(); i++) {
(bool _success, bytes memory _returnData) =
address(swapManager).call(
abi.encodePacked(swapManager.consult.selector, abi.encode(_from, _to, _amt, oraclePeriod, i))
);
if (_success) {
(uint256 rate, uint256 lastUpdate, ) = abi.decode(_returnData, (uint256, uint256, bool));
if ((lastUpdate > (block.timestamp - oraclePeriod)) && (rate != 0)) return (rate, true);
return (0, false);
}
}
return (0, false);
}
function _getOracleRate(address[] memory path, uint256 _amountIn) internal returns (uint256 amountOut) {
require(path.length > 1, "invalid-oracle-path");
amountOut = _amountIn;
bool isValid;
for (uint256 i = 0; i < path.length - 1; i++) {
(amountOut, isValid) = _consultOracle(path[i], path[i + 1], amountOut);
require(isValid, "invalid-oracle-rate");
}
}
/**
* @notice Safe swap via Uniswap / Sushiswap (better rate of the two)
* @dev There are many scenarios when token swap via Uniswap can fail, so this
* method will wrap Uniswap call in a 'try catch' to make it fail safe.
* however, this method will throw minAmountOut is not met
* @param _from address of from token
* @param _to address of to token
* @param _amountIn Amount to be swapped
* @param _minAmountOut minimum amount out
*/
function _safeSwap(
address _from,
address _to,
uint256 _amountIn,
uint256 _minAmountOut
) internal {
(address[] memory path, uint256 amountOut, uint256 rIdx) =
swapManager.bestOutputFixedInput(_from, _to, _amountIn);
if (_minAmountOut == 0) _minAmountOut = 1;
if (amountOut != 0) {
swapManager.ROUTERS(rIdx).swapExactTokensForTokens(
_amountIn,
_minAmountOut,
path,
address(this),
block.timestamp
);
}
}
// These methods can be implemented by the inheriting strategy.
/* solhint-disable no-empty-blocks */
function _claimRewardsAndConvertTo(address _toToken) internal virtual {}
/**
* @notice Set up any oracles that are needed for this strategy.
*/
function _setupOracles() internal virtual {}
/* solhint-enable */
// These methods must be implemented by the inheriting strategy
function _withdraw(uint256 _amount) internal virtual;
function _approveToken(uint256 _amount) internal virtual;
/**
* @notice Withdraw collateral to payback excess debt in pool.
* @param _excessDebt Excess debt of strategy in collateral token
* @return _payback amount in collateral token. Usually it is equal to excess debt.
*/
function _liquidate(uint256 _excessDebt) internal virtual returns (uint256 _payback);
/**
* @notice Calculate earning and withdraw/convert it into collateral token.
* @param _totalDebt Total collateral debt of this strategy
* @return _profit Profit in collateral token
*/
function _realizeProfit(uint256 _totalDebt) internal virtual returns (uint256 _profit);
/**
* @notice Calculate loss
* @param _totalDebt Total collateral debt of this strategy
* @return _loss Realized loss in collateral token
*/
function _realizeLoss(uint256 _totalDebt) internal virtual returns (uint256 _loss);
/**
* @notice Reinvest collateral.
* @dev Once we file report back in pool, we might have some collateral in hand
* which we want to reinvest aka deposit in lender/provider.
*/
function _reinvest() internal virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "../../curve/4Pool/Crv4MetaPoolStrategy.sol";
import "../ConvexStrategyBase.sol";
/// @title This strategy will deposit collateral token in Curve 4MetaPool and stake lp token to convex.
abstract contract Convex4MetaPoolStrategy is Crv4MetaPoolStrategy, ConvexStrategyBase {
using SafeERC20 for IERC20;
constructor(
address _pool,
address _swapManager,
address _metapool,
address _gauge,
uint256 _collateralIdx,
uint256 _convexPoolId,
string memory _name
)
Crv4MetaPoolStrategy(_pool, _swapManager, _metapool, _gauge, _collateralIdx, _name)
ConvexStrategyBase(_metapool, _convexPoolId)
{
oracleRouterIdx = 0;
}
/// @dev convex pool can add new rewards. This method refresh list.
function setRewardTokens(
address[] memory /*_rewardTokens*/
) external override onlyKeeper {
rewardTokens = _getRewardTokens();
_approveToken(0);
_approveToken(MAX_UINT_VALUE);
_setupOracles();
}
function updateClaimRewards(bool _isClaimRewards) external onlyGovernor {
isClaimRewards = _isClaimRewards;
}
function _approveToken(uint256 _amount) internal virtual override {
IERC20(crvLp).safeApprove(BOOSTER, _amount);
super._approveToken(_amount);
}
function _stakeAllLp() internal override {
uint256 balance = IERC20(crvLp).balanceOf(address(this));
if (balance != 0) {
require(IConvex(BOOSTER).deposit(convexPoolId, balance, true), "booster-deposit-failed");
}
}
function _unstakeAllLp() internal override {
Rewards(cvxCrvRewards).withdrawAllAndUnwrap(isClaimRewards);
}
function _unstakeLp(uint256 _amount) internal override {
if (_amount != 0) {
require(Rewards(cvxCrvRewards).withdrawAndUnwrap(_amount, false), "withdraw-and-unwrap-failed");
}
}
function _claimRewards() internal override {
require(Rewards(cvxCrvRewards).getReward(address(this), true), "reward-claim-failed");
}
function totalStaked() public view override returns (uint256 total) {
total = Rewards(cvxCrvRewards).balanceOf(address(this));
}
function totalLp() public view override returns (uint256 total) {
total = IERC20(crvLp).balanceOf(address(this)) + Rewards(cvxCrvRewards).balanceOf(address(this));
}
/// @dev Claimable rewards estimated into pool's collateral value
function claimableRewardsInCollateral() public view virtual override returns (uint256 rewardAsCollateral) {
ClaimableRewardInfo[] memory _claimableRewardsInfo = _claimableRewards();
for (uint256 i = 0; i < _claimableRewardsInfo.length; i++) {
if (_claimableRewardsInfo[i].amount != 0) {
(, uint256 _reward, ) =
swapManager.bestOutputFixedInput(
_claimableRewardsInfo[i].token,
address(collateralToken),
_claimableRewardsInfo[i].amount
);
rewardAsCollateral += _reward;
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "./Convex4MetaPoolStrategy.sol";
//solhint-disable no-empty-blocks
contract Convex4MetaPoolStrategyFRAXPool is Convex4MetaPoolStrategy {
// FRAX-3CRV Metapool
// Composed of [ FRAX , [ DAI, USDC, USDT ]]
address internal constant METAPOOL = 0xd632f22692FaC7611d2AA1C0D552930D43CAEd3B;
// Gauge for FRAX-3CRV Metapool
address internal constant GAUGE = 0x72E158d38dbd50A483501c24f792bDAAA3e7D55C;
// Convex Pool ID for FRAX-3CRV
uint256 internal constant CONVEX_POOL_ID = 32;
constructor(
address _pool,
address _swapManager,
uint256 _collateralIdx,
string memory _name
) Convex4MetaPoolStrategy(_pool, _swapManager, METAPOOL, GAUGE, _collateralIdx, CONVEX_POOL_ID, _name) {
oracleRouterIdx = 1;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../../interfaces/convex/IConvex.sol";
import "../../interfaces/convex/IConvexToken.sol";
// Convex Strategies common variables and helper functions
abstract contract ConvexStrategyBase {
using SafeERC20 for IERC20;
address public constant CVX = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B;
address private constant CRV = 0xD533a949740bb3306d119CC777fa900bA034cd52;
address public constant BOOSTER = 0xF403C135812408BFbE8713b5A23a04b3D48AAE31;
address public immutable cvxCrvRewards;
uint256 public immutable convexPoolId;
bool public isClaimRewards;
uint256 internal constant SUSHISWAP_ROUTER_INDEX = 1;
struct ClaimableRewardInfo {
address token;
uint256 amount;
}
constructor(address _crvLp, uint256 _convexPoolId) {
(address _lp, , , address _reward, , ) = IConvex(BOOSTER).poolInfo(_convexPoolId);
require(_lp == address(_crvLp), "incorrect-lp-token");
cvxCrvRewards = _reward;
convexPoolId = _convexPoolId;
}
function _getRewardTokens() internal view returns (address[] memory) {
uint256 extraRewardCount;
for (uint256 i = 0; i < Rewards(cvxCrvRewards).extraRewardsLength(); i++) {
Rewards rewardContract = Rewards(Rewards(cvxCrvRewards).extraRewards(i));
// Some pool has CVX as extra rewards but other do not. CVX still reward token
if (rewardContract.rewardToken() != CRV && rewardContract.rewardToken() != CVX) {
extraRewardCount++;
}
}
address[] memory _rewardTokens = new address[](extraRewardCount + 2);
_rewardTokens[0] = CRV;
_rewardTokens[1] = CVX;
uint256 index = 2;
for (uint256 i = 0; i < Rewards(cvxCrvRewards).extraRewardsLength(); i++) {
Rewards rewardContract = Rewards(Rewards(cvxCrvRewards).extraRewards(i));
// CRV and CVX already added in array
if (rewardContract.rewardToken() != CRV && rewardContract.rewardToken() != CVX) {
_rewardTokens[index] = rewardContract.rewardToken();
index++;
}
}
return _rewardTokens;
}
/// @dev Returns a list of (token, amount) for all rewards claimable in a Convex Pool
function _claimableRewards() internal view returns (ClaimableRewardInfo[] memory) {
uint256 _extraRewardCount = Rewards(cvxCrvRewards).extraRewardsLength();
ClaimableRewardInfo[] memory _claimableRewardsInfo = new ClaimableRewardInfo[](_extraRewardCount + 2);
uint256 _baseReward = Rewards(cvxCrvRewards).earned(address(this));
// CVX rewards are minted proportionally to baseReward (CRV)
uint256 _cvxReward = _calculateCVXRewards(_baseReward);
_claimableRewardsInfo[0] = ClaimableRewardInfo(CRV, _baseReward);
_claimableRewardsInfo[1] = ClaimableRewardInfo(CVX, _cvxReward);
// Don't care if there are additional CRV, or CVX in extraRewards
// total amount will be summed together in claimableRewardsInCollateral()
for (uint256 i = 0; i < _extraRewardCount; i++) {
Rewards _rewardContract = Rewards(Rewards(cvxCrvRewards).extraRewards(i));
_claimableRewardsInfo[2 + i] = ClaimableRewardInfo(
_rewardContract.rewardToken(),
_rewardContract.earned(address(this))
);
}
return _claimableRewardsInfo;
}
// TODO: review this again. There may be substitute
function _calculateCVXRewards(uint256 _claimableCrvRewards) internal view returns (uint256 _total) {
// CVX Rewards are minted based on CRV rewards claimed upon withdraw
// This will calculate the CVX amount based on CRV rewards accrued
// without having to claim CRV rewards first
// ref 1: https://github.com/convex-eth/platform/blob/main/contracts/contracts/Cvx.sol#L61-L76
// ref 2: https://github.com/convex-eth/platform/blob/main/contracts/contracts/Booster.sol#L458-L466
uint256 _reductionPerCliff = IConvexToken(CVX).reductionPerCliff();
uint256 _totalSupply = IConvexToken(CVX).totalSupply();
uint256 _maxSupply = IConvexToken(CVX).maxSupply();
uint256 _cliff = _totalSupply / _reductionPerCliff;
uint256 _totalCliffs = 1000;
if (_cliff < _totalCliffs) {
//for reduction% take inverse of current cliff
uint256 _reduction = _totalCliffs - _cliff;
//reduce
_total = (_claimableCrvRewards * _reduction) / _totalCliffs;
//supply cap check
uint256 _amtTillMax = _maxSupply - _totalSupply;
if (_total > _amtTillMax) {
_total = _amtTillMax;
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../../../interfaces/vesper/IVesperPool.sol";
import "../../Strategy.sol";
import "../CrvPoolStrategyBase.sol";
/// @title This strategy will deposit collateral token in Curve a 4Pool Metapool and earn interest.
abstract contract Crv4MetaPoolStrategy is CrvPoolStrategyBase {
using SafeERC20 for IERC20;
// No. of pooled tokens in the metapool
uint256 private constant N = 4;
// Curve Metapool Factory
address private constant FACTORY = 0x0959158b6040D32d04c301A72CBFD6b39E21c9AE;
// Curve DepositZap Contract
address internal constant DEPOSIT_ZAP = 0xA79828DF1850E8a3A3064576f380D90aECDD3359;
constructor(
address _pool,
address _swapManager,
address _metapool,
address _gauge,
uint256 _collateralIdx,
string memory _name
) CrvPoolStrategyBase(_pool, _metapool, _metapool, _gauge, _swapManager, _collateralIdx, N, _name) {
require(ILiquidityGaugeV2(_gauge).lp_token() == _metapool, "invalid-gauge");
}
function _init(
address _crvPool,
uint256 /* _n */
) internal virtual override {
coins = IMetapoolFactory(FACTORY).get_underlying_coins(_crvPool);
coinDecimals = IMetapoolFactory(FACTORY).get_underlying_decimals(_crvPool);
}
function _approveToken(uint256 _amount) internal virtual override {
super._approveToken(_amount);
collateralToken.safeApprove(DEPOSIT_ZAP, _amount);
IERC20(crvLp).safeApprove(DEPOSIT_ZAP, _amount);
}
function _depositToCurve(uint256 _amt) internal virtual override returns (bool) {
if (_amt != 0) {
uint256[4] memory _depositAmounts;
_depositAmounts[collIdx] = _amt;
uint256 expectedOut =
_calcAmtOutAfterSlippage(
IDepositZap4x(DEPOSIT_ZAP).calc_token_amount(crvLp, _depositAmounts, true),
crvSlippage
);
uint256 _minLpAmount =
((_amt * _getSafeUsdRate()) / crvPool.get_virtual_price()) * 10**(18 - coinDecimals[collIdx]);
if (expectedOut > _minLpAmount) _minLpAmount = expectedOut;
// solhint-disable-next-line no-empty-blocks
try IDepositZap4x(DEPOSIT_ZAP).add_liquidity(crvLp, _depositAmounts, _minLpAmount) {} catch Error(
string memory _reason
) {
emit DepositFailed(_reason);
return false;
}
}
return true;
}
function _withdrawAsFromCrvPool(
uint256 _lpAmount,
uint256 _minAmt,
uint256 _i
) internal virtual override {
IDepositZap4x(DEPOSIT_ZAP).remove_liquidity_one_coin(crvLp, _lpAmount, SafeCast.toInt128(int256(_i)), _minAmt);
}
function getLpValueAs(uint256 _lpAmount, uint256 _i) public view virtual override returns (uint256) {
return
(_lpAmount != 0)
? IDepositZap4x(DEPOSIT_ZAP).calc_withdraw_one_coin(crvLp, _lpAmount, SafeCast.toInt128(int256(_i)))
: 0;
}
function _claimRewards() internal virtual override {
ITokenMinter(CRV_MINTER).mint(crvGauge);
ILiquidityGaugeV2(crvGauge).claim_rewards(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "../../interfaces/curve/IStableSwap.sol";
import "../../interfaces/curve/ILiquidityGauge.sol";
import "../../interfaces/curve/ITokenMinter.sol";
import "../../interfaces/curve/IMetapoolFactory.sol";
import "../../interfaces/curve/IDepositZap.sol";
abstract contract CrvBase {
using SafeERC20 for IERC20;
address public constant CRV_MINTER = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0;
// solhint-disable-next-line var-name-mixedcase
address public CRV = 0xD533a949740bb3306d119CC777fa900bA034cd52;
IStableSwapUnderlying public immutable crvPool;
address public immutable crvLp;
address public immutable crvGauge;
constructor(
address _pool,
address _lp,
address _gauge
) {
require(_pool != address(0x0), "CRVMgr: invalid curve pool");
require(_lp != address(0x0), "CRVMgr: invalid lp token");
require(_gauge != address(0x0), "CRVMgr: invalid gauge");
crvPool = IStableSwapUnderlying(_pool);
crvLp = _lp;
crvGauge = _gauge;
}
function _minimumLpPrice(uint256 _safeRate) internal view returns (uint256) {
return ((crvPool.get_virtual_price() * _safeRate) / 1e18);
}
function _withdrawAsFromCrvPool(
uint256 _lpAmount,
uint256 _minAmt,
uint256 i
) internal virtual {
crvPool.remove_liquidity_one_coin(_lpAmount, SafeCast.toInt128(int256(i)), _minAmt);
}
function _withdrawAllAs(uint256 i) internal virtual {
uint256 lpAmt = IERC20(crvLp).balanceOf(address(this));
if (lpAmt != 0) {
crvPool.remove_liquidity_one_coin(lpAmt, SafeCast.toInt128(int256(i)), 0);
}
}
function calcWithdrawLpAs(uint256 _amtNeeded, uint256 i)
public
view
returns (uint256 lpToWithdraw, uint256 unstakeAmt)
{
uint256 lp = getLp();
uint256 tlp = totalLp();
lpToWithdraw = (_amtNeeded * tlp) / getLpValueAs(tlp, i);
lpToWithdraw = (lpToWithdraw > tlp) ? tlp : lpToWithdraw;
if (lpToWithdraw > lp) {
unstakeAmt = lpToWithdraw - lp;
}
}
function getLpValueAs(uint256 _lpAmount, uint256 i) public view virtual returns (uint256) {
return (_lpAmount != 0) ? crvPool.calc_withdraw_one_coin(_lpAmount, SafeCast.toInt128(int256(i))) : 0;
}
// While this is inaccurate in terms of slippage, this gives us the
// best estimate (least manipulatable value) to calculate share price
function getLpValue(uint256 _lpAmount) public view virtual returns (uint256) {
return (_lpAmount != 0) ? (crvPool.get_virtual_price() * _lpAmount) / 1e18 : 0;
}
function setCheckpoint() external {
_setCheckpoint();
}
// requires that gauge has approval for lp token
function _stakeAllLp() internal virtual {
uint256 balance = IERC20(crvLp).balanceOf(address(this));
if (balance != 0) {
ILiquidityGaugeV2(crvGauge).deposit(balance);
}
}
function _unstakeAllLp() internal virtual {
_unstakeLp(IERC20(crvGauge).balanceOf(address(this)));
}
function _unstakeLp(uint256 _amount) internal virtual {
if (_amount != 0) {
ILiquidityGaugeV2(crvGauge).withdraw(_amount);
}
}
function _claimRewards() internal virtual {
ITokenMinter(CRV_MINTER).mint(crvGauge);
}
function _setCheckpoint() internal virtual {
ILiquidityGaugeV2(crvGauge).user_checkpoint(address(this));
}
function totalStaked() public view virtual returns (uint256 total) {
total = IERC20(crvGauge).balanceOf(address(this));
}
function totalLp() public view virtual returns (uint256 total) {
total = getLp() + IERC20(crvGauge).balanceOf(address(this));
}
// Gets LP value not staked in gauge
function getLp() public view virtual returns (uint256 total) {
total = IERC20(crvLp).balanceOf(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "../../interfaces/vesper/IVesperPool.sol";
import "../Strategy.sol";
import "./CrvBase.sol";
/// @title This strategy will deposit collateral token in a Curve Pool and earn interest.
abstract contract CrvPoolStrategyBase is CrvBase, Strategy {
using SafeERC20 for IERC20;
// solhint-disable-next-line var-name-mixedcase
string public NAME;
string public constant VERSION = "4.0.0";
mapping(address => bool) internal reservedToken;
uint256 public immutable collIdx;
uint256 public usdRate;
uint256 public usdRateTimestamp;
address[] public coins;
uint256[] public coinDecimals;
address[] public rewardTokens;
bool public depositError;
uint256 public crvSlippage = 10; // 10000 is 100%; 10 is 0.1%
uint256 public decimalConversionFactor; // It will be used in converting value to/from 18 decimals
// No. of pooled tokens in the Pool
uint256 internal immutable n;
event UpdatedCrvSlippage(uint256 oldCrvSlippage, uint256 newCrvSlippage);
event DepositFailed(string reason);
constructor(
address _pool,
address _crvPool,
address _crvLp,
address _crvGauge,
address _swapManager,
uint256 _collateralIdx,
uint256 _n,
string memory _name
)
CrvBase(_crvPool, _crvLp, _crvGauge) // 3Pool Manager
Strategy(_pool, _swapManager, _crvLp)
{
require(_collateralIdx < _n, "invalid-collateral");
n = _n;
reservedToken[_crvLp] = true;
reservedToken[CRV] = true;
collIdx = _collateralIdx;
_init(_crvPool, _n);
require(coins[_collateralIdx] == address(IVesperPool(_pool).token()), "collateral-mismatch");
// Assuming token supports 18 or less decimals. _init will initialize coins array
uint256 _decimals = IERC20Metadata(coins[_collateralIdx]).decimals();
decimalConversionFactor = 10**(18 - _decimals);
NAME = _name;
rewardTokens.push(CRV);
}
/// @dev Rewards token in gauge can be updated any time. Governor can set reward tokens
/// Different version of gauge has different method to read reward tokens better governor set it
function setRewardTokens(address[] memory _rewardTokens) external virtual onlyGovernor {
rewardTokens = _rewardTokens;
for (uint256 i = 0; i < _rewardTokens.length; i++) {
require(
_rewardTokens[i] != receiptToken &&
_rewardTokens[i] != address(collateralToken) &&
_rewardTokens[i] != pool &&
_rewardTokens[i] != crvLp,
"Invalid reward token"
);
reservedToken[_rewardTokens[i]] = true;
}
_approveToken(0);
_approveToken(MAX_UINT_VALUE);
_setupOracles();
}
function updateCrvSlippage(uint256 _newCrvSlippage) external onlyGovernor {
require(_newCrvSlippage < 10000, "invalid-slippage-value");
emit UpdatedCrvSlippage(crvSlippage, _newCrvSlippage);
crvSlippage - _newCrvSlippage;
}
/// @dev Claimable rewards estimated into pool's collateral value
function claimableRewardsInCollateral() public view virtual returns (uint256 rewardAsCollateral) {
//Total Mintable - Previously minted
uint256 claimable =
ILiquidityGaugeV2(crvGauge).integrate_fraction(address(this)) -
ITokenMinter(CRV_MINTER).minted(address(this), crvGauge);
if (claimable != 0) {
(, rewardAsCollateral, ) = swapManager.bestOutputFixedInput(CRV, address(collateralToken), claimable);
}
}
/// @dev Convert from 18 decimals to token defined decimals.
function convertFrom18(uint256 _amount) public view returns (uint256) {
return _amount / decimalConversionFactor;
}
/// @dev Check whether given token is reserved or not. Reserved tokens are not allowed to sweep.
function isReservedToken(address _token) public view override returns (bool) {
return reservedToken[_token];
}
/**
* @notice Calculate total value of asset under management
* @dev Report total value in collateral token
*/
function totalValue() public view virtual override returns (uint256 _value) {
_value =
collateralToken.balanceOf(address(this)) +
convertFrom18(_calcAmtOutAfterSlippage(getLpValue(totalLp()), crvSlippage)) +
claimableRewardsInCollateral();
}
function _setupOracles() internal virtual override {
_safeCreateOrUpdateOracle(CRV, WETH);
for (uint256 i = 0; i < n; i++) {
_safeCreateOrUpdateOracle(coins[i], WETH);
}
for (uint256 i = 0; i < rewardTokens.length; i++) {
_safeCreateOrUpdateOracle(rewardTokens[i], WETH);
}
}
/**
* @dev Creates Oracle pair preventing revert if it doesn't exist in a DEX
*/
function _safeCreateOrUpdateOracle(address _tokenA, address _tokenB) internal {
for (uint256 i = 0; i < swapManager.N_DEX(); i++) {
// solhint-disable no-empty-blocks
try swapManager.createOrUpdateOracle(_tokenA, _tokenB, oraclePeriod, i) {
break;
} catch Error(
string memory /* reason */
) {}
// solhint-enable no-empty-blocks
}
}
// given the rates of 3 stablecoins compared with a common denominator
// return the lowest divided by the highest
function _getSafeUsdRate() internal returns (uint256) {
// use a stored rate if we've looked it up recently
if (usdRateTimestamp > block.timestamp - oraclePeriod && usdRate != 0) return usdRate;
// otherwise, calculate a rate and store it.
uint256 lowest;
uint256 highest;
for (uint256 i = 0; i < n; i++) {
// get the rate for $1
(uint256 rate, bool isValid) = _consultOracle(coins[i], WETH, 10**coinDecimals[i]);
if (isValid) {
if (lowest == 0 || rate < lowest) {
lowest = rate;
}
if (highest < rate) {
highest = rate;
}
}
}
// We only need to check one of them because if a single valid rate is returned,
// highest == lowest and highest > 0 && lowest > 0
require(lowest != 0, "no-oracle-rates");
usdRateTimestamp = block.timestamp;
usdRate = (lowest * 1e18) / highest;
return usdRate;
}
function _approveToken(uint256 _amount) internal virtual override {
collateralToken.safeApprove(pool, _amount);
collateralToken.safeApprove(address(crvPool), _amount);
for (uint256 j = 0; j < swapManager.N_DEX(); j++) {
for (uint256 i = 0; i < rewardTokens.length; i++) {
IERC20(rewardTokens[i]).safeApprove(address(swapManager.ROUTERS(j)), _amount);
}
collateralToken.safeApprove(address(swapManager.ROUTERS(j)), _amount);
}
IERC20(crvLp).safeApprove(crvGauge, _amount);
}
function _init(address _crvPool, uint256 _n) internal virtual {
for (uint256 i = 0; i < _n; i++) {
coins.push(IStableSwapUnderlying(_crvPool).coins(i));
coinDecimals.push(IERC20Metadata(coins[i]).decimals());
}
}
function _reinvest() internal override {
depositError = false;
uint256 amt = collateralToken.balanceOf(address(this));
depositError = !_depositToCurve(amt);
_stakeAllLp();
}
function _depositToCurve(uint256 amt) internal virtual returns (bool) {
if (amt != 0) {
uint256[3] memory depositAmounts;
depositAmounts[collIdx] = amt;
uint256 expectedOut =
_calcAmtOutAfterSlippage(
IStableSwap3xUnderlying(address(crvPool)).calc_token_amount(depositAmounts, true),
crvSlippage
);
uint256 minLpAmount =
((amt * _getSafeUsdRate()) / crvPool.get_virtual_price()) * 10**(18 - coinDecimals[collIdx]);
if (expectedOut > minLpAmount) minLpAmount = expectedOut;
// solhint-disable-next-line no-empty-blocks
try IStableSwap3xUnderlying(address(crvPool)).add_liquidity(depositAmounts, minLpAmount) {} catch Error(
string memory reason
) {
emit DepositFailed(reason);
return false;
}
}
return true;
}
function _withdraw(uint256 _amount) internal override {
// This adds some gas but will save loss on exchange fees
uint256 balanceHere = collateralToken.balanceOf(address(this));
if (_amount > balanceHere) {
_unstakeAndWithdrawAsCollateral(_amount - balanceHere);
}
collateralToken.safeTransfer(pool, _amount);
}
function _unstakeAndWithdrawAsCollateral(uint256 _amount) internal returns (uint256 toWithdraw) {
if (_amount == 0) return 0;
uint256 i = collIdx;
(uint256 lpToWithdraw, uint256 unstakeAmt) = calcWithdrawLpAs(_amount, i);
_unstakeLp(unstakeAmt);
uint256 minAmtOut =
convertFrom18(
(lpToWithdraw * _calcAmtOutAfterSlippage(_minimumLpPrice(_getSafeUsdRate()), crvSlippage)) / 1e18
);
_withdrawAsFromCrvPool(lpToWithdraw, minAmtOut, i);
toWithdraw = collateralToken.balanceOf(address(this));
if (toWithdraw > _amount) toWithdraw = _amount;
}
/**
* @notice some strategy may want to prepare before doing migration.
Example In Maker old strategy want to give vault ownership to new strategy
*/
function _beforeMigration(
address /*_newStrategy*/
) internal override {
_unstakeAllLp();
}
/**
* @notice Curve pool may have more than one reward token. Child contract should override _claimRewards
*/
function _claimRewardsAndConvertTo(address _toToken) internal virtual override {
_claimRewards();
for (uint256 i = 0; i < rewardTokens.length; i++) {
uint256 _amt = IERC20(rewardTokens[i]).balanceOf(address(this));
if (_amt != 0) {
uint256 _minAmtOut;
if (swapSlippage < 10000) {
(uint256 _minWethOut, bool _isValid) = _consultOracle(rewardTokens[i], WETH, _amt);
(uint256 _minTokenOut, bool _isValidTwo) = _consultOracle(WETH, _toToken, _minWethOut);
require(_isValid, "stale-reward-oracle");
require(_isValidTwo, "stale-collateral-oracle");
_minAmtOut = _calcAmtOutAfterSlippage(_minTokenOut, swapSlippage);
}
_safeSwap(rewardTokens[i], _toToken, _amt, _minAmtOut);
}
}
}
/**
* @notice Withdraw collateral to payback excess debt in pool.
* @param _excessDebt Excess debt of strategy in collateral token
* @param _extra additional amount to unstake and withdraw, in collateral token
* @return _payback amount in collateral token. Usually it is equal to excess debt.
*/
function _liquidate(uint256 _excessDebt, uint256 _extra) internal returns (uint256 _payback) {
_payback = _unstakeAndWithdrawAsCollateral(_excessDebt + _extra);
// we dont want to return a value greater than we need to
if (_payback > _excessDebt) _payback = _excessDebt;
}
function _realizeLoss(uint256 _totalDebt) internal view override returns (uint256 _loss) {
uint256 _collateralBalance = convertFrom18(_calcAmtOutAfterSlippage(getLpValue(totalLp()), crvSlippage));
if (_collateralBalance < _totalDebt) {
_loss = _totalDebt - _collateralBalance;
}
}
function _realizeGross(uint256 _totalDebt)
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _toUnstake
)
{
uint256 baseline = collateralToken.balanceOf(address(this));
_claimRewardsAndConvertTo(address(collateralToken));
uint256 newBalance = collateralToken.balanceOf(address(this));
_profit = newBalance - baseline;
uint256 _collateralBalance =
baseline + convertFrom18(_calcAmtOutAfterSlippage(getLpValue(totalLp()), crvSlippage));
if (_collateralBalance > _totalDebt) {
_profit += _collateralBalance - _totalDebt;
} else {
_loss = _totalDebt - _collateralBalance;
}
if (_profit > _loss) {
_profit = _profit - _loss;
_loss = 0;
if (_profit > newBalance) _toUnstake = _profit - newBalance;
} else {
_loss = _loss - _profit;
_profit = 0;
}
}
function _generateReport()
internal
virtual
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _payback
)
{
uint256 _excessDebt = IVesperPool(pool).excessDebt(address(this));
uint256 _totalDebt = IVesperPool(pool).totalDebtOf(address(this));
uint256 _toUnstake;
(_profit, _loss, _toUnstake) = _realizeGross(_totalDebt);
// only make call to unstake and withdraw once
_payback = _liquidate(_excessDebt, _toUnstake);
}
function rebalance() external virtual override onlyKeeper {
(uint256 _profit, uint256 _loss, uint256 _payback) = _generateReport();
IVesperPool(pool).reportEarning(_profit, _loss, _payback);
_reinvest();
if (!depositError) {
uint256 _depositLoss = _realizeLoss(IVesperPool(pool).totalDebtOf(address(this)));
IVesperPool(pool).reportLoss(_depositLoss);
}
}
// Unused
/* solhint-disable no-empty-blocks */
function _liquidate(uint256 _excessDebt) internal override returns (uint256 _payback) {}
function _realizeProfit(uint256 _totalDebt) internal override returns (uint256 _profit) {}
} | This adds some gas but will save loss on exchange fees | function _withdraw(uint256 _amount) internal override {
uint256 balanceHere = collateralToken.balanceOf(address(this));
if (_amount > balanceHere) {
_unstakeAndWithdrawAsCollateral(_amount - balanceHere);
}
collateralToken.safeTransfer(pool, _amount);
}
| 5,825,346 | [
1,
2503,
4831,
2690,
16189,
1496,
903,
1923,
8324,
603,
7829,
1656,
281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
1918,
9446,
12,
11890,
5034,
389,
8949,
13,
2713,
3849,
288,
203,
3639,
2254,
5034,
11013,
26715,
273,
4508,
2045,
287,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
309,
261,
67,
8949,
405,
11013,
26715,
13,
288,
203,
5411,
389,
23412,
911,
1876,
1190,
9446,
1463,
13535,
2045,
287,
24899,
8949,
300,
11013,
26715,
1769,
203,
3639,
289,
203,
3639,
4508,
2045,
287,
1345,
18,
4626,
5912,
12,
6011,
16,
389,
8949,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.6;
pragma experimental ABIEncoderV2;
import {Initializable} from "Initializable.sol";
import {IERC721} from "IERC721.sol";
import {IERC20} from "IERC20.sol";
import {SafeERC20} from "SafeERC20.sol";
import {ReentrancyGuard} from "ReentrancyGuard.sol";
import {IERC165} from "IERC165.sol";
import {DataTypes} from "DataTypes.sol";
import {Errors} from "Errors.sol";
import {AdminPausableUpgradeSafe} from "AdminPausableUpgradeSafe.sol";
import "IERC721TokenAuthor.sol";
/**
* @dev Auction between NFT holders and participants.
*/
contract Auction is AdminPausableUpgradeSafe, ReentrancyGuard, Initializable {
using SafeERC20 for IERC20;
mapping(uint256 /*tokenId*/ => DataTypes.AuctionData) internal _nftId2auction;
uint256 public minPriceStepNumerator;
uint256 constant public DENOMINATOR = 10000;
uint256 constant public MIN_MIN_PRICE_STEP_NUMERATOR = 1; // 0.01%
uint256 constant public MAX_MIN_PRICE_STEP_NUMERATOR = 10000; // 100%
uint256 public authorRoyaltyNumerator;
uint256 public overtimeWindow;
uint256 public auctionDuration;
uint256 constant MAX_OVERTIME_WINDOW = 365 days;
uint256 constant MIN_OVERTIME_WINDOW = 1 minutes;
uint256 constant MAX_AUCTION_DURATION = 365 days;
uint256 constant MIN_AUCTION_DURATION = 1 minutes;
IERC20 public payableToken;
IERC721 public nft;
address public treasury;
uint256 public feeCreatorToBuyerTokenNumerator;
uint256 public feeResellerToBuyerTokenNumerator;
uint256 public feeCreatorToBuyerETHNumerator;
uint256 public feeResellerToBuyerETHNumerator;
/**
* @notice Emitted when a new treasury is set.
*
* @param treasury The treasury address.
*/
event TreasurySet(
address indexed treasury
);
/**
* @notice Emitted when a new feeCreatorToBuyerTokenNumerator is set.
*
* @param feeCreatorToBuyerTokenNumerator The feeCreatorToBuyerTokenNumerator value.
*/
event FeeCreatorToBuyerTokenNumeratorSet(
uint256 indexed feeCreatorToBuyerTokenNumerator
);
/**
* @notice Emitted when a new feeResellerToBuyerTokenNumerator is set.
*
* @param feeResellerToBuyerTokenNumerator The feeResellerToBuyerTokenNumerator value.
*/
event FeeResellerToBuyerTokenNumeratorSet(
uint256 indexed feeResellerToBuyerTokenNumerator
);
/**
* @notice Emitted when a new feeCreatorToBuyerETHNumerator is set.
*
* @param feeCreatorToBuyerETHNumerator The feeCreatorToBuyerETHNumerator value.
*/
event FeeCreatorToBuyerETHNumeratorSet(
uint256 indexed feeCreatorToBuyerETHNumerator
);
/**
* @notice Emitted whepaidToAuctioneern a new feeResellerToBuyerETHNumerator is set.
*
* @param feeResellerToBuyerETHNumerator The feeResellerToBuyerETHNumerator value.
*/
event FeeResellerToBuyerETHNumeratorSet(
uint256 indexed feeResellerToBuyerETHNumerator
);
/**
* @notice Emitted when a new auction is created.
*
* @param nftId The NFT ID of the token to auction.
* @param auctioneer The creator.
* @param startPrice The auction's starting price.
* @param priceToken The token of startPrice or 0 for ether.
*/
event AuctionCreated(
uint256 indexed nftId,
address indexed auctioneer,
uint256 startPrice,
address priceToken
);
/**
* @notice Emitted when a royalty paid to an author.
*
* @param nftId The NFT ID of the token to auction.
* @param author The author.
* @param amount The royalty amount.
* @param amountToken The token of royalty amount or 0 for ether.
*/
event RoyaltyPaid(
uint256 indexed nftId,
address indexed author,
uint256 amount,
address amountToken
);
/**
* @notice Emitted when fee is paid to treasury.
*
* @param nftId The NFT ID of the token to auction.
* @param payer The payer.
* @param feeAmount The fee amount.
* @param amountToken The token of amount or 0 for ether.
*/
event FeePaid(
uint256 indexed nftId,
address indexed payer,
uint256 feeAmount,
address amountToken
);
/**
* @notice Emitted when an auction is canceled.
*
* @param nftId The NFT ID of the token to auction.
* @param canceler Who canceled the auction.
*/
event AuctionCanceled(
uint256 indexed nftId,
address indexed canceler
);
/**
* @notice Emitted when a new auction params are set.
*
* @param minPriceStepNumerator.
*/
event MinPriceStepNumeratorSet(
uint256 minPriceStepNumerator
);
/**
* @notice Emitted when a new auction params are set.
*
* @param auctionDuration.
*/
event AuctionDurationSet(
uint256 auctionDuration
);
/**
* @notice Emitted when a new auction params are set.
*
* @param overtimeWindow.
*/
event OvertimeWindowSet(
uint256 overtimeWindow
);
/**
* @notice Emitted when a new auction params are set.
*
* @param authorRoyaltyNumerator.
*/
event AuthorRoyaltyNumeratorSet(
uint256 authorRoyaltyNumerator
);
/**
* @notice Emitted when a new bid or outbid is created on a given NFT.
*
* @param nftId The NFT ID of the token bid on.
* @param bidder The bidder address.
* @param amount The amount used to bid.
* @param amountToken The token of amount bid or 0 for ether.
* @param endTimestamp The new end timestamp.
*/
event BidSubmitted(
uint256 indexed nftId,
address indexed bidder,
uint256 amount,
address amountToken,
uint256 endTimestamp
);
/**
* @notice Emitted when an NFT is won and claimed.
*
* @param nftId The NFT ID of the token claimed.
* @param winner The winner of the NFT.
* @param claimCaller Who called the claim method.
* @param wonBidAmount The total bid amount.
* @param paidToAuctioneer How much tokens are paid to auctioneer (excluding fee and royalty).
*/
event WonNftClaimed(
uint256 indexed nftId,
address indexed winner,
address claimCaller,
uint256 wonBidAmount,
uint256 paidToAuctioneer
);
/**
* @notice Emitted when auction reserve price changed.
*
* @param nftId The NFT ID of the token changed.
* @param startPrice The new reserve price.
* @param startPriceToken The token of start price or 0 for ether.
* @param reservePriceChanger The caller of the method.
*/
event ReservePriceChanged(
uint256 indexed nftId,
uint256 startPrice,
address startPriceToken,
address indexed reservePriceChanger
);
function getPaused() external view returns(bool) {
return _paused;
}
/**
* @dev Initializes the contract.
*
* @param _overtimeWindow The overtime window,
* triggers on bid `endTimestamp := max(endTimestamp, bid.timestamp + overtimeWindow)`
* @param _auctionDuration The minimum auction duration. (e.g. 24*3600)
* @param _minStepNumerator The minimum auction price step. (e.g. 500 ~ 5% see `DENOMINATOR`)
* @param _payableToken The address of payable token.
* @param _nft Only one NFT is allowed.
* @param _adminAddress The administrator address to set, allows pausing and editing settings.
* @param _treasury The address of treasury.
* @param _feeCreatorToBuyerTokenNumerator fee for token auctions.
* @param _feeResellerToBuyerTokenNumerator fee for token auctions.
* @param _feeCreatorToBuyerETHNumerator fee for ETH auctions.
* @param _feeResellerToBuyerETHNumerator fee for ETH auctions.
*/
function initialize(
uint256 _overtimeWindow,
uint256 _auctionDuration,
uint256 _minStepNumerator,
uint256 _authorRoyaltyNumerator,
address _payableToken,
address _nft,
address _adminAddress,
address _treasury,
uint256 _feeCreatorToBuyerTokenNumerator,
uint256 _feeResellerToBuyerTokenNumerator,
uint256 _feeCreatorToBuyerETHNumerator,
uint256 _feeResellerToBuyerETHNumerator
) external initializer {
require(
_adminAddress != address(0),
Errors.ZERO_ADDRESS
);
require(
_payableToken != address(0),
Errors.ZERO_ADDRESS
);
require(
_nft != address(0),
Errors.ZERO_ADDRESS
);
require(
_treasury != address(0),
Errors.ZERO_ADDRESS
);
_admin = _adminAddress;
payableToken = IERC20(_payableToken);
nft = IERC721(_nft);
treasury = _treasury;
setAuctionDuration(_auctionDuration);
setOvertimeWindow(_overtimeWindow);
setMinPriceStepNumerator(_minStepNumerator);
setAuthorRoyaltyNumerator(_authorRoyaltyNumerator);
setFeeCreatorToBuyerTokenNumerator(_feeCreatorToBuyerTokenNumerator);
setFeeResellerToBuyerTokenNumerator(_feeResellerToBuyerTokenNumerator);
setFeeCreatorToBuyerETHNumerator(_feeCreatorToBuyerETHNumerator);
setFeeResellerToBuyerETHNumerator(_feeResellerToBuyerETHNumerator);
}
/**
* @dev Admin function to set new treasury address.
*
* @param treasuryAddress The new treasury address.
*/
function setTreasury(address treasuryAddress) external onlyAdmin {
require(
treasuryAddress != address(0),
Errors.ZERO_ADDRESS
);
treasury = treasuryAddress;
emit TreasurySet(treasuryAddress);
}
/**
* @dev Admin function to change the auction duration.
*
* @param newAuctionDuration The new minimum auction duration to set.
*/
function setAuctionDuration(uint256 newAuctionDuration) public onlyAdmin {
require(newAuctionDuration >= MIN_AUCTION_DURATION && newAuctionDuration <= MAX_AUCTION_DURATION,
Errors.INVALID_AUCTION_PARAMS);
auctionDuration = newAuctionDuration;
emit AuctionDurationSet(newAuctionDuration);
}
/**
* @dev Admin function to set the auction overtime window.
*
* @param newOvertimeWindow The new overtime window to set.
*/
function setOvertimeWindow(uint256 newOvertimeWindow) public onlyAdmin {
require(newOvertimeWindow >= MIN_OVERTIME_WINDOW && newOvertimeWindow <= MAX_OVERTIME_WINDOW,
Errors.INVALID_AUCTION_PARAMS);
overtimeWindow = newOvertimeWindow;
emit OvertimeWindowSet(newOvertimeWindow);
}
/**
* @dev Admin function to set the auction price step numerator.
*
* @param newMinPriceStepNumerator The new overtime window to set.
*/
function setMinPriceStepNumerator(uint256 newMinPriceStepNumerator) public onlyAdmin {
require(newMinPriceStepNumerator >= MIN_MIN_PRICE_STEP_NUMERATOR &&
newMinPriceStepNumerator <= MAX_MIN_PRICE_STEP_NUMERATOR,
Errors.INVALID_AUCTION_PARAMS);
minPriceStepNumerator = newMinPriceStepNumerator;
emit MinPriceStepNumeratorSet(newMinPriceStepNumerator);
}
/**
* @dev Admin function to set author royalty numerator.
*
* @param newAuthorRoyaltyNumerator The new overtime window to set.
*/
function setAuthorRoyaltyNumerator(uint256 newAuthorRoyaltyNumerator) public onlyAdmin {
require(newAuthorRoyaltyNumerator <= DENOMINATOR, Errors.INVALID_AUCTION_PARAMS);
authorRoyaltyNumerator = newAuthorRoyaltyNumerator;
emit AuthorRoyaltyNumeratorSet(newAuthorRoyaltyNumerator);
}
/**
* @dev Admin function to set setFeeCreatorToBuyerTokenNumerator.
*
* @param newFeeCreatorToBuyerTokenNumerator The new value.
*/
function setFeeCreatorToBuyerTokenNumerator(uint256 newFeeCreatorToBuyerTokenNumerator) public onlyAdmin {
require(newFeeCreatorToBuyerTokenNumerator <= DENOMINATOR, Errors.INVALID_AUCTION_PARAMS);
feeCreatorToBuyerTokenNumerator = newFeeCreatorToBuyerTokenNumerator;
emit FeeCreatorToBuyerTokenNumeratorSet(newFeeCreatorToBuyerTokenNumerator);
}
/**
* @dev Admin function to set setFeeResellerToBuyerTokenNumerator.
*
* @param newFeeResellerToBuyerTokenNumerator The new value.
*/
function setFeeResellerToBuyerTokenNumerator(uint256 newFeeResellerToBuyerTokenNumerator) public onlyAdmin {
require(newFeeResellerToBuyerTokenNumerator <= DENOMINATOR, Errors.INVALID_AUCTION_PARAMS);
feeResellerToBuyerTokenNumerator = newFeeResellerToBuyerTokenNumerator;
emit FeeResellerToBuyerTokenNumeratorSet(newFeeResellerToBuyerTokenNumerator);
}
/**
* @dev Admin function to set setFeeCreatorToBuyerETHNumerator.
*
* @param newFeeCreatorToBuyerETHNumerator The new value.
*/
function setFeeCreatorToBuyerETHNumerator(uint256 newFeeCreatorToBuyerETHNumerator) public onlyAdmin {
require(newFeeCreatorToBuyerETHNumerator <= DENOMINATOR, Errors.INVALID_AUCTION_PARAMS);
feeCreatorToBuyerETHNumerator = newFeeCreatorToBuyerETHNumerator;
emit FeeCreatorToBuyerETHNumeratorSet(newFeeCreatorToBuyerETHNumerator);
}
/**
* @dev Admin function to set setFeeResellerToBuyerETHNumerator.
*
* @param newFeeResellerToBuyerETHNumerator The new value.
*/
function setFeeResellerToBuyerETHNumerator(uint256 newFeeResellerToBuyerETHNumerator) public onlyAdmin {
require(newFeeResellerToBuyerETHNumerator <= DENOMINATOR, Errors.INVALID_AUCTION_PARAMS);
feeResellerToBuyerETHNumerator = newFeeResellerToBuyerETHNumerator;
emit FeeResellerToBuyerETHNumeratorSet(newFeeResellerToBuyerETHNumerator);
}
/**
* @dev Create new auction.
*
* @param nftId Id of NFT token for the auction (must be approved for transfer by Auction smart-contract).
* @param startPrice Minimum price for the first bid in ether or tokens depending on isEtherPrice value.
* @param isEtherPrice True to create auction in ether, false to create auction in payableToken.
*/
function createAuction(
uint256 nftId,
uint256 startPrice,
bool isEtherPrice
) external nonReentrant whenNotPaused {
require(_nftId2auction[nftId].auctioneer == address(0), Errors.AUCTION_EXISTS);
require(startPrice > 0, Errors.INVALID_AUCTION_PARAMS);
address token = isEtherPrice ? address(0) : address(payableToken);
DataTypes.AuctionData memory auctionData = DataTypes.AuctionData(
startPrice,
token,
msg.sender,
address(0), // bidder
0 // endTimestamp
);
_nftId2auction[nftId] = auctionData;
IERC721(nft).transferFrom(msg.sender, address(this), nftId); // maybe use safeTransferFrom
emit AuctionCreated(nftId, msg.sender, startPrice, token);
}
/**
* @notice Claims a won NFT after an auction. Can be called by anyone.
*
* @param nftId The NFT ID of the token to claim.
*/
function claimWonNFT(uint256 nftId) external nonReentrant whenNotPaused {
DataTypes.AuctionData storage auction = _nftId2auction[nftId];
address auctioneer = auction.auctioneer;
address winner = auction.currentBidder;
uint256 endTimestamp = auction.endTimestamp;
uint256 currentBid = auction.currentBid;
uint256 payToAuctioneer = currentBid;
address bidToken = auction.bidToken;
require(block.timestamp > endTimestamp, Errors.AUCTION_NOT_FINISHED);
require(winner != address(0), Errors.EMPTY_WINNER); // auction does not exist or did not start, no bid
delete _nftId2auction[nftId]; // storage change before external calls
// warning: will not work for usual erc721
address author = IERC721TokenAuthor(address(nft)).tokenAuthor(nftId);
if (author != auctioneer) { // pay royalty
uint256 payToAuthor = currentBid * authorRoyaltyNumerator / DENOMINATOR;
payToAuctioneer -= payToAuthor;
emit RoyaltyPaid(nftId, author, payToAuthor, bidToken);
if (bidToken == address(0)) { // eth
payable(author).transfer(payToAuthor);
} else { // erc20
payableToken.safeTransfer(author, payToAuthor);
}
// note: as the result of this mechanism, there is one contr-intuitive consequence:
// creator receives the discount on buying back his created NFT.
// New nft holder must be informed that he will not receive 100%
// of money from his auction because of the roylaty
}
if (bidToken == address(0)) { // eth
uint256 fee = 0;
if (author == auctioneer) { // creatorToBuyer
fee = payToAuctioneer * uint256(feeCreatorToBuyerETHNumerator) / uint256(DENOMINATOR);
} else { // resellerToBuyer
fee = payToAuctioneer * uint256(feeResellerToBuyerETHNumerator) / uint256(DENOMINATOR);
}
if (fee > 0) {
payToAuctioneer -= fee;
payable(treasury).transfer(fee);
}
emit FeePaid({
nftId: nftId,
payer: winner,
feeAmount: fee,
amountToken: address(0)
});
emit WonNftClaimed(nftId, winner, msg.sender, currentBid, payToAuctioneer);
payable(auctioneer).transfer(payToAuctioneer);
} else { //erc20
uint256 fee = 0;
if (author == auctioneer) { // creatorToBuyer
fee = payToAuctioneer * uint256(feeCreatorToBuyerTokenNumerator) / uint256(DENOMINATOR);
} else { // resellerToBuyer
fee = payToAuctioneer * uint256(feeResellerToBuyerTokenNumerator) / uint256(DENOMINATOR);
}
if (fee > 0) {
payToAuctioneer -= fee;
payableToken.safeTransfer(treasury, fee);
}
emit FeePaid({
nftId: nftId,
payer: winner,
feeAmount: fee,
amountToken: address(payableToken)
});
emit WonNftClaimed(nftId, winner, msg.sender, currentBid, payToAuctioneer);
payableToken.safeTransfer(auctioneer, payToAuctioneer);
}
// sine we use the only one nft, we don't need to call safeTransferFrom
IERC721(nft).transferFrom(address(this), winner, nftId);
}
/**
* @notice Returns the auction data for a given NFT.
*
* @param nftId The NFT ID to query.
*
* @return The AuctionData containing all data related to a given NFT.
*/
function getAuctionData(uint256 nftId) external view returns (DataTypes.AuctionData memory) {
DataTypes.AuctionData memory auction = _nftId2auction[nftId];
require(auction.auctioneer != address(0), Errors.AUCTION_NOT_EXISTS);
return auction;
}
/**
* @notice Cancel an auction. Can be called by the auctioneer or by the admin.
*
* @param nftId The NFT ID of the token to cancel.
*/
function cancelAuction(
uint256 nftId
) external whenNotPaused nonReentrant {
DataTypes.AuctionData memory auction = _nftId2auction[nftId];
require(
auction.auctioneer != address(0),
Errors.AUCTION_NOT_EXISTS
);
require(
msg.sender == auction.auctioneer || msg.sender == _admin, // do we really need admin control?
Errors.NO_RIGHTS
);
require(
auction.currentBidder == address(0),
Errors.AUCTION_ALREADY_STARTED
); // auction can't be canceled if someone placed a bid.
delete _nftId2auction[nftId];
emit AuctionCanceled(nftId, msg.sender);
// maybe use safeTransfer (I don't want unclear onERC721Received stuff)
IERC721(nft).transferFrom(address(this), auction.auctioneer, nftId);
}
/**
* @notice Change the reserve price (minimum price) of the auction.
*
* @param nftId The NFT ID of the token.
* @param startPrice New start price in tokens or ether depending on auction type.
* @param isEtherPrice Should the bidToken be ETH or ERC20.
*/
function changeReservePrice(
uint256 nftId,
uint256 startPrice,
bool isEtherPrice
) external whenNotPaused nonReentrant {
DataTypes.AuctionData memory auction = _nftId2auction[nftId];
require(
auction.auctioneer != address(0),
Errors.AUCTION_NOT_EXISTS
);
require(
msg.sender == auction.auctioneer || msg.sender == _admin, // do we really need admin control?
Errors.NO_RIGHTS
);
require(
auction.currentBidder == address(0),
Errors.AUCTION_ALREADY_STARTED
); // auction can't be canceled if someone placed a bid.
require(
startPrice > 0,
Errors.INVALID_AUCTION_PARAMS
);
address bidToken = isEtherPrice ? address(0) : address(payableToken);
_nftId2auction[nftId].currentBid = startPrice;
_nftId2auction[nftId].bidToken = bidToken;
emit ReservePriceChanged({
nftId: nftId,
startPrice: startPrice,
startPriceToken: bidToken,
reservePriceChanger: msg.sender
});
}
/**
* @notice Place the bid in ERC20 tokens.
*
* @param nftId The NFT ID of the token.
* @param amount Bid amount in ERC20 tokens.
*/
function bid(
uint256 nftId,
uint256 amount
) external whenNotPaused nonReentrant {
_bid(nftId, amount, address(payableToken));
}
/**
* @notice Place the bid in ETH.
*
* @param nftId The NFT ID of the token.
* @param amount Bid amount in ETH.
*/
function bidEther(
uint256 nftId,
uint256 amount
) external payable whenNotPaused nonReentrant {
_bid(nftId, amount, address(0));
}
/**
* @notice Place the bid.
*
* @param nftId The NFT id.
* @param amount Bid amount.
*/
function _bid(
uint256 nftId,
uint256 amount,
address auctionToken
) internal {
DataTypes.AuctionData storage auction = _nftId2auction[nftId];
require(auction.auctioneer != address(0), Errors.AUCTION_NOT_EXISTS);
uint256 currentBid = auction.currentBid;
address currentBidder = auction.currentBidder;
uint256 endTimestamp = auction.endTimestamp;
if (auctionToken != address(0)){ // erc20
require(
auction.bidToken == auctionToken,
Errors.CANT_BID_ETHER_AUCTION_BY_TOKENS
);
} else { // eth
require(
auction.bidToken == address(0),
Errors.CANT_BID_TOKEN_AUCTION_BY_ETHER
);
}
require(
block.timestamp < endTimestamp || // already finished
endTimestamp == 0, // or not started
Errors.AUCTION_FINISHED
);
uint256 newEndTimestamp = auction.endTimestamp;
if (endTimestamp == 0) { // first bid
require(amount >= currentBid, Errors.SMALL_BID_AMOUNT); // >= startPrice stored in currentBid
newEndTimestamp = block.timestamp + auctionDuration;
auction.endTimestamp = newEndTimestamp;
} else {
require(amount >= (DENOMINATOR + minPriceStepNumerator) * currentBid / DENOMINATOR,
Errors.SMALL_BID_AMOUNT); // >= step over the previous bid
if (block.timestamp > endTimestamp - overtimeWindow) {
newEndTimestamp = block.timestamp + overtimeWindow;
auction.endTimestamp = newEndTimestamp;
}
}
auction.currentBidder = msg.sender;
auction.currentBid = amount;
// emit here to avoid reentry events mis-ordering
emit BidSubmitted(nftId, msg.sender, amount, auction.bidToken, newEndTimestamp);
if (auctionToken != address(0)){ // erc20
if (currentBidder != msg.sender) {
if (currentBidder != address(0)) {
payableToken.safeTransfer(currentBidder, currentBid);
}
payableToken.safeTransferFrom(msg.sender, address(this), amount);
} else {
uint256 more = amount - currentBid;
payableToken.safeTransferFrom(msg.sender, address(this), more);
}
} else { // eth
if (currentBidder != msg.sender) {
require(msg.value == amount, Errors.INVALID_ETHER_AMOUNT);
if (currentBidder != address(0)) {
payable(currentBidder).transfer(currentBid);
}
} else {
uint256 more = amount - currentBid;
require(msg.value == more, Errors.INVALID_ETHER_AMOUNT);
}
}
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "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;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "IERC20.sol";
import "Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.6;
library DataTypes {
struct AuctionData {
uint256 currentBid;
address bidToken; // determines currentBid token, zero address means ether
address auctioneer;
address currentBidder;
uint256 endTimestamp;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.6;
// Contains error code strings
library Errors {
string public constant INVALID_AUCTION_PARAMS = 'INVALID_AUCTION_PARAMS';
string public constant INVALID_ETHER_AMOUNT = 'INVALID_ETHER_AMOUNT';
string public constant AUCTION_EXISTS = 'AUCTION_EXISTS';
string public constant AUCTION_NOT_FINISHED = 'AUCTION_NOT_FINISHED';
string public constant AUCTION_FINISHED = 'AUCTION_FINISHED';
string public constant SMALL_BID_AMOUNT = 'SMALL_BID_AMOUNT';
string public constant PAUSED = 'PAUSED';
string public constant NO_RIGHTS = 'NO_RIGHTS';
string public constant NOT_ADMIN = 'NOT_ADMIN';
string public constant NOT_OWNER = 'NOT_OWNER';
string public constant NOT_EXISTS = 'NOT_EXISTS';
string public constant EMPTY_WINNER = 'EMPTY_WINNER';
string public constant AUCTION_ALREADY_STARTED = 'AUCTION_ALREADY_STARTED';
string public constant AUCTION_NOT_EXISTS = 'AUCTION_NOT_EXISTS';
string public constant ZERO_ADDRESS = 'ZERO_ADDRESS';
string public constant CANT_BID_TOKEN_AUCTION_BY_ETHER = 'CANT_BID_TOKEN_AUCTION_BY_ETHER';
string public constant CANT_BID_ETHER_AUCTION_BY_TOKENS = 'CANT_BID_ETHER_AUCTION_BY_TOKENS';
string public constant EMPTY_METADATA = 'EMPTY_METADATA';
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.6;
import {Errors} from "Errors.sol";
/**
* @title AdminPausableUpgradeSafe
*
* @dev Contract to be inherited from that adds simple administrator pausable functionality. This does not
* implement any changes on its own as there is no constructor or initializer. Both _admin and _paused must
* be initialized in the inheriting contract.
* @dev Inspired by `@openzeppelin-upgradeable/contracts/security/PausableUpgradeable.sol`
*/
contract AdminPausableUpgradeSafe {
address internal _admin;
bool internal _paused;
/**
* @notice Emitted when the contract is paused.
*
* @param admin The current administrator address.
*/
event Paused(address admin);
/**
* @notice Emitted when the contract is unpaused.
*
* @param admin The current administrator address.
*/
event Unpaused(address admin);
/**
* @notice Emitted when the admin is set to a different address.
*
* @param to The address of the new administrator.
*/
event AdminChanged(address to);
/**
* @dev Modifier to only allow functions to be called when not paused.
*/
modifier whenNotPaused() {
require(!_paused, Errors.PAUSED);
_;
}
/**
* @dev Modifier to only allow the admin as the caller.
*/
modifier onlyAdmin() {
require(msg.sender == _admin, Errors.NOT_ADMIN);
_;
}
/**
* @dev Admin function pauses the contract.
*/
function pause() external onlyAdmin {
_paused = true;
emit Paused(_admin);
}
/**
* @dev Admin function unpauses the contract.
*/
function unpause() external onlyAdmin {
_paused = false;
emit Unpaused(_admin);
}
/**
* @dev Admin function that changes the administrator.
* @dev It is possible to set admin to address(0) (to disable administration), be careful!
*/
function changeAdmin(address to) external onlyAdmin {
_admin = to;
emit AdminChanged(to);
}
/**
* @dev View function that returns the current admin.
*/
function getAdmin() external view returns (address) {
return _admin;
}
uint256[3] private __gap; // contract uses small number of slots (5 in total)
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.6;
/**
* @dev Interface of extension of the ERC721 standard to allow `tokenAuthor` method.
*/
interface IERC721TokenAuthor {
/**
* @dev Returns the amount of tokens in existence.
*/
function tokenAuthor(uint256 tokenId) external view returns(address);
} | * @dev Admin function to set the auction overtime window. @param newOvertimeWindow The new overtime window to set./ | function setOvertimeWindow(uint256 newOvertimeWindow) public onlyAdmin {
require(newOvertimeWindow >= MIN_OVERTIME_WINDOW && newOvertimeWindow <= MAX_OVERTIME_WINDOW,
Errors.INVALID_AUCTION_PARAMS);
overtimeWindow = newOvertimeWindow;
emit OvertimeWindowSet(newOvertimeWindow);
}
| 1,656,977 | [
1,
4446,
445,
358,
444,
326,
279,
4062,
1879,
957,
2742,
18,
225,
394,
4851,
957,
3829,
1021,
394,
1879,
957,
2742,
358,
444,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
444,
4851,
957,
3829,
12,
11890,
5034,
394,
4851,
957,
3829,
13,
1071,
1338,
4446,
288,
203,
3639,
2583,
12,
2704,
4851,
957,
3829,
1545,
6989,
67,
12959,
4684,
67,
23407,
597,
394,
4851,
957,
3829,
1648,
4552,
67,
12959,
4684,
67,
23407,
16,
203,
5411,
9372,
18,
9347,
67,
14237,
3106,
67,
16785,
1769,
203,
3639,
1879,
957,
3829,
273,
394,
4851,
957,
3829,
31,
203,
3639,
3626,
10752,
957,
3829,
694,
12,
2704,
4851,
957,
3829,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x235b25f9f56B39eFD8293C0d2A9Ee70719E25B85/sources/src/libraries/PairMath.sol | @dev Refer to [mint-math.md](https://github.com/buttonwood-protocol/buttonswap-core/blob/main/notes/mint-math.md#single-sided-mint) for more detail. `movingAveragePriceA` is a UQ112x112 and so is a uint224 that needs to be divided by 2^112 after being multiplied. Here we need to use the inverse price however, which means we multiply the numerator by 2^112 and then divide that by movingAveragePriceA to get the result, all without risk of overflow. Inverse price so again we can use it without overflow risk Update totals to account for the fixed price swap | function getSingleSidedMintLiquidityOutAmountB(
uint256 totalLiquidity,
uint256 mintAmountB,
uint256 totalA,
uint256 totalB,
uint256 movingAveragePriceA
) internal pure returns (uint256 liquidityOut, uint256 swappedReservoirAmountA) {
uint256 tokenBToSwap =
(mintAmountB * totalA) / (((2 ** 112 * (totalB + mintAmountB)) / movingAveragePriceA) + totalA);
swappedReservoirAmountA = (tokenBToSwap * (2 ** 112)) / movingAveragePriceA;
totalA -= swappedReservoirAmountA;
totalB += tokenBToSwap;
uint256 tokenBRemaining = mintAmountB - tokenBToSwap;
liquidityOut =
getDualSidedMintLiquidityOutAmount(totalLiquidity, swappedReservoirAmountA, tokenBRemaining, totalA, totalB);
}
| 4,108,399 | [
1,
426,
586,
358,
306,
81,
474,
17,
15949,
18,
1264,
29955,
4528,
2207,
6662,
18,
832,
19,
5391,
91,
4773,
17,
8373,
19,
5391,
22270,
17,
3644,
19,
10721,
19,
5254,
19,
12903,
19,
81,
474,
17,
15949,
18,
1264,
7526,
17,
7722,
785,
17,
81,
474,
13,
364,
1898,
7664,
18,
1375,
81,
13767,
17115,
5147,
37,
68,
353,
279,
587,
53,
17666,
92,
17666,
471,
1427,
353,
279,
2254,
23622,
716,
4260,
358,
506,
26057,
635,
576,
66,
17666,
1839,
3832,
27789,
18,
13743,
732,
1608,
358,
999,
326,
8322,
6205,
14025,
16,
1492,
4696,
732,
10194,
326,
16730,
635,
576,
66,
17666,
471,
1508,
12326,
716,
282,
635,
12499,
17115,
5147,
37,
358,
336,
326,
563,
16,
777,
2887,
18404,
434,
9391,
18,
657,
2476,
6205,
1427,
3382,
732,
848,
999,
518,
2887,
9391,
18404,
2315,
19489,
358,
2236,
364,
326,
5499,
6205,
7720,
2,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0
] | [
1,
565,
445,
19108,
55,
13898,
49,
474,
48,
18988,
24237,
1182,
6275,
38,
12,
203,
3639,
2254,
5034,
2078,
48,
18988,
24237,
16,
203,
3639,
2254,
5034,
312,
474,
6275,
38,
16,
203,
3639,
2254,
5034,
2078,
37,
16,
203,
3639,
2254,
5034,
2078,
38,
16,
203,
3639,
2254,
5034,
12499,
17115,
5147,
37,
203,
565,
262,
2713,
16618,
1135,
261,
11890,
5034,
4501,
372,
24237,
1182,
16,
2254,
5034,
7720,
1845,
607,
264,
31238,
6275,
37,
13,
288,
203,
3639,
2254,
5034,
1147,
38,
774,
12521,
273,
203,
5411,
261,
81,
474,
6275,
38,
380,
2078,
37,
13,
342,
261,
12443,
22,
2826,
23543,
380,
261,
4963,
38,
397,
312,
474,
6275,
38,
3719,
342,
12499,
17115,
5147,
37,
13,
397,
2078,
37,
1769,
203,
3639,
7720,
1845,
607,
264,
31238,
6275,
37,
273,
261,
2316,
38,
774,
12521,
380,
261,
22,
2826,
23543,
3719,
342,
12499,
17115,
5147,
37,
31,
203,
3639,
2078,
37,
3947,
7720,
1845,
607,
264,
31238,
6275,
37,
31,
203,
3639,
2078,
38,
1011,
1147,
38,
774,
12521,
31,
203,
3639,
2254,
5034,
1147,
38,
11429,
273,
312,
474,
6275,
38,
300,
1147,
38,
774,
12521,
31,
203,
3639,
4501,
372,
24237,
1182,
273,
203,
5411,
2343,
1462,
55,
13898,
49,
474,
48,
18988,
24237,
1182,
6275,
12,
4963,
48,
18988,
24237,
16,
7720,
1845,
607,
264,
31238,
6275,
37,
16,
1147,
38,
11429,
16,
2078,
37,
16,
2078,
38,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x2917a1c69E6f74772ECe4f575A37b934a06C2aB6/sources/browser/btp.sol | * @title Issusable @dev The Issusable contract has an owner address, and provides basic authorization control functions, this simplifies the implementation of "user permissions"./ | contract Issusable is Ownable {
address public Issuser;
uint IssuseAmount;
uint LastIssuseTime = 0;
uint PreIssuseTime=0;
constructor() internal {
Issuser = msg.sender;
}
modifier onlyIssuser() {
require(msg.sender == Issuser);
_;
}
function transferIssusership(address newIssuser) public onlyOwner {
if (newIssuser != address(0)) {
Issuser = newIssuser;
}
}
function transferIssusership(address newIssuser) public onlyOwner {
if (newIssuser != address(0)) {
Issuser = newIssuser;
}
}
}
| 2,966,602 | [
1,
7568,
16665,
225,
1021,
9310,
16665,
6835,
711,
392,
3410,
1758,
16,
471,
8121,
5337,
6093,
3325,
4186,
16,
333,
9330,
5032,
326,
4471,
434,
315,
1355,
4371,
9654,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
9310,
16665,
353,
14223,
6914,
288,
203,
565,
1758,
1071,
9310,
1355,
31,
203,
565,
2254,
225,
9310,
1202,
6275,
31,
203,
565,
2254,
6825,
7568,
1202,
950,
273,
374,
31,
203,
565,
2254,
2962,
7568,
1202,
950,
33,
20,
31,
203,
565,
3885,
1435,
2713,
288,
203,
3639,
9310,
1355,
273,
1234,
18,
15330,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
7568,
1355,
1435,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
9310,
1355,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
7412,
7568,
5577,
5310,
12,
2867,
394,
7568,
1355,
13,
1071,
1338,
5541,
288,
203,
3639,
309,
261,
2704,
7568,
1355,
480,
1758,
12,
20,
3719,
288,
203,
5411,
9310,
1355,
273,
394,
7568,
1355,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
7412,
7568,
5577,
5310,
12,
2867,
394,
7568,
1355,
13,
1071,
1338,
5541,
288,
203,
3639,
309,
261,
2704,
7568,
1355,
480,
1758,
12,
20,
3719,
288,
203,
5411,
9310,
1355,
273,
394,
7568,
1355,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
* @title: DyDx lending tokenization
* @summary: Used for crete and ERC20 representing lending positions
* on DyDx protocol.
* @author: Idle Labs Inc., idle.finance
*/
pragma solidity 0.5.16;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../interfaces/DyDx.sol";
import '../interfaces/DyDxStructs.sol';
contract yxTokenNoConst is DyDxStructs, ERC20, ERC20Detailed {
using SafeERC20 for IERC20;
using SafeMath for uint256;
uint256 public marketId;
uint256 public secondsInAYear;
// underlying token (token eg DAI) address
address public underlying;
address public dydxAddressesProvider = address(0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e);
DyDx dydx = DyDx(dydxAddressesProvider);
/**
* @param _underlying : underlying token (eg DAI) address
* @param _marketId : dydx market id
* @param _name : dydx tokenized name
* @param _symbol : dydx tokenized symbol
* @param _decimals : dydx tokenized decimals (same decimals as the underlying)
*/
constructor(address _underlying, uint256 _marketId, string memory _name, string memory _symbol, uint8 _decimals)
public ERC20Detailed(_name, _symbol, _decimals) {
require(_underlying != address(0), 'Underlying is 0');
underlying = _underlying;
marketId = _marketId; // 0, ETH, (1 SAI not available), 2 USDC, 3 DAI
IERC20(_underlying).approve(dydxAddressesProvider, uint256(-1));
}
/**
* @return current price of yxToken always 18 decimals
*/
function price() public view returns (uint256) {
(, uint256 supplyIndex) = DyDx(dydxAddressesProvider).getMarketCurrentIndex(marketId);
return supplyIndex;
}
function availableLiquidity() external view returns (uint256) {
return IERC20(underlying).balanceOf(dydxAddressesProvider);
}
function balanceInUnderlying(address who) external view returns (uint256) {
return balanceOf(who).mul(price()).div(10**18);
}
/**
* Gets all underlying tokens in this contract and mints yxTokens
* tokens are then transferred to msg.sender
* NOTE: one must approve this contract before calling this method
*
* @return yxTokens minted
*/
function mint(uint256 _amount)
external
returns (uint256 newTokens) {
// mint IERC20 for dydx tokenized position
newTokens = _amount.mul(10**18).div(price());
_mint(msg.sender, newTokens);
IERC20(underlying).safeTransferFrom(msg.sender, address(this), _amount);
// Use underlying and supply it to dydx
_mintDyDx(_amount);
}
function _mintDyDx(uint256 _amount)
internal {
Info[] memory infos = new Info[](1);
infos[0] = Info(address(this), 0);
AssetAmount memory amt = AssetAmount(true, AssetDenomination.Wei, AssetReference.Delta, _amount);
ActionArgs memory act;
act.actionType = ActionType.Deposit;
act.accountId = 0;
act.amount = amt;
act.primaryMarketId = marketId;
act.otherAddress = address(this);
ActionArgs[] memory args = new ActionArgs[](1);
args[0] = act;
DyDx(dydxAddressesProvider).operate(infos, args);
}
/**
* Gets all yxTokens in this contract and redeems underlying tokens.
* underlying tokens are then transferred to `_account`
* NOTE: yxTokens needs to be sended here before calling this
*
* @return underlying tokens redeemd
*/
function redeem(uint256 _amount, address _account)
external
returns (uint256 tokens) {
_redeemDyDx(_amount.mul(price()).div(10**18));
// transfer redeemed tokens to _account
IERC20 _underlying = IERC20(underlying);
tokens = _underlying.balanceOf(address(this));
_underlying.safeTransfer(_account, tokens);
_burn(msg.sender, _amount);
}
function _redeemDyDx(uint256 _amount)
internal {
Info[] memory infos = new Info[](1);
infos[0] = Info(address(this), 0);
AssetAmount memory amt = AssetAmount(false, AssetDenomination.Wei, AssetReference.Delta, _amount);
ActionArgs memory act;
act.actionType = ActionType.Withdraw;
act.accountId = 0;
act.amount = amt;
act.primaryMarketId = marketId;
act.otherAddress = address(this);
ActionArgs[] memory args = new ActionArgs[](1);
args[0] = act;
DyDx(dydxAddressesProvider).operate(infos, args);
}
}
| * Gets all underlying tokens in this contract and mints yxTokens tokens are then transferred to msg.sender NOTE: one must approve this contract before calling this method @return yxTokens minted/ mint IERC20 for dydx tokenized position Use underlying and supply it to dydx | function mint(uint256 _amount)
external
returns (uint256 newTokens) {
newTokens = _amount.mul(10**18).div(price());
_mint(msg.sender, newTokens);
IERC20(underlying).safeTransferFrom(msg.sender, address(this), _amount);
_mintDyDx(_amount);
}
| 6,387,954 | [
1,
3002,
777,
6808,
2430,
316,
333,
6835,
471,
312,
28142,
677,
92,
5157,
2430,
854,
1508,
906,
4193,
358,
1234,
18,
15330,
5219,
30,
1245,
1297,
6617,
537,
333,
6835,
1865,
4440,
333,
707,
327,
677,
92,
5157,
312,
474,
329,
19,
312,
474,
467,
654,
39,
3462,
364,
7732,
13437,
26073,
1754,
2672,
6808,
471,
14467,
518,
358,
7732,
13437,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
312,
474,
12,
11890,
5034,
389,
8949,
13,
203,
565,
3903,
203,
565,
1135,
261,
11890,
5034,
394,
5157,
13,
288,
203,
1377,
394,
5157,
273,
389,
8949,
18,
16411,
12,
2163,
636,
2643,
2934,
2892,
12,
8694,
10663,
203,
1377,
389,
81,
474,
12,
3576,
18,
15330,
16,
394,
5157,
1769,
203,
203,
1377,
467,
654,
39,
3462,
12,
9341,
6291,
2934,
4626,
5912,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
389,
8949,
1769,
203,
203,
1377,
389,
81,
474,
40,
93,
40,
92,
24899,
8949,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0xcA905F6466C253f8195b9940C819Ba32d273447d/sources/contracts/SettingsInternal.sol | Matrix Branch Limit
| uint8 max_expansion; | 860,356 | [
1,
4635,
15449,
7214,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
28,
943,
67,
2749,
12162,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
abstract contract stKSM is IERC20, Pausable {
/**
* @dev stKSM balances are dynamic and are calculated based on the accounts' shares
* and the total amount of KSM controlled by the protocol. Account shares aren't
* normalized, so the contract also stores the sum of all shares to calculate
* each account's token balance which equals to:
*
* shares[account] * _getTotalPooledKSM() / _getTotalShares()
*/
mapping (address => uint256) private shares;
/**
* @dev Allowances are nominated in tokens, not token shares.
*/
mapping (address => mapping (address => uint256)) private allowances;
/**
* @dev Storage position used for holding the total amount of shares in existence.
*/
uint256 internal totalShares;
/**
* @return the amount of tokens in existence.
*
* @dev Always equals to `_getTotalPooledKSM()` since token amount
* is pegged to the total amount of KSM controlled by the protocol.
*/
function totalSupply() public view override returns (uint256) {
return _getTotalPooledKSM();
}
/**
* @return the entire amount of KSMs controlled by the protocol.
*
* @dev The sum of all KSM balances in the protocol.
*/
function getTotalPooledKSM() public view returns (uint256) {
return _getTotalPooledKSM();
}
/**
* @return the amount of tokens owned by the `_account`.
*
* @dev Balances are dynamic and equal the `_account`'s share in the amount of the
* total KSM controlled by the protocol. See `sharesOf`.
*/
function balanceOf(address _account) public view override returns (uint256) {
return getPooledKSMByShares(_sharesOf(_account));
}
/**
* @notice Moves `_amount` tokens from the caller's account to the `_recipient` account.
*
* @return a boolean value indicating whether the operation succeeded.
* Emits a `Transfer` event.
*
* Requirements:
*
* - `_recipient` cannot be the zero address.
* - the caller must have a balance of at least `_amount`.
* - the contract must not be paused.
*
* @dev The `_amount` argument is the amount of tokens, not shares.
*/
function transfer(address _recipient, uint256 _amount) public override returns (bool) {
_transfer(msg.sender, _recipient, _amount);
return true;
}
/**
* @return the remaining number of tokens that `_spender` is allowed to spend
* on behalf of `_owner` through `transferFrom`. This is zero by default.
*
* @dev This value changes when `approve` or `transferFrom` is called.
*/
function allowance(address _owner, address _spender) public view override returns (uint256) {
return allowances[_owner][_spender];
}
/**
* @notice Sets `_amount` as the allowance of `_spender` over the caller's tokens.
*
* @return a boolean value indicating whether the operation succeeded.
* Emits an `Approval` event.
*
* Requirements:
*
* - `_spender` cannot be the zero address.
* - the contract must not be paused.
*
* @dev The `_amount` argument is the amount of tokens, not shares.
*/
function approve(address _spender, uint256 _amount) public override returns (bool) {
_approve(msg.sender, _spender, _amount);
return true;
}
/**
* @notice Moves `_amount` tokens from `_sender` to `_recipient` using the
* allowance mechanism. `_amount` is then deducted from the caller's
* allowance.
*
* @return a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
* Emits an `Approval` event indicating the updated allowance.
*
* Requirements:
*
* - `_sender` and `_recipient` cannot be the zero addresses.
* - `_sender` must have a balance of at least `_amount`.
* - the caller must have allowance for `_sender`'s tokens of at least `_amount`.
* - the contract must not be paused.
*
* @dev The `_amount` argument is the amount of tokens, not shares.
*/
function transferFrom(address _sender, address _recipient, uint256 _amount) public override returns (bool) {
uint256 currentAllowance = allowances[_sender][msg.sender];
require(currentAllowance >= _amount, "TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE");
_transfer(_sender, _recipient, _amount);
_approve(_sender, msg.sender, currentAllowance -_amount);
return true;
}
/**
* @notice Atomically increases the allowance granted to `_spender` by the caller by `_addedValue`.
*
* This is an alternative to `approve` that can be used as a mitigation for
* problems described in:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol#L42
* Emits an `Approval` event indicating the updated allowance.
*
* Requirements:
*
* - `_spender` cannot be the the zero address.
* - the contract must not be paused.
*/
function increaseAllowance(address _spender, uint256 _addedValue) public returns (bool) {
_approve(msg.sender, _spender, allowances[msg.sender][_spender] + _addedValue);
return true;
}
/**
* @notice Atomically decreases the allowance granted to `_spender` by the caller by `_subtractedValue`.
*
* This is an alternative to `approve` that can be used as a mitigation for
* problems described in:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol#L42
* 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`.
* - the contract must not be paused.
*/
function decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool) {
uint256 currentAllowance = allowances[msg.sender][_spender];
require(currentAllowance >= _subtractedValue, "DECREASED_ALLOWANCE_BELOW_ZERO");
_approve(msg.sender, _spender, currentAllowance-_subtractedValue);
return true;
}
/**
* @return the total amount of shares in existence.
*
* @dev The sum of all accounts' shares can be an arbitrary number, therefore
* it is necessary to store it in order to calculate each account's relative share.
*/
function getTotalShares() public view returns (uint256) {
return _getTotalShares();
}
/**
* @return the amount of shares owned by `_account`.
*/
function sharesOf(address _account) public view returns (uint256) {
return _sharesOf(_account);
}
/**
* @return the amount of shares that corresponds to `_ethAmount` protocol-controlled KSM.
*/
function getSharesByPooledKSM(uint256 _amount) public view returns (uint256) {
uint256 totalPooledKSM = _getTotalPooledKSM();
if (totalPooledKSM == 0) {
return 0;
} else {
return _amount * _getTotalShares() / totalPooledKSM;
}
}
/**
* @return the amount of KSM that corresponds to `_sharesAmount` token shares.
*/
function getPooledKSMByShares(uint256 _sharesAmount) public view returns (uint256) {
uint256 _totalShares = _getTotalShares();
if (totalShares == 0) {
return 0;
} else {
return _sharesAmount * _getTotalPooledKSM() / _totalShares;
}
}
/**
* @return the total amount (in wei) of KSM controlled by the protocol.
* @dev This is used for calaulating tokens from shares and vice versa.
* @dev This function is required to be implemented in a derived contract.
*/
function _getTotalPooledKSM() internal view virtual returns (uint256);
/**
* @notice Moves `_amount` tokens from `_sender` to `_recipient`.
* Emits a `Transfer` event.
*/
function _transfer(address _sender, address _recipient, uint256 _amount) internal {
uint256 _sharesToTransfer = getSharesByPooledKSM(_amount);
_transferShares(_sender, _recipient, _sharesToTransfer);
emit Transfer(_sender, _recipient, _amount);
}
/**
* @notice Sets `_amount` as the allowance of `_spender` over the `_owner` s tokens.
*
* Emits an `Approval` event.
*
* Requirements:
*
* - `_owner` cannot be the zero address.
* - `_spender` cannot be the zero address.
* - the contract must not be paused.
*/
function _approve(address _owner, address _spender, uint256 _amount) internal whenNotPaused {
require(_owner != address(0), "APPROVE_FROM_ZERO_ADDRESS");
require(_spender != address(0), "APPROVE_TO_ZERO_ADDRESS");
allowances[_owner][_spender] = _amount;
emit Approval(_owner, _spender, _amount);
}
/**
* @return the total amount of shares in existence.
*/
function _getTotalShares() internal view returns (uint256) {
return totalShares;
}
/**
* @return the amount of shares owned by `_account`.
*/
function _sharesOf(address _account) internal view returns (uint256) {
return shares[_account];
}
/**
* @notice Moves `_sharesAmount` shares from `_sender` to `_recipient`.
*
* Requirements:
*
* - `_sender` cannot be the zero address.
* - `_recipient` cannot be the zero address.
* - `_sender` must hold at least `_sharesAmount` shares.
* - the contract must not be paused.
*/
function _transferShares(address _sender, address _recipient, uint256 _sharesAmount) internal whenNotPaused {
require(_sender != address(0), "TRANSFER_FROM_THE_ZERO_ADDRESS");
require(_recipient != address(0), "TRANSFER_TO_THE_ZERO_ADDRESS");
uint256 currentSenderShares = shares[_sender];
require(_sharesAmount <= currentSenderShares, "TRANSFER_AMOUNT_EXCEEDS_BALANCE");
shares[_sender] = currentSenderShares - _sharesAmount;
shares[_recipient] = shares[_recipient] + _sharesAmount;
}
/**
* @notice Creates `_sharesAmount` shares and assigns them to `_recipient`, increasing the total amount of shares.
* @dev This doesn't increase the token total supply.
*
* Requirements:
*
* - `_recipient` cannot be the zero address.
* - the contract must not be paused.
*/
function _mintShares(address _recipient, uint256 _sharesAmount) internal whenNotPaused returns (uint256 newTotalShares) {
require(_recipient != address(0), "MINT_TO_THE_ZERO_ADDRESS");
newTotalShares = _getTotalShares() + _sharesAmount;
totalShares = newTotalShares;
shares[_recipient] = shares[_recipient] + _sharesAmount;
// Notice: we're not emitting a Transfer event from the zero address here since shares mint
// works by taking the amount of tokens corresponding to the minted shares from all other
// token holders, proportionally to their share. The total supply of the token doesn't change
// as the result. This is equivalent to performing a send from each other token holder's
// address to `address`, but we cannot reflect this as it would require sending an unbounded
// number of events.
}
/**
* @notice Destroys `_sharesAmount` shares from `_account`'s holdings, decreasing the total amount of shares.
* @dev This doesn't decrease the token total supply.
*
* Requirements:
*
* - `_account` cannot be the zero address.
* - `_account` must hold at least `_sharesAmount` shares.
* - the contract must not be paused.
*/
function _burnShares(address _account, uint256 _sharesAmount) internal whenNotPaused returns (uint256 newTotalShares) {
require(_account != address(0), "BURN_FROM_THE_ZERO_ADDRESS");
uint256 accountShares = shares[_account];
require(_sharesAmount <= accountShares, "BURN_AMOUNT_EXCEEDS_BALANCE");
newTotalShares = _getTotalShares() - _sharesAmount;
totalShares = newTotalShares;
shares[_account] = accountShares - _sharesAmount;
// Notice: we're not emitting a Transfer event to the zero address here since shares burn
// works by redistributing the amount of tokens corresponding to the burned shares between
// all other token holders. The total supply of the token doesn't change as the result.
// This is equivalent to performing a send from `address` to each other token holder address,
// but we cannot reflect this as it would require sending an unbounded number of events.
}
}
| * @dev stKSM balances are dynamic and are calculated based on the accounts' shares and the total amount of KSM controlled by the protocol. Account shares aren't normalized, so the contract also stores the sum of all shares to calculate each account's token balance which equals to: shares[account] _getTotalPooledKSM() / _getTotalShares()/* @dev Allowances are nominated in tokens, not token shares./* @dev Storage position used for holding the total amount of shares in existence./* @return the amount of tokens in existence. @dev Always equals to `_getTotalPooledKSM()` since token amount is pegged to the total amount of KSM controlled by the protocol./ | function totalSupply() public view override returns (uint256) {
return _getTotalPooledKSM();
}
| 2,510,472 | [
1,
334,
47,
7303,
324,
26488,
854,
5976,
471,
854,
8894,
2511,
603,
326,
9484,
11,
24123,
471,
326,
2078,
3844,
434,
1475,
7303,
25934,
635,
326,
1771,
18,
6590,
24123,
11526,
1404,
5640,
16,
1427,
326,
6835,
2546,
9064,
326,
2142,
434,
777,
24123,
358,
4604,
1517,
2236,
1807,
1147,
11013,
1492,
1606,
358,
30,
282,
24123,
63,
4631,
65,
225,
389,
588,
5269,
52,
22167,
47,
7303,
1435,
342,
389,
588,
5269,
24051,
1435,
19,
225,
7852,
6872,
854,
12457,
7458,
316,
2430,
16,
486,
1147,
24123,
18,
19,
225,
5235,
1754,
1399,
364,
19918,
326,
2078,
3844,
434,
24123,
316,
15782,
18,
19,
327,
326,
3844,
434,
2430,
316,
15782,
18,
225,
14178,
1606,
358,
1375,
67,
588,
5269,
52,
22167,
47,
7303,
20338,
3241,
1147,
3844,
353,
29231,
2423,
358,
326,
2078,
3844,
434,
1475,
7303,
25934,
635,
326,
1771,
18,
19,
2,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0
] | [
1,
565,
445,
2078,
3088,
1283,
1435,
1071,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
588,
5269,
52,
22167,
47,
7303,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "fungible_CDPToken.sol";
import "inheritingForTestPurpose.sol";
// Uniswap Pair Interface
interface UniswapV2PairLike {
function getReserves()
external
view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
}
// Uniswap Factory Interface
interface UniswapV2FactoryLike {
function getPair(address tokenA, address tokenB)
external
view
returns (address pair);
}
// Vat Interface
contract VatLike {
struct Ilk {
uint256 Art; // Total Normalised Debt [wad]
uint256 rate; // Accumulated Rates [ray]
uint256 spot; // Price with Safety Margin [ray]
uint256 line; // Debt Ceiling [rad]
uint256 dust; // Urn Debt Floor [rad]
}
struct Urn {
uint256 ink; // Locked Collateral [wad]
uint256 art; // Normalised Debt [wad]
}
mapping(bytes32 => Ilk) public ilks;
mapping(bytes32 => mapping(address => Urn)) public urns;
}
interface DSSProxyLike {
function execute(address _target, bytes memory _data)
external
payable
returns (bytes32 response);
}
contract CDPWrapper is inheritingForTestPurpose{
address private owner;
mapping(address => uint256) tokenizedCDPs; // Keep track of senders` CDP IDs
mapping(uint256 => uint256) tokenization; // Keep track of swap ratios
mapping(uint256 => uint256) depts;
uint256[] private wrappedCDPs;
CDPToken cdp_token; // Token Contract
// Maker Dao
DssCdpManagerLike private mk_cdpman = DssCdpManagerLike(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
ProxyRegistryLike private mk_proxy = ProxyRegistryLike(0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4);
UniswapV2FactoryLike private us_fac = UniswapV2FactoryLike(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f);
VatLike private vat = VatLike(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B);
address private DAI_TOKEN = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address private Wrapped_ETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
// Only Owner
modifier onlyOwner {
require(msg.sender==owner, "Not the owner");
_;
}
constructor() {
owner = msg.sender;
}
/**
* @dev Create CDPToken Contract
*
* The contract required a `CdpTokenizer` to be defined
* The `CdpTokenizer` is set to the address of this contract to
* permit others minting and burning tokens
*/
function createTokenContract() public onlyOwner returns(address) {
cdp_token = new CDPToken(address(this));
return address(cdp_token);
}
/**
* @dev Update Tokenizer within the Token Contract
*
* This function allows to flexibly upgrade this Contract
* Execute this function after deploying the upgraded contract
*/
function updateCDPTokenizer(address newtokenizer) public onlyOwner {
require(cdp_token.setTokenizer(newtokenizer), "Switch failed");
}
/**
* @dev Tokenize CDP by transfering ownership and reciving tokens.
*
* Automatically takes the `sender` first CDP
*/
function tokenizeCDP() public {
// Get Proxy of sender
address proxy = mk_proxy.proxies(msg.sender);
// Get CDP ID of first Vault
uint CDPID = mk_cdpman.first(proxy);
address urn = mk_cdpman.urns(CDPID);
(, uint256 rate,,,) = vat.ilks(ilk);
(uint256 collateral, uint256 dept) = vat.urns(ilk, urn);
require(dept*rate/10**27 * 2 < collateral, "CDP not enough collateralized; 200% required");
DSSProxyLike _proxy = DSSProxyLike(proxy);
// Make sure that everything that exceeds the 200% collateralization is directly paid back (20 dollar tolerance)
if (dept*rate/10**27 * 2 - 20 ether > collateral) {
uint256 change = collateral - dept*rate/10**27;
}
uint256 dai_eth = getExchangeRate();
uint256 amoutToMint = collateral - (dept*rate/10**27/dai_eth); // Differance between collateral in ETH and stablecoin dept in ETH
// Create proxy instance and execute the give function through it
bytes memory payload = abi.encodeWithSignature("give(uint256,address)", CDPID, address(this));
_proxy.execute(address(mk_cdpman), payload);
cdp_token.mint(msg.sender, amoutToMint);
depts[CDPID] = amoutToMint;
wrappedCDPs.push(CDPID);
}
/**
* @dev Overloaded function, see above.
*
* Allows to specify a specific CDP by ID
*/
function tokenizeCDP(uint256 CDPID) public {
address urn = mk_cdpman.urns(CDPID);
(, uint256 rate,,,) = vat.ilks(ilk);
(uint256 collateral, uint256 dept) = vat.urns(ilk, urn);
uint256 dai_eth = getExchangeRate();
uint256 amoutToMint = collateral - (dept*rate/10**27/dai_eth); // Differance between collateral in ETH and stablecoin dept in ETH
mk_cdpman.give(CDPID, address(this));
cdp_token.mint(msg.sender, amoutToMint);
depts[CDPID] = amoutToMint;
wrappedCDPs.push(CDPID);
}
/**
* @dev Unlock any CDP without any arguments
*/
function unlockAnyCDP() public returns(uint256 cdpid){
// Get Token balance of sender
uint256 balance = cdp_token.balanceOf(msg.sender);
for (uint256 i=0; i<wrappedCDPs.length-1; i++) {
if(depts[wrappedCDPs[i]] <= balance) {
cdp_token.burn(msg.sender, depts[wrappedCDPs[i]]);
// Grant access right of CDP to sender
mk_cdpman.give(wrappedCDPs[i], msg.sender);
wrappedCDPs[i] = wrappedCDPs[wrappedCDPs.length - 1];
delete wrappedCDPs[wrappedCDPs.length - 1];
wrappedCDPs.pop();
return wrappedCDPs[i];
}
}
return 0;
}
/**
* @dev Unlock specific CDP by providing its ID
*/
function unlockspecificCDP(uint256 CDPID) public returns(uint256 cdpid){
// Get Token balance of sender
uint256 balance = cdp_token.balanceOf(msg.sender);
require(balance >= depts[CDPID], "Not enough tokens to unlock this vault");
cdp_token.burn(msg.sender, depts[CDPID]);
// Grant access right of CDP to sender
mk_cdpman.give(CDPID, msg.sender);
wrappedCDPs[CDPID] = wrappedCDPs[wrappedCDPs.length - 1];
delete wrappedCDPs[wrappedCDPs.length - 1];
wrappedCDPs.pop();
return CDPID;
}
function getWrappedCDPCount() public view returns(uint count) {
return wrappedCDPs.length;
}
// get Uniswap's exchange rate of DAI/WETH
function getExchangeRate() public view returns (uint256) {
(uint256 a, uint256 b) = getTokenReserves_uni();
return a / b;
}
// get token reserves from the pool to determine the current exchange rate
function getTokenReserves_uni()
public
view
returns (uint256, uint256)
{
address pair = us_fac.getPair(DAI_TOKEN, Wrapped_ETH);
(uint256 reserve0, uint256 reserve1, ) = UniswapV2PairLike(pair).getReserves();
return (reserve0, reserve1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CDP Interface
interface DssCdpManagerLike {
function first(address) external returns(uint256); // Owner => First CDPId
function urns(uint256) external returns(address); // CDPId => UrnHandler
function give(uint cdp, address dst) external;
}
// Proxy Registry Interface
interface ProxyRegistryLike {
function proxies(address) external view returns (address);
// build proxy contract
function build(address owner) external;
}
contract inheritingForTestPurpose{
ProxyRegistryLike private mk_proxy = ProxyRegistryLike(0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4);
address private mk_action = 0x82ecD135Dce65Fbc6DbdD0e4237E0AF93FFD5038;
DssCdpManagerLike private mk_cdpman = DssCdpManagerLike(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
address private mk_jug = 0x19c0976f590D67707E62397C87829d896Dc0f1F1;
address private mk_ethjoin = 0x2F0b23f53734252Bda2277357e97e1517d6B042A;
address private mk_daijoin = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
bytes32 ilk =
0x4554482d41000000000000000000000000000000000000000000000000000000;
uint256 public cdpi;
function buildProxyOpenCdpLockETH() public payable {
if (mk_proxy.proxies(msg.sender) == address(0)) {
mk_proxy.build(msg.sender);
}
bytes memory payload =
abi.encodeWithSignature(
"openLockETHAndDraw(address,address,address,address,bytes32,uint256)",
mk_cdpman,
mk_jug,
mk_ethjoin,
mk_daijoin,
ilk,
0
);
(bool success, ) = mk_proxy.proxies(msg.sender).call{value: msg.value}(abi.encodeWithSignature("execute(address,bytes)",
mk_action,
payload
));
require(success, "no success");
cdpi = mk_cdpman.first(mk_proxy.proxies(msg.sender));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "IERC20.sol";
import "IERC20Metadata.sol";
import "Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract CDPToken is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name = "TokenizedCDP";
string private _symbol = "tCDP";
address private _tokenizer;
modifier onlyCdpTokenizer {
require(msg.sender==_tokenizer, "Not the Tokenizer");
_;
}
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (address tokenizer_) {
_tokenizer = tokenizer_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves 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");
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);
}
/** @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");
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
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);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function mint(address account, uint256 amount) public onlyCdpTokenizer returns (bool) {
_mint(account, amount);
return true;
}
function burn(address account, uint256 amount) public onlyCdpTokenizer returns (bool) {
_burn(account, amount);
return true;
}
function setTokenizer(address account) public onlyCdpTokenizer returns (bool) {
_tokenizer = account;
return true;
}
function tokenizerAddress() public view virtual returns (address) {
return _tokenizer;
}
}
| Keep track of senders` CDP IDs
| mapping(address => uint256) tokenizedCDPs; | 7,218,894 | [
1,
11523,
3298,
434,
1366,
414,
68,
385,
8640,
7115,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
26073,
39,
8640,
87,
31,
282,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-10-27
*/
/*
KakaShi-Inu
Telegram: https://t.me/KakashiInuERC
1 Quadrillion supply
2% Dev tax
5% marketing
1% liquidity
2% Reflection to Holders
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return payable(msg.sender);
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount)
external
returns (bool);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
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);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage
) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: weiValue}(
data
);
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract Ownable is Context {
address private _owner;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
function getUnlockTime() public view returns (uint256) {
return _lockTime;
}
function getTime() public view returns (uint256) {
return block.timestamp;
}
}
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 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 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 IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
contract KakashiInu is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
address payable public marketingAddress;
address payable public devAddress;
address payable public liquidityAddress;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
bool public transferDelayEnabled = true;
bool public limitsInEffect = true;
mapping(address => bool) private _isExcludedFromFee;
mapping(address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1 * 1e15 * 1e9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private constant _name = "Kakashi-Inu";
string private constant _symbol = "HATAKE";
uint8 private constant _decimals = 9;
// these values are pretty much arbitrary since they get overwritten for every txn, but the placeholders make it easier to work with current contract.
uint256 private _taxFee;
uint256 private _previousTaxFee = _taxFee;
uint256 private _marketingFee;
uint256 private _liquidityFee;
uint256 private _previousLiquidityFee = _liquidityFee;
uint256 private constant BUY = 1;
uint256 private constant SELL = 2;
uint256 private constant TRANSFER = 3;
uint256 private buyOrSellSwitch;
uint256 public _buyTaxFee = 2;
uint256 public _buyLiquidityFee = 1;
uint256 public _buyMarketingFee = 7;
uint256 public _sellTaxFee = 2;
uint256 public _sellLiquidityFee = 1;
uint256 public _sellMarketingFee = 7;
uint256 public tradingActiveBlock = 0; // 0 means trading is not active
mapping(address => bool) public boughtEarly; // mapping to track addresses that buy within the first 2 blocks pay a 3x tax for 24 hours to sell
uint256 public earlyBuyPenaltyEnd; // determines when snipers/bots can sell without extra penalty
uint256 public _liquidityTokensToSwap;
uint256 public _marketingTokensToSwap;
uint256 public maxTransactionAmount;
uint256 public maxWalletAmount;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
bool private gasLimitActive = true;
uint256 private gasPriceLimit = 500 * 1 gwei; // do not allow over 500 gwei for launch
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
uint256 private minimumTokensBeforeSwap;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = false;
bool public tradingActive = false;
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event SwapETHForTokens(uint256 amountIn, address[] path);
event SwapTokensForETH(uint256 amountIn, address[] path);
event SetAutomatedMarketMakerPair(address pair, bool value);
event ExcludeFromReward(address excludedAddress);
event IncludeInReward(address includedAddress);
event ExcludeFromFee(address excludedAddress);
event IncludeInFee(address includedAddress);
event SetBuyFee(uint256 marketingFee, uint256 liquidityFee, uint256 reflectFee);
event SetSellFee(uint256 marketingFee, uint256 liquidityFee, uint256 reflectFee);
event TransferForeignToken(address token, uint256 amount);
event UpdatedMarketingAddress(address marketing);
event UpdatedLiquidityAddress(address liquidity);
event OwnerForcedSwapBack(uint256 timestamp);
event BoughtEarly(address indexed sniper);
event RemovedSniper(address indexed notsnipersupposedly);
modifier lockTheSwap() {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor() payable {
_rOwned[_msgSender()] = _rTotal / 1000 * 400;
_rOwned[address(this)] = _rTotal / 1000 * 600;
maxTransactionAmount = _tTotal * 5 / 1000; // 0.5% maxTransactionAmountTxn
maxWalletAmount = _tTotal * 15 / 1000; // 1.5% maxWalletAmount
minimumTokensBeforeSwap = _tTotal * 5 / 10000; // 0.05% swap tokens amount
marketingAddress = payable(0xdD54C821566a6119B5A894A43ee33F80FAA4A60F); // Marketing Address
devAddress = payable(0xc23062d9b7d1048119a29C59EFeC76C2Fec0Ba68); // Dev Address
liquidityAddress = payable(owner());
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[marketingAddress] = true;
_isExcludedFromFee[liquidityAddress] = true;
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
emit Transfer(address(0), _msgSender(), _tTotal * 400 / 1000);
emit Transfer(address(0), address(this), _tTotal * 600 / 1000);
}
function name() external pure returns (string memory) {
return _name;
}
function symbol() external pure returns (string memory) {
return _symbol;
}
function decimals() external pure returns (uint8) {
return _decimals;
}
function totalSupply() external pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount)
external
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
external
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) external override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function increaseAllowance(address spender, uint256 addedValue)
external
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(addedValue)
);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue)
external
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
"ERC20: decreased allowance below zero"
)
);
return true;
}
function isExcludedFromReward(address account)
external
view
returns (bool)
{
return _isExcluded[account];
}
function totalFees() external view returns (uint256) {
return _tFeeTotal;
}
// remove limits after token is stable - 30-60 minutes
function removeLimits() external onlyOwner returns (bool){
limitsInEffect = false;
gasLimitActive = false;
transferDelayEnabled = false;
return true;
}
// disable Transfer delay
function disableTransferDelay() external onlyOwner returns (bool){
transferDelayEnabled = false;
return true;
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
// once enabled, can never be turned off
function enableTrading() internal onlyOwner {
tradingActive = true;
swapAndLiquifyEnabled = true;
tradingActiveBlock = block.number;
earlyBuyPenaltyEnd = block.timestamp + 72 hours;
}
// send tokens and ETH for liquidity to contract directly, then call this (not required, can still use Uniswap to add liquidity manually, but this ensures everything is excluded properly and makes for a great stealth launch)
function launch(address[] memory airdropWallets, uint256[] memory amounts) external onlyOwner returns (bool){
require(!tradingActive, "Trading is already active, cannot relaunch.");
require(airdropWallets.length < 200, "Can only airdrop 200 wallets per txn due to gas limits"); // allows for airdrop + launch at the same exact time, reducing delays and reducing sniper input.
for(uint256 i = 0; i < airdropWallets.length; i++){
address wallet = airdropWallets[i];
uint256 amount = amounts[i] * (10 ** _decimals);
_transfer(msg.sender, wallet, amount);
}
enableTrading();
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
_approve(address(this), address(uniswapV2Router), _tTotal);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
require(address(this).balance > 0, "Must have ETH on contract to launch");
addLiquidity(balanceOf(address(this)), address(this).balance);
return true;
}
function minimumTokensBeforeSwapAmount() external view returns (uint256) {
return minimumTokensBeforeSwap;
}
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;
_isExcludedMaxTransactionAmount[pair] = value;
if(value){excludeFromReward(pair);}
if(!value){includeInReward(pair);}
}
function setGasPriceLimit(uint256 gas) external onlyOwner {
require(gas >= 200);
gasPriceLimit = gas * 1 gwei;
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee)
external
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");
require(_excluded.length + 1 <= 50, "Cannot exclude more than 50 accounts. Include a previously excluded address.");
if (_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) public onlyOwner {
require(_isExcluded[account], "Account is not 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 _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(!tradingActive){
require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet.");
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!inSwapAndLiquify
){
if(from != owner() && to != uniswapV2Pair && block.number == tradingActiveBlock){
boughtEarly[to] = true;
emit BoughtEarly(to);
}
// only use to prevent sniper buys in the first blocks.
if (gasLimitActive && automatedMarketMakerPairs[from]) {
require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit.");
}
// at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[to] < block.number && _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[to] = block.number;
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
//when buy
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
}
//when sell
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
if (!_isExcludedMaxTransactionAmount[to]) {
require(balanceOf(to) + amount <= maxWalletAmount, "Max wallet exceeded");
}
}
}
uint256 totalTokensToSwap = _liquidityTokensToSwap.add(_marketingTokensToSwap);
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap;
// swap and liquify
if (
!inSwapAndLiquify &&
swapAndLiquifyEnabled &&
balanceOf(uniswapV2Pair) > 0 &&
totalTokensToSwap > 0 &&
!_isExcludedFromFee[to] &&
!_isExcludedFromFee[from] &&
automatedMarketMakerPairs[to] &&
overMinimumTokenBalance
) {
swapBack();
}
bool takeFee = true;
// If any account belongs to _isExcludedFromFee account then remove the fee
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
buyOrSellSwitch = TRANSFER; // TRANSFERs do not pay a tax.
} else {
// Buy
if (automatedMarketMakerPairs[from]) {
removeAllFee();
_taxFee = _buyTaxFee;
_liquidityFee = _buyLiquidityFee + _buyMarketingFee;
buyOrSellSwitch = BUY;
}
// Sell
else if (automatedMarketMakerPairs[to]) {
removeAllFee();
_taxFee = _sellTaxFee;
_liquidityFee = _sellLiquidityFee + _sellMarketingFee;
buyOrSellSwitch = SELL;
// higher tax if bought in the same block as trading active for 72 hours (sniper protect)
if(boughtEarly[from] && earlyBuyPenaltyEnd > block.timestamp){
_taxFee = _taxFee * 5;
_liquidityFee = _liquidityFee * 5;
}
// Normal transfers do not get taxed
} else {
require(!boughtEarly[from] || earlyBuyPenaltyEnd <= block.timestamp, "Snipers can't transfer tokens to sell cheaper until penalty timeframe is over. DM a Mod.");
removeAllFee();
buyOrSellSwitch = TRANSFER; // TRANSFERs do not pay a tax.
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function swapBack() private lockTheSwap {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = _liquidityTokensToSwap + _marketingTokensToSwap;
// Halve the amount of liquidity tokens
uint256 tokensForLiquidity = _liquidityTokensToSwap.div(2);
uint256 amountToSwapForETH = contractBalance.sub(tokensForLiquidity);
uint256 initialETHBalance = address(this).balance;
swapTokensForETH(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(_marketingTokensToSwap).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance.sub(ethForMarketing);
uint256 ethForDev= ethForMarketing * 2 / 7; // 2/7 gos to dev
ethForMarketing -= ethForDev;
_liquidityTokensToSwap = 0;
_marketingTokensToSwap = 0;
(bool success,) = address(marketingAddress).call{value: ethForMarketing}("");
(success,) = address(devAddress).call{value: ethForDev}("");
addLiquidity(tokensForLiquidity, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
// send leftover BNB to the marketing wallet so it doesn't get stuck on the contract.
if(address(this).balance > 1e17){
(success,) = address(marketingAddress).call{value: address(this).balance}("");
}
}
// force Swap back if slippage above 49% for launch.
function forceSwapBack() external onlyOwner {
uint256 contractBalance = balanceOf(address(this));
require(contractBalance >= _tTotal / 100, "Can only swap back if more than 1% of tokens stuck on contract");
swapBack();
emit OwnerForcedSwapBack(block.timestamp);
}
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, // accept any amount of ETH
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, // slippage is unavoidable
0, // slippage is unavoidable
liquidityAddress,
block.timestamp
);
}
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]) {
_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);
}
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 _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 {
if(buyOrSellSwitch == BUY){
_liquidityTokensToSwap += tLiquidity * _buyLiquidityFee / _liquidityFee;
_marketingTokensToSwap += tLiquidity * _buyMarketingFee / _liquidityFee;
} else if(buyOrSellSwitch == SELL){
_liquidityTokensToSwap += tLiquidity * _sellLiquidityFee / _liquidityFee;
_marketingTokensToSwap += tLiquidity * _sellMarketingFee / _liquidityFee;
}
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if (_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(10**2);
}
function calculateLiquidityFee(uint256 _amount)
private
view
returns (uint256)
{
return _amount.mul(_liquidityFee).div(10**2);
}
function removeAllFee() private {
if (_taxFee == 0 && _liquidityFee == 0) return;
_previousTaxFee = _taxFee;
_previousLiquidityFee = _liquidityFee;
_taxFee = 0;
_liquidityFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_liquidityFee = _previousLiquidityFee;
}
function isExcludedFromFee(address account) external view returns (bool) {
return _isExcludedFromFee[account];
}
function removeBoughtEarly(address account) external onlyOwner {
boughtEarly[account] = false;
emit RemovedSniper(account);
}
function excludeFromFee(address account) external onlyOwner {
_isExcludedFromFee[account] = true;
emit ExcludeFromFee(account);
}
function includeInFee(address account) external onlyOwner {
_isExcludedFromFee[account] = false;
emit IncludeInFee(account);
}
function setBuyFee(uint256 buyTaxFee, uint256 buyLiquidityFee, uint256 buyMarketingFee)
external
onlyOwner
{
_buyTaxFee = buyTaxFee;
_buyLiquidityFee = buyLiquidityFee;
_buyMarketingFee = buyMarketingFee;
require(_buyTaxFee + _buyLiquidityFee + _buyMarketingFee <= 10, "Must keep buy taxes below 10%");
emit SetBuyFee(buyMarketingFee, buyLiquidityFee, buyTaxFee);
}
function setSellFee(uint256 sellTaxFee, uint256 sellLiquidityFee, uint256 sellMarketingFee)
external
onlyOwner
{
_sellTaxFee = sellTaxFee;
_sellLiquidityFee = sellLiquidityFee;
_sellMarketingFee = sellMarketingFee;
require(_sellTaxFee + _sellLiquidityFee + _sellMarketingFee <= 15, "Must keep sell taxes below 15%");
emit SetSellFee(sellMarketingFee, sellLiquidityFee, sellTaxFee);
}
function setMarketingAddress(address _marketingAddress) external onlyOwner {
require(_marketingAddress != address(0), "_marketingAddress address cannot be 0");
_isExcludedFromFee[marketingAddress] = false;
marketingAddress = payable(_marketingAddress);
_isExcludedFromFee[marketingAddress] = true;
emit UpdatedMarketingAddress(_marketingAddress);
}
function setLiquidityAddress(address _liquidityAddress) public onlyOwner {
require(_liquidityAddress != address(0), "_liquidityAddress address cannot be 0");
liquidityAddress = payable(_liquidityAddress);
_isExcludedFromFee[liquidityAddress] = true;
emit UpdatedLiquidityAddress(_liquidityAddress);
}
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
// To receive ETH from uniswapV2Router when swapping
receive() external payable {}
function transferForeignToken(address _token, address _to)
external
onlyOwner
returns (bool _sent)
{
require(_token != address(0), "_token address cannot be 0");
require(_token != address(this), "Can't withdraw native tokens");
uint256 _contractBalance = IERC20(_token).balanceOf(address(this));
_sent = IERC20(_token).transfer(_to, _contractBalance);
emit TransferForeignToken(_token, _contractBalance);
}
// withdraw ETH if stuck before launch
function withdrawStuckETH() external onlyOwner {
require(!tradingActive, "Can only withdraw if trading hasn't started");
bool success;
(success,) = address(msg.sender).call{value: address(this).balance}("");
}
} | send tokens and ETH for liquidity to contract directly, then call this (not required, can still use Uniswap to add liquidity manually, but this ensures everything is excluded properly and makes for a great stealth launch) | function launch(address[] memory airdropWallets, uint256[] memory amounts) external onlyOwner returns (bool){
require(!tradingActive, "Trading is already active, cannot relaunch.");
for(uint256 i = 0; i < airdropWallets.length; i++){
address wallet = airdropWallets[i];
uint256 amount = amounts[i] * (10 ** _decimals);
_transfer(msg.sender, wallet, amount);
}
enableTrading();
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
_approve(address(this), address(uniswapV2Router), _tTotal);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
require(address(this).balance > 0, "Must have ETH on contract to launch");
addLiquidity(balanceOf(address(this)), address(this).balance);
return true;
}
| 15,263,984 | [
1,
4661,
2430,
471,
512,
2455,
364,
4501,
372,
24237,
358,
6835,
5122,
16,
1508,
745,
333,
261,
902,
1931,
16,
848,
4859,
999,
1351,
291,
91,
438,
358,
527,
4501,
372,
24237,
10036,
16,
1496,
333,
11932,
7756,
353,
8845,
8214,
471,
7297,
364,
279,
18825,
18654,
4162,
8037,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
8037,
12,
2867,
8526,
3778,
279,
6909,
1764,
26558,
2413,
16,
2254,
5034,
8526,
3778,
30980,
13,
3903,
1338,
5541,
1135,
261,
6430,
15329,
203,
3639,
2583,
12,
5,
313,
14968,
3896,
16,
315,
1609,
7459,
353,
1818,
2695,
16,
2780,
1279,
4760,
1199,
1769,
203,
3639,
364,
12,
11890,
5034,
277,
273,
374,
31,
277,
411,
279,
6909,
1764,
26558,
2413,
18,
2469,
31,
277,
27245,
95,
203,
5411,
1758,
9230,
273,
279,
6909,
1764,
26558,
2413,
63,
77,
15533,
203,
5411,
2254,
5034,
3844,
273,
30980,
63,
77,
65,
380,
261,
2163,
2826,
389,
31734,
1769,
203,
5411,
389,
13866,
12,
3576,
18,
15330,
16,
9230,
16,
3844,
1769,
203,
3639,
289,
203,
3639,
4237,
1609,
7459,
5621,
203,
3639,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
389,
318,
291,
91,
438,
58,
22,
8259,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
12,
20,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
71,
42,
25,
5520,
27,
5520,
72,
42,
22,
39,
25,
72,
37,
7358,
24,
71,
26,
6162,
42,
3247,
5482,
40,
1769,
203,
3639,
4433,
1265,
2747,
3342,
12,
2867,
24899,
318,
291,
91,
438,
58,
22,
8259,
3631,
638,
1769,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
3639,
389,
12908,
537,
12,
2867,
12,
2211,
3631,
1758,
12,
318,
291,
91,
438,
58,
22,
8259,
3631,
389,
88,
5269,
1769,
203,
3639,
640,
291,
91,
438,
58,
2
] |
/**
*Submitted for verification at Etherscan.io on 2021-07-05
*/
pragma solidity 0.8.4;
// SPDX-License-Identifier: Apache-2.0
// https://t.me/RealSpaceGhost
interface IERC20 {
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @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;
}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event 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 burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// pragma solidity >=0.6.2;
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract SpaceGhost is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
uint256 private _totalSupply = 1_000_000_000_000_000 * 10**9;
string private _name = "Spce Ghost";
string private _symbol = "SGHOST";
uint8 private _decimals = 9;
uint256 public _liquidityFee = 6;
uint256 private _previousLiquidityFee = _liquidityFee;
uint256 public _devFee = 2;
uint256 private _previousDevFee = _devFee;
address payable private _teamDevAddress;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool currentlySwapping;
bool public swapAndRedirectEthFeesEnabled = true;
uint256 private tokensSoldThresholdForEthSwap = 10000 * 10**9;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndRedirectEthFeesUpdated(bool enabled);
event OnSwapAndRedirectEthFees(
uint256 tokensSwapped,
uint256 ethToLiquidity,
uint256 ethToDevWallet
);
modifier lockTheSwap {
currentlySwapping = true;
_;
currentlySwapping = false;
}
constructor () {
_balances[_msgSender()] = _totalSupply;
emit Transfer(address(0), _msgSender(), _totalSupply);
}
function initContract() external onlyOwner() {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
// Create a uniswap pair for this new token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
// exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_teamDevAddress = payable(0xBdCa8ED2E34df859505324a9aef9581da32D5FA4);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _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(amount > 0, "Transfer amount must be greater than zero");
// 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 uniswap pair.
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinTokenBalance = contractTokenBalance >= tokensSoldThresholdForEthSwap;
if (
overMinTokenBalance &&
!currentlySwapping &&
from != uniswapV2Pair &&
swapAndRedirectEthFeesEnabled
) {
// add liquidity and dev eth fees
swapAndRedirectEthFees(contractTokenBalance);
}
// transfer amount
_tokenTransfer(from, to, amount);
}
//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(address sender, address recipient, uint256 amount) private {
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]) {
removeAllFee();
}
(uint256 tTransferAmount, uint256 tLiquidity, uint256 tDev) = _getValues(amount);
_balances[sender] = _balances[sender].sub(tTransferAmount);
_balances[recipient] = _balances[recipient].add(tTransferAmount);
_takeLiquidity(tLiquidity);
_takeDevFee(tDev);
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]) {
restoreAllFee();
}
emit Transfer(sender, recipient, tTransferAmount);
}
//to recieve ETH from uniswapV2Router when swaping
receive() external payable {}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256) {
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tDev = calculateDevFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tLiquidity).sub(tDev);
return (tTransferAmount, tLiquidity, tDev);
}
function _takeLiquidity(uint256 liquidityAmount) private {
_balances[address(this)] = _balances[address(this)].add(liquidityAmount);
}
function _takeDevFee(uint256 devAmount) private {
_balances[address(this)] = _balances[address(this)].add(devAmount);
}
function calculateDevFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_devFee).div(100);
}
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_liquidityFee).div(100);
}
function removeAllFee() private {
if(_liquidityFee == 0 && _devFee== 0) return;
_previousLiquidityFee = _liquidityFee;
_previousDevFee = _devFee;
_liquidityFee = 0;
_devFee = 0;
}
function restoreAllFee() private {
_liquidityFee = _previousLiquidityFee;
_devFee = _previousDevFee;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function swapAndRedirectEthFees(uint256 contractTokenBalance) private lockTheSwap {
// balance token fees based on variable percents
uint256 totalRedirectTokenFee = _devFee.add(_liquidityFee);
uint256 liquidityTokenBalance = contractTokenBalance.mul(_liquidityFee).div(totalRedirectTokenFee);
uint256 devTokenBalance = contractTokenBalance.mul(_devFee).div(totalRedirectTokenFee);
// split the liquidity balance into halves
uint256 halfLiquidity = liquidityTokenBalance.div(2);
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the fee events include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(devTokenBalance.add(halfLiquidity));
uint256 newBalance = address(this).balance.sub(initialBalance);
if(newBalance > 0) {
// rebalance ETH fees proportionally to half the liquidity
uint256 totalRedirectEthFee = _devFee.add(_liquidityFee.div(2));
uint256 liquidityEthBalance = newBalance.mul(_liquidityFee.div(2)).div(totalRedirectEthFee);
uint256 devEthBalance = newBalance.mul(_devFee).div(totalRedirectEthFee);
//
// for liquidity
// add to uniswap
//
addLiquidity(halfLiquidity, liquidityEthBalance);
//
// for dev fee
// send to the dev address
//
sendEthToDevAddress(devEthBalance);
emit OnSwapAndRedirectEthFees(contractTokenBalance, liquidityEthBalance, devEthBalance);
}
}
function sendEthToDevAddress(uint256 amount) private {
_teamDevAddress.transfer(amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount} (
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(),
block.timestamp
);
}
function manualSwap() external onlyOwner() {
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualSend() external onlyOwner() {
uint256 contractEthBalance = address(this).balance;
sendEthToDevAddress(contractEthBalance);
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function disableAllFees() external onlyOwner() {
_devFee = 0;
_liquidityFee = 0;
_previousLiquidityFee = _liquidityFee;
_previousDevFee = _devFee;
swapAndRedirectEthFeesEnabled = false;
emit SwapAndRedirectEthFeesUpdated(false);
}
function _setDevWallet(address payable teamDevAddress) external onlyOwner() {
_teamDevAddress = teamDevAddress;
}
function setRouterAddress(address newRouter) public onlyOwner() {
IUniswapV2Router02 _newUniswapRouter = IUniswapV2Router02(newRouter);
uniswapV2Pair = IUniswapV2Factory(_newUniswapRouter.factory()).createPair(address(this), _newUniswapRouter.WETH());
uniswapV2Router = _newUniswapRouter;
}
function setSwapAndRedirectEthFeesEnabled(bool _enabled) public onlyOwner {
swapAndRedirectEthFeesEnabled = _enabled;
emit SwapAndRedirectEthFeesUpdated(_enabled);
}
} | Create a uniswap pair for this new token set the rest of the contract variables exclude owner and this contract from fee | function initContract() external onlyOwner() {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_teamDevAddress = payable(0xBdCa8ED2E34df859505324a9aef9581da32D5FA4);
}
| 2,100,472 | [
1,
1684,
279,
640,
291,
91,
438,
3082,
364,
333,
394,
1147,
444,
326,
3127,
434,
326,
6835,
3152,
4433,
3410,
471,
333,
6835,
628,
14036,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1208,
8924,
1435,
3903,
1338,
5541,
1435,
288,
203,
3639,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
389,
318,
291,
91,
438,
58,
22,
8259,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
12,
20,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
71,
42,
25,
5520,
27,
5520,
72,
42,
22,
39,
25,
72,
37,
7358,
24,
71,
26,
6162,
42,
3247,
5482,
40,
1769,
203,
3639,
640,
291,
91,
438,
58,
22,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
24899,
318,
291,
91,
438,
58,
22,
8259,
18,
6848,
10756,
203,
5411,
263,
2640,
4154,
12,
2867,
12,
2211,
3631,
389,
318,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
10663,
203,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
540,
203,
3639,
389,
291,
16461,
1265,
14667,
63,
8443,
1435,
65,
273,
638,
31,
203,
3639,
389,
291,
16461,
1265,
14667,
63,
2867,
12,
2211,
25887,
273,
638,
31,
203,
540,
203,
3639,
389,
10035,
8870,
1887,
273,
8843,
429,
12,
20,
20029,
72,
23508,
28,
2056,
22,
41,
5026,
2180,
28,
6162,
3361,
25,
1578,
24,
69,
29,
8906,
74,
29,
8204,
21,
2414,
1578,
40,
25,
2046,
24,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.0 <0.8.0;
contract crowdfunding {
enum Status { processing, success, failed }
struct Investor {
address payable addr;
uint amount;
}
struct Funding {
address payable creator;
uint num_investors;
mapping(uint => Investor) investors;
uint start_time;
uint end_time;
string title;
string info;
uint amount_goal;
uint amount_get;
Status status; // 0: processing 1: success 2: failed
uint num_requests;
mapping(uint => Request) requests;
}
struct Request {
string purpose;
uint amount;
mapping(uint => uint) reply_status; // investor's reply:
//0: no reply 1: agree 2: disagree
Status status;
uint pass_amount;
uint nopass_amount;
}
uint num_funding;
mapping(uint => Funding) fundings;
function create_funding(string memory title, string memory info, uint e_time, uint amount) public returns(uint fundingID) {
require(e_time > block.timestamp);
fundingID = num_funding++;
Funding storage tmp = fundings[fundingID];
tmp.title = title;
tmp.info = info;
tmp.creator = msg.sender;
tmp.start_time = block.timestamp;
tmp.end_time = e_time;
tmp.amount_goal = amount;
}
function participant_funding(uint fundingID) public payable {
require(fundingID >= 0 && fundingID < num_funding);
require(fundings[fundingID].status == Status.processing);
require(msg.value > 0 && msg.value <= fundings[fundingID].amount_goal - fundings[fundingID].amount_get);
Funding storage tmp = fundings[fundingID];
tmp.investors[tmp.num_investors++] = Investor({addr: msg.sender, amount: msg.value});
tmp.amount_get += msg.value;
bool reach = check_goal_reached(fundingID);
if(reach == true) {
tmp.status = Status.success;
}
}
function return_eth(uint fundingID) public {
require(fundingID >= 0 && fundingID < num_funding);
Funding storage tmp = fundings[fundingID];
for(uint i = 0; i < tmp.num_investors; i++) {
if(tmp.investors[i].addr == msg.sender) {
tmp.investors[i].addr.transfer(tmp.investors[i].amount);
tmp.amount_get -= tmp.investors[i].amount;
tmp.investors[i].amount = 0;
}
}
}
function check_goal_reached(uint fundingID) view public returns (bool reached) {
Funding storage tmp = fundings[fundingID];
if(tmp.amount_get < tmp.amount_goal)
return false;
return true;
}
function create_request(uint fundingID, string memory p, uint a) public {
require(fundingID >= 0 && fundingID < num_funding);
require(fundings[fundingID].status == Status.success);
require(a <= fundings[fundingID].amount_get);
require(msg.sender == fundings[fundingID].creator);
Funding storage tmp = fundings[fundingID];
uint requestID = tmp.num_requests++;
Request storage request = tmp.requests[requestID];
request.amount = a;
request.purpose = p;
}
function reply(uint fundingID, uint requestID, bool agree) public {
require(fundingID >= 0 && fundingID < num_funding);
require(requestID >= 0 && requestID < fundings[fundingID].num_requests);
require(fundings[fundingID].requests[requestID].status == Status.processing);
for(uint i = 0; i < fundings[fundingID].num_investors; i++) {
if(fundings[fundingID].investors[i].addr == msg.sender) {
if(agree) {
fundings[fundingID].requests[requestID].reply_status[i] == 1;
fundings[fundingID].requests[requestID].pass_amount += fundings[fundingID].investors[i].amount;
} else {
fundings[fundingID].requests[requestID].reply_status[i] == 2;
fundings[fundingID].requests[requestID].nopass_amount += fundings[fundingID].investors[i].amount;
}
}
}
check_pass(fundingID, requestID);
}
function check_pass(uint fundingID, uint requestID) public{
if(fundings[fundingID].requests[requestID].pass_amount >= fundings[fundingID].amount_goal / 2) {
fundings[fundingID].requests[requestID].status = Status.success;
fundings[fundingID].creator.transfer(fundings[fundingID].requests[requestID].amount);
} else if(fundings[fundingID].requests[requestID].nopass_amount >= fundings[fundingID].amount_goal / 2) {
fundings[fundingID].requests[requestID].status = Status.failed;
}
}
function get_num_fundings() public view returns(uint n) {
return num_funding;
}
function get_funding(uint index) public view returns(uint id, address payable creator, uint amount, uint amount_get, uint start_time, uint end_time, Status status, string memory info, string memory title) {
Funding storage tmp = fundings[index];
return (index, tmp.creator, tmp.amount_goal, tmp.amount_get, tmp.start_time, tmp.end_time, tmp.status, tmp.info, tmp.title);
}
function get_funding_con(uint index, address payable s) public view returns(uint id, address payable creator, uint amount, uint amount_get, uint start_time, uint end_time, Status status, string memory info, string memory title, uint contribution) {
Funding storage tmp = fundings[index];
uint res;
for(uint i = 0; i < tmp.num_investors; i++) {
if(tmp.investors[i].addr == s) {
res = tmp.investors[i].amount;
}
}
return (index, tmp.creator, tmp.amount_goal, tmp.amount_get, tmp.start_time, tmp.end_time, tmp.status, tmp.info, tmp.title, res);
}
function get_num_request(uint id) public view returns(uint n) {
return fundings[id].num_requests;
}
function get_request(uint index, uint rid, address payable inv) public view returns(string memory purpose, uint amount, Status status, uint r) {
Request storage tmp = fundings[index].requests[rid];
uint ind;
for(uint i = 0; i < fundings[index].num_investors; i++) {
if(fundings[index].investors[i].addr == inv) {
ind = i;
}
}
return (tmp.purpose, tmp.amount, tmp.status, tmp.reply_status[ind]);
}
function check_part(uint index, address addr) public view returns(bool r) {
Funding storage tmp = fundings[index];
bool res = false;
for(uint i = 0; i < tmp.num_investors; i++) {
if(addr == tmp.investors[i].addr) {
res = true;
break;
}
}
return res;
}
function check_time() public {
for(uint i = 0; i < num_funding; i++) {
if(fundings[i].end_time < block.timestamp && fundings[i].status == Status.processing) {
fundings[i].status = Status.failed;
}
}
}
} | investor's reply:
| mapping(uint => uint) reply_status; | 12,800,768 | [
1,
5768,
395,
280,
1807,
4332,
30,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2874,
12,
11890,
516,
2254,
13,
4332,
67,
2327,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.6.12;
interface IERC20 { // brief interface for erc20 token tx
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
}
library Address { // helper for address type - see openzeppelin-contracts/blob/master/contracts/utils/Address.sol
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
}
library SafeERC20 { // wrapper around erc20 token tx for non-standard contract - see openzeppelin-contracts/blob/master/contracts/token/ERC20/SafeERC20.sol
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 _callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returnData) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returnData.length > 0) { // return data is optional
require(abi.decode(returnData, (bool)), "SafeERC20: erc20 operation did not succeed");
}
}
}
library SafeMath { // arithmetic wrapper for unit under/overflow check
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
}
contract ReentrancyGuard { // call wrapper for reentrancy check
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() internal {
_status = _NOT_ENTERED;
}
modifier nonReentrant() {
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
_status = _ENTERED;
_;
_status = _NOT_ENTERED;
}
}
contract MSTX is ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeMath for uint256;
/***************
GLOBAL CONSTANTS
***************/
address public depositToken; // deposit token contract reference - default = wETH
address public stakeToken; // stake token contract reference for guild voting shares
address public constant wETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // canonical ether token wrapper contract reference
uint256 public proposalDeposit; // default = 10 deposit token
uint256 public processingReward; // default = 0.1 - amount of deposit token to give to whoever processes a proposal
uint256 public periodDuration; // default = 17280 = 4.8 hours in seconds (5 periods per day)
uint256 public votingPeriodLength; // default = 35 periods (7 days)
uint256 public gracePeriodLength; // default = 35 periods (7 days)
uint256 public dilutionBound; // default = 3 - maximum multiplier a YES voter will be obligated to pay in case of mass ragequit
uint256 public summoningTime; // needed to determine the current period
bool private initialized; // internally tracks deployment under eip-1167 proxy pattern
// HARD-CODED LIMITS
uint256 constant MAX_GUILD_BOUND = 10**36; // maximum bound for guild member accounting
uint256 constant MAX_TOKEN_WHITELIST_COUNT = 400; // maximum number of whitelisted tokens
uint256 constant MAX_TOKEN_GUILDBANK_COUNT = 200; // maximum number of tokens with non-zero balance in guildbank
// GUILD TOKEN DETAILS
uint8 public constant decimals = 18;
string public constant name = "MSTX";
string public constant symbol = "MSTX";
// *******************
// INTERNAL ACCOUNTING
// *******************
address public constant GUILD = address(0xdead);
address public constant ESCROW = address(0xdeaf);
address public constant TOTAL = address(0xdeed);
uint256 public proposalCount; // total proposals submitted
uint256 public totalShares; // total shares across all members
uint256 public totalLoot; // total loot across all members
uint256 public totalSupply; // total shares & loot across all members (total guild tokens)
uint256 public totalGuildBankTokens; // total tokens with non-zero balance in guild bank
mapping(uint256 => bytes) public actions; // proposalId => action data
mapping(address => uint256) public balanceOf; // guild token balances
mapping(address => mapping(address => uint256)) public allowance; // guild token (loot) allowances
mapping(address => mapping(address => uint256)) private userTokenBalances; // userTokenBalances[userAddress][tokenAddress]
address[] public approvedTokens;
mapping(address => bool) public tokenWhitelist;
uint256[] public proposalQueue;
mapping(uint256 => Proposal) public proposals;
mapping(address => bool) public proposedToWhitelist;
mapping(address => bool) public proposedToKick;
mapping(address => Member) public members;
mapping(address => address) public memberAddressByDelegateKey;
// **************
// EVENT TRACKING
// **************
event SubmitProposal(address indexed applicant, uint256 sharesRequested, uint256 lootRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, bytes32 details, uint8[9] flags, bytes data, uint256 proposalId, address indexed delegateKey, address indexed memberAddress);
event CancelProposal(uint256 indexed proposalId, address applicantAddress);
event SponsorProposal(address indexed delegateKey, address indexed memberAddress, uint256 proposalId, uint256 proposalIndex, uint256 startingPeriod);
event SubmitVote(uint256 proposalId, uint256 indexed proposalIndex, address indexed delegateKey, address indexed memberAddress, uint8 uintVote);
event ProcessProposal(uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass);
event ProcessActionProposal(uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass);
event ProcessGuildKickProposal(uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass);
event ProcessWhitelistProposal(uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass);
event ProcessWithdrawalProposal(uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass);
event UpdateDelegateKey(address indexed memberAddress, address newDelegateKey);
event Ragequit(address indexed memberAddress, uint256 sharesToBurn, uint256 lootToBurn);
event TokensCollected(address indexed token, uint256 amountToCollect);
event Withdraw(address indexed memberAddress, address token, uint256 amount);
event ConvertSharesToLoot(address indexed memberAddress, uint256 amount);
event StakeTokenForShares(address indexed memberAddress, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount); // guild token (loot) allowance tracking
event Transfer(address indexed sender, address indexed recipient, uint256 amount); // guild token mint, burn & loot transfer tracking
enum Vote {
Null, // default value, counted as abstention
Yes,
No
}
struct Member {
address delegateKey; // the key responsible for submitting proposals & voting - defaults to member address unless updated
uint8 exists; // always true (1) once a member has been created
uint256 shares; // the # of voting shares assigned to this member
uint256 loot; // the loot amount available to this member (combined with shares on ragekick) - transferable by guild token
uint256 highestIndexYesVote; // highest proposal index # on which the member voted YES
uint256 jailed; // set to proposalIndex of a passing guild kick proposal for this member, prevents voting on & sponsoring proposals
}
struct Proposal {
address applicant; // the applicant who wishes to become a member - this key will be used for withdrawals (doubles as target for alt. proposals)
address proposer; // the account that submitted the proposal (can be non-member)
address sponsor; // the member that sponsored the proposal (moving it into the queue)
address tributeToken; // tribute token contract reference
address paymentToken; // payment token contract reference
uint8[9] flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick, action, withdrawal, standard]
uint256 sharesRequested; // the # of shares the applicant is requesting
uint256 lootRequested; // the amount of loot the applicant is requesting
uint256 paymentRequested; // amount of tokens requested as payment
uint256 tributeOffered; // amount of tokens offered as tribute
uint256 startingPeriod; // the period in which voting can start for this proposal
uint256 yesVotes; // the total number of YES votes for this proposal
uint256 noVotes; // the total number of NO votes for this proposal
uint256 maxTotalSharesAndLootAtYesVote; // the maximum # of total shares encountered at a yes vote on this proposal
bytes32 details; // proposal details to add context for members
mapping(address => Vote) votesByMember; // the votes on this proposal by each member
}
modifier onlyDelegate {
require(members[memberAddressByDelegateKey[msg.sender]].shares > 0, "!delegate");
_;
}
function init(
address _depositToken,
address _stakeToken,
address[] memory _summoner,
uint256[] memory _summonerShares,
uint256 _summonerDeposit,
uint256 _proposalDeposit,
uint256 _processingReward,
uint256 _periodDuration,
uint256 _votingPeriodLength,
uint256 _gracePeriodLength,
uint256 _dilutionBound
) external {
require(!initialized, "initialized");
require(_depositToken != _stakeToken, "depositToken = stakeToken");
require(_summoner.length == _summonerShares.length, "summoner != summonerShares");
require(_proposalDeposit >= _processingReward, "_processingReward > _proposalDeposit");
for (uint256 i = 0; i < _summoner.length; i++) {
growGuild(_summoner[i], _summonerShares[i], 0);
}
require(totalShares <= MAX_GUILD_BOUND, "guild maxed");
tokenWhitelist[_depositToken] = true;
approvedTokens.push(_depositToken);
if (_summonerDeposit > 0) {
totalGuildBankTokens += 1;
unsafeAddToBalance(GUILD, _depositToken, _summonerDeposit);
}
depositToken = _depositToken;
stakeToken = _stakeToken;
proposalDeposit = _proposalDeposit;
processingReward = _processingReward;
periodDuration = _periodDuration;
votingPeriodLength = _votingPeriodLength;
gracePeriodLength = _gracePeriodLength;
dilutionBound = _dilutionBound;
summoningTime = now;
initialized = true;
}
/*****************
PROPOSAL FUNCTIONS
*****************/
function submitProposal(
address applicant,
uint256 sharesRequested,
uint256 lootRequested,
uint256 tributeOffered,
address tributeToken,
uint256 paymentRequested,
address paymentToken,
bytes32 details
) external nonReentrant payable returns (uint256 proposalId) {
require(sharesRequested.add(lootRequested) <= MAX_GUILD_BOUND, "guild maxed");
require(tokenWhitelist[tributeToken], "tributeToken != whitelist");
require(tokenWhitelist[paymentToken], "paymentToken != whitelist");
require(applicant != GUILD && applicant != ESCROW && applicant != TOTAL, "applicant unreservable");
require(members[applicant].jailed == 0, "applicant jailed");
if (tributeOffered > 0 && userTokenBalances[GUILD][tributeToken] == 0) {
require(totalGuildBankTokens < MAX_TOKEN_GUILDBANK_COUNT, "guildbank maxed");
}
// collect tribute from proposer & store it in MSTX until the proposal is processed - if ether, wrap into wETH
if (msg.value > 0) {
require(tributeToken == wETH && msg.value == tributeOffered, "!ethBalance");
(bool success, ) = wETH.call{value: msg.value}("");
require(success, "!ethCall");
IERC20(wETH).safeTransfer(address(this), msg.value);
} else {
IERC20(tributeToken).safeTransferFrom(msg.sender, address(this), tributeOffered);
}
unsafeAddToBalance(ESCROW, tributeToken, tributeOffered);
uint8[9] memory flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick, action, withdrawal, standard]
flags[8] = 1; // standard
_submitProposal(applicant, sharesRequested, lootRequested, tributeOffered, tributeToken, paymentRequested, paymentToken, details, flags, "");
return proposalCount - 1; // return proposalId - contracts calling submit might want it
}
function submitActionProposal( // stages arbitrary function calls for member vote - based on Raid Guild 'Minion'
address actionTo, // target account for action (e.g., address to receive ether, token, dao, etc.)
uint256 actionTokenAmount, // helps check outbound guild bank token amount does not exceed internal balance / amount to update bank if successful
uint256 actionValue, // ether value, if any, in call
bytes32 details, // details tx staged for member execution - as external, extra care should be applied in diligencing action
bytes calldata data // data for function call
) external returns (uint256 proposalId) {
uint8[9] memory flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick, action, withdrawal, standard]
flags[6] = 1; // action
_submitProposal(actionTo, 0, 0, actionValue, address(0), actionTokenAmount, address(0), details, flags, data);
return proposalCount - 1;
}
function submitGuildKickProposal(address memberToKick, bytes32 details) external returns (uint256 proposalId) {
Member memory member = members[memberToKick];
require(member.shares > 0 || member.loot > 0, "!share||loot");
require(members[memberToKick].jailed == 0, "jailed");
uint8[9] memory flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick, action, withdrawal, standard]
flags[5] = 1; // guildkick
_submitProposal(memberToKick, 0, 0, 0, address(0), 0, address(0), details, flags, "");
return proposalCount - 1;
}
function submitWhitelistProposal(address tokenToWhitelist, bytes32 details) external returns (uint256 proposalId) {
require(tokenToWhitelist != address(0), "!token");
require(tokenToWhitelist != stakeToken, "tokenToWhitelist = stakeToken");
require(!tokenWhitelist[tokenToWhitelist], "whitelisted");
require(approvedTokens.length < MAX_TOKEN_WHITELIST_COUNT, "whitelist maxed");
uint8[9] memory flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick, action, withdrawal, standard]
flags[4] = 1; // whitelist
_submitProposal(address(0), 0, 0, 0, tokenToWhitelist, 0, address(0), details, flags, "");
return proposalCount - 1;
}
function submitWithdrawalProposal(address withdrawalTo, bytes32 details) external returns (uint256 proposalId) {
uint8[9] memory flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick, action, withdrawal, standard]
flags[7] = 1; // withdrawal
_submitProposal(withdrawalTo, 0, 0, 0, address(0), 0, address(0), details, flags, "");
return proposalCount - 1;
}
function _submitProposal(
address applicant,
uint256 sharesRequested,
uint256 lootRequested,
uint256 tributeOffered,
address tributeToken,
uint256 paymentRequested,
address paymentToken,
bytes32 details,
uint8[9] memory flags,
bytes memory data
) internal {
Proposal memory proposal = Proposal({
applicant : applicant,
proposer : msg.sender,
sponsor : address(0),
tributeToken : tributeToken,
paymentToken : paymentToken,
flags : flags,
sharesRequested : sharesRequested,
lootRequested : lootRequested,
paymentRequested : paymentRequested,
tributeOffered : tributeOffered,
startingPeriod : 0,
yesVotes : 0,
noVotes : 0,
maxTotalSharesAndLootAtYesVote : 0,
details : details
});
if (proposal.flags[6] == 1) {
actions[proposalCount] = data;
}
proposals[proposalCount] = proposal;
// NOTE: argument order matters, avoid stack too deep
emit SubmitProposal(applicant, sharesRequested, lootRequested, tributeOffered, tributeToken, paymentRequested, paymentToken, details, flags, data, proposalCount, msg.sender, memberAddressByDelegateKey[msg.sender]);
proposalCount += 1;
}
function sponsorProposal(uint256 proposalId) external nonReentrant onlyDelegate {
// collect proposal deposit from sponsor & store it in MSTX until the proposal is processed
IERC20(depositToken).safeTransferFrom(msg.sender, address(this), proposalDeposit);
unsafeAddToBalance(ESCROW, depositToken, proposalDeposit);
Proposal storage proposal = proposals[proposalId];
require(proposal.proposer != address(0), "!proposed");
require(proposal.flags[0] == 0, "sponsored");
require(proposal.flags[3] == 0, "cancelled");
require(members[proposal.applicant].jailed == 0, "applicant jailed");
if (proposal.tributeOffered > 0 && userTokenBalances[GUILD][proposal.tributeToken] == 0) {
require(totalGuildBankTokens < MAX_TOKEN_GUILDBANK_COUNT, "guildbank maxed");
}
// whitelist proposal
if (proposal.flags[4] == 1) {
require(!tokenWhitelist[address(proposal.tributeToken)], "whitelisted");
require(!proposedToWhitelist[address(proposal.tributeToken)], "whitelist proposed");
require(approvedTokens.length < MAX_TOKEN_WHITELIST_COUNT, "whitelist maxed");
proposedToWhitelist[address(proposal.tributeToken)] = true;
// guild kick proposal
} else if (proposal.flags[5] == 1) {
require(!proposedToKick[proposal.applicant], "kick proposed");
proposedToKick[proposal.applicant] = true;
}
// compute startingPeriod for proposal
uint256 startingPeriod = max(
getCurrentPeriod(),
proposalQueue.length == 0 ? 0 : proposals[proposalQueue[proposalQueue.length - 1]].startingPeriod
) + 1;
proposal.startingPeriod = startingPeriod;
proposal.sponsor = memberAddressByDelegateKey[msg.sender];
proposal.flags[0] = 1; // sponsored
// append proposal to the queue
proposalQueue.push(proposalId);
emit SponsorProposal(msg.sender, proposal.sponsor, proposalId, proposalQueue.length - 1, startingPeriod);
}
// NOTE: In MSTX, proposalIndex != proposalId
function submitVote(uint256 proposalIndex, uint8 uintVote) external nonReentrant onlyDelegate {
address memberAddress = memberAddressByDelegateKey[msg.sender];
Member storage member = members[memberAddress];
require(proposalIndex < proposalQueue.length, "!proposed");
uint256 proposalId = proposalQueue[proposalIndex];
Proposal storage proposal = proposals[proposalId];
require(uintVote < 3, ">2");
Vote vote = Vote(uintVote);
require(getCurrentPeriod() >= proposal.startingPeriod, "pending");
require(!hasVotingPeriodExpired(proposal.startingPeriod), "expired");
require(proposal.votesByMember[memberAddress] == Vote.Null, "voted");
require(vote == Vote.Yes || vote == Vote.No, "!Yes||No");
proposal.votesByMember[memberAddress] = vote;
if (vote == Vote.Yes) {
proposal.yesVotes += member.shares;
// set highest index (latest) yes vote - must be processed for member to ragequit
if (proposalIndex > member.highestIndexYesVote) {
member.highestIndexYesVote = proposalIndex;
}
// set maximum of total shares encountered at a yes vote - used to bound dilution for yes voters
if (totalSupply > proposal.maxTotalSharesAndLootAtYesVote) {
proposal.maxTotalSharesAndLootAtYesVote = totalSupply;
}
} else if (vote == Vote.No) {
proposal.noVotes += member.shares;
}
// NOTE: subgraph indexes by proposalId not proposalIndex since proposalIndex isn't set until it's been sponsored but proposal is created on submission
emit SubmitVote(proposalId, proposalIndex, msg.sender, memberAddress, uintVote);
}
function processProposal(uint256 proposalIndex) external nonReentrant {
_validateProposalForProcessing(proposalIndex);
uint256 proposalId = proposalQueue[proposalIndex];
Proposal storage proposal = proposals[proposalId];
require(proposal.flags[8] == 1, "!standard");
proposal.flags[1] = 1; // processed
bool didPass = _didPass(proposalIndex);
// Make the proposal fail if the new total number of shares & loot exceeds the limit
if (totalSupply.add(proposal.sharesRequested).add(proposal.lootRequested) > MAX_GUILD_BOUND) {
didPass = false;
}
// Make the proposal fail if it is requesting more tokens as payment than the available guild bank balance
if (proposal.paymentRequested > userTokenBalances[GUILD][proposal.paymentToken]) {
didPass = false;
}
// Make the proposal fail if it would result in too many tokens with non-zero balance in guild bank
if (proposal.tributeOffered > 0 && userTokenBalances[GUILD][proposal.tributeToken] == 0 && totalGuildBankTokens >= MAX_TOKEN_GUILDBANK_COUNT) {
didPass = false;
}
// PROPOSAL PASSED
if (didPass) {
proposal.flags[2] = 1; // didPass
growGuild(proposal.applicant, proposal.sharesRequested, proposal.lootRequested);
// if the proposal tribute is the first token of its kind to make it into the guild bank, increment total guild bank tokens
if (userTokenBalances[GUILD][proposal.tributeToken] == 0 && proposal.tributeOffered > 0) {
totalGuildBankTokens += 1;
}
unsafeInternalTransfer(ESCROW, GUILD, proposal.tributeToken, proposal.tributeOffered);
unsafeInternalTransfer(GUILD, proposal.applicant, proposal.paymentToken, proposal.paymentRequested);
// if the proposal spends 100% of guild bank balance for a token, decrement total guild bank tokens
if (userTokenBalances[GUILD][proposal.paymentToken] == 0 && proposal.paymentRequested > 0) {
totalGuildBankTokens -= 1;
}
// PROPOSAL FAILED
} else {
// return all tokens to the proposer (not the applicant, because funds come from proposer)
unsafeInternalTransfer(ESCROW, proposal.proposer, proposal.tributeToken, proposal.tributeOffered);
}
_returnDeposit(proposal.sponsor);
emit ProcessProposal(proposalIndex, proposalId, didPass);
}
function processActionProposal(uint256 proposalIndex) external nonReentrant returns (bool, bytes memory) {
_validateProposalForProcessing(proposalIndex);
uint256 proposalId = proposalQueue[proposalIndex];
bytes storage action = actions[proposalId];
Proposal storage proposal = proposals[proposalId];
require(proposal.flags[6] == 1, "!action");
proposal.flags[1] = 1; // processed
bool didPass = _didPass(proposalIndex);
// Make the proposal fail if it is requesting more accounted tokens than the available guild bank balance
if (tokenWhitelist[proposal.applicant] && proposal.paymentRequested > userTokenBalances[GUILD][proposal.applicant]) {
didPass = false;
}
// Make the proposal fail if it is requesting more ether than the available local balance
if (proposal.tributeOffered > address(this).balance) {
didPass = false;
}
if (didPass) {
proposal.flags[2] = 1; // didPass
(bool success, bytes memory returnData) = proposal.applicant.call{value: proposal.tributeOffered}(action);
if (tokenWhitelist[proposal.applicant]) {
unsafeSubtractFromBalance(GUILD, proposal.applicant, proposal.paymentRequested);
// if the action proposal spends 100% of guild bank balance for a token, decrement total guild bank tokens
if (userTokenBalances[GUILD][proposal.applicant] == 0 && proposal.paymentRequested > 0) {totalGuildBankTokens -= 1;}
}
return (success, returnData);
}
_returnDeposit(proposal.sponsor);
emit ProcessActionProposal(proposalIndex, proposalId, didPass);
}
function processGuildKickProposal(uint256 proposalIndex) external nonReentrant {
_validateProposalForProcessing(proposalIndex);
uint256 proposalId = proposalQueue[proposalIndex];
Proposal storage proposal = proposals[proposalId];
require(proposal.flags[5] == 1, "!kick");
proposal.flags[1] = 1; // processed
bool didPass = _didPass(proposalIndex);
if (didPass) {
proposal.flags[2] = 1; // didPass
Member storage member = members[proposal.applicant];
member.jailed = proposalIndex;
// transfer shares to loot
member.loot = member.loot.add(member.shares);
totalShares = totalShares.sub(member.shares);
totalLoot = totalLoot.add(member.shares);
member.shares = 0; // revoke all shares
}
proposedToKick[proposal.applicant] = false;
_returnDeposit(proposal.sponsor);
emit ProcessGuildKickProposal(proposalIndex, proposalId, didPass);
}
function processWhitelistProposal(uint256 proposalIndex) external {
_validateProposalForProcessing(proposalIndex);
uint256 proposalId = proposalQueue[proposalIndex];
Proposal storage proposal = proposals[proposalId];
require(proposal.flags[4] == 1, "!whitelist");
proposal.flags[1] = 1; // processed
bool didPass = _didPass(proposalIndex);
if (approvedTokens.length >= MAX_TOKEN_WHITELIST_COUNT) {
didPass = false;
}
if (didPass) {
proposal.flags[2] = 1; // didPass
tokenWhitelist[address(proposal.tributeToken)] = true;
approvedTokens.push(proposal.tributeToken);
}
proposedToWhitelist[address(proposal.tributeToken)] = false;
_returnDeposit(proposal.sponsor);
emit ProcessWhitelistProposal(proposalIndex, proposalId, didPass);
}
function processWithdrawalProposal(uint256 proposalIndex) external nonReentrant {
_validateProposalForProcessing(proposalIndex);
uint256 proposalId = proposalQueue[proposalIndex];
Proposal storage proposal = proposals[proposalId];
require(proposal.flags[7] == 1, "!withdrawal");
proposal.flags[1] = 1; // processed
bool didPass = _didPass(proposalIndex);
if (didPass) {
proposal.flags[2] = 1; // didPass
for (uint256 i = 0; i < approvedTokens.length; i++) {
// deliberately not using safemath here to keep overflows from preventing the function execution (which would break withdrawal)
// if a token overflows, it is because the supply was artificially inflated to oblivion, so we probably don't care about it anyways
uint256 withdrawalAmount = userTokenBalances[GUILD][approvedTokens[i]];
userTokenBalances[GUILD][approvedTokens[i]] -= withdrawalAmount;
userTokenBalances[proposal.applicant][approvedTokens[i]] += withdrawalAmount;
}
totalGuildBankTokens -= approvedTokens.length;
}
_returnDeposit(proposal.sponsor);
emit ProcessWithdrawalProposal(proposalIndex, proposalId, didPass);
}
function _didPass(uint256 proposalIndex) internal view returns (bool didPass) {
Proposal memory proposal = proposals[proposalQueue[proposalIndex]];
if (proposal.yesVotes > proposal.noVotes) {
didPass = true;
}
// Make the proposal fail if the dilutionBound is exceeded
if ((totalSupply.mul(dilutionBound)) < proposal.maxTotalSharesAndLootAtYesVote) {
didPass = false;
}
// Make the proposal fail if the applicant is jailed
// - for standard proposals, we don't want the applicant to get any shares/loot/payment
// - for guild kick proposals, we should never be able to propose to kick a jailed member (or have two kick proposals active), so it doesn't matter
if (members[proposal.applicant].jailed != 0) {
didPass = false;
}
return didPass;
}
function _validateProposalForProcessing(uint256 proposalIndex) internal view {
require(proposalIndex < proposalQueue.length, "!proposal");
Proposal memory proposal = proposals[proposalQueue[proposalIndex]];
require(getCurrentPeriod() >= proposal.startingPeriod.add(votingPeriodLength).add(gracePeriodLength), "!ready");
require(proposal.flags[1] == 0, "processed");
require(proposalIndex == 0 || proposals[proposalQueue[proposalIndex - 1]].flags[1] == 1, "prior !processed");
}
function _returnDeposit(address sponsor) internal {
unsafeInternalTransfer(ESCROW, msg.sender, depositToken, processingReward);
unsafeInternalTransfer(ESCROW, sponsor, depositToken, proposalDeposit - processingReward);
}
function ragequit(uint256 sharesToBurn, uint256 lootToBurn) external nonReentrant {
require(members[msg.sender].exists == 1, "!member");
_ragequit(msg.sender, sharesToBurn, lootToBurn);
}
function _ragequit(address memberAddress, uint256 sharesToBurn, uint256 lootToBurn) internal {
uint256 initialTotalSharesAndLoot = totalSupply;
Member storage member = members[memberAddress];
require(member.shares >= sharesToBurn, "!shares");
require(member.loot >= lootToBurn, "!loot");
require(canRagequit(member.highestIndexYesVote), "!ragequit until highest index proposal member voted YES processes");
uint256 sharesAndLootToBurn = sharesToBurn.add(lootToBurn);
// burn guild token, shares & loot
balanceOf[memberAddress] = balanceOf[memberAddress].sub(sharesAndLootToBurn);
member.shares = member.shares.sub(sharesToBurn);
member.loot = member.loot.sub(lootToBurn);
totalShares = totalShares.sub(sharesToBurn);
totalLoot = totalLoot.sub(lootToBurn);
totalSupply = totalShares.add(totalLoot);
for (uint256 i = 0; i < approvedTokens.length; i++) {
uint256 amountToRagequit = fairShare(userTokenBalances[GUILD][approvedTokens[i]], sharesAndLootToBurn, initialTotalSharesAndLoot);
if (amountToRagequit > 0) { // gas optimization to allow a higher maximum token limit
// deliberately not using safemath here to keep overflows from preventing the function execution (which would break ragekicks)
// if a token overflows, it is because the supply was artificially inflated to oblivion, so we probably don't care about it anyways
userTokenBalances[GUILD][approvedTokens[i]] -= amountToRagequit;
userTokenBalances[memberAddress][approvedTokens[i]] += amountToRagequit;
}
}
emit Ragequit(memberAddress, sharesToBurn, lootToBurn);
emit Transfer(memberAddress, address(0), sharesAndLootToBurn);
}
function ragekick(address memberToKick) external nonReentrant onlyDelegate {
Member storage member = members[memberToKick];
require(member.jailed != 0, "!jailed");
require(member.loot > 0, "!loot"); // note - should be impossible for jailed member to have shares
require(canRagequit(member.highestIndexYesVote), "!ragequit until highest index proposal member voted YES processes");
_ragequit(memberToKick, 0, member.loot);
}
function withdrawBalance(address token, uint256 amount) external nonReentrant {
_withdrawBalance(token, amount);
}
function withdrawBalances(address[] calldata tokens, uint256[] calldata amounts, bool max) external nonReentrant {
require(tokens.length == amounts.length, "tokens != amounts");
for (uint256 i=0; i < tokens.length; i++) {
uint256 withdrawAmount = amounts[i];
if (max) { // withdraw the maximum balance
withdrawAmount = userTokenBalances[msg.sender][tokens[i]];
}
_withdrawBalance(tokens[i], withdrawAmount);
}
}
function _withdrawBalance(address token, uint256 amount) internal {
require(userTokenBalances[msg.sender][token] >= amount, "!balance");
IERC20(token).safeTransfer(msg.sender, amount);
unsafeSubtractFromBalance(msg.sender, token, amount);
emit Withdraw(msg.sender, token, amount);
}
function collectTokens(address token) external nonReentrant onlyDelegate {
uint256 amountToCollect = IERC20(token).balanceOf(address(this)).sub(userTokenBalances[TOTAL][token]);
// only collect if 1) there are tokens to collect & 2) token is whitelisted
require(amountToCollect > 0, "!amount");
require(tokenWhitelist[token], "!whitelisted");
if (userTokenBalances[GUILD][token] == 0 && totalGuildBankTokens < MAX_TOKEN_GUILDBANK_COUNT) {totalGuildBankTokens += 1;}
unsafeAddToBalance(GUILD, token, amountToCollect);
emit TokensCollected(token, amountToCollect);
}
// NOTE: requires that delegate key which sent the original proposal cancels, msg.sender = proposal.proposer
function cancelProposal(uint256 proposalId) external nonReentrant {
Proposal storage proposal = proposals[proposalId];
require(proposal.flags[0] == 0, "sponsored");
require(proposal.flags[3] == 0, "cancelled");
require(msg.sender == proposal.proposer, "!proposer");
proposal.flags[3] = 1; // cancelled
unsafeInternalTransfer(ESCROW, proposal.proposer, proposal.tributeToken, proposal.tributeOffered);
emit CancelProposal(proposalId, msg.sender);
}
function updateDelegateKey(address newDelegateKey) external {
require(members[msg.sender].shares > 0, "!shareholder");
require(newDelegateKey != address(0), "newDelegateKey = 0");
// skip checks if member is setting the delegate key to their member address
if (newDelegateKey != msg.sender) {
require(members[newDelegateKey].exists == 0, "!overwrite members");
require(members[memberAddressByDelegateKey[newDelegateKey]].exists == 0, "!overwrite keys");
}
Member storage member = members[msg.sender];
memberAddressByDelegateKey[member.delegateKey] = address(0);
memberAddressByDelegateKey[newDelegateKey] = msg.sender;
member.delegateKey = newDelegateKey;
emit UpdateDelegateKey(msg.sender, newDelegateKey);
}
// can only ragequit if the latest proposal you voted YES on has been processed
function canRagequit(uint256 highestIndexYesVote) public view returns (bool) {
require(highestIndexYesVote < proposalQueue.length, "!proposal");
return proposals[proposalQueue[highestIndexYesVote]].flags[1] == 1;
}
function hasVotingPeriodExpired(uint256 startingPeriod) public view returns (bool) {
return getCurrentPeriod() >= startingPeriod.add(votingPeriodLength);
}
/***************
GETTER FUNCTIONS
***************/
function max(uint256 x, uint256 y) internal pure returns (uint256) {
return x >= y ? x : y;
}
function getCurrentPeriod() public view returns (uint256) {
return now.sub(summoningTime).div(periodDuration);
}
function getMemberProposalVote(address memberAddress, uint256 proposalIndex) external view returns (Vote) {
require(members[memberAddress].exists == 1, "!member");
require(proposalIndex < proposalQueue.length, "!proposed");
return proposals[proposalQueue[proposalIndex]].votesByMember[memberAddress];
}
function getProposalFlags(uint256 proposalId) external view returns (uint8[9] memory) {
return proposals[proposalId].flags;
}
function getProposalQueueLength() external view returns (uint256) {
return proposalQueue.length;
}
function getTokenCount() external view returns (uint256) {
return approvedTokens.length;
}
function getUserTokenBalance(address user, address token) external view returns (uint256) {
return userTokenBalances[user][token];
}
/***************
HELPER FUNCTIONS
***************/
receive() external payable {}
function fairShare(uint256 balance, uint256 shares, uint256 totalSharesAndLoot) internal pure returns (uint256) {
require(totalSharesAndLoot != 0);
if (balance == 0) { return 0; }
uint256 prod = balance * shares;
if (prod / balance == shares) { // no overflow in multiplication above?
return prod / totalSharesAndLoot;
}
return (balance / totalSharesAndLoot) * shares;
}
function growGuild(address account, uint256 shares, uint256 loot) internal {
// if the account is already a member, add to their existing shares & loot
if (members[account].exists == 1) {
members[account].shares = members[account].shares.add(shares);
members[account].loot = members[account].loot.add(loot);
// if the account is a new member, create a new record for them
} else {
// if new member is already taken by a member's delegateKey, reset it to their member address
if (members[memberAddressByDelegateKey[account]].exists == 1) {
address memberToOverride = memberAddressByDelegateKey[account];
memberAddressByDelegateKey[memberToOverride] = memberToOverride;
members[memberToOverride].delegateKey = memberToOverride;
}
members[account] = Member({
delegateKey : account,
exists : 1, // 'true'
shares : shares,
loot : loot.add(members[account].loot), // take into account loot from pre-membership transfers
highestIndexYesVote : 0,
jailed : 0
});
memberAddressByDelegateKey[account] = account;
}
uint256 sharesAndLoot = shares.add(loot);
// mint new guild token, update total shares & loot
balanceOf[account] = balanceOf[account].add(sharesAndLoot);
totalShares = totalShares.add(shares);
totalLoot = totalLoot.add(loot);
totalSupply = totalShares.add(totalLoot);
emit Transfer(address(0), account, sharesAndLoot);
}
function unsafeAddToBalance(address user, address token, uint256 amount) internal {
userTokenBalances[user][token] += amount;
userTokenBalances[TOTAL][token] += amount;
}
function unsafeInternalTransfer(address from, address to, address token, uint256 amount) internal {
unsafeSubtractFromBalance(from, token, amount);
unsafeAddToBalance(to, token, amount);
}
function unsafeSubtractFromBalance(address user, address token, uint256 amount) internal {
userTokenBalances[user][token] -= amount;
userTokenBalances[TOTAL][token] -= amount;
}
/********************
GUILD TOKEN FUNCTIONS
********************/
function approve(address spender, uint256 amount) external returns (bool) {
require(amount == 0 || allowance[msg.sender][spender] == 0);
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function convertSharesToLoot(uint256 sharesToLoot) external nonReentrant {
members[msg.sender].shares = members[msg.sender].shares.sub(sharesToLoot);
members[msg.sender].loot = members[msg.sender].loot.add(sharesToLoot);
totalShares = totalShares.sub(sharesToLoot);
totalLoot = totalLoot.add(sharesToLoot);
emit ConvertSharesToLoot(msg.sender, sharesToLoot);
}
function stakeTokenForShares(uint256 amount) external nonReentrant {
IERC20(stakeToken).safeTransferFrom(msg.sender, address(this), amount); // deposit stake token & claim shares (1:1)
growGuild(msg.sender, amount, 0);
require(totalSupply <= MAX_GUILD_BOUND, "guild maxed");
emit StakeTokenForShares(msg.sender, amount);
}
function transfer(address recipient, uint256 lootToTransfer) external returns (bool) {
members[msg.sender].loot = members[msg.sender].loot.sub(lootToTransfer);
members[recipient].loot = members[recipient].loot.add(lootToTransfer);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(lootToTransfer);
balanceOf[recipient] = balanceOf[recipient].add(lootToTransfer);
emit Transfer(msg.sender, recipient, lootToTransfer);
return true;
}
function transferFrom(address sender, address recipient, uint256 lootToTransfer) external returns (bool) {
allowance[sender][msg.sender] = allowance[sender][msg.sender].sub(lootToTransfer);
members[sender].loot = members[sender].loot.sub(lootToTransfer);
members[recipient].loot = members[recipient].loot.add(lootToTransfer);
balanceOf[sender] = balanceOf[sender].sub(lootToTransfer);
balanceOf[recipient] = balanceOf[recipient].add(lootToTransfer);
emit Transfer(sender, recipient, lootToTransfer);
return true;
}
}
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
contract CloneFactory { // MSTX implementation of eip-1167 - see https://eips.ethereum.org/EIPS/eip-1167
function createClone(address payable target) internal returns (address payable result) {
bytes20 targetBytes = bytes20(target);
assembly {
let clone := mload(0x40)
mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone, 0x14), targetBytes)
mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
result := create(0, clone, 0x37)
}
}
}
contract MSTXSummoner is CloneFactory {
address payable public immutable template;
constructor(address payable _template) public {
template = _template;
}
event SummonMSTX(address indexed mstx, address depositToken, address stakeToken, address[] summoner, uint256[] summonerShares, uint256 summoningDeposit, uint256 proposalDeposit, uint256 processingReward, uint256 periodDuration, uint256 votingPeriodLength, uint256 gracePeriodLength, uint256 dilutionBound, uint256 summoningTime);
function summonMSTX(
address _depositToken,
address _stakeToken,
address[] memory _summoner,
uint256[] memory _summonerShares,
uint256 _summonerDeposit,
uint256 _proposalDeposit,
uint256 _processingReward,
uint256 _periodDuration,
uint256 _votingPeriodLength,
uint256 _gracePeriodLength,
uint256 _dilutionBound
) external returns (address) {
MSTX mstx = MSTX(createClone(template));
mstx.init(
_depositToken,
_stakeToken,
_summoner,
_summonerShares,
_summonerDeposit,
_proposalDeposit,
_processingReward,
_periodDuration,
_votingPeriodLength,
_gracePeriodLength,
_dilutionBound
);
require(IERC20(_depositToken).transferFrom(msg.sender, address(mstx), _summonerDeposit), "!transfer"); // transfer summoner deposit to new MSTX
emit SummonMSTX(address(mstx), _depositToken, _stakeToken, _summoner, _summonerShares, _summonerDeposit, _proposalDeposit, _processingReward, _periodDuration, _votingPeriodLength, _gracePeriodLength, _dilutionBound, now);
return address(mstx);
}
} | skip checks if member is setting the delegate key to their member address | function updateDelegateKey(address newDelegateKey) external {
require(members[msg.sender].shares > 0, "!shareholder");
require(newDelegateKey != address(0), "newDelegateKey = 0");
if (newDelegateKey != msg.sender) {
require(members[newDelegateKey].exists == 0, "!overwrite members");
require(members[memberAddressByDelegateKey[newDelegateKey]].exists == 0, "!overwrite keys");
}
Member storage member = members[msg.sender];
memberAddressByDelegateKey[member.delegateKey] = address(0);
memberAddressByDelegateKey[newDelegateKey] = msg.sender;
member.delegateKey = newDelegateKey;
emit UpdateDelegateKey(msg.sender, newDelegateKey);
}
| 1,235,867 | [
1,
7457,
4271,
309,
3140,
353,
3637,
326,
7152,
498,
358,
3675,
3140,
1758,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1089,
9586,
653,
12,
2867,
394,
9586,
653,
13,
3903,
288,
203,
3639,
2583,
12,
7640,
63,
3576,
18,
15330,
8009,
30720,
405,
374,
16,
17528,
14419,
4505,
8863,
203,
3639,
2583,
12,
2704,
9586,
653,
480,
1758,
12,
20,
3631,
315,
2704,
9586,
653,
273,
374,
8863,
203,
203,
3639,
309,
261,
2704,
9586,
653,
480,
1234,
18,
15330,
13,
288,
203,
5411,
2583,
12,
7640,
63,
2704,
9586,
653,
8009,
1808,
422,
374,
16,
17528,
19274,
4833,
8863,
203,
5411,
2583,
12,
7640,
63,
5990,
1887,
858,
9586,
653,
63,
2704,
9586,
653,
65,
8009,
1808,
422,
374,
16,
17528,
19274,
1311,
8863,
203,
3639,
289,
203,
203,
3639,
8596,
2502,
3140,
273,
4833,
63,
3576,
18,
15330,
15533,
203,
3639,
3140,
1887,
858,
9586,
653,
63,
5990,
18,
22216,
653,
65,
273,
1758,
12,
20,
1769,
203,
3639,
3140,
1887,
858,
9586,
653,
63,
2704,
9586,
653,
65,
273,
1234,
18,
15330,
31,
203,
3639,
3140,
18,
22216,
653,
273,
394,
9586,
653,
31,
203,
203,
3639,
3626,
2315,
9586,
653,
12,
3576,
18,
15330,
16,
394,
9586,
653,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.4.25;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./SafeDecimalMath.sol";
import "./SelfDestructible.sol";
// AggregatorInterface from Chainlink represents a decentralized pricing network for a single currency key
import "chainlink/contracts/interfaces/AggregatorInterface.sol";
/**
* @title The repository for exchange rates
*/
contract ExchangeRates is SelfDestructible {
using SafeMath for uint;
using SafeDecimalMath for uint;
struct RateAndUpdatedTime {
uint216 rate;
uint40 time;
}
// Exchange rates and update times stored by currency code, e.g. 'SNX', or 'sUSD'
mapping(bytes32 => mapping(uint => RateAndUpdatedTime)) private _rates;
// The address of the oracle which pushes rate updates to this contract
address public oracle;
// Decentralized oracle networks that feed into pricing aggregators
mapping(bytes32 => AggregatorInterface) public aggregators;
// List of aggregator keys for convenient iteration
bytes32[] public aggregatorKeys;
// Do not allow the oracle to submit times any further forward into the future than this constant.
uint private constant ORACLE_FUTURE_LIMIT = 10 minutes;
// How long will the contract assume the rate of any asset is correct
uint public rateStalePeriod = 3 hours;
// For inverted prices, keep a mapping of their entry, limits and frozen status
struct InversePricing {
uint entryPoint;
uint upperLimit;
uint lowerLimit;
bool frozen;
}
mapping(bytes32 => InversePricing) public inversePricing;
bytes32[] public invertedKeys;
mapping(bytes32 => uint) currentRoundForRate;
//
// ========== CONSTRUCTOR ==========
/**
* @dev Constructor
* @param _owner The owner of this contract.
* @param _oracle The address which is able to update rate information.
* @param _currencyKeys The initial currency keys to store (in order).
* @param _newRates The initial currency amounts for each currency (in order).
*/
constructor(
// SelfDestructible (Ownable)
address _owner,
// Oracle values - Allows for rate updates
address _oracle,
bytes32[] _currencyKeys,
uint[] _newRates
)
public
/* Owned is initialised in SelfDestructible */
SelfDestructible(_owner)
{
require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match.");
oracle = _oracle;
// The sUSD rate is always 1 and is never stale.
_setRate("sUSD", SafeDecimalMath.unit(), now);
internalUpdateRates(_currencyKeys, _newRates, now);
}
/* ========== SETTERS ========== */
/**
* @notice Set the Oracle that pushes the rate information to this contract
* @param _oracle The new oracle address
*/
function setOracle(address _oracle) external onlyOwner {
oracle = _oracle;
emit OracleUpdated(oracle);
}
/**
* @notice Set the stale period on the updated rate variables
* @param _time The new rateStalePeriod
*/
function setRateStalePeriod(uint _time) external onlyOwner {
rateStalePeriod = _time;
emit RateStalePeriodUpdated(rateStalePeriod);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Set the rates stored in this contract
* @param currencyKeys The currency keys you wish to update the rates for (in order)
* @param newRates The rates for each currency (in order)
* @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).
* This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even
* if it takes a long time for the transaction to confirm.
*/
function updateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) external onlyOracle returns (bool) {
return internalUpdateRates(currencyKeys, newRates, timeSent);
}
/**
* @notice Delete a rate stored in the contract
* @param currencyKey The currency key you wish to delete the rate for
*/
function deleteRate(bytes32 currencyKey) external onlyOracle {
require(getRate(currencyKey) > 0, "Rate is zero");
delete _rates[currencyKey][currentRoundForRate[currencyKey]];
currentRoundForRate[currencyKey]--;
emit RateDeleted(currencyKey);
}
/**
* @notice Set an inverse price up for the currency key.
*
* An inverse price is one which has an entryPoint, an uppper and a lower limit. Each update, the
* rate is calculated as double the entryPrice minus the current rate. If this calculation is
* above or below the upper or lower limits respectively, then the rate is frozen, and no more
* rate updates will be accepted.
*
* @param currencyKey The currency to update
* @param entryPoint The entry price point of the inverted price
* @param upperLimit The upper limit, at or above which the price will be frozen
* @param lowerLimit The lower limit, at or below which the price will be frozen
* @param freeze Whether or not to freeze this rate immediately. Note: no frozen event will be configured
* @param freezeAtUpperLimit When the freeze flag is true, this flag indicates whether the rate
* to freeze at is the upperLimit or lowerLimit..
*/
function setInversePricing(
bytes32 currencyKey,
uint entryPoint,
uint upperLimit,
uint lowerLimit,
bool freeze,
bool freezeAtUpperLimit
) external onlyOwner {
require(entryPoint > 0, "entryPoint must be above 0");
require(lowerLimit > 0, "lowerLimit must be above 0");
require(upperLimit > entryPoint, "upperLimit must be above the entryPoint");
require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint");
require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint");
if (inversePricing[currencyKey].entryPoint <= 0) {
// then we are adding a new inverse pricing, so add this
invertedKeys.push(currencyKey);
}
inversePricing[currencyKey].entryPoint = entryPoint;
inversePricing[currencyKey].upperLimit = upperLimit;
inversePricing[currencyKey].lowerLimit = lowerLimit;
inversePricing[currencyKey].frozen = freeze;
emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit);
// When indicating to freeze, we need to know the rate to freeze it at - either upper or lower
// this is useful in situations where ExchangeRates is updated and there are existing inverted
// rates already frozen in the current contract that need persisting across the upgrade
if (freeze) {
emit InversePriceFrozen(currencyKey);
_setRate(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, now);
}
}
/**
* @notice Remove an inverse price for the currency key
* @param currencyKey The currency to remove inverse pricing for
*/
function removeInversePricing(bytes32 currencyKey) external onlyOwner {
require(inversePricing[currencyKey].entryPoint > 0, "No inverted price exists");
inversePricing[currencyKey].entryPoint = 0;
inversePricing[currencyKey].upperLimit = 0;
inversePricing[currencyKey].lowerLimit = 0;
inversePricing[currencyKey].frozen = false;
// now remove inverted key from array
bool wasRemoved = removeFromArray(currencyKey, invertedKeys);
if (wasRemoved) {
emit InversePriceConfigured(currencyKey, 0, 0, 0);
}
}
/**
* @notice Add a pricing aggregator for the given key. Note: existing aggregators may be overridden.
* @param currencyKey The currency key to add an aggregator for
*/
function addAggregator(bytes32 currencyKey, address aggregatorAddress) external onlyOwner {
AggregatorInterface aggregator = AggregatorInterface(aggregatorAddress);
require(aggregator.latestTimestamp() >= 0, "Given Aggregator is invalid");
if (aggregators[currencyKey] == address(0)) {
aggregatorKeys.push(currencyKey);
}
aggregators[currencyKey] = aggregator;
emit AggregatorAdded(currencyKey, aggregator);
}
/**
* @notice Remove a pricing aggregator for the given key
* @param currencyKey The currency key to remove an aggregator for
*/
function removeAggregator(bytes32 currencyKey) external onlyOwner {
address aggregator = aggregators[currencyKey];
require(aggregator != address(0), "No aggregator exists for key");
delete aggregators[currencyKey];
bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys);
if (wasRemoved) {
emit AggregatorRemoved(currencyKey, aggregator);
}
}
function getLastRoundIdBeforeElapsedSecs(
bytes32 currencyKey,
uint startingRoundId,
uint startingTimestamp,
uint timediff
) external view returns (uint) {
uint roundId = startingRoundId;
uint nextTimestamp = 0;
while (true) {
(, nextTimestamp) = getRateAndTimestampAtRound(currencyKey, roundId + 1);
// if there's no new round, then the previous roundId was the latest
if (nextTimestamp == 0 || nextTimestamp > startingTimestamp + timediff) {
return roundId;
}
roundId++;
}
return roundId;
}
function getCurrentRoundId(bytes32 currencyKey) external view returns (uint) {
if (aggregators[currencyKey] != address(0)) {
AggregatorInterface aggregator = aggregators[currencyKey];
return aggregator.latestRound();
} else {
return currentRoundForRate[currencyKey];
}
}
function effectiveValueAtRound(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
uint roundIdForSrc,
uint roundIdForDest
) external view rateNotStale(sourceCurrencyKey) rateNotStale(destinationCurrencyKey) returns (uint) {
// If there's no change in the currency, then just return the amount they gave us
if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount;
(uint srcRate, ) = getRateAndTimestampAtRound(sourceCurrencyKey, roundIdForSrc);
(uint destRate, ) = getRateAndTimestampAtRound(destinationCurrencyKey, roundIdForDest);
// Calculate the effective value by going from source -> USD -> destination
return sourceAmount.multiplyDecimalRound(srcRate).divideDecimalRound(destRate);
}
function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time) {
return getRateAndTimestampAtRound(currencyKey, roundId);
}
/* ========== VIEWS ========== */
/**
* @notice Retrieves the timestamp the given rate was last updated.
*/
function lastRateUpdateTimes(bytes32 currencyKey) public view returns (uint256) {
return getRateAndUpdatedTime(currencyKey).time;
}
/**
* @notice Retrieve the last update time for a list of currencies
*/
function lastRateUpdateTimesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) {
uint[] memory lastUpdateTimes = new uint[](currencyKeys.length);
for (uint i = 0; i < currencyKeys.length; i++) {
lastUpdateTimes[i] = lastRateUpdateTimes(currencyKeys[i]);
}
return lastUpdateTimes;
}
/**
* @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency
* @param sourceCurrencyKey The currency the amount is specified in
* @param sourceAmount The source amount, specified in UNIT base
* @param destinationCurrencyKey The destination currency
*/
function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey)
public
view
rateNotStale(sourceCurrencyKey)
rateNotStale(destinationCurrencyKey)
returns (uint)
{
// If there's no change in the currency, then just return the amount they gave us
if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount;
// Calculate the effective value by going from source -> USD -> destination
return
sourceAmount.multiplyDecimalRound(getRate(sourceCurrencyKey)).divideDecimalRound(
getRate(destinationCurrencyKey)
);
}
/**
* @notice Retrieve the rate for a specific currency
*/
function rateForCurrency(bytes32 currencyKey) external view returns (uint) {
return getRateAndUpdatedTime(currencyKey).rate;
}
/**
* @notice Retrieve the rates for a list of currencies
*/
function ratesForCurrencies(bytes32[] currencyKeys) external view returns (uint[]) {
uint[] memory _localRates = new uint[](currencyKeys.length);
for (uint i = 0; i < currencyKeys.length; i++) {
_localRates[i] = getRate(currencyKeys[i]);
}
return _localRates;
}
/**
* @notice Retrieve the rates and isAnyStale for a list of currencies
*/
function ratesAndStaleForCurrencies(bytes32[] currencyKeys) external view returns (uint[], bool) {
uint[] memory _localRates = new uint[](currencyKeys.length);
bool anyRateStale = false;
uint period = rateStalePeriod;
for (uint i = 0; i < currencyKeys.length; i++) {
RateAndUpdatedTime memory rateAndUpdateTime = getRateAndUpdatedTime(currencyKeys[i]);
_localRates[i] = uint256(rateAndUpdateTime.rate);
if (!anyRateStale) {
anyRateStale = (currencyKeys[i] != "sUSD" && uint256(rateAndUpdateTime.time).add(period) < now);
}
}
return (_localRates, anyRateStale);
}
/**
* @notice Check if a specific currency's rate hasn't been updated for longer than the stale period.
*/
function rateIsStale(bytes32 currencyKey) public view returns (bool) {
// sUSD is a special case and is never stale.
if (currencyKey == "sUSD") return false;
return lastRateUpdateTimes(currencyKey).add(rateStalePeriod) < now;
}
/**
* @notice Check if any rate is frozen (cannot be exchanged into)
*/
function rateIsFrozen(bytes32 currencyKey) external view returns (bool) {
return inversePricing[currencyKey].frozen;
}
/**
* @notice Check if any of the currency rates passed in haven't been updated for longer than the stale period.
*/
function anyRateIsStale(bytes32[] currencyKeys) external view returns (bool) {
// Loop through each key and check whether the data point is stale.
uint256 i = 0;
while (i < currencyKeys.length) {
// sUSD is a special case and is never false
if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes(currencyKeys[i]).add(rateStalePeriod) < now) {
return true;
}
i += 1;
}
return false;
}
/* ========== INTERNAL FUNCTIONS ========== */
function _setRate(bytes32 currencyKey, uint256 rate, uint256 time) internal {
// Note: this will effectively start the rounds at 1, which matches Chainlink's Agggregators
currentRoundForRate[currencyKey]++;
_rates[currencyKey][currentRoundForRate[currencyKey]] = RateAndUpdatedTime({
rate: uint216(rate),
time: uint40(time)
});
}
/**
* @notice Internal function which sets the rates stored in this contract
* @param currencyKeys The currency keys you wish to update the rates for (in order)
* @param newRates The rates for each currency (in order)
* @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract
* This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even
* if it takes a long time for the transaction to confirm.
*/
function internalUpdateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) internal returns (bool) {
require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length.");
require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future");
// Loop through each key and perform update.
for (uint i = 0; i < currencyKeys.length; i++) {
bytes32 currencyKey = currencyKeys[i];
// Should not set any rate to zero ever, as no asset will ever be
// truely worthless and still valid. In this scenario, we should
// delete the rate and remove it from the system.
require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead.");
require(currencyKey != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT.");
// We should only update the rate if it's at least the same age as the last rate we've got.
if (timeSent < lastRateUpdateTimes(currencyKey)) {
continue;
}
newRates[i] = rateOrInverted(currencyKey, newRates[i]);
// Ok, go ahead with the update.
_setRate(currencyKey, newRates[i], timeSent);
}
emit RatesUpdated(currencyKeys, newRates);
return true;
}
/**
* @notice Internal function to get the inverted rate, if any, and mark an inverted
* key as frozen if either limits are reached.
*
* Inverted rates are ones that take a regular rate, perform a simple calculation (double entryPrice and
* subtract the rate) on them and if the result of the calculation is over or under predefined limits, it freezes the
* rate at that limit, preventing any future rate updates.
*
* For example, if we have an inverted rate iBTC with the following parameters set:
* - entryPrice of 200
* - upperLimit of 300
* - lower of 100
*
* if this function is invoked with params iETH and 184 (or rather 184e18),
* then the rate would be: 200 * 2 - 184 = 216. 100 < 216 < 200, so the rate would be 216,
* and remain unfrozen.
*
* If this function is then invoked with params iETH and 301 (or rather 301e18),
* then the rate would be: 200 * 2 - 301 = 99. 99 < 100, so the rate would be 100 and the
* rate would become frozen, no longer accepting future price updates until the synth is unfrozen
* by the owner function: setInversePricing().
*
* @param currencyKey The price key to lookup
* @param rate The rate for the given price key
*/
function rateOrInverted(bytes32 currencyKey, uint rate) internal returns (uint) {
// if an inverse mapping exists, adjust the price accordingly
InversePricing storage inverse = inversePricing[currencyKey];
if (inverse.entryPoint <= 0) {
return rate;
}
// set the rate to the current rate initially (if it's frozen, this is what will be returned)
uint newInverseRate = getRate(currencyKey);
// get the new inverted rate if not frozen
if (!inverse.frozen) {
uint doubleEntryPoint = inverse.entryPoint.mul(2);
if (doubleEntryPoint <= rate) {
// avoid negative numbers for unsigned ints, so set this to 0
// which by the requirement that lowerLimit be > 0 will
// cause this to freeze the price to the lowerLimit
newInverseRate = 0;
} else {
newInverseRate = doubleEntryPoint.sub(rate);
}
// now if new rate hits our limits, set it to the limit and freeze
if (newInverseRate >= inverse.upperLimit) {
newInverseRate = inverse.upperLimit;
} else if (newInverseRate <= inverse.lowerLimit) {
newInverseRate = inverse.lowerLimit;
}
if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) {
inverse.frozen = true;
emit InversePriceFrozen(currencyKey);
}
}
return newInverseRate;
}
function getRateAndUpdatedTime(bytes32 currencyKey) internal view returns (RateAndUpdatedTime) {
if (aggregators[currencyKey] != address(0)) {
return
RateAndUpdatedTime({
rate: uint216(aggregators[currencyKey].latestAnswer() * 1e10),
time: uint40(aggregators[currencyKey].latestTimestamp())
});
} else {
return _rates[currencyKey][currentRoundForRate[currencyKey]];
}
}
/**
* @notice Remove a single value from an array by iterating through until it is found.
* @param entry The entry to find
* @param array The array to mutate
* @return bool Whether or not the entry was found and removed
*/
function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) {
for (uint i = 0; i < array.length; i++) {
if (array[i] == entry) {
delete array[i];
// Copy the last key into the place of the one we just deleted
// If there's only one key, this is array[0] = array[0].
// If we're deleting the last one, it's also a NOOP in the same way.
array[i] = array[array.length - 1];
// Decrease the size of the array by one.
array.length--;
return true;
}
}
return false;
}
function getRateAndTimestampAtRound(bytes32 currencyKey, uint roundId) internal view returns (uint rate, uint time) {
if (aggregators[currencyKey] != address(0)) {
AggregatorInterface aggregator = aggregators[currencyKey];
return (uint(aggregator.getAnswer(roundId) * 1e10), aggregator.getTimestamp(roundId));
} else {
RateAndUpdatedTime storage update = _rates[currencyKey][roundId];
return (update.rate, update.time);
}
}
function getRate(bytes32 currencyKey) internal view returns (uint256) {
return getRateAndUpdatedTime(currencyKey).rate;
}
/* ========== MODIFIERS ========== */
modifier rateNotStale(bytes32 currencyKey) {
require(!rateIsStale(currencyKey), "Rate stale or nonexistant currency");
_;
}
modifier onlyOracle {
require(msg.sender == oracle, "Only the oracle can perform this action");
_;
}
/* ========== EVENTS ========== */
event OracleUpdated(address newOracle);
event RateStalePeriodUpdated(uint rateStalePeriod);
event RatesUpdated(bytes32[] currencyKeys, uint[] newRates);
event RateDeleted(bytes32 currencyKey);
event InversePriceConfigured(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit);
event InversePriceFrozen(bytes32 currencyKey);
event AggregatorAdded(bytes32 currencyKey, address aggregator);
event AggregatorRemoved(bytes32 currencyKey, address aggregator);
}
| * @notice Set an inverse price up for the currency key. An inverse price is one which has an entryPoint, an uppper and a lower limit. Each update, the rate is calculated as double the entryPrice minus the current rate. If this calculation is above or below the upper or lower limits respectively, then the rate is frozen, and no more rate updates will be accepted. @param currencyKey The currency to update @param entryPoint The entry price point of the inverted price @param upperLimit The upper limit, at or above which the price will be frozen @param lowerLimit The lower limit, at or below which the price will be frozen @param freeze Whether or not to freeze this rate immediately. Note: no frozen event will be configured @param freezeAtUpperLimit When the freeze flag is true, this flag indicates whether the rate to freeze at is the upperLimit or lowerLimit../ then we are adding a new inverse pricing, so add this When indicating to freeze, we need to know the rate to freeze it at - either upper or lower this is useful in situations where ExchangeRates is updated and there are existing inverted rates already frozen in the current contract that need persisting across the upgrade | function setInversePricing(
bytes32 currencyKey,
uint entryPoint,
uint upperLimit,
uint lowerLimit,
bool freeze,
bool freezeAtUpperLimit
) external onlyOwner {
require(entryPoint > 0, "entryPoint must be above 0");
require(lowerLimit > 0, "lowerLimit must be above 0");
require(upperLimit > entryPoint, "upperLimit must be above the entryPoint");
require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint");
require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint");
if (inversePricing[currencyKey].entryPoint <= 0) {
invertedKeys.push(currencyKey);
}
inversePricing[currencyKey].entryPoint = entryPoint;
inversePricing[currencyKey].upperLimit = upperLimit;
inversePricing[currencyKey].lowerLimit = lowerLimit;
inversePricing[currencyKey].frozen = freeze;
emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit);
if (freeze) {
emit InversePriceFrozen(currencyKey);
_setRate(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, now);
}
}
| 914,237 | [
1,
694,
392,
8322,
6205,
731,
364,
326,
5462,
498,
18,
1922,
8322,
6205,
353,
1245,
1492,
711,
392,
28671,
16,
392,
731,
84,
457,
471,
279,
2612,
1800,
18,
8315,
1089,
16,
326,
4993,
353,
8894,
487,
1645,
326,
1241,
5147,
12647,
326,
783,
4993,
18,
971,
333,
11096,
353,
5721,
578,
5712,
326,
3854,
578,
2612,
8181,
19629,
16,
1508,
326,
4993,
353,
12810,
16,
471,
1158,
1898,
4993,
4533,
903,
506,
8494,
18,
225,
5462,
653,
1021,
5462,
358,
1089,
225,
28671,
1021,
1241,
6205,
1634,
434,
326,
18150,
6205,
225,
3854,
3039,
1021,
3854,
1800,
16,
622,
578,
5721,
1492,
326,
6205,
903,
506,
12810,
225,
2612,
3039,
1021,
2612,
1800,
16,
622,
578,
5712,
1492,
326,
6205,
903,
506,
12810,
225,
16684,
17403,
578,
486,
358,
16684,
333,
4993,
7636,
18,
3609,
30,
1158,
12810,
871,
903,
506,
4351,
225,
16684,
861,
5988,
3039,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
565,
445,
444,
16376,
52,
1512,
310,
12,
203,
3639,
1731,
1578,
5462,
653,
16,
203,
3639,
2254,
28671,
16,
203,
3639,
2254,
3854,
3039,
16,
203,
3639,
2254,
2612,
3039,
16,
203,
3639,
1426,
16684,
16,
203,
3639,
1426,
16684,
861,
5988,
3039,
203,
565,
262,
3903,
1338,
5541,
288,
203,
3639,
2583,
12,
4099,
2148,
405,
374,
16,
315,
4099,
2148,
1297,
506,
5721,
374,
8863,
203,
3639,
2583,
12,
8167,
3039,
405,
374,
16,
315,
8167,
3039,
1297,
506,
5721,
374,
8863,
203,
3639,
2583,
12,
5797,
3039,
405,
28671,
16,
315,
5797,
3039,
1297,
506,
5721,
326,
28671,
8863,
203,
3639,
2583,
12,
5797,
3039,
411,
28671,
18,
16411,
12,
22,
3631,
315,
5797,
3039,
1297,
506,
5242,
2353,
1645,
28671,
8863,
203,
3639,
2583,
12,
8167,
3039,
411,
28671,
16,
315,
8167,
3039,
1297,
506,
5712,
326,
28671,
8863,
203,
203,
3639,
309,
261,
22552,
52,
1512,
310,
63,
7095,
653,
8009,
4099,
2148,
1648,
374,
13,
288,
203,
5411,
18150,
2396,
18,
6206,
12,
7095,
653,
1769,
203,
3639,
289,
203,
3639,
8322,
52,
1512,
310,
63,
7095,
653,
8009,
4099,
2148,
273,
28671,
31,
203,
3639,
8322,
52,
1512,
310,
63,
7095,
653,
8009,
5797,
3039,
273,
3854,
3039,
31,
203,
3639,
8322,
52,
1512,
310,
63,
7095,
653,
8009,
8167,
3039,
273,
2612,
3039,
31,
203,
3639,
8322,
52,
1512,
310,
63,
7095,
653,
8009,
28138,
273,
16684,
31,
203,
203,
3639,
3626,
657,
2476,
5147,
15334,
12,
7095,
653,
16,
28671,
16,
3854,
3039,
16,
2
] |
pragma solidity 0.6.12;
//----------------------------------------------------------------------------------
// I n s t a n t
//
// .:mmm. .:mmm:. .ii. .:SSSSSSSSSSSSS. .oOOOOOOOOOOOo.
// .mMM'':Mm. .:MM'':Mm:. .II: :SSs.......... .oOO'''''''''''OOo.
// .:Mm' ':Mm. .:Mm' 'MM:. .II: 'sSSSSSSSSSSSSS:. :OO. .OO:
// .'mMm' ':MM:.:MMm' ':MM:. .II: .:...........:SS. 'OOo:.........:oOO'
// 'mMm' ':MMmm' 'mMm: II: 'sSSSSSSSSSSSSS' 'oOOOOOOOOOOOO'
//
//----------------------------------------------------------------------------------
// GP: Token escrow, lock up tokens for a period of time
import "./Utils/CloneFactory.sol";
import "./Access/MISOAccessControls.sol";
contract MISOFermenter is CloneFactory {
/// @notice Responsible for access rights to the contract.
MISOAccessControls public accessControls;
/// @notice Whether farm factory has been initialized or not.
bool private initialised;
/// @notice Struct to track Fermenter template.
struct Fermenter{
bool exists;
uint256 templateId;
uint256 index;
}
/// @notice Escrows created using the factory.
address[] public escrows;
/// @notice Template id to track respective escrow template.
uint256 public escrowTemplateId;
/// @notice Mapping from template id to escrow template address.
mapping(uint256 => address) private escrowTemplates;
/// @notice mapping from escrow template address to escrow template id
mapping(address => uint256) private escrowTemplateToId;
/// @notice mapping from escrow address to struct Fermenter
mapping(address => Fermenter) public isChildEscrow;
/// @notice Event emitted when first initializing MISO fermenter.
event MisoInitFermenter(address sender);
/// @notice Event emitted when escrow template added.
event EscrowTemplateAdded(address newTemplate, uint256 templateId);
/// @notice Event emitted when escrow template is removed.
event EscrowTemplateRemoved(address template, uint256 templateId);
/// @notice Event emitted when escrow is created.
event EscrowCreated(address indexed owner, address indexed addr,address escrowTemplate);
/**
* @notice Single gateway to initialize the MISO Market with proper address.
* @dev Can only be initialized once.
* @param _accessControls Sets address to get the access controls from.
*/
function _initMISOFermenter(address _accessControls) external {
/// @dev Maybe missing require message?
require(!initialised);
initialised = true;
accessControls = MISOAccessControls(_accessControls);
emit MisoInitFermenter(msg.sender);
}
/**
* @notice Creates a new escrow corresponding to template Id.
* @param _templateId Template id of the escrow to create.
* @return newEscrow Escrow address.
*/
function createEscrow(uint256 _templateId) external returns (address newEscrow) {
/// @dev Maybe missing require message?
require(escrowTemplates[_templateId]!= address(0));
newEscrow = createClone(escrowTemplates[_templateId]);
isChildEscrow[address(newEscrow)] = Fermenter(true,_templateId,escrows.length-1);
escrows.push(newEscrow);
emit EscrowCreated(msg.sender,address(newEscrow),escrowTemplates[_templateId]);
}
/**
* @notice Function to add a escrow template to create through factory.
* @dev Should have operator access.
* @param _escrowTemplate Escrow template to create a token.
*/
function addEscrowTemplate(address _escrowTemplate) external {
require(
accessControls.hasOperatorRole(msg.sender),
"MISOFermenter: Sender must be operator"
);
escrowTemplateId++;
escrowTemplates[escrowTemplateId] = _escrowTemplate;
escrowTemplateToId[_escrowTemplate] = escrowTemplateId;
emit EscrowTemplateAdded(_escrowTemplate, escrowTemplateId);
}
/**
* @notice Function to remove a escrow template.
* @dev Should have operator access.
* @param _templateId Refers to template that is to be deleted.
*/
function removeEscrowTemplate(uint256 _templateId) external {
require(escrowTemplates[_templateId] != address(0));
address template = escrowTemplates[_templateId];
escrowTemplates[_templateId] = address(0);
delete escrowTemplateToId[template];
emit EscrowTemplateRemoved(template, _templateId);
}
/**
* @notice Get the address of the escrow template based on template ID.
* @param _templateId Escrow template ID.
* @return Address of the required template ID.
*/
function getEscrowTemplate(uint256 _templateId) external view returns (address) {
return escrowTemplates[_templateId];
}
/**
* @notice Get the ID based on template address.
* @param _escrowTemplate Escrow template address.
* @return templateId ID of the required template address.
*/
function getTemplateId(address _escrowTemplate) external view returns (uint256 templateId) {
return escrowTemplateToId[_escrowTemplate];
}
/**
* @notice Get the total number of escrows in the factory.
* @return Escrow count.
*/
function numberOfTokens() external view returns (uint256) {
return escrows.length;
}
}
| GP: Token escrow, lock up tokens for a period of time | import "./Utils/CloneFactory.sol";
| 7,313,034 | [
1,
9681,
30,
3155,
2904,
492,
16,
2176,
731,
2430,
364,
279,
3879,
434,
813,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5666,
25165,
1989,
19,
10930,
1733,
18,
18281,
14432,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/43114/0x32B8a4C67fcCF8A3d62cDa812079325554EA066d/sources/avaxtaoli.sol | TokenInterface(tokenCoin).deposit.value(4)(); | TokenInterface(tokenCoin).withdraw(getBalance(TokenInterface(tokenCoin)));
| 4,514,561 | [
1,
1345,
1358,
12,
2316,
27055,
2934,
323,
1724,
18,
1132,
12,
24,
13,
5621,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
29938,
12,
2316,
27055,
2934,
1918,
9446,
12,
588,
13937,
12,
1345,
1358,
12,
2316,
27055,
3719,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.5;
pragma experimental ABIEncoderV2;
contract VoteContract {
address public owner;
uint ElectionsCounter;
struct Candidate{
string name;
uint voteCount;
uint candidateId;
}
struct Voter{
address voterAddress;
string name;
string uniqueID;
bool hasVoted;
bool isVerified;
}
struct Election{
address election_owner;
string title;
Voter[] Election_Voters;
Candidate[] Election_Candidates;
bool start;
bool end;
uint candidateCount;
uint voterCount;
}
mapping(uint => Election) public Elections;
constructor(){
owner = msg.sender;
ElectionsCounter = 0;
}
//modifier to specify functions that only the election creator/admin can access
modifier onlyElectionAdmin(uint _electionID){
require(Elections[_electionID].election_owner == msg.sender);
_;
}
// this function is used to create a new election
function createElection(string memory _title) public {
Elections[ElectionsCounter].election_owner = msg.sender;
Elections[ElectionsCounter].title = _title;
Elections[ElectionsCounter].start = false;
Elections[ElectionsCounter].end = false;
Elections[ElectionsCounter].candidateCount = 0;
Elections[ElectionsCounter].voterCount = 0;
ElectionsCounter++;
}
// Only election creator/admin has access to this function
function addCandidate(string memory _name, uint _electionID) public onlyElectionAdmin(_electionID){
Elections[_electionID].Election_Candidates.push(Candidate({
name:_name,
voteCount: 0,
candidateId : Elections[_electionID].candidateCount
}));
Elections[_electionID].candidateCount += 1;
}
// request to be added as voter
function applyToVote(string memory _name, string memory _uniqueID, uint _electionID) public {
Elections[_electionID].Election_Voters.push(Voter({
voterAddress : msg.sender,
name : _name,
uniqueID : _uniqueID,
hasVoted : false,
isVerified : false
}));
Elections[_electionID].voterCount +=1;
}
//Voting function
function vote(uint candidateId, uint _electionID) public{
uint voterNumber;
for(uint i=0;i<Elections[_electionID].voterCount;i++){
if(Elections[_electionID].Election_Voters[i].voterAddress == msg.sender){
voterNumber = i;
}
}
require(Elections[_electionID].Election_Voters[voterNumber].hasVoted == false); // require that voter hasn't voted already.
require(Elections[_electionID].Election_Voters[voterNumber].isVerified == true); // require that voter is verified.
require(Elections[_electionID].start == true); // require that the voting process has started
require(Elections[_electionID].end == false); // and has not ended yet
Elections[_electionID].Election_Candidates[candidateId].voteCount += 1;
Elections[_electionID].Election_Voters[voterNumber].hasVoted = true;
}
// verify a specific voter address
function verifyVoter(address _address, uint _electionID) public onlyElectionAdmin(_electionID){
uint voterNumber;
for(uint i=0;i<Elections[_electionID].voterCount;i++){
if(Elections[_electionID].Election_Voters[i].voterAddress == _address){
voterNumber = i;
}
}
Elections[_electionID].Election_Voters[voterNumber].isVerified = true;
}
// start the voting process
function startElection(uint _electionID) public onlyElectionAdmin(_electionID){
Elections[_electionID].start = true;
Elections[_electionID].end = false;
}
// end the voting process
function endElection(uint _electionID) public onlyElectionAdmin(_electionID){
Elections[_electionID].end = true;
Elections[_electionID].start = false;
}
// return start value to know if voting process has started
function getStart(uint _electionID) public view returns (bool) {
return Elections[_electionID].start;
}
// return end value to know if voting process has ended
function getEnd(uint _electionID) public view returns (bool) {
return Elections[_electionID].end;
}
// get the address of the owner of a specific election
function getElectionOwner(uint _electionID) public view returns(address){
return Elections[_electionID].election_owner;
}
// get a specific election name based on ID
function getElectionName(uint _electionID) public view returns(string memory){
return Elections[_electionID].title;
}
// get total number of elections created
function getElectionsCounter() public view returns(uint){
return ElectionsCounter;
}
// get total number of candidates of a specific election
function getCandidateNumber(uint _electionID) public view returns (uint) {
return Elections[_electionID].candidateCount;
}
// get total number of voters
function getVoterCount(uint _electionID) public view returns (uint) {
return Elections[_electionID].voterCount;
}
//check if given voterID already exists in the list
function voterExists(uint _electionID,string memory _voterID) public view returns(bool){
for(uint i=0; i < Elections[_electionID].voterCount;i++){
//use this cause solidity doesn't support string comparison with '=='
if(keccak256(bytes(Elections[_electionID].Election_Voters[i].uniqueID)) == keccak256(bytes(_voterID))){
return true;
}
}
return false;
}
// return status of specified voter (is he verified? did he already vote?)
function getVotingDetails(address _address,uint _electionID)public view returns(bool isVerified,bool hasVoted){
for(uint i=0;i<Elections[_electionID].voterCount;i++){
if(Elections[_electionID].Election_Voters[i].voterAddress == _address){
return (Elections[_electionID].Election_Voters[i].isVerified, Elections[_electionID].Election_Voters[i].hasVoted);
}
}
}
// return true if voter has already registered for the election given
function isVoterRegistered(address _address,uint _electionID) public view returns(bool isRegistered){
for(uint i=0;i<Elections[_electionID].voterCount;i++){
if(Elections[_electionID].Election_Voters[i].voterAddress == _address){
return true;
}
}
return false;
}
//get all the candidates from a specific election
function getCandidates(uint _electionID) public view returns(Candidate [] memory){
return Elections[_electionID].Election_Candidates;
}
//get all the voters from a specific Election
function getVoters(uint _electionID) public view returns(Voter [] memory){
return Elections[_electionID].Election_Voters;
}
} | get total number of elections created | function getElectionsCounter() public view returns(uint){
return ElectionsCounter;
}
| 13,081,960 | [
1,
588,
2078,
1300,
434,
25526,
87,
2522,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
282,
445,
4774,
942,
87,
4789,
1435,
1071,
1476,
1135,
12,
11890,
15329,
203,
1377,
327,
512,
942,
87,
4789,
31,
203,
282,
289,
203,
27699,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.21;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title 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 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 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 SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 value
)
internal
{
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/* solium-disable security/no-block-members */
/**
* @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 _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
function TokenVesting(
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);
}
}
}
/**
* @title PresaleTokenVesting
* @dev PresaleTokenVesting allows for vesting periods which begin at
* the time the token sale ends.
*/
contract PresaleTokenVesting is TokenVesting {
function PresaleTokenVesting(address _beneficiary, uint256 _duration) TokenVesting(_beneficiary, 0, _duration, _duration, false) public {
}
function vestedAmount(ERC20Basic token) public view returns (uint256) {
UrbitToken urbit = UrbitToken(token);
if (!urbit.saleClosed()) {
return(0);
} else {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
uint256 saleClosedTime = urbit.saleClosedTimestamp();
if (block.timestamp >= duration.add(saleClosedTime)) { // solium-disable-line security/no-block-members
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(saleClosedTime)).div(duration); // solium-disable-line security/no-block-members
}
}
}
}
/**
* @title TokenVault
* @dev TokenVault is a token holder contract that will allow a
* beneficiary to spend the tokens from some function of a specified ERC20 token
*/
contract TokenVault {
using SafeERC20 for ERC20;
// ERC20 token contract being held
ERC20 public token;
function TokenVault(ERC20 _token) public {
token = _token;
}
/**
* @notice Allow the token itself to send tokens
* using transferFrom().
*/
function fillUpAllowance() public {
uint256 amount = token.balanceOf(this);
require(amount > 0);
token.approve(token, amount);
}
}
/**
* @title UrbitToken
* @dev UrbitToken is a contract for the Urbit token sale, creating the
* tokens and managing the vaults.
*/
contract UrbitToken is BurnableToken, StandardToken {
string public constant name = "Urbit Token"; // solium-disable-line uppercase
string public constant symbol = "URB"; // solium-disable-line uppercase
uint8 public constant decimals = 18; // solium-disable-line uppercase
uint256 public constant MAGNITUDE = 10**uint256(decimals);
/// Maximum tokens to be allocated (600 million)
uint256 public constant HARD_CAP = 600000000 * MAGNITUDE;
/// This address is used to manage the admin functions and allocate vested tokens
address public urbitAdminAddress;
/// This address is used to keep the tokens for sale
address public saleTokensAddress;
/// This vault is used to keep the bounty and marketing tokens
TokenVault public bountyTokensVault;
/// This vault is used to keep the team and founders tokens
TokenVault public urbitTeamTokensVault;
/// This vault is used to keep the advisors tokens
TokenVault public advisorsTokensVault;
/// This vault is used to keep the rewards tokens
TokenVault public rewardsTokensVault;
/// This vault is used to keep the retained tokens
TokenVault public retainedTokensVault;
/// Store the vesting contracts addresses
mapping(address => address[]) public vestingsOf;
/// when the token sale is closed, the trading is open
uint256 public saleClosedTimestamp = 0;
/// Only allowed to execute before the token sale is closed
modifier beforeSaleClosed {
require(!saleClosed());
_;
}
/// Limiting functions to the admins of the token only
modifier onlyAdmin {
require(senderIsAdmin());
_;
}
function UrbitToken(
address _urbitAdminAddress,
address _saleTokensAddress) public
{
require(_urbitAdminAddress != address(0));
require(_saleTokensAddress != address(0));
urbitAdminAddress = _urbitAdminAddress;
saleTokensAddress = _saleTokensAddress;
}
/// @dev allows the admin to assign a new admin
function changeAdmin(address _newUrbitAdminAddress) external onlyAdmin {
require(_newUrbitAdminAddress != address(0));
urbitAdminAddress = _newUrbitAdminAddress;
}
/// @dev creates the tokens needed for sale
function createSaleTokens() external onlyAdmin beforeSaleClosed {
require(bountyTokensVault == address(0));
/// Maximum tokens to be allocated on the sale
/// 252,000,000 URB
createTokens(252000000, saleTokensAddress);
/// Bounty tokens - 24M URB
bountyTokensVault = createTokenVault(24000000);
}
/// @dev Close the token sale
function closeSale() external onlyAdmin beforeSaleClosed {
createAwardTokens();
saleClosedTimestamp = block.timestamp; // solium-disable-line security/no-block-members
}
/// @dev Once the token sale is closed and tokens are distributed,
/// burn the remaining unsold, undistributed tokens
function burnUnsoldTokens() external onlyAdmin {
require(saleClosed());
_burn(saleTokensAddress, balances[saleTokensAddress]);
_burn(bountyTokensVault, balances[bountyTokensVault]);
}
function lockBountyTokens(uint256 _tokensAmount, address _beneficiary, uint256 _duration) external beforeSaleClosed {
require(msg.sender == saleTokensAddress || senderIsAdmin());
_presaleLock(bountyTokensVault, _tokensAmount, _beneficiary, _duration);
}
/// @dev Shorter version of vest tokens (lock for a single whole period)
function lockTokens(address _fromVault, uint256 _tokensAmount, address _beneficiary, uint256 _unlockTime) external onlyAdmin {
this.vestTokens(_fromVault, _tokensAmount, _beneficiary, _unlockTime, 0, 0, false); // solium-disable-line arg-overflow
}
/// @dev Vest tokens
function vestTokens(
address _fromVault,
uint256 _tokensAmount,
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable)
external onlyAdmin
{
TokenVesting vesting = new TokenVesting(_beneficiary, _start, _cliff, _duration, _revocable);
vestingsOf[_beneficiary].push(address(vesting));
require(this.transferFrom(_fromVault, vesting, _tokensAmount));
}
/// @dev releases vested tokens for the caller's own address
function releaseVestedTokens() external {
this.releaseVestedTokensFor(msg.sender);
}
/// @dev releases vested tokens for the specified address.
/// Can be called by any account for any address.
function releaseVestedTokensFor(address _owner) external {
ERC20Basic token = ERC20Basic(address(this));
for (uint i = 0; i < vestingsOf[_owner].length; i++) {
TokenVesting tv = TokenVesting(vestingsOf[_owner][i]);
if (tv.releasableAmount(token) > 0) {
tv.release(token);
}
}
}
/// @dev returns whether the sender is admin (or the contract itself)
function senderIsAdmin() public view returns (bool) {
return (msg.sender == urbitAdminAddress || msg.sender == address(this));
}
/// @dev The sale is closed when the saleClosedTimestamp is set.
function saleClosed() public view returns (bool) {
return (saleClosedTimestamp > 0);
}
/// @dev check the locked balance for an address
function lockedBalanceOf(address _owner) public view returns (uint256) {
uint256 result = 0;
for (uint i = 0; i < vestingsOf[_owner].length; i++) {
result += balances[vestingsOf[_owner][i]];
}
return result;
}
/// @dev check the locked but releasable balance for an address
function releasableBalanceOf(address _owner) public view returns (uint256) {
uint256 result = 0;
for (uint i = 0; i < vestingsOf[_owner].length; i++) {
result += TokenVesting(vestingsOf[_owner][i]).releasableAmount(this);
}
return result;
}
/// @dev get the number of TokenVesting contracts for an address
function vestingCountOf(address _owner) public view returns (uint) {
return vestingsOf[_owner].length;
}
/// @dev get the specified TokenVesting contract address for an address
function vestingOf(address _owner, uint _index) public view returns (address) {
return vestingsOf[_owner][_index];
}
/// @dev Trading is limited before the sale is closed
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
if (saleClosed() || msg.sender == saleTokensAddress || senderIsAdmin()) {
return super.transferFrom(_from, _to, _value);
}
return false;
}
/// @dev Trading is limited before the sale is closed
function transfer(address _to, uint256 _value) public returns (bool) {
if (saleClosed() || msg.sender == saleTokensAddress || senderIsAdmin()) {
return super.transfer(_to, _value);
}
return false;
}
/// @dev Grant tokens which begin vesting upon close of sale.
function _presaleLock(TokenVault _fromVault, uint256 _tokensAmount, address _beneficiary, uint256 _duration) internal {
PresaleTokenVesting vesting = new PresaleTokenVesting(_beneficiary, _duration);
vestingsOf[_beneficiary].push(address(vesting));
require(this.transferFrom(_fromVault, vesting, _tokensAmount));
}
// @dev create specified number of toekns and transfer to destination
function createTokens(uint32 count, address destination) internal onlyAdmin {
uint256 tokens = count * MAGNITUDE;
totalSupply_ = totalSupply_.add(tokens);
balances[destination] = tokens;
emit Transfer(0x0, destination, tokens);
}
/// @dev Create a TokenVault and fill with the specified newly minted tokens
function createTokenVault(uint32 count) internal onlyAdmin returns (TokenVault) {
TokenVault tokenVault = new TokenVault(ERC20(this));
createTokens(count, tokenVault);
tokenVault.fillUpAllowance();
return tokenVault;
}
/// @dev Creates the tokens awarded after the sale is closed
function createAwardTokens() internal onlyAdmin {
/// Team tokens - 30M URB
urbitTeamTokensVault = createTokenVault(30000000);
/// Advisors tokens - 24M URB
advisorsTokensVault = createTokenVault(24000000);
/// Rewards tokens - 150M URB
rewardsTokensVault = createTokenVault(150000000);
/// Retained tokens - 120M URB
retainedTokensVault = createTokenVault(120000000);
}
} | Limiting functions to the admins of the token only | modifier onlyAdmin {
require(senderIsAdmin());
_;
}
| 12,947,476 | [
1,
3039,
310,
4186,
358,
326,
31116,
434,
326,
1147,
1338,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
9606,
1338,
4446,
288,
203,
3639,
2583,
12,
15330,
2520,
4446,
10663,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x46955ccEc435465C8C70BD64E2f5FFBd33308C8C/sources/InsurancePool.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/ 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. | abstract contract ReentrancyGuard {
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () public {
_status = _NOT_ENTERED;
}
modifier nonReentrant() {
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
_status = _ENTERED;
_;
_status = _NOT_ENTERED;
}
}
| 4,268,459 | [
1,
8924,
1605,
716,
21814,
5309,
283,
8230,
970,
4097,
358,
279,
445,
18,
25953,
310,
628,
1375,
426,
8230,
12514,
16709,
68,
903,
1221,
326,
288,
5836,
426,
8230,
970,
97,
9606,
2319,
16,
1492,
848,
506,
6754,
358,
4186,
358,
1221,
3071,
1915,
854,
1158,
4764,
261,
2842,
313,
970,
13,
4097,
358,
2182,
18,
3609,
716,
2724,
1915,
353,
279,
2202,
1375,
5836,
426,
8230,
970,
68,
11026,
16,
4186,
9350,
487,
1375,
5836,
426,
8230,
970,
68,
2026,
486,
745,
1245,
4042,
18,
1220,
848,
506,
28613,
6740,
635,
10480,
5348,
4186,
1375,
1152,
9191,
471,
1508,
6534,
1375,
9375,
68,
1375,
5836,
426,
8230,
970,
68,
1241,
3143,
358,
2182,
18,
399,
2579,
30,
971,
1846,
4102,
3007,
358,
16094,
1898,
2973,
283,
8230,
12514,
471,
10355,
16226,
358,
17151,
5314,
518,
16,
866,
596,
3134,
10700,
1603,
19,
605,
11887,
634,
854,
1898,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
17801,
6835,
868,
8230,
12514,
16709,
288,
203,
203,
565,
2254,
5034,
3238,
5381,
389,
4400,
67,
12278,
2056,
273,
404,
31,
203,
565,
2254,
5034,
3238,
5381,
389,
12278,
2056,
273,
576,
31,
203,
203,
565,
2254,
5034,
3238,
389,
2327,
31,
203,
203,
203,
203,
565,
3885,
1832,
1071,
288,
203,
3639,
389,
2327,
273,
389,
4400,
67,
12278,
2056,
31,
203,
565,
289,
203,
203,
565,
9606,
1661,
426,
8230,
970,
1435,
288,
203,
3639,
2583,
24899,
2327,
480,
389,
12278,
2056,
16,
315,
426,
8230,
12514,
16709,
30,
283,
8230,
970,
745,
8863,
203,
203,
3639,
389,
2327,
273,
389,
12278,
2056,
31,
203,
203,
3639,
389,
31,
203,
203,
3639,
389,
2327,
273,
389,
4400,
67,
12278,
2056,
31,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: UNLICENSED
// Cauldron
// ( ( (
// )\ ) ( )\ )\ ) (
// (((_) ( /( ))\ ((_)(()/( )( ( (
// )\___ )(_)) /((_) _ ((_))(()\ )\ )\ )
// ((/ __|((_)_ (_))( | | _| | ((_) ((_) _(_/(
// | (__ / _` || || || |/ _` | | '_|/ _ \| ' \))
// \___|\__,_| \_,_||_|\__,_| |_| \___/|_||_|
// Copyright (c) 2021 BoringCrypto - All rights reserved
// Twitter: @Boring_Crypto
// Special thanks to:
// @0xKeno - for all his invaluable contributions
// @burger_crypto - for the idea of trying to let the LPs benefit from liquidations
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@boringcrypto/boring-solidity/contracts/BoringOwnable.sol";
import "@boringcrypto/boring-solidity/contracts/ERC20.sol";
import "@boringcrypto/boring-solidity/contracts/interfaces/IMasterContract.sol";
import "@boringcrypto/boring-solidity/contracts/libraries/BoringRebase.sol";
import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
import "./MagicInternetMoney.sol";
import "./interfaces/IOracle.sol";
import "./interfaces/ISwapper.sol";
// solhint-disable avoid-low-level-calls
// solhint-disable no-inline-assembly
/// @title Cauldron
/// @dev This contract allows contract calls to any contract (except BentoBox)
/// from arbitrary callers thus, don't trust calls from this contract in any circumstances.
contract CauldronV3 is BoringOwnable, IMasterContract {
using BoringMath for uint256;
using BoringMath128 for uint128;
using RebaseLibrary for Rebase;
using BoringERC20 for IERC20;
event LogExchangeRate(uint256 rate);
event LogAccrue(uint128 accruedAmount);
event LogAddCollateral(address indexed from, address indexed to, uint256 share);
event LogRemoveCollateral(address indexed from, address indexed to, uint256 share);
event LogBorrow(address indexed from, address indexed to, uint256 amount, uint256 part);
event LogRepay(address indexed from, address indexed to, uint256 amount, uint256 part);
event LogFeeTo(address indexed newFeeTo);
event LogWithdrawFees(address indexed feeTo, uint256 feesEarnedFraction);
event LogInterestChange(uint64 oldInterestRate, uint64 newInterestRate);
event LogChangeBorrowLimit(uint128 newLimit, uint128 perAddressPart);
event LogLiquidation(
address indexed from,
address indexed user,
address indexed to,
uint256 collateralShare,
uint256 borrowAmount,
uint256 borrowPart
);
// Immutables (for MasterContract and all clones)
IBentoBoxV1 public immutable bentoBox;
CauldronV3 public immutable masterContract;
IERC20 public immutable magicInternetMoney;
// MasterContract variables
address public feeTo;
// Per clone variables
// Clone init settings
IERC20 public collateral;
IOracle public oracle;
bytes public oracleData;
struct BorrowCap {
uint128 total;
uint128 borrowPartPerAddress;
}
BorrowCap public borrowLimit;
// Total amounts
uint256 public totalCollateralShare; // Total collateral supplied
Rebase public totalBorrow; // elastic = Total token amount to be repayed by borrowers, base = Total parts of the debt held by borrowers
// User balances
mapping(address => uint256) public userCollateralShare;
mapping(address => uint256) public userBorrowPart;
/// @notice Exchange and interest rate tracking.
/// This is 'cached' here because calls to Oracles can be very expensive.
uint256 public exchangeRate;
struct AccrueInfo {
uint64 lastAccrued;
uint128 feesEarned;
uint64 INTEREST_PER_SECOND;
}
AccrueInfo public accrueInfo;
/// @notice tracking of last interest update
uint256 private lastInterestUpdate;
// Settings
uint256 public COLLATERIZATION_RATE;
uint256 private constant COLLATERIZATION_RATE_PRECISION = 1e5; // Must be less than EXCHANGE_RATE_PRECISION (due to optimization in math)
uint256 private constant EXCHANGE_RATE_PRECISION = 1e18;
uint256 public LIQUIDATION_MULTIPLIER;
uint256 private constant LIQUIDATION_MULTIPLIER_PRECISION = 1e5;
uint256 public BORROW_OPENING_FEE;
uint256 private constant BORROW_OPENING_FEE_PRECISION = 1e5;
uint256 private constant DISTRIBUTION_PART = 10;
uint256 private constant DISTRIBUTION_PRECISION = 100;
modifier onlyMasterContractOwner() {
require(msg.sender == masterContract.owner(), "Caller is not the owner");
_;
}
/// @notice The constructor is only used for the initial master contract. Subsequent clones are initialised via `init`.
constructor(IBentoBoxV1 bentoBox_, IERC20 magicInternetMoney_) public {
bentoBox = bentoBox_;
magicInternetMoney = magicInternetMoney_;
masterContract = this;
}
/// @notice Serves as the constructor for clones, as clones can't have a regular constructor
/// @dev `data` is abi encoded in the format: (IERC20 collateral, IERC20 asset, IOracle oracle, bytes oracleData)
function init(bytes calldata data) public payable override {
require(address(collateral) == address(0), "Cauldron: already initialized");
(collateral, oracle, oracleData, accrueInfo.INTEREST_PER_SECOND, LIQUIDATION_MULTIPLIER, COLLATERIZATION_RATE, BORROW_OPENING_FEE) = abi.decode(data, (IERC20, IOracle, bytes, uint64, uint256, uint256, uint256));
borrowLimit = BorrowCap(type(uint128).max, type(uint128).max);
require(address(collateral) != address(0), "Cauldron: bad pair");
(, exchangeRate) = oracle.get(oracleData);
}
/// @notice Accrues the interest on the borrowed tokens and handles the accumulation of fees.
function accrue() public {
AccrueInfo memory _accrueInfo = accrueInfo;
// Number of seconds since accrue was called
uint256 elapsedTime = block.timestamp - _accrueInfo.lastAccrued;
if (elapsedTime == 0) {
return;
}
_accrueInfo.lastAccrued = uint64(block.timestamp);
Rebase memory _totalBorrow = totalBorrow;
if (_totalBorrow.base == 0) {
accrueInfo = _accrueInfo;
return;
}
// Accrue interest
uint128 extraAmount = (uint256(_totalBorrow.elastic).mul(_accrueInfo.INTEREST_PER_SECOND).mul(elapsedTime) / 1e18).to128();
_totalBorrow.elastic = _totalBorrow.elastic.add(extraAmount);
_accrueInfo.feesEarned = _accrueInfo.feesEarned.add(extraAmount);
totalBorrow = _totalBorrow;
accrueInfo = _accrueInfo;
emit LogAccrue(extraAmount);
}
/// @notice Concrete implementation of `isSolvent`. Includes a third parameter to allow caching `exchangeRate`.
/// @param _exchangeRate The exchange rate. Used to cache the `exchangeRate` between calls.
function _isSolvent(address user, uint256 _exchangeRate) internal view returns (bool) {
// accrue must have already been called!
uint256 borrowPart = userBorrowPart[user];
if (borrowPart == 0) return true;
uint256 collateralShare = userCollateralShare[user];
if (collateralShare == 0) return false;
Rebase memory _totalBorrow = totalBorrow;
return
bentoBox.toAmount(
collateral,
collateralShare.mul(EXCHANGE_RATE_PRECISION / COLLATERIZATION_RATE_PRECISION).mul(COLLATERIZATION_RATE),
false
) >=
// Moved exchangeRate here instead of dividing the other side to preserve more precision
borrowPart.mul(_totalBorrow.elastic).mul(_exchangeRate) / _totalBorrow.base;
}
/// @dev Checks if the user is solvent in the closed liquidation case at the end of the function body.
modifier solvent() {
_;
(, uint256 _exchangeRate) = updateExchangeRate();
require(_isSolvent(msg.sender, _exchangeRate), "Cauldron: user insolvent");
}
/// @notice Gets the exchange rate. I.e how much collateral to buy 1e18 asset.
/// This function is supposed to be invoked if needed because Oracle queries can be expensive.
/// @return updated True if `exchangeRate` was updated.
/// @return rate The new exchange rate.
function updateExchangeRate() public returns (bool updated, uint256 rate) {
(updated, rate) = oracle.get(oracleData);
if (updated) {
exchangeRate = rate;
emit LogExchangeRate(rate);
} else {
// Return the old rate if fetching wasn't successful
rate = exchangeRate;
}
}
/// @dev Helper function to move tokens.
/// @param token The ERC-20 token.
/// @param share The amount in shares to add.
/// @param total Grand total amount to deduct from this contract's balance. Only applicable if `skim` is True.
/// Only used for accounting checks.
/// @param skim If True, only does a balance check on this contract.
/// False if tokens from msg.sender in `bentoBox` should be transferred.
function _addTokens(
IERC20 token,
uint256 share,
uint256 total,
bool skim
) internal {
if (skim) {
require(share <= bentoBox.balanceOf(token, address(this)).sub(total), "Cauldron: Skim too much");
} else {
bentoBox.transfer(token, msg.sender, address(this), share);
}
}
/// @notice Adds `collateral` from msg.sender to the account `to`.
/// @param to The receiver of the tokens.
/// @param skim True if the amount should be skimmed from the deposit balance of msg.sender.x
/// False if tokens from msg.sender in `bentoBox` should be transferred.
/// @param share The amount of shares to add for `to`.
function addCollateral(
address to,
bool skim,
uint256 share
) public {
userCollateralShare[to] = userCollateralShare[to].add(share);
uint256 oldTotalCollateralShare = totalCollateralShare;
totalCollateralShare = oldTotalCollateralShare.add(share);
_addTokens(collateral, share, oldTotalCollateralShare, skim);
emit LogAddCollateral(skim ? address(bentoBox) : msg.sender, to, share);
}
/// @dev Concrete implementation of `removeCollateral`.
function _removeCollateral(address to, uint256 share) internal {
userCollateralShare[msg.sender] = userCollateralShare[msg.sender].sub(share);
totalCollateralShare = totalCollateralShare.sub(share);
emit LogRemoveCollateral(msg.sender, to, share);
bentoBox.transfer(collateral, address(this), to, share);
}
/// @notice Removes `share` amount of collateral and transfers it to `to`.
/// @param to The receiver of the shares.
/// @param share Amount of shares to remove.
function removeCollateral(address to, uint256 share) public solvent {
// accrue must be called because we check solvency
accrue();
_removeCollateral(to, share);
}
/// @dev Concrete implementation of `borrow`.
function _borrow(address to, uint256 amount) internal returns (uint256 part, uint256 share) {
uint256 feeAmount = amount.mul(BORROW_OPENING_FEE) / BORROW_OPENING_FEE_PRECISION; // A flat % fee is charged for any borrow
(totalBorrow, part) = totalBorrow.add(amount.add(feeAmount), true);
BorrowCap memory cap = borrowLimit;
require(totalBorrow.elastic <= cap.total, "Borrow Limit reached");
accrueInfo.feesEarned = accrueInfo.feesEarned.add(uint128(feeAmount));
uint256 newBorrowPart = userBorrowPart[msg.sender].add(part);
require(newBorrowPart <= cap.borrowPartPerAddress, "Borrow Limit reached");
userBorrowPart[msg.sender] = newBorrowPart;
// As long as there are tokens on this contract you can 'mint'... this enables limiting borrows
share = bentoBox.toShare(magicInternetMoney, amount, false);
bentoBox.transfer(magicInternetMoney, address(this), to, share);
emit LogBorrow(msg.sender, to, amount.add(feeAmount), part);
}
/// @notice Sender borrows `amount` and transfers it to `to`.
/// @return part Total part of the debt held by borrowers.
/// @return share Total amount in shares borrowed.
function borrow(address to, uint256 amount) public solvent returns (uint256 part, uint256 share) {
accrue();
(part, share) = _borrow(to, amount);
}
/// @dev Concrete implementation of `repay`.
function _repay(
address to,
bool skim,
uint256 part
) internal returns (uint256 amount) {
(totalBorrow, amount) = totalBorrow.sub(part, true);
userBorrowPart[to] = userBorrowPart[to].sub(part);
uint256 share = bentoBox.toShare(magicInternetMoney, amount, true);
bentoBox.transfer(magicInternetMoney, skim ? address(bentoBox) : msg.sender, address(this), share);
emit LogRepay(skim ? address(bentoBox) : msg.sender, to, amount, part);
}
/// @notice Repays a loan.
/// @param to Address of the user this payment should go.
/// @param skim True if the amount should be skimmed from the deposit balance of msg.sender.
/// False if tokens from msg.sender in `bentoBox` should be transferred.
/// @param part The amount to repay. See `userBorrowPart`.
/// @return amount The total amount repayed.
function repay(
address to,
bool skim,
uint256 part
) public returns (uint256 amount) {
accrue();
amount = _repay(to, skim, part);
}
// Functions that need accrue to be called
uint8 internal constant ACTION_REPAY = 2;
uint8 internal constant ACTION_REMOVE_COLLATERAL = 4;
uint8 internal constant ACTION_BORROW = 5;
uint8 internal constant ACTION_GET_REPAY_SHARE = 6;
uint8 internal constant ACTION_GET_REPAY_PART = 7;
uint8 internal constant ACTION_ACCRUE = 8;
// Functions that don't need accrue to be called
uint8 internal constant ACTION_ADD_COLLATERAL = 10;
uint8 internal constant ACTION_UPDATE_EXCHANGE_RATE = 11;
// Function on BentoBox
uint8 internal constant ACTION_BENTO_DEPOSIT = 20;
uint8 internal constant ACTION_BENTO_WITHDRAW = 21;
uint8 internal constant ACTION_BENTO_TRANSFER = 22;
uint8 internal constant ACTION_BENTO_TRANSFER_MULTIPLE = 23;
uint8 internal constant ACTION_BENTO_SETAPPROVAL = 24;
// Any external call (except to BentoBox)
uint8 internal constant ACTION_CALL = 30;
int256 internal constant USE_VALUE1 = -1;
int256 internal constant USE_VALUE2 = -2;
/// @dev Helper function for choosing the correct value (`value1` or `value2`) depending on `inNum`.
function _num(
int256 inNum,
uint256 value1,
uint256 value2
) internal pure returns (uint256 outNum) {
outNum = inNum >= 0 ? uint256(inNum) : (inNum == USE_VALUE1 ? value1 : value2);
}
/// @dev Helper function for depositing into `bentoBox`.
function _bentoDeposit(
bytes memory data,
uint256 value,
uint256 value1,
uint256 value2
) internal returns (uint256, uint256) {
(IERC20 token, address to, int256 amount, int256 share) = abi.decode(data, (IERC20, address, int256, int256));
amount = int256(_num(amount, value1, value2)); // Done this way to avoid stack too deep errors
share = int256(_num(share, value1, value2));
return bentoBox.deposit{value: value}(token, msg.sender, to, uint256(amount), uint256(share));
}
/// @dev Helper function to withdraw from the `bentoBox`.
function _bentoWithdraw(
bytes memory data,
uint256 value1,
uint256 value2
) internal returns (uint256, uint256) {
(IERC20 token, address to, int256 amount, int256 share) = abi.decode(data, (IERC20, address, int256, int256));
return bentoBox.withdraw(token, msg.sender, to, _num(amount, value1, value2), _num(share, value1, value2));
}
/// @dev Helper function to perform a contract call and eventually extracting revert messages on failure.
/// Calls to `bentoBox` are not allowed for obvious security reasons.
/// This also means that calls made from this contract shall *not* be trusted.
function _call(
uint256 value,
bytes memory data,
uint256 value1,
uint256 value2
) internal returns (bytes memory, uint8) {
(address callee, bytes memory callData, bool useValue1, bool useValue2, uint8 returnValues) =
abi.decode(data, (address, bytes, bool, bool, uint8));
if (useValue1 && !useValue2) {
callData = abi.encodePacked(callData, value1);
} else if (!useValue1 && useValue2) {
callData = abi.encodePacked(callData, value2);
} else if (useValue1 && useValue2) {
callData = abi.encodePacked(callData, value1, value2);
}
require(callee != address(bentoBox) && callee != address(this), "Cauldron: can't call");
(bool success, bytes memory returnData) = callee.call{value: value}(callData);
require(success, "Cauldron: call failed");
return (returnData, returnValues);
}
struct CookStatus {
bool needsSolvencyCheck;
bool hasAccrued;
}
/// @notice Executes a set of actions and allows composability (contract calls) to other contracts.
/// @param actions An array with a sequence of actions to execute (see ACTION_ declarations).
/// @param values A one-to-one mapped array to `actions`. ETH amounts to send along with the actions.
/// Only applicable to `ACTION_CALL`, `ACTION_BENTO_DEPOSIT`.
/// @param datas A one-to-one mapped array to `actions`. Contains abi encoded data of function arguments.
/// @return value1 May contain the first positioned return value of the last executed action (if applicable).
/// @return value2 May contain the second positioned return value of the last executed action which returns 2 values (if applicable).
function cook(
uint8[] calldata actions,
uint256[] calldata values,
bytes[] calldata datas
) external payable returns (uint256 value1, uint256 value2) {
CookStatus memory status;
for (uint256 i = 0; i < actions.length; i++) {
uint8 action = actions[i];
if (!status.hasAccrued && action < 10) {
accrue();
status.hasAccrued = true;
}
if (action == ACTION_ADD_COLLATERAL) {
(int256 share, address to, bool skim) = abi.decode(datas[i], (int256, address, bool));
addCollateral(to, skim, _num(share, value1, value2));
} else if (action == ACTION_REPAY) {
(int256 part, address to, bool skim) = abi.decode(datas[i], (int256, address, bool));
_repay(to, skim, _num(part, value1, value2));
} else if (action == ACTION_REMOVE_COLLATERAL) {
(int256 share, address to) = abi.decode(datas[i], (int256, address));
_removeCollateral(to, _num(share, value1, value2));
status.needsSolvencyCheck = true;
} else if (action == ACTION_BORROW) {
(int256 amount, address to) = abi.decode(datas[i], (int256, address));
(value1, value2) = _borrow(to, _num(amount, value1, value2));
status.needsSolvencyCheck = true;
} else if (action == ACTION_UPDATE_EXCHANGE_RATE) {
(bool must_update, uint256 minRate, uint256 maxRate) = abi.decode(datas[i], (bool, uint256, uint256));
(bool updated, uint256 rate) = updateExchangeRate();
require((!must_update || updated) && rate > minRate && (maxRate == 0 || rate > maxRate), "Cauldron: rate not ok");
} else if (action == ACTION_BENTO_SETAPPROVAL) {
(address user, address _masterContract, bool approved, uint8 v, bytes32 r, bytes32 s) =
abi.decode(datas[i], (address, address, bool, uint8, bytes32, bytes32));
bentoBox.setMasterContractApproval(user, _masterContract, approved, v, r, s);
} else if (action == ACTION_BENTO_DEPOSIT) {
(value1, value2) = _bentoDeposit(datas[i], values[i], value1, value2);
} else if (action == ACTION_BENTO_WITHDRAW) {
(value1, value2) = _bentoWithdraw(datas[i], value1, value2);
} else if (action == ACTION_BENTO_TRANSFER) {
(IERC20 token, address to, int256 share) = abi.decode(datas[i], (IERC20, address, int256));
bentoBox.transfer(token, msg.sender, to, _num(share, value1, value2));
} else if (action == ACTION_BENTO_TRANSFER_MULTIPLE) {
(IERC20 token, address[] memory tos, uint256[] memory shares) = abi.decode(datas[i], (IERC20, address[], uint256[]));
bentoBox.transferMultiple(token, msg.sender, tos, shares);
} else if (action == ACTION_CALL) {
(bytes memory returnData, uint8 returnValues) = _call(values[i], datas[i], value1, value2);
if (returnValues == 1) {
(value1) = abi.decode(returnData, (uint256));
} else if (returnValues == 2) {
(value1, value2) = abi.decode(returnData, (uint256, uint256));
}
} else if (action == ACTION_GET_REPAY_SHARE) {
int256 part = abi.decode(datas[i], (int256));
value1 = bentoBox.toShare(magicInternetMoney, totalBorrow.toElastic(_num(part, value1, value2), true), true);
} else if (action == ACTION_GET_REPAY_PART) {
int256 amount = abi.decode(datas[i], (int256));
value1 = totalBorrow.toBase(_num(amount, value1, value2), false);
}
}
if (status.needsSolvencyCheck) {
(, uint256 _exchangeRate) = updateExchangeRate();
require(_isSolvent(msg.sender, _exchangeRate), "Cauldron: user insolvent");
}
}
/// @notice Handles the liquidation of users' balances, once the users' amount of collateral is too low.
/// @param users An array of user addresses.
/// @param maxBorrowParts A one-to-one mapping to `users`, contains maximum (partial) borrow amounts (to liquidate) of the respective user.
/// @param to Address of the receiver in open liquidations if `swapper` is zero.
function liquidate(
address[] calldata users,
uint256[] calldata maxBorrowParts,
address to,
ISwapper swapper
) public {
// Oracle can fail but we still need to allow liquidations
(, uint256 _exchangeRate) = updateExchangeRate();
accrue();
uint256 allCollateralShare;
uint256 allBorrowAmount;
uint256 allBorrowPart;
Rebase memory _totalBorrow = totalBorrow;
Rebase memory bentoBoxTotals = bentoBox.totals(collateral);
for (uint256 i = 0; i < users.length; i++) {
address user = users[i];
if (!_isSolvent(user, _exchangeRate)) {
uint256 borrowPart;
{
uint256 availableBorrowPart = userBorrowPart[user];
borrowPart = maxBorrowParts[i] > availableBorrowPart ? availableBorrowPart : maxBorrowParts[i];
userBorrowPart[user] = availableBorrowPart.sub(borrowPart);
}
uint256 borrowAmount = _totalBorrow.toElastic(borrowPart, false);
uint256 collateralShare =
bentoBoxTotals.toBase(
borrowAmount.mul(LIQUIDATION_MULTIPLIER).mul(_exchangeRate) /
(LIQUIDATION_MULTIPLIER_PRECISION * EXCHANGE_RATE_PRECISION),
false
);
userCollateralShare[user] = userCollateralShare[user].sub(collateralShare);
emit LogRemoveCollateral(user, to, collateralShare);
emit LogRepay(msg.sender, user, borrowAmount, borrowPart);
emit LogLiquidation(msg.sender, user, to, collateralShare, borrowAmount, borrowPart);
// Keep totals
allCollateralShare = allCollateralShare.add(collateralShare);
allBorrowAmount = allBorrowAmount.add(borrowAmount);
allBorrowPart = allBorrowPart.add(borrowPart);
}
}
require(allBorrowAmount != 0, "Cauldron: all are solvent");
_totalBorrow.elastic = _totalBorrow.elastic.sub(allBorrowAmount.to128());
_totalBorrow.base = _totalBorrow.base.sub(allBorrowPart.to128());
totalBorrow = _totalBorrow;
totalCollateralShare = totalCollateralShare.sub(allCollateralShare);
// Apply a percentual fee share to sSpell holders
{
uint256 distributionAmount = (allBorrowAmount.mul(LIQUIDATION_MULTIPLIER) / LIQUIDATION_MULTIPLIER_PRECISION).sub(allBorrowAmount).mul(DISTRIBUTION_PART) / DISTRIBUTION_PRECISION; // Distribution Amount
allBorrowAmount = allBorrowAmount.add(distributionAmount);
accrueInfo.feesEarned = accrueInfo.feesEarned.add(distributionAmount.to128());
}
uint256 allBorrowShare = bentoBox.toShare(magicInternetMoney, allBorrowAmount, true);
// Swap using a swapper freely chosen by the caller
// Open (flash) liquidation: get proceeds first and provide the borrow after
bentoBox.transfer(collateral, address(this), to, allCollateralShare);
if (swapper != ISwapper(0)) {
swapper.swap(collateral, magicInternetMoney, msg.sender, allBorrowShare, allCollateralShare);
}
allBorrowShare = bentoBox.toShare(magicInternetMoney, allBorrowAmount, true);
bentoBox.transfer(magicInternetMoney, msg.sender, address(this), allBorrowShare);
}
/// @notice Withdraws the fees accumulated.
function withdrawFees() public {
accrue();
address _feeTo = masterContract.feeTo();
uint256 _feesEarned = accrueInfo.feesEarned;
uint256 share = bentoBox.toShare(magicInternetMoney, _feesEarned, false);
bentoBox.transfer(magicInternetMoney, address(this), _feeTo, share);
accrueInfo.feesEarned = 0;
emit LogWithdrawFees(_feeTo, _feesEarned);
}
/// @notice Sets the beneficiary of interest accrued.
/// MasterContract Only Admin function.
/// @param newFeeTo The address of the receiver.
function setFeeTo(address newFeeTo) public onlyOwner {
feeTo = newFeeTo;
emit LogFeeTo(newFeeTo);
}
/// @notice reduces the supply of MIM
/// @param amount amount to reduce supply by
function reduceSupply(uint256 amount) public onlyMasterContractOwner {
bentoBox.withdraw(magicInternetMoney, address(this), masterContract.owner(), amount, 0);
}
/// @notice allows to change the interest rate
/// @param newInterestRate new interest rate
function changeInterestRate(uint64 newInterestRate) public onlyMasterContractOwner {
uint64 oldInterestRate = accrueInfo.INTEREST_PER_SECOND;
require(newInterestRate < oldInterestRate + oldInterestRate * 3 / 4 , "Interest rate increase > 75%");
require(lastInterestUpdate + 3 days < block.timestamp, "Update only every 3 days");
lastInterestUpdate = block.timestamp;
accrueInfo.INTEREST_PER_SECOND = newInterestRate;
emit LogInterestChange(oldInterestRate, newInterestRate);
}
/// @notice allows to change the borrow limit
/// @param newBorrowLimit new borrow limit
/// @param perAddressPart new borrow limit per address
function changeBorrowLimit(uint128 newBorrowLimit, uint128 perAddressPart) public onlyMasterContractOwner {
borrowLimit = BorrowCap(newBorrowLimit, perAddressPart);
emit LogChangeBorrowLimit(newBorrowLimit, perAddressPart);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/// @notice A library for performing overflow-/underflow-safe math,
/// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math).
library BoringMath {
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow");
}
function to128(uint256 a) internal pure returns (uint128 c) {
require(a <= uint128(-1), "BoringMath: uint128 Overflow");
c = uint128(a);
}
function to64(uint256 a) internal pure returns (uint64 c) {
require(a <= uint64(-1), "BoringMath: uint64 Overflow");
c = uint64(a);
}
function to32(uint256 a) internal pure returns (uint32 c) {
require(a <= uint32(-1), "BoringMath: uint32 Overflow");
c = uint32(a);
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128.
library BoringMath128 {
function add(uint128 a, uint128 b) internal pure returns (uint128 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint128 a, uint128 b) internal pure returns (uint128 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint64.
library BoringMath64 {
function add(uint64 a, uint64 b) internal pure returns (uint64 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint64 a, uint64 b) internal pure returns (uint64 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32.
library BoringMath32 {
function add(uint32 a, uint32 b) internal pure returns (uint32 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint32 a, uint32 b) internal pure returns (uint32 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
// Audit on 5-Jan-2021 by Keno and BoringCrypto
// Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol + Claimable.sol
// Edited by BoringCrypto
contract BoringOwnableData {
address public owner;
address public pendingOwner;
}
contract BoringOwnable is BoringOwnableData {
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/// @notice `owner` defaults to msg.sender on construction.
constructor() public {
owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
/// @notice Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner.
/// Can only be invoked by the current `owner`.
/// @param newOwner Address of the new owner.
/// @param direct True if `newOwner` should be set immediately. False if `newOwner` needs to use `claimOwnership`.
/// @param renounce Allows the `newOwner` to be `address(0)` if `direct` and `renounce` is True. Has no effect otherwise.
function transferOwnership(
address newOwner,
bool direct,
bool renounce
) public onlyOwner {
if (direct) {
// Checks
require(newOwner != address(0) || renounce, "Ownable: zero address");
// Effects
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
pendingOwner = address(0);
} else {
// Effects
pendingOwner = newOwner;
}
}
/// @notice Needs to be called by `pendingOwner` to claim ownership.
function claimOwnership() public {
address _pendingOwner = pendingOwner;
// Checks
require(msg.sender == _pendingOwner, "Ownable: caller != pending owner");
// Effects
emit OwnershipTransferred(owner, _pendingOwner);
owner = _pendingOwner;
pendingOwner = address(0);
}
/// @notice Only allows the `owner` to execute the function.
modifier onlyOwner() {
require(msg.sender == owner, "Ownable: caller is not the owner");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./interfaces/IERC20.sol";
import "./Domain.sol";
// solhint-disable no-inline-assembly
// solhint-disable not-rely-on-time
// Data part taken out for building of contracts that receive delegate calls
contract ERC20Data {
/// @notice owner > balance mapping.
mapping(address => uint256) public balanceOf;
/// @notice owner > spender > allowance mapping.
mapping(address => mapping(address => uint256)) public allowance;
/// @notice owner > nonce mapping. Used in `permit`.
mapping(address => uint256) public nonces;
}
abstract contract ERC20 is IERC20, Domain {
/// @notice owner > balance mapping.
mapping(address => uint256) public override balanceOf;
/// @notice owner > spender > allowance mapping.
mapping(address => mapping(address => uint256)) public override allowance;
/// @notice owner > nonce mapping. Used in `permit`.
mapping(address => uint256) public nonces;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/// @notice Transfers `amount` tokens from `msg.sender` to `to`.
/// @param to The address to move the tokens.
/// @param amount of the tokens to move.
/// @return (bool) Returns True if succeeded.
function transfer(address to, uint256 amount) public returns (bool) {
// If `amount` is 0, or `msg.sender` is `to` nothing happens
if (amount != 0 || msg.sender == to) {
uint256 srcBalance = balanceOf[msg.sender];
require(srcBalance >= amount, "ERC20: balance too low");
if (msg.sender != to) {
require(to != address(0), "ERC20: no zero address"); // Moved down so low balance calls safe some gas
balanceOf[msg.sender] = srcBalance - amount; // Underflow is checked
balanceOf[to] += amount;
}
}
emit Transfer(msg.sender, to, amount);
return true;
}
/// @notice Transfers `amount` tokens from `from` to `to`. Caller needs approval for `from`.
/// @param from Address to draw tokens from.
/// @param to The address to move the tokens.
/// @param amount The token amount to move.
/// @return (bool) Returns True if succeeded.
function transferFrom(
address from,
address to,
uint256 amount
) public returns (bool) {
// If `amount` is 0, or `from` is `to` nothing happens
if (amount != 0) {
uint256 srcBalance = balanceOf[from];
require(srcBalance >= amount, "ERC20: balance too low");
if (from != to) {
uint256 spenderAllowance = allowance[from][msg.sender];
// If allowance is infinite, don't decrease it to save on gas (breaks with EIP-20).
if (spenderAllowance != type(uint256).max) {
require(spenderAllowance >= amount, "ERC20: allowance too low");
allowance[from][msg.sender] = spenderAllowance - amount; // Underflow is checked
}
require(to != address(0), "ERC20: no zero address"); // Moved down so other failed calls safe some gas
balanceOf[from] = srcBalance - amount; // Underflow is checked
balanceOf[to] += amount;
}
}
emit Transfer(from, to, amount);
return true;
}
/// @notice Approves `amount` from sender to be spend by `spender`.
/// @param spender Address of the party that can draw from msg.sender's account.
/// @param amount The maximum collective amount that `spender` can draw.
/// @return (bool) Returns True if approved.
function approve(address spender, uint256 amount) public override returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32) {
return _domainSeparator();
}
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 private constant PERMIT_SIGNATURE_HASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
/// @notice Approves `value` from `owner_` to be spend by `spender`.
/// @param owner_ Address of the owner.
/// @param spender The address of the spender that gets approved to draw from `owner_`.
/// @param value The maximum collective amount that `spender` can draw.
/// @param deadline This permit must be redeemed before this deadline (UTC timestamp in seconds).
function permit(
address owner_,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external override {
require(owner_ != address(0), "ERC20: Owner cannot be 0");
require(block.timestamp < deadline, "ERC20: Expired");
require(
ecrecover(_getDigest(keccak256(abi.encode(PERMIT_SIGNATURE_HASH, owner_, spender, value, nonces[owner_]++, deadline))), v, r, s) ==
owner_,
"ERC20: Invalid Signature"
);
allowance[owner_][spender] = value;
emit Approval(owner_, spender, value);
}
}
contract ERC20WithSupply is IERC20, ERC20 {
uint256 public override totalSupply;
function _mint(address user, uint256 amount) private {
uint256 newTotalSupply = totalSupply + amount;
require(newTotalSupply >= totalSupply, "Mint overflow");
totalSupply = newTotalSupply;
balanceOf[user] += amount;
}
function _burn(address user, uint256 amount) private {
require(balanceOf[user] >= amount, "Burn too much");
totalSupply -= amount;
balanceOf[user] -= amount;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IMasterContract {
/// @notice Init function that gets called from `BoringFactory.deploy`.
/// Also kown as the constructor for cloned contracts.
/// Any ETH send to `BoringFactory.deploy` ends up here.
/// @param data Can be abi encoded arguments or anything else.
function init(bytes calldata data) external payable;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./BoringMath.sol";
struct Rebase {
uint128 elastic;
uint128 base;
}
/// @notice A rebasing library using overflow-/underflow-safe math.
library RebaseLibrary {
using BoringMath for uint256;
using BoringMath128 for uint128;
/// @notice Calculates the base value in relationship to `elastic` and `total`.
function toBase(
Rebase memory total,
uint256 elastic,
bool roundUp
) internal pure returns (uint256 base) {
if (total.elastic == 0) {
base = elastic;
} else {
base = elastic.mul(total.base) / total.elastic;
if (roundUp && base.mul(total.elastic) / total.base < elastic) {
base = base.add(1);
}
}
}
/// @notice Calculates the elastic value in relationship to `base` and `total`.
function toElastic(
Rebase memory total,
uint256 base,
bool roundUp
) internal pure returns (uint256 elastic) {
if (total.base == 0) {
elastic = base;
} else {
elastic = base.mul(total.elastic) / total.base;
if (roundUp && elastic.mul(total.base) / total.elastic < base) {
elastic = elastic.add(1);
}
}
}
/// @notice Add `elastic` to `total` and doubles `total.base`.
/// @return (Rebase) The new total.
/// @return base in relationship to `elastic`.
function add(
Rebase memory total,
uint256 elastic,
bool roundUp
) internal pure returns (Rebase memory, uint256 base) {
base = toBase(total, elastic, roundUp);
total.elastic = total.elastic.add(elastic.to128());
total.base = total.base.add(base.to128());
return (total, base);
}
/// @notice Sub `base` from `total` and update `total.elastic`.
/// @return (Rebase) The new total.
/// @return elastic in relationship to `base`.
function sub(
Rebase memory total,
uint256 base,
bool roundUp
) internal pure returns (Rebase memory, uint256 elastic) {
elastic = toElastic(total, base, roundUp);
total.elastic = total.elastic.sub(elastic.to128());
total.base = total.base.sub(base.to128());
return (total, elastic);
}
/// @notice Add `elastic` and `base` to `total`.
function add(
Rebase memory total,
uint256 elastic,
uint256 base
) internal pure returns (Rebase memory) {
total.elastic = total.elastic.add(elastic.to128());
total.base = total.base.add(base.to128());
return total;
}
/// @notice Subtract `elastic` and `base` to `total`.
function sub(
Rebase memory total,
uint256 elastic,
uint256 base
) internal pure returns (Rebase memory) {
total.elastic = total.elastic.sub(elastic.to128());
total.base = total.base.sub(base.to128());
return total;
}
/// @notice Add `elastic` to `total` and update storage.
/// @return newElastic Returns updated `elastic`.
function addElastic(Rebase storage total, uint256 elastic) internal returns (uint256 newElastic) {
newElastic = total.elastic = total.elastic.add(elastic.to128());
}
/// @notice Subtract `elastic` from `total` and update storage.
/// @return newElastic Returns updated `elastic`.
function subElastic(Rebase storage total, uint256 elastic) internal returns (uint256 newElastic) {
newElastic = total.elastic = total.elastic.sub(elastic.to128());
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "../interfaces/IERC20.sol";
// solhint-disable avoid-low-level-calls
library BoringERC20 {
bytes4 private constant SIG_SYMBOL = 0x95d89b41; // symbol()
bytes4 private constant SIG_NAME = 0x06fdde03; // name()
bytes4 private constant SIG_DECIMALS = 0x313ce567; // decimals()
bytes4 private constant SIG_TRANSFER = 0xa9059cbb; // transfer(address,uint256)
bytes4 private constant SIG_TRANSFER_FROM = 0x23b872dd; // transferFrom(address,address,uint256)
function returnDataToString(bytes memory data) internal pure returns (string memory) {
if (data.length >= 64) {
return abi.decode(data, (string));
} else if (data.length == 32) {
uint8 i = 0;
while(i < 32 && data[i] != 0) {
i++;
}
bytes memory bytesArray = new bytes(i);
for (i = 0; i < 32 && data[i] != 0; i++) {
bytesArray[i] = data[i];
}
return string(bytesArray);
} else {
return "???";
}
}
/// @notice Provides a safe ERC20.symbol version which returns '???' as fallback string.
/// @param token The address of the ERC-20 token contract.
/// @return (string) Token symbol.
function safeSymbol(IERC20 token) internal view returns (string memory) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_SYMBOL));
return success ? returnDataToString(data) : "???";
}
/// @notice Provides a safe ERC20.name version which returns '???' as fallback string.
/// @param token The address of the ERC-20 token contract.
/// @return (string) Token name.
function safeName(IERC20 token) internal view returns (string memory) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_NAME));
return success ? returnDataToString(data) : "???";
}
/// @notice Provides a safe ERC20.decimals version which returns '18' as fallback value.
/// @param token The address of the ERC-20 token contract.
/// @return (uint8) Token decimals.
function safeDecimals(IERC20 token) internal view returns (uint8) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_DECIMALS));
return success && data.length == 32 ? abi.decode(data, (uint8)) : 18;
}
/// @notice Provides a safe ERC20.transfer version for different ERC-20 implementations.
/// Reverts on a failed transfer.
/// @param token The address of the ERC-20 token.
/// @param to Transfer tokens to.
/// @param amount The token amount.
function safeTransfer(
IERC20 token,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER, to, amount));
require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: Transfer failed");
}
/// @notice Provides a safe ERC20.transferFrom version for different ERC-20 implementations.
/// Reverts on a failed transfer.
/// @param token The address of the ERC-20 token.
/// @param from Transfer tokens from.
/// @param to Transfer tokens to.
/// @param amount The token amount.
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER_FROM, from, to, amount));
require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: TransferFrom failed");
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import '@boringcrypto/boring-solidity/contracts/interfaces/IERC20.sol';
import '@boringcrypto/boring-solidity/contracts/libraries/BoringRebase.sol';
import './IBatchFlashBorrower.sol';
import './IFlashBorrower.sol';
import './IStrategy.sol';
interface IBentoBoxV1 {
event LogDeploy(address indexed masterContract, bytes data, address indexed cloneAddress);
event LogDeposit(address indexed token, address indexed from, address indexed to, uint256 amount, uint256 share);
event LogFlashLoan(address indexed borrower, address indexed token, uint256 amount, uint256 feeAmount, address indexed receiver);
event LogRegisterProtocol(address indexed protocol);
event LogSetMasterContractApproval(address indexed masterContract, address indexed user, bool approved);
event LogStrategyDivest(address indexed token, uint256 amount);
event LogStrategyInvest(address indexed token, uint256 amount);
event LogStrategyLoss(address indexed token, uint256 amount);
event LogStrategyProfit(address indexed token, uint256 amount);
event LogStrategyQueued(address indexed token, address indexed strategy);
event LogStrategySet(address indexed token, address indexed strategy);
event LogStrategyTargetPercentage(address indexed token, uint256 targetPercentage);
event LogTransfer(address indexed token, address indexed from, address indexed to, uint256 share);
event LogWhiteListMasterContract(address indexed masterContract, bool approved);
event LogWithdraw(address indexed token, address indexed from, address indexed to, uint256 amount, uint256 share);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function balanceOf(IERC20, address) external view returns (uint256);
function batch(bytes[] calldata calls, bool revertOnFail) external payable returns (bool[] memory successes, bytes[] memory results);
function batchFlashLoan(IBatchFlashBorrower borrower, address[] calldata receivers, IERC20[] calldata tokens, uint256[] calldata amounts, bytes calldata data) external;
function claimOwnership() external;
function deploy(address masterContract, bytes calldata data, bool useCreate2) external payable;
function deposit(IERC20 token_, address from, address to, uint256 amount, uint256 share) external payable returns (uint256 amountOut, uint256 shareOut);
function flashLoan(IFlashBorrower borrower, address receiver, IERC20 token, uint256 amount, bytes calldata data) external;
function harvest(IERC20 token, bool balance, uint256 maxChangeAmount) external;
function masterContractApproved(address, address) external view returns (bool);
function masterContractOf(address) external view returns (address);
function nonces(address) external view returns (uint256);
function owner() external view returns (address);
function pendingOwner() external view returns (address);
function pendingStrategy(IERC20) external view returns (IStrategy);
function permitToken(IERC20 token, address from, address to, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
function registerProtocol() external;
function setMasterContractApproval(address user, address masterContract, bool approved, uint8 v, bytes32 r, bytes32 s) external;
function setStrategy(IERC20 token, IStrategy newStrategy) external;
function setStrategyTargetPercentage(IERC20 token, uint64 targetPercentage_) external;
function strategy(IERC20) external view returns (IStrategy);
function strategyData(IERC20) external view returns (uint64 strategyStartDate, uint64 targetPercentage, uint128 balance);
function toAmount(IERC20 token, uint256 share, bool roundUp) external view returns (uint256 amount);
function toShare(IERC20 token, uint256 amount, bool roundUp) external view returns (uint256 share);
function totals(IERC20) external view returns (Rebase memory totals_);
function transfer(IERC20 token, address from, address to, uint256 share) external;
function transferMultiple(IERC20 token, address from, address[] calldata tos, uint256[] calldata shares) external;
function transferOwnership(address newOwner, bool direct, bool renounce) external;
function whitelistMasterContract(address masterContract, bool approved) external;
function whitelistedMasterContracts(address) external view returns (bool);
function withdraw(IERC20 token_, address from, address to, uint256 amount, uint256 share) external returns (uint256 amountOut, uint256 shareOut);
}
// SPDX-License-Identifier: MIT
// Magic Internet Money
// ███╗ ███╗██╗███╗ ███╗
// ████╗ ████║██║████╗ ████║
// ██╔████╔██║██║██╔████╔██║
// ██║╚██╔╝██║██║██║╚██╔╝██║
// ██║ ╚═╝ ██║██║██║ ╚═╝ ██║
// ╚═╝ ╚═╝╚═╝╚═╝ ╚═╝
// BoringCrypto, 0xMerlin
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@boringcrypto/boring-solidity/contracts/ERC20.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
import "@boringcrypto/boring-solidity/contracts/BoringOwnable.sol";
/// @title Cauldron
/// @dev This contract allows contract calls to any contract (except BentoBox)
/// from arbitrary callers thus, don't trust calls from this contract in any circumstances.
contract MagicInternetMoney is ERC20, BoringOwnable {
using BoringMath for uint256;
// ERC20 'variables'
string public constant symbol = "MIM";
string public constant name = "Magic Internet Money";
uint8 public constant decimals = 18;
uint256 public override totalSupply;
struct Minting {
uint128 time;
uint128 amount;
}
Minting public lastMint;
uint256 private constant MINTING_PERIOD = 24 hours;
uint256 private constant MINTING_INCREASE = 15000;
uint256 private constant MINTING_PRECISION = 1e5;
function mint(address to, uint256 amount) public onlyOwner {
require(to != address(0), "MIM: no mint to zero address");
// Limits the amount minted per period to a convergence function, with the period duration restarting on every mint
uint256 totalMintedAmount = uint256(lastMint.time < block.timestamp - MINTING_PERIOD ? 0 : lastMint.amount).add(amount);
require(totalSupply == 0 || totalSupply.mul(MINTING_INCREASE) / MINTING_PRECISION >= totalMintedAmount);
lastMint.time = block.timestamp.to128();
lastMint.amount = totalMintedAmount.to128();
totalSupply = totalSupply + amount;
balanceOf[to] += amount;
emit Transfer(address(0), to, amount);
}
function mintToBentoBox(address clone, uint256 amount, IBentoBoxV1 bentoBox) public onlyOwner {
mint(address(bentoBox), amount);
bentoBox.deposit(IERC20(address(this)), address(bentoBox), clone, amount, 0);
}
function burn(uint256 amount) public {
require(amount <= balanceOf[msg.sender], "MIM: not enough");
balanceOf[msg.sender] -= amount;
totalSupply -= amount;
emit Transfer(msg.sender, address(0), amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
interface IOracle {
/// @notice Get the latest exchange rate.
/// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle.
/// For example:
/// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256));
/// @return success if no valid (recent) rate is available, return false else true.
/// @return rate The rate of the requested asset / pair / pool.
function get(bytes calldata data) external returns (bool success, uint256 rate);
/// @notice Check the last exchange rate without any state changes.
/// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle.
/// For example:
/// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256));
/// @return success if no valid (recent) rate is available, return false else true.
/// @return rate The rate of the requested asset / pair / pool.
function peek(bytes calldata data) external view returns (bool success, uint256 rate);
/// @notice Check the current spot exchange rate without any state changes. For oracles like TWAP this will be different from peek().
/// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle.
/// For example:
/// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256));
/// @return rate The rate of the requested asset / pair / pool.
function peekSpot(bytes calldata data) external view returns (uint256 rate);
/// @notice Returns a human readable (short) name about this oracle.
/// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle.
/// For example:
/// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256));
/// @return (string) A human readable symbol name about this oracle.
function symbol(bytes calldata data) external view returns (string memory);
/// @notice Returns a human readable name about this oracle.
/// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle.
/// For example:
/// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256));
/// @return (string) A human readable name about this oracle.
function name(bytes calldata data) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
import "@boringcrypto/boring-solidity/contracts/interfaces/IERC20.sol";
interface ISwapper {
/// @notice Withdraws 'amountFrom' of token 'from' from the BentoBox account for this swapper.
/// Swaps it for at least 'amountToMin' of token 'to'.
/// Transfers the swapped tokens of 'to' into the BentoBox using a plain ERC20 transfer.
/// Returns the amount of tokens 'to' transferred to BentoBox.
/// (The BentoBox skim function will be used by the caller to get the swapped funds).
function swap(
IERC20 fromToken,
IERC20 toToken,
address recipient,
uint256 shareToMin,
uint256 shareFrom
) external returns (uint256 extraShare, uint256 shareReturned);
/// @notice Calculates the amount of token 'from' needed to complete the swap (amountFrom),
/// this should be less than or equal to amountFromMax.
/// Withdraws 'amountFrom' of token 'from' from the BentoBox account for this swapper.
/// Swaps it for exactly 'exactAmountTo' of token 'to'.
/// Transfers the swapped tokens of 'to' into the BentoBox using a plain ERC20 transfer.
/// Transfers allocated, but unused 'from' tokens within the BentoBox to 'refundTo' (amountFromMax - amountFrom).
/// Returns the amount of 'from' tokens withdrawn from BentoBox (amountFrom).
/// (The BentoBox skim function will be used by the caller to get the swapped funds).
function swapExact(
IERC20 fromToken,
IERC20 toToken,
address recipient,
address refundTo,
uint256 shareFromSupplied,
uint256 shareToExact
) external returns (uint256 shareUsed, uint256 shareReturned);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
/// @notice EIP 2612
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// SPDX-License-Identifier: MIT
// Based on code and smartness by Ross Campbell and Keno
// Uses immutable to store the domain separator to reduce gas usage
// If the chain id changes due to a fork, the forked chain will calculate on the fly.
pragma solidity 0.6.12;
// solhint-disable no-inline-assembly
contract Domain {
bytes32 private constant DOMAIN_SEPARATOR_SIGNATURE_HASH = keccak256("EIP712Domain(uint256 chainId,address verifyingContract)");
// See https://eips.ethereum.org/EIPS/eip-191
string private constant EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA = "\x19\x01";
// solhint-disable var-name-mixedcase
bytes32 private immutable _DOMAIN_SEPARATOR;
uint256 private immutable DOMAIN_SEPARATOR_CHAIN_ID;
/// @dev Calculate the DOMAIN_SEPARATOR
function _calculateDomainSeparator(uint256 chainId) private view returns (bytes32) {
return keccak256(
abi.encode(
DOMAIN_SEPARATOR_SIGNATURE_HASH,
chainId,
address(this)
)
);
}
constructor() public {
uint256 chainId; assembly {chainId := chainid()}
_DOMAIN_SEPARATOR = _calculateDomainSeparator(DOMAIN_SEPARATOR_CHAIN_ID = chainId);
}
/// @dev Return the DOMAIN_SEPARATOR
// It's named internal to allow making it public from the contract that uses it by creating a simple view function
// with the desired public name, such as DOMAIN_SEPARATOR or domainSeparator.
// solhint-disable-next-line func-name-mixedcase
function _domainSeparator() internal view returns (bytes32) {
uint256 chainId; assembly {chainId := chainid()}
return chainId == DOMAIN_SEPARATOR_CHAIN_ID ? _DOMAIN_SEPARATOR : _calculateDomainSeparator(chainId);
}
function _getDigest(bytes32 dataHash) internal view returns (bytes32 digest) {
digest =
keccak256(
abi.encodePacked(
EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA,
_domainSeparator(),
dataHash
)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import '@boringcrypto/boring-solidity/contracts/interfaces/IERC20.sol';
interface IBatchFlashBorrower {
function onBatchFlashLoan(
address sender,
IERC20[] calldata tokens,
uint256[] calldata amounts,
uint256[] calldata fees,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import '@boringcrypto/boring-solidity/contracts/interfaces/IERC20.sol';
interface IFlashBorrower {
function onFlashLoan(
address sender,
IERC20 token,
uint256 amount,
uint256 fee,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IStrategy {
// Send the assets to the Strategy and call skim to invest them
function skim(uint256 amount) external;
// Harvest any profits made converted to the asset and pass them to the caller
function harvest(uint256 balance, address sender) external returns (int256 amountAdded);
// Withdraw assets. The returned amount can differ from the requested amount due to rounding.
// The actualAmount should be very close to the amount. The difference should NOT be used to report a loss. That's what harvest is for.
function withdraw(uint256 amount) external returns (uint256 actualAmount);
// Withdraw all assets in the safest way possible. This shouldn't fail.
function exit(uint256 balance) external returns (int256 amountAdded);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol";
import "../interfaces/ISwapper.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
contract SushiSwapSwapper is ISwapper {
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public immutable bentoBox;
IUniswapV2Factory public immutable factory;
bytes32 public immutable pairCodeHash;
constructor(
IBentoBoxV1 bentoBox_,
IUniswapV2Factory factory_,
bytes32 pairCodeHash_
) public {
bentoBox = bentoBox_;
factory = factory_;
pairCodeHash = pairCodeHash_;
}
// Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// Given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// Swaps to a flexible amount, from an exact input amount
/// @inheritdoc ISwapper
function swap(
IERC20 fromToken,
IERC20 toToken,
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public override returns (uint256 extraShare, uint256 shareReturned) {
(IERC20 token0, IERC20 token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken);
IUniswapV2Pair pair = IUniswapV2Pair(
uint256(
keccak256(abi.encodePacked(hex"ff", factory, keccak256(abi.encodePacked(address(token0), address(token1))), pairCodeHash))
)
);
(uint256 amountFrom, ) = bentoBox.withdraw(fromToken, address(this), address(pair), 0, shareFrom);
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 amountTo;
if (toToken > fromToken) {
amountTo = getAmountOut(amountFrom, reserve0, reserve1);
pair.swap(0, amountTo, address(bentoBox), new bytes(0));
} else {
amountTo = getAmountOut(amountFrom, reserve1, reserve0);
pair.swap(amountTo, 0, address(bentoBox), new bytes(0));
}
(, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
// Swaps to an exact amount, from a flexible input amount
/// @inheritdoc ISwapper
function swapExact(
IERC20 fromToken,
IERC20 toToken,
address recipient,
address refundTo,
uint256 shareFromSupplied,
uint256 shareToExact
) public override returns (uint256 shareUsed, uint256 shareReturned) {
IUniswapV2Pair pair;
{
(IERC20 token0, IERC20 token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken);
pair = IUniswapV2Pair(
uint256(
keccak256(
abi.encodePacked(hex"ff", factory, keccak256(abi.encodePacked(address(token0), address(token1))), pairCodeHash)
)
)
);
}
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 amountToExact = bentoBox.toAmount(toToken, shareToExact, true);
uint256 amountFrom;
if (toToken > fromToken) {
amountFrom = getAmountIn(amountToExact, reserve0, reserve1);
(, shareUsed) = bentoBox.withdraw(fromToken, address(this), address(pair), amountFrom, 0);
pair.swap(0, amountToExact, address(bentoBox), "");
} else {
amountFrom = getAmountIn(amountToExact, reserve1, reserve0);
(, shareUsed) = bentoBox.withdraw(fromToken, address(this), address(pair), amountFrom, 0);
pair.swap(amountToExact, 0, address(bentoBox), "");
}
bentoBox.deposit(toToken, address(bentoBox), recipient, 0, shareToExact);
shareReturned = shareFromSupplied.sub(shareUsed);
if (shareReturned > 0) {
bentoBox.transfer(fromToken, address(this), refundTo, shareReturned);
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function migrator() 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 setMigrator(address) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol";
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "../libraries/UniswapV2Library.sol";
import "@sushiswap/core/contracts/uniswapv2/libraries/TransferHelper.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
contract SushiSwapMultiSwapper {
using BoringERC20 for IERC20;
using BoringMath for uint256;
address private immutable factory;
IBentoBoxV1 private immutable bentoBox;
bytes32 private immutable pairCodeHash;
constructor(
address _factory,
IBentoBoxV1 _bentoBox,
bytes32 _pairCodeHash
) public {
factory = _factory;
bentoBox = _bentoBox;
pairCodeHash = _pairCodeHash;
}
function getOutputAmount(
IERC20 tokenIn,
IERC20 tokenOut,
uint256 amountMinOut,
address[] calldata path,
uint256 shareIn
) external view returns (uint256 amountOut) {
uint256 amountIn = bentoBox.toAmount(tokenIn, shareIn, false);
uint256[] memory amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path, pairCodeHash);
amountOut = amounts[amounts.length - 1];
}
function swap(
IERC20 tokenIn,
IERC20 tokenOut,
uint256 amountMinOut,
address[] calldata path,
uint256 shareIn
) external returns (uint256 amountOut, uint256 shareOut) {
(uint256 amountIn, ) = bentoBox.withdraw(tokenIn, address(this), address(this), 0, shareIn);
amountOut = _swapExactTokensForTokens(amountIn, amountMinOut, path, address(bentoBox));
(, shareOut) = bentoBox.deposit(tokenOut, address(bentoBox), msg.sender, amountOut, 0);
}
// Swaps an exact amount of tokens for another token through the path passed as an argument
// Returns the amount of the final token
function _swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] memory path,
address to
) internal returns (uint256 amountOut) {
uint256[] memory amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path, pairCodeHash);
amountOut = amounts[amounts.length - 1];
require(amountOut >= amountOutMin, "insufficient-amount-out");
IERC20(path[0]).safeTransfer(UniswapV2Library.pairFor(factory, path[0], path[1], pairCodeHash), amountIn);
_swap(amounts, path, to);
}
// requires the initial amount to have already been sent to the first pair
function _swap(
uint256[] memory amounts,
address[] memory path,
address _to
) internal virtual {
for (uint256 i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0, ) = UniswapV2Library.sortTokens(input, output);
uint256 amountOut = amounts[i + 1];
(uint256 amount0Out, uint256 amount1Out) = input == token0 ? (uint256(0), amountOut) : (amountOut, uint256(0));
address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2], pairCodeHash) : _to;
IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output, pairCodeHash)).swap(amount0Out, amount1Out, to, new bytes(0));
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol";
import "@sushiswap/core/contracts/uniswapv2/libraries/SafeMath.sol";
library UniswapV2Library {
using SafeMathUniswap for uint256;
// 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,
bytes32 pairCodeHash
) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encodePacked(token0, token1)),
pairCodeHash // init code hash
)
)
)
);
}
// fetches and sorts the reserves for a pair
function getReserves(
address factory,
address tokenA,
address tokenB,
bytes32 pairCodeHash
) internal view returns (uint256 reserveA, uint256 reserveB) {
(address token0, ) = sortTokens(tokenA, tokenB);
(uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB, pairCodeHash)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) internal pure returns (uint256 amountB) {
require(amountA > 0, "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(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
require(amountIn > 0, "UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT");
require(reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY");
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
require(amountOut > 0, "UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT");
require(reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY");
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(
address factory,
uint256 amountIn,
address[] memory path,
bytes32 pairCodeHash
) internal view returns (uint256[] memory amounts) {
require(path.length >= 2, "UniswapV2Library: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[0] = amountIn;
for (uint256 i; i < path.length - 1; i++) {
(uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i], path[i + 1], pairCodeHash);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(
address factory,
uint256 amountOut,
address[] memory path,
bytes32 pairCodeHash
) internal view returns (uint256[] memory amounts) {
require(path.length >= 2, "UniswapV2Library: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint256 i = path.length - 1; i > 0; i--) {
(uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i - 1], path[i], pairCodeHash);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity =0.6.12;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMathUniswap {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
// License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol";
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "../libraries/UniswapV2Library.sol";
import "@sushiswap/core/contracts/uniswapv2/libraries/TransferHelper.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
import "@boringcrypto/boring-solidity/contracts/BoringOwnable.sol";
interface CurvePool {
function exchange_underlying(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy,
address receiver
) external returns (uint256);
}
interface TetherToken {
function approve(address _spender, uint256 _value) external;
}
contract SpellSwapper is BoringOwnable {
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966);
CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B);
TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7);
IERC20 public constant SPELL = IERC20(0x090185f2135308BaD17527004364eBcC2D37e5F6);
address public constant sSPELL = 0x26FA3fFFB6EfE8c1E69103aCb4044C26B9A106a9;
IUniswapV2Pair constant SPELL_WETH = IUniswapV2Pair(0xb5De0C3753b6E1B4dBA616Db82767F17513E6d4E);
IUniswapV2Pair constant pair = IUniswapV2Pair(0x06da0fd433C1A5d7a4faa01111c044910A184553);
IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3);
address public constant treasury = 0x5A7C5505f3CFB9a0D9A8493EC41bf27EE48c406D;
mapping(address => bool) public verified;
constructor() public {
MIM.approve(address(MIM3POOL), type(uint256).max);
verified[msg.sender] = true;
}
// Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// Given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
modifier onlyVerified() {
require(verified[msg.sender], "Only verified operators");
_;
}
function setVerified(address operator, bool status) public onlyOwner {
verified[operator] = status;
}
// Swaps to a flexible amount, from an exact input amount
function swap(uint256 amountToMin) public onlyVerified {
uint256 amountFirst;
uint256 amountIntermediate;
{
uint256 shareFrom = bentoBox.balanceOf(MIM, address(this));
uint256 treasuryShare = shareFrom / 4;
bentoBox.withdraw(MIM, address(this), treasury, 0, treasuryShare);
(uint256 amountMIMFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom.sub(treasuryShare));
amountFirst = MIM3POOL.exchange_underlying(0, 3, amountMIMFrom, 0, address(pair));
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
amountIntermediate = getAmountOut(amountFirst, reserve1, reserve0);
}
uint256 amountThird;
{
pair.swap(amountIntermediate, 0, address(SPELL_WETH), new bytes(0));
(uint256 reserve0, uint256 reserve1, ) = SPELL_WETH.getReserves();
amountThird = getAmountOut(amountIntermediate, reserve1, reserve0);
require(amountThird >= amountToMin, "Minimum must be reached");
}
SPELL_WETH.swap(amountThird, 0, sSPELL, new bytes(0));
}
}
// SPDX-License-Identifier: MIT
// Spell
// Special thanks to:
// @BoringCrypto for his great libraries
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@boringcrypto/boring-solidity/contracts/ERC20.sol";
import "@boringcrypto/boring-solidity/contracts/BoringOwnable.sol";
/// @title Spell
/// @author 0xMerlin
/// @dev This contract allows contract calls to any contract (except BentoBox)
/// from arbitrary callers thus, don't trust calls from this contract in any circumstances.
contract Spell is ERC20, BoringOwnable {
using BoringMath for uint256;
// ERC20 'variables'
string public constant symbol = "SPELL";
string public constant name = "Spell Token";
uint8 public constant decimals = 18;
uint256 public override totalSupply;
uint256 public constant MAX_SUPPLY = 420 * 1e27;
function mint(address to, uint256 amount) public onlyOwner {
require(to != address(0), "SPELL: no mint to zero address");
require(MAX_SUPPLY >= totalSupply.add(amount), "SPELL: Don't go over MAX");
totalSupply = totalSupply + amount;
balanceOf[to] += amount;
emit Transfer(address(0), to, amount);
}
}
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol";
import "@boringcrypto/boring-solidity/contracts/Domain.sol";
import "@boringcrypto/boring-solidity/contracts/ERC20.sol";
import "@boringcrypto/boring-solidity/contracts/BoringBatchable.sol";
// Staking in sSpell inspired by Chef Nomi's SushiBar - MIT license (originally WTFPL)
// modified by BoringCrypto for DictatorDAO
contract sSpell is IERC20, Domain {
using BoringMath for uint256;
using BoringMath128 for uint128;
using BoringERC20 for IERC20;
string public constant symbol = "sSPELL";
string public constant name = "Staked Spell Tokens";
uint8 public constant decimals = 18;
uint256 public override totalSupply;
uint256 private constant LOCK_TIME = 24 hours;
IERC20 public immutable token;
constructor(IERC20 _token) public {
token = _token;
}
struct User {
uint128 balance;
uint128 lockedUntil;
}
/// @notice owner > balance mapping.
mapping(address => User) public users;
/// @notice owner > spender > allowance mapping.
mapping(address => mapping(address => uint256)) public override allowance;
/// @notice owner > nonce mapping. Used in `permit`.
mapping(address => uint256) public nonces;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function balanceOf(address user) public view override returns (uint256 balance) {
return users[user].balance;
}
function _transfer(
address from,
address to,
uint256 shares
) internal {
User memory fromUser = users[from];
require(block.timestamp >= fromUser.lockedUntil, "Locked");
if (shares != 0) {
require(fromUser.balance >= shares, "Low balance");
if (from != to) {
require(to != address(0), "Zero address"); // Moved down so other failed calls safe some gas
User memory toUser = users[to];
users[from].balance = fromUser.balance - shares.to128(); // Underflow is checked
users[to].balance = toUser.balance + shares.to128(); // Can't overflow because totalSupply would be greater than 2^128-1;
}
}
emit Transfer(from, to, shares);
}
function _useAllowance(address from, uint256 shares) internal {
if (msg.sender == from) {
return;
}
uint256 spenderAllowance = allowance[from][msg.sender];
// If allowance is infinite, don't decrease it to save on gas (breaks with EIP-20).
if (spenderAllowance != type(uint256).max) {
require(spenderAllowance >= shares, "Low allowance");
allowance[from][msg.sender] = spenderAllowance - shares; // Underflow is checked
}
}
/// @notice Transfers `shares` tokens from `msg.sender` to `to`.
/// @param to The address to move the tokens.
/// @param shares of the tokens to move.
/// @return (bool) Returns True if succeeded.
function transfer(address to, uint256 shares) public returns (bool) {
_transfer(msg.sender, to, shares);
return true;
}
/// @notice Transfers `shares` tokens from `from` to `to`. Caller needs approval for `from`.
/// @param from Address to draw tokens from.
/// @param to The address to move the tokens.
/// @param shares The token shares to move.
/// @return (bool) Returns True if succeeded.
function transferFrom(
address from,
address to,
uint256 shares
) public returns (bool) {
_useAllowance(from, shares);
_transfer(from, to, shares);
return true;
}
/// @notice Approves `amount` from sender to be spend by `spender`.
/// @param spender Address of the party that can draw from msg.sender's account.
/// @param amount The maximum collective amount that `spender` can draw.
/// @return (bool) Returns True if approved.
function approve(address spender, uint256 amount) public override returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32) {
return _domainSeparator();
}
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 private constant PERMIT_SIGNATURE_HASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
/// @notice Approves `value` from `owner_` to be spend by `spender`.
/// @param owner_ Address of the owner.
/// @param spender The address of the spender that gets approved to draw from `owner_`.
/// @param value The maximum collective amount that `spender` can draw.
/// @param deadline This permit must be redeemed before this deadline (UTC timestamp in seconds).
function permit(
address owner_,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external override {
require(owner_ != address(0), "Zero owner");
require(block.timestamp < deadline, "Expired");
require(
ecrecover(_getDigest(keccak256(abi.encode(PERMIT_SIGNATURE_HASH, owner_, spender, value, nonces[owner_]++, deadline))), v, r, s) ==
owner_,
"Invalid Sig"
);
allowance[owner_][spender] = value;
emit Approval(owner_, spender, value);
}
/// math is ok, because amount, totalSupply and shares is always 0 <= amount <= 100.000.000 * 10^18
/// theoretically you can grow the amount/share ratio, but it's not practical and useless
function mint(uint256 amount) public returns (bool) {
require(msg.sender != address(0), "Zero address");
User memory user = users[msg.sender];
uint256 totalTokens = token.balanceOf(address(this));
uint256 shares = totalSupply == 0 ? amount : (amount * totalSupply) / totalTokens;
user.balance += shares.to128();
user.lockedUntil = (block.timestamp + LOCK_TIME).to128();
users[msg.sender] = user;
totalSupply += shares;
token.safeTransferFrom(msg.sender, address(this), amount);
emit Transfer(address(0), msg.sender, shares);
return true;
}
function _burn(
address from,
address to,
uint256 shares
) internal {
require(to != address(0), "Zero address");
User memory user = users[from];
require(block.timestamp >= user.lockedUntil, "Locked");
uint256 amount = (shares * token.balanceOf(address(this))) / totalSupply;
users[from].balance = user.balance.sub(shares.to128()); // Must check underflow
totalSupply -= shares;
token.safeTransfer(to, amount);
emit Transfer(from, address(0), shares);
}
function burn(address to, uint256 shares) public returns (bool) {
_burn(msg.sender, to, shares);
return true;
}
function burnFrom(
address from,
address to,
uint256 shares
) public returns (bool) {
_useAllowance(from, shares);
_burn(from, to, shares);
return true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// solhint-disable avoid-low-level-calls
// solhint-disable no-inline-assembly
// Audit on 5-Jan-2021 by Keno and BoringCrypto
import "./interfaces/IERC20.sol";
contract BaseBoringBatchable {
/// @dev Helper function to extract a useful revert message from a failed call.
/// If the returned data is malformed or not correctly abi encoded then this call can fail itself.
function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) {
// If the _res length is less than 68, then the transaction failed silently (without a revert message)
if (_returnData.length < 68) return "Transaction reverted silently";
assembly {
// Slice the sighash.
_returnData := add(_returnData, 0x04)
}
return abi.decode(_returnData, (string)); // All that remains is the revert string
}
/// @notice Allows batched call to self (this contract).
/// @param calls An array of inputs for each call.
/// @param revertOnFail If True then reverts after a failed call and stops doing further calls.
// F1: External is ok here because this is the batch function, adding it to a batch makes no sense
// F2: Calls in the batch may be payable, delegatecall operates in the same context, so each call in the batch has access to msg.value
// C3: The length of the loop is fully under user control, so can't be exploited
// C7: Delegatecall is only used on the same contract, so it's safe
function batch(bytes[] calldata calls, bool revertOnFail) external payable {
for (uint256 i = 0; i < calls.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(calls[i]);
if (!success && revertOnFail) {
revert(_getRevertMsg(result));
}
}
}
}
contract BoringBatchable is BaseBoringBatchable {
/// @notice Call wrapper that performs `ERC20.permit` on `token`.
/// Lookup `IERC20.permit`.
// F6: Parameters can be used front-run the permit and the user's permit will fail (due to nonce or other revert)
// if part of a batch this could be used to grief once as the second call would not need the permit
function permitToken(
IERC20 token,
address from,
address to,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public {
token.permit(from, to, amount, deadline, v, r, s);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol";
import "../../interfaces/ISwapper.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
interface CurvePool {
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
}
interface YearnVault {
function withdraw(uint256 maxShares, address recipient) external returns (uint256);
}
interface TetherToken {
function approve(address _spender, uint256 _value) external;
}
contract YVYFISwapper is ISwapper {
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public immutable bentoBox;
CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B);
YearnVault public constant YFI_VAULT = YearnVault(0xE14d13d8B3b85aF791b2AADD661cDBd5E6097Db1);
TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7);
IUniswapV2Pair constant YFI_WETH = IUniswapV2Pair(0x088ee5007C98a9677165D78dD2109AE4a3D04d0C);
IUniswapV2Pair constant pair = IUniswapV2Pair(0x06da0fd433C1A5d7a4faa01111c044910A184553);
constructor(
IBentoBoxV1 bentoBox_
) public {
bentoBox = bentoBox_;
TETHER.approve(address(MIM3POOL), type(uint256).max);
}
// Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// Given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// Swaps to a flexible amount, from an exact input amount
/// @inheritdoc ISwapper
function swap(
IERC20 fromToken,
IERC20 toToken,
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public override returns (uint256 extraShare, uint256 shareReturned) {
uint256 amountFirst;
{
bentoBox.withdraw(fromToken, address(this), address(this), 0, shareFrom);
uint256 amountFrom = YFI_VAULT.withdraw(type(uint256).max, address(YFI_WETH));
(uint256 reserve0, uint256 reserve1, ) = YFI_WETH.getReserves();
amountFirst = getAmountOut(amountFrom, reserve0, reserve1);
}
YFI_WETH.swap(0, amountFirst, address(pair), new bytes(0));
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 amountIntermediate = getAmountOut(amountFirst, reserve0, reserve1);
pair.swap(0, amountIntermediate, address(this), new bytes(0));
uint256 amountTo = MIM3POOL.exchange_underlying(3, 0, amountIntermediate, 0, address(bentoBox));
(, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
// Swaps to an exact amount, from a flexible input amount
/// @inheritdoc ISwapper
function swapExact(
IERC20 fromToken,
IERC20 toToken,
address recipient,
address refundTo,
uint256 shareFromSupplied,
uint256 shareToExact
) public override returns (uint256 shareUsed, uint256 shareReturned) {
return (0,0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol";
import "../../interfaces/ISwapper.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
interface CurvePool {
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
}
interface YearnVault {
function withdraw(uint256 maxShares, address recipient) external returns (uint256);
}
interface TetherToken {
function approve(address _spender, uint256 _value) external;
}
contract YVWETHSwapper is ISwapper {
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public immutable bentoBox;
CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B);
TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7);
YearnVault public constant WETH_VAULT = YearnVault(0xa258C4606Ca8206D8aA700cE2143D7db854D168c);
IUniswapV2Pair constant pair = IUniswapV2Pair(0x06da0fd433C1A5d7a4faa01111c044910A184553);
constructor(
IBentoBoxV1 bentoBox_
) public {
bentoBox = bentoBox_;
TETHER.approve(address(MIM3POOL), type(uint256).max);
}
// Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// Given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// Swaps to a flexible amount, from an exact input amount
/// @inheritdoc ISwapper
function swap(
IERC20 fromToken,
IERC20 toToken,
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public override returns (uint256 extraShare, uint256 shareReturned) {
bentoBox.withdraw(fromToken, address(this), address(this), 0, shareFrom);
uint256 amountFrom = WETH_VAULT.withdraw(type(uint256).max, address(pair));
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 amountIntermediate = getAmountOut(amountFrom, reserve0, reserve1);
pair.swap(0, amountIntermediate, address(this), new bytes(0));
uint256 amountTo = MIM3POOL.exchange_underlying(3, 0, amountIntermediate, 0, address(bentoBox));
(, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
// Swaps to an exact amount, from a flexible input amount
/// @inheritdoc ISwapper
function swapExact(
IERC20 fromToken,
IERC20 toToken,
address recipient,
address refundTo,
uint256 shareFromSupplied,
uint256 shareToExact
) public override returns (uint256 shareUsed, uint256 shareReturned) {
return (0,0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol";
import "../../interfaces/ISwapper.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
interface CurvePool {
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
}
interface YearnVault {
function withdraw() external returns (uint256);
}
interface TetherToken {
function approve(address _spender, uint256 _value) external;
}
contract YVUSDTSwapper is ISwapper {
using BoringMath for uint256;
using BoringERC20 for IERC20;
// Local variables
IBentoBoxV1 public immutable bentoBox;
CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B);
TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7);
YearnVault public constant TETHER_VAULT = YearnVault(0x7Da96a3891Add058AdA2E826306D812C638D87a7);
constructor(
IBentoBoxV1 bentoBox_
) public {
bentoBox = bentoBox_;
TETHER.approve(address(MIM3POOL), type(uint256).max);
}
// Swaps to a flexible amount, from an exact input amount
/// @inheritdoc ISwapper
function swap(
IERC20 fromToken,
IERC20 toToken,
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public override returns (uint256 extraShare, uint256 shareReturned) {
bentoBox.withdraw(fromToken, address(this), address(this), 0, shareFrom);
uint256 amountFrom =TETHER_VAULT.withdraw();
uint256 amountTo = MIM3POOL.exchange_underlying(3, 0, amountFrom, 0, address(bentoBox));
(, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
// Swaps to an exact amount, from a flexible input amount
/// @inheritdoc ISwapper
function swapExact(
IERC20 fromToken,
IERC20 toToken,
address recipient,
address refundTo,
uint256 shareFromSupplied,
uint256 shareToExact
) public override returns (uint256 shareUsed, uint256 shareReturned) {
return (1,1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol";
import "../../interfaces/ISwapper.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
interface CurvePool {
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
}
interface YearnVault {
function withdraw() external returns (uint256);
}
contract YVUSDCSwapper is ISwapper {
using BoringMath for uint256;
using BoringERC20 for IERC20;
// Local variables
IBentoBoxV1 public immutable bentoBox;
CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B);
IERC20 public constant TETHER = IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7);
YearnVault public constant USDC_VAULT = YearnVault(0x5f18C75AbDAe578b483E5F43f12a39cF75b973a9);
IERC20 public constant USDC = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
constructor(
IBentoBoxV1 bentoBox_
) public {
bentoBox = bentoBox_;
USDC.approve(address(MIM3POOL), type(uint256).max);
}
// Swaps to a flexible amount, from an exact input amount
/// @inheritdoc ISwapper
function swap(
IERC20 fromToken,
IERC20 toToken,
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public override returns (uint256 extraShare, uint256 shareReturned) {
bentoBox.withdraw(fromToken, address(this), address(this), 0, shareFrom);
uint256 amountFrom = USDC_VAULT.withdraw();
uint256 amountTo = MIM3POOL.exchange_underlying(2, 0, amountFrom, 0, address(bentoBox));
(, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
// Swaps to an exact amount, from a flexible input amount
/// @inheritdoc ISwapper
function swapExact(
IERC20 fromToken,
IERC20 toToken,
address recipient,
address refundTo,
uint256 shareFromSupplied,
uint256 shareToExact
) public override returns (uint256 shareUsed, uint256 shareReturned) {
return (1,1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
interface CurvePool {
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
}
interface YearnVault {
function withdraw() external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
}
interface TetherToken {
function approve(address _spender, uint256 _value) external;
}
contract YVUSDTLevSwapper {
using BoringMath for uint256;
using BoringERC20 for IERC20;
// Local variables
IBentoBoxV1 public immutable bentoBox;
CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B);
TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7);
YearnVault public constant USDT_VAULT = YearnVault(0x7Da96a3891Add058AdA2E826306D812C638D87a7);
IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3);
constructor(
IBentoBoxV1 bentoBox_
) public {
bentoBox = bentoBox_;
MIM.approve(address(MIM3POOL), type(uint256).max);
TETHER.approve(address(USDT_VAULT), type(uint256).max);
}
// Swaps to a flexible amount, from an exact input amount
function swap(
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public returns (uint256 extraShare, uint256 shareReturned) {
(uint256 amountFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom);
MIM3POOL.exchange_underlying(0, 3, amountFrom, 0, address(this));
uint256 amountTo = USDT_VAULT.deposit(type(uint256).max, address(bentoBox));
(, shareReturned) = bentoBox.deposit(IERC20(address(USDT_VAULT)), address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
interface CurvePool {
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
}
interface YearnVault {
function withdraw() external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
}
contract YVUSDCLeverageSwapper {
using BoringMath for uint256;
using BoringERC20 for IERC20;
// Local variables
IBentoBoxV1 public immutable bentoBox;
CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B);
YearnVault public constant USDC_VAULT = YearnVault(0x5f18C75AbDAe578b483E5F43f12a39cF75b973a9);
IERC20 public constant USDC = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3);
constructor(
IBentoBoxV1 bentoBox_
) public {
bentoBox = bentoBox_;
MIM.approve(address(MIM3POOL), type(uint256).max);
USDC.approve(address(USDC_VAULT), type(uint256).max);
}
// Swaps to a flexible amount, from an exact input amount
function swap(
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public returns (uint256 extraShare, uint256 shareReturned) {
(uint256 amountFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom);
uint256 amountIntermediate = MIM3POOL.exchange_underlying(0, 2, amountFrom, 0, address(this));
uint256 amountTo = USDC_VAULT.deposit(type(uint256).max, address(bentoBox));
(, shareReturned) = bentoBox.deposit(IERC20(address(USDC_VAULT)), address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
interface CurvePool {
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
function approve(address _spender, uint256 _value) external returns (bool);
function add_liquidity(uint256[3] memory amounts, uint256 _min_mint_amount, bool _use_underlying) external returns (uint256);
}
interface YearnVault {
function withdraw() external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
}
interface TetherToken {
function approve(address _spender, uint256 _value) external;
}
contract YVIBLevSwapper {
using BoringMath for uint256;
using BoringERC20 for IERC20;
// Local variables
IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966);
CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B);
CurvePool constant public IronBank = CurvePool(0x2dded6Da1BF5DBdF597C45fcFaa3194e53EcfeAF);
YearnVault constant public YVIB = YearnVault(0x27b7b1ad7288079A66d12350c828D3C00A6F07d7);
TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7);
IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3);
IERC20 public constant CurveToken = IERC20(0x5282a4eF67D9C33135340fB3289cc1711c13638C);
constructor() public {
MIM.approve(address(MIM3POOL), type(uint256).max);
TETHER.approve(address(IronBank), type(uint256).max);
CurveToken.approve(address(YVIB), type(uint256).max);
}
// Swaps to a flexible amount, from an exact input amount
function swap(
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public returns (uint256 extraShare, uint256 shareReturned) {
(uint256 amountFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom);
uint256 amountIntermediate = MIM3POOL.exchange_underlying(0, 3, amountFrom, 0, address(this));
uint256[3] memory amountsAdded = [0,0, amountIntermediate];
IronBank.add_liquidity(amountsAdded, 0, true);
uint256 amountTo = YVIB.deposit(type(uint256).max, address(bentoBox));
(, shareReturned) = bentoBox.deposit(IERC20(address(YVIB)), address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
interface CurvePool {
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
function approve(address _spender, uint256 _value) external returns (bool);
function add_liquidity(uint256[3] memory amounts, uint256 _min_mint_amount, bool _use_underlying) external returns (uint256);
function add_liquidity(uint256[2] memory amounts, uint256 _min_mint_amount) external payable returns (uint256);
}
interface YearnVault {
function withdraw() external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
}
interface TetherToken {
function approve(address _spender, uint256 _value) external;
}
interface IWETH is IERC20 {
function transfer(address _to, uint256 _value) external returns (bool success);
function deposit() external payable;
function withdraw(uint wad) external;
}
contract YVCrvStETHLevSwapper {
using BoringMath for uint256;
using BoringERC20 for IERC20;
// Local variables
IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966);
CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B);
CurvePool constant public STETH = CurvePool(0xDC24316b9AE028F1497c275EB9192a3Ea0f67022);
YearnVault constant public YVSTETH = YearnVault(0xdCD90C7f6324cfa40d7169ef80b12031770B4325);
TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7);
IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3);
IERC20 public constant CurveToken = IERC20(0x06325440D014e39736583c165C2963BA99fAf14E);
IUniswapV2Pair constant pair = IUniswapV2Pair(0x06da0fd433C1A5d7a4faa01111c044910A184553);
IWETH public constant WETH = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
constructor() public {
MIM.approve(address(MIM3POOL), type(uint256).max);
TETHER.approve(address(STETH), type(uint256).max);
CurveToken.approve(address(YVSTETH), type(uint256).max);
}
// Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// Given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
receive() external payable {}
// Swaps to a flexible amount, from an exact input amount
function swap(
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public returns (uint256 extraShare, uint256 shareReturned) {
(uint256 amountFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom);
uint256 amountThird;
{
uint256 amountSecond = MIM3POOL.exchange_underlying(0, 3, amountFrom, 0, address(pair));
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
amountThird = getAmountOut(amountSecond, reserve1, reserve0);
pair.swap(amountThird, 0, address(this), new bytes(0));
}
WETH.withdraw(amountThird);
uint256[2] memory amountsAdded = [amountThird,0];
STETH.add_liquidity{value: amountThird}(amountsAdded, 0);
uint256 amountTo = YVSTETH.deposit(type(uint256).max, address(bentoBox));
(, shareReturned) = bentoBox.deposit(IERC20(address(YVSTETH)), address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
interface CurvePool {
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
function approve(address _spender, uint256 _value) external returns (bool);
function add_liquidity(uint256[2] memory amounts, uint256 _min_mint_amount) external;
}
interface IThreeCrypto is CurvePool {
function exchange(uint256 i, uint256 j, uint256 dx, uint256 min_dy) external;
}
interface TetherToken {
function approve(address _spender, uint256 _value) external;
}
contract WethLevSwapper {
using BoringMath for uint256;
using BoringERC20 for IERC20;
// Local variables
IBentoBoxV1 public constant degenBox = IBentoBoxV1(0xd96f48665a1410C0cd669A88898ecA36B9Fc2cce);
CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B);
IThreeCrypto constant public threecrypto = IThreeCrypto(0xD51a44d3FaE010294C616388b506AcdA1bfAAE46);
TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7);
IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3);
IERC20 public constant WETH = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
constructor() public {
MIM.approve(address(MIM3POOL), type(uint256).max);
TETHER.approve(address(threecrypto), type(uint256).max);
WETH.approve(address(degenBox), type(uint256).max);
}
// Swaps to a flexible amount, from an exact input amount
function swap(
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public returns (uint256 extraShare, uint256 shareReturned) {
(uint256 amountFrom, ) = degenBox.withdraw(MIM, address(this), address(this), 0, shareFrom);
uint256 amountOne = MIM3POOL.exchange_underlying(0, 3, amountFrom, 0, address(this));
threecrypto.exchange(0, 2, amountOne, 0);
uint256 amountTo = WETH.balanceOf(address(this));
(, shareReturned) = degenBox.deposit(WETH, address(this), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
interface CurvePool {
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
function approve(address _spender, uint256 _value) external returns (bool);
function add_liquidity(uint256[2] memory amounts, uint256 _min_mint_amount) external;
}
interface IThreeCrypto is CurvePool {
function exchange(uint256 i, uint256 j, uint256 dx, uint256 min_dy) external;
}
interface TetherToken {
function approve(address _spender, uint256 _value) external;
}
contract WbtcLevSwapper {
using BoringMath for uint256;
using BoringERC20 for IERC20;
// Local variables
IBentoBoxV1 public constant degenBox = IBentoBoxV1(0xd96f48665a1410C0cd669A88898ecA36B9Fc2cce);
CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B);
IThreeCrypto constant public threecrypto = IThreeCrypto(0xD51a44d3FaE010294C616388b506AcdA1bfAAE46);
TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7);
IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3);
IERC20 public constant WBTC = IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599);
constructor() public {
MIM.approve(address(MIM3POOL), type(uint256).max);
TETHER.approve(address(threecrypto), type(uint256).max);
WBTC.approve(address(degenBox), type(uint256).max);
}
// Swaps to a flexible amount, from an exact input amount
function swap(
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public returns (uint256 extraShare, uint256 shareReturned) {
(uint256 amountFrom, ) = degenBox.withdraw(MIM, address(this), address(this), 0, shareFrom);
uint256 amountOne = MIM3POOL.exchange_underlying(0, 3, amountFrom, 0, address(this));
threecrypto.exchange(0, 1, amountOne, 0);
uint256 amountTo = WBTC.balanceOf(address(this));
(, shareReturned) = degenBox.deposit(WBTC, address(this), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
interface CurvePool {
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
function approve(address _spender, uint256 _value) external returns (bool);
function add_liquidity(uint256[3] memory amounts, uint256 _min_mint_amount) external;
}
interface YearnVault {
function withdraw() external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
}
interface TetherToken {
function approve(address _spender, uint256 _value) external;
}
interface IConvex is IERC20{
function withdrawAndUnwrap(uint256 _amount) external;
//deposit a curve token
function deposit(uint256 _amount, address _to) external;
}
contract ThreeCryptoLevSwapper {
using BoringMath for uint256;
using BoringERC20 for IERC20;
// Local variables
IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966);
CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B);
CurvePool constant public threecrypto = CurvePool(0xD51a44d3FaE010294C616388b506AcdA1bfAAE46);
IConvex public constant cvx3Crypto = IConvex(0x5958A8DB7dfE0CC49382209069b00F54e17929C2);
TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7);
IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3);
IERC20 public constant CurveToken = IERC20(0xc4AD29ba4B3c580e6D59105FFf484999997675Ff);
constructor() public {
MIM.approve(address(MIM3POOL), type(uint256).max);
TETHER.approve(address(threecrypto), type(uint256).max);
CurveToken.approve(address(cvx3Crypto), type(uint256).max);
}
// Swaps to a flexible amount, from an exact input amount
function swap(
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public returns (uint256 extraShare, uint256 shareReturned) {
(uint256 amountFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom);
uint256 amountIntermediate = MIM3POOL.exchange_underlying(0, 3, amountFrom, 0, address(this));
uint256[3] memory amountsAdded = [amountIntermediate, 0, 0];
threecrypto.add_liquidity(amountsAdded, 0);
uint256 amountTo = CurveToken.balanceOf(address(this));
cvx3Crypto.deposit(amountTo, address(bentoBox));
(, shareReturned) = bentoBox.deposit(cvx3Crypto, address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@boringcrypto/boring-solidity/contracts/interfaces/IERC20.sol";
import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
interface CurvePool {
function exchange_underlying(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy,
address receiver
) external returns (uint256);
function approve(address _spender, uint256 _value) external returns (bool);
function add_liquidity(
address pool,
uint256[4] memory amounts,
uint256 _min_mint_amount
) external returns (uint256);
}
interface YearnVault {
function withdraw() external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
}
interface TetherToken {
function approve(address _spender, uint256 _value) external;
}
interface IConvex is IERC20 {
function withdrawAndUnwrap(uint256 _amount) external;
//deposit a curve token
function deposit(uint256 _amount, address _to) external;
}
contract StkFrax3CrvLevSwapper {
using BoringMath for uint256;
using BoringERC20 for IERC20;
// Local variables
IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966);
CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B);
CurvePool public constant threePool = CurvePool(0xA79828DF1850E8a3A3064576f380D90aECDD3359);
IConvex public immutable stkFrax3Crv;
TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7);
IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3);
IERC20 public constant FRAX3CRV = IERC20(0xd632f22692FaC7611d2AA1C0D552930D43CAEd3B);
constructor(IConvex _stkFrax3Crv) public {
stkFrax3Crv = _stkFrax3Crv;
MIM.approve(address(MIM3POOL), type(uint256).max);
TETHER.approve(address(threePool), type(uint256).max);
FRAX3CRV.approve(address(_stkFrax3Crv), type(uint256).max);
}
// Swaps to a flexible amount, from an exact input amount
function swap(
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public returns (uint256 extraShare, uint256 shareReturned) {
(uint256 amountFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom);
uint256 amountUSDT = MIM3POOL.exchange_underlying(0, 3, amountFrom, 0, address(this));
// Pool token order is FRAX, DAI, USDC, USDT
uint256[4] memory amountsAdded = [0, 0, 0, amountUSDT];
uint256 frax3CrvAmount = threePool.add_liquidity(address(FRAX3CRV), amountsAdded, 0);
stkFrax3Crv.deposit(frax3CrvAmount, address(bentoBox));
(, shareReturned) = bentoBox.deposit(stkFrax3Crv, address(bentoBox), recipient, frax3CrvAmount, 0);
extraShare = shareReturned.sub(shareToMin);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
interface CurvePool {
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
function approve(address _spender, uint256 _value) external returns (bool);
function add_liquidity(uint256[2] memory amounts, uint256 _min_mint_amount) external;
}
interface IThreeCrypto is CurvePool {
function exchange(uint256 i, uint256 j, uint256 dx, uint256 min_dy) external;
}
interface YearnVault {
function withdraw() external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
}
interface TetherToken {
function approve(address _spender, uint256 _value) external;
}
interface IConvex is IERC20{
function withdrawAndUnwrap(uint256 _amount) external;
//deposit a curve token
function deposit(uint256 _amount, address _to) external;
}
contract RenCrvLevSwapper {
using BoringMath for uint256;
using BoringERC20 for IERC20;
// Local variables
IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966);
CurvePool constant public renCrv = CurvePool(0x93054188d876f558f4a66B2EF1d97d16eDf0895B);
CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B);
IThreeCrypto constant public threecrypto = IThreeCrypto(0xD51a44d3FaE010294C616388b506AcdA1bfAAE46);
IConvex public constant cvxRen = IConvex(0xB65eDE134521F0EFD4E943c835F450137dC6E83e);
TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7);
IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3);
IERC20 public constant CurveToken = IERC20(0x49849C98ae39Fff122806C06791Fa73784FB3675);
IERC20 public constant WBTC = IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599);
constructor() public {
MIM.approve(address(MIM3POOL), type(uint256).max);
TETHER.approve(address(threecrypto), type(uint256).max);
WBTC.approve(address(renCrv), type(uint256).max);
CurveToken.approve(address(cvxRen), type(uint256).max);
}
// Swaps to a flexible amount, from an exact input amount
function swap(
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public returns (uint256 extraShare, uint256 shareReturned) {
(uint256 amountFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom);
uint256 amountOne = MIM3POOL.exchange_underlying(0, 3, amountFrom, 0, address(this));
threecrypto.exchange(0, 1, amountOne, 0);
uint256 amountIntermediate = WBTC.balanceOf(address(this));
uint256[2] memory amountsAdded = [0, amountIntermediate];
renCrv.add_liquidity(amountsAdded, 0);
uint256 amountTo = CurveToken.balanceOf(address(this));
cvxRen.deposit(amountTo, address(bentoBox));
(, shareReturned) = bentoBox.deposit(cvxRen, address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@sushiswap/bentobox-sdk/contracts/IStrategy.sol";
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol";
// solhint-disable not-rely-on-time
contract SimpleStrategyMock is IStrategy {
using BoringMath for uint256;
using BoringERC20 for IERC20;
IERC20 private immutable token;
address private immutable bentoBox;
modifier onlyBentoBox() {
require(msg.sender == bentoBox, "Ownable: caller is not the owner");
_;
}
constructor(address bentoBox_, IERC20 token_) public {
bentoBox = bentoBox_;
token = token_;
}
// Send the assets to the Strategy and call skim to invest them
function skim(uint256) external override onlyBentoBox {
// Leave the tokens on the contract
return;
}
// Harvest any profits made converted to the asset and pass them to the caller
function harvest(uint256 balance, address) external override onlyBentoBox returns (int256 amountAdded) {
amountAdded = int256(token.balanceOf(address(this)).sub(balance));
token.safeTransfer(bentoBox, uint256(amountAdded)); // Add as profit
}
// Withdraw assets. The returned amount can differ from the requested amount due to rounding or if the request was more than there is.
function withdraw(uint256 amount) external override onlyBentoBox returns (uint256 actualAmount) {
token.safeTransfer(bentoBox, uint256(amount)); // Add as profit
actualAmount = amount;
}
// Withdraw all assets in the safest way possible. This shouldn't fail.
function exit(uint256 balance) external override onlyBentoBox returns (int256 amountAdded) {
amountAdded = 0;
token.safeTransfer(bentoBox, balance);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
interface IYearnVault {
function deposit(uint256 amount, address recipient) external returns (uint256 shares);
}
contract YearnLiquidityMigrationHelper {
using BoringMath for uint256;
using BoringERC20 for IERC20;
// Local variables
IBentoBoxV1 public immutable bentoBox;
constructor(IBentoBoxV1 bentoBox_) public {
bentoBox = bentoBox_;
}
function migrate(
IERC20 token,
IYearnVault vault,
uint256 amount,
address recipient
) external {
token.approve(address(vault), amount);
uint256 shares = vault.deposit(amount, address(bentoBox));
bentoBox.deposit(token, address(bentoBox), recipient, shares, 0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol";
import "../../interfaces/ISwapper.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
interface CurvePool {
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
function approve(address _spender, uint256 _value) external returns (bool);
function remove_liquidity_one_coin(uint256 tokenAmount, int128 i, uint256 min_amount, bool use_underlying) external returns(uint256);
}
interface YearnVault {
function withdraw() external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
}
interface TetherToken {
function approve(address _spender, uint256 _value) external;
function balanceOf(address user) external view returns (uint256);
}
contract YVIBSwapper is ISwapper {
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966);
CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B);
CurvePool constant public IronBank = CurvePool(0x2dded6Da1BF5DBdF597C45fcFaa3194e53EcfeAF);
YearnVault constant public YVIB = YearnVault(0x27b7b1ad7288079A66d12350c828D3C00A6F07d7);
TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7);
IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3);
constructor() public {
MIM.approve(address(MIM3POOL), type(uint256).max);
TETHER.approve(address(MIM3POOL), type(uint256).max);
}
// Swaps to a flexible amount, from an exact input amount
/// @inheritdoc ISwapper
function swap(
IERC20 fromToken,
IERC20 toToken,
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public override returns (uint256 extraShare, uint256 shareReturned) {
bentoBox.withdraw(fromToken, address(this), address(this), 0, shareFrom);
uint256 amountFrom = YVIB.withdraw();
IronBank.remove_liquidity_one_coin(amountFrom, 2, 0, true);
uint256 amountIntermediate = TETHER.balanceOf(address(this));
uint256 amountTo = MIM3POOL.exchange_underlying(3, 0, amountIntermediate, 0, address(bentoBox));
(, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
// Swaps to an exact amount, from a flexible input amount
/// @inheritdoc ISwapper
function swapExact(
IERC20 fromToken,
IERC20 toToken,
address recipient,
address refundTo,
uint256 shareFromSupplied,
uint256 shareToExact
) public override returns (uint256 shareUsed, uint256 shareReturned) {
return (0,0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol";
import "../../interfaces/ISwapper.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
interface CurvePool {
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
function approve(address _spender, uint256 _value) external returns (bool);
function remove_liquidity_one_coin(uint256 tokenAmount, int128 i, uint256 min_amount) external returns(uint256);
}
interface YearnVault {
function withdraw() external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
}
interface TetherToken {
function approve(address _spender, uint256 _value) external;
function balanceOf(address user) external view returns (uint256);
}
interface IWETH is IERC20 {
function transfer(address _to, uint256 _value) external returns (bool success);
function deposit() external payable;
}
contract YVCrvStETHSwapper is ISwapper {
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966);
IWETH public constant WETH = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B);
CurvePool constant public STETH = CurvePool(0xDC24316b9AE028F1497c275EB9192a3Ea0f67022);
YearnVault constant public YVSTETH = YearnVault(0xdCD90C7f6324cfa40d7169ef80b12031770B4325);
TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7);
IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3);
IUniswapV2Pair constant pair = IUniswapV2Pair(0x06da0fd433C1A5d7a4faa01111c044910A184553);
constructor() public {
MIM.approve(address(MIM3POOL), type(uint256).max);
TETHER.approve(address(MIM3POOL), type(uint256).max);
}
// Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// Given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
receive() external payable {}
// Swaps to a flexible amount, from an exact input amount
/// @inheritdoc ISwapper
function swap(
IERC20 fromToken,
IERC20 toToken,
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public override returns (uint256 extraShare, uint256 shareReturned) {
bentoBox.withdraw(fromToken, address(this), address(this), 0, shareFrom);
{
uint256 amountFrom = YVSTETH.withdraw();
STETH.remove_liquidity_one_coin(amountFrom, 0, 0);
}
uint256 amountSecond = address(this).balance;
WETH.deposit{value: amountSecond}();
WETH.transfer(address(pair), amountSecond);
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 amountIntermediate = getAmountOut(amountSecond, reserve0, reserve1);
pair.swap(0, amountIntermediate, address(this), new bytes(0));
uint256 amountTo = MIM3POOL.exchange_underlying(3, 0, amountIntermediate, 0, address(bentoBox));
(, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
// Swaps to an exact amount, from a flexible input amount
/// @inheritdoc ISwapper
function swapExact(
IERC20 fromToken,
IERC20 toToken,
address recipient,
address refundTo,
uint256 shareFromSupplied,
uint256 shareToExact
) public override returns (uint256 shareUsed, uint256 shareReturned) {
return (0,0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol";
import "../../interfaces/ISwapper.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
interface CurvePool {
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
}
interface SushiBar {
function leave(uint256 share) external;
}
interface Sushi is IERC20 {
function transfer(address _to, uint256 _value) external returns (bool success);
}
interface TetherToken {
function approve(address _spender, uint256 _value) external;
}
contract YVXSushiSwapper is ISwapper {
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public immutable bentoBox;
CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B);
TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7);
SushiBar public constant xSushi = SushiBar(0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272);
Sushi public constant SUSHI = Sushi(0x6B3595068778DD592e39A122f4f5a5cF09C90fE2);
IUniswapV2Pair constant SUSHI_WETH = IUniswapV2Pair(0x795065dCc9f64b5614C407a6EFDC400DA6221FB0);
IUniswapV2Pair constant pair = IUniswapV2Pair(0x06da0fd433C1A5d7a4faa01111c044910A184553);
constructor(
IBentoBoxV1 bentoBox_
) public {
bentoBox = bentoBox_;
TETHER.approve(address(MIM3POOL), type(uint256).max);
}
// Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// Given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// Swaps to a flexible amount, from an exact input amount
/// @inheritdoc ISwapper
function swap(
IERC20 fromToken,
IERC20 toToken,
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public override returns (uint256 extraShare, uint256 shareReturned) {
{
(uint256 amountXSushiFrom, ) = bentoBox.withdraw(fromToken, address(this), address(this), 0, shareFrom);
xSushi.leave(amountXSushiFrom);
}
uint256 amountFirst;
{
uint256 amountFrom = SUSHI.balanceOf(address(this));
SUSHI.transfer(address(SUSHI_WETH), amountFrom);
(uint256 reserve0, uint256 reserve1, ) = SUSHI_WETH.getReserves();
amountFirst = getAmountOut(amountFrom, reserve0, reserve1);
}
SUSHI_WETH.swap(0, amountFirst, address(pair), new bytes(0));
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 amountIntermediate = getAmountOut(amountFirst, reserve0, reserve1);
pair.swap(0, amountIntermediate, address(this), new bytes(0));
uint256 amountTo = MIM3POOL.exchange_underlying(3, 0, amountIntermediate, 0, address(bentoBox));
(, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
// Swaps to an exact amount, from a flexible input amount
/// @inheritdoc ISwapper
function swapExact(
IERC20 fromToken,
IERC20 toToken,
address recipient,
address refundTo,
uint256 shareFromSupplied,
uint256 shareToExact
) public override returns (uint256 shareUsed, uint256 shareReturned) {
return (0,0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol";
import "../../interfaces/ISwapper.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
import "../../libraries/UniswapV2Library.sol";
interface IxBOO {
function leave(uint256 share) external;
}
interface IBoo is IERC20 {
function transfer(address _to, uint256 _value) external returns (bool success);
}
interface ICurvePool {
function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
}
contract xBooSwapper is ISwapper {
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0x74A0BcA2eeEdf8883cb91E37e9ff49430f20a616);
IUniswapV2Pair constant USDC_WFTM = IUniswapV2Pair(0x2b4C76d0dc16BE1C31D4C1DC53bF9B45987Fc75c);
IERC20 constant WFTM = IERC20(0x21be370D5312f44cB42ce377BC9b8a0cEF1A4C83);
IERC20 constant USDC = IERC20(0x04068DA6C83AFCFA0e13ba15A6696662335D5B75);
IxBOO constant xBOO = IxBOO(0xa48d959AE2E88f1dAA7D5F611E01908106dE7598);
IBoo constant BOO = IBoo(0x841FAD6EAe12c286d1Fd18d1d525DFfA75C7EFFE);
IUniswapV2Pair constant BOO_FTM = IUniswapV2Pair(0xEc7178F4C41f346b2721907F5cF7628E388A7a58);
IERC20 public constant MIM = IERC20(0x82f0B8B456c1A451378467398982d4834b6829c1);
ICurvePool public constant ThreeCrypto = ICurvePool(0x2dd7C9371965472E5A5fD28fbE165007c61439E1);
constructor() public {
USDC.approve(address(ThreeCrypto), type(uint256).max);
}
// Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// Given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// Swaps to a flexible amount, from an exact input amount
/// @inheritdoc ISwapper
function swap(
IERC20 fromToken,
IERC20 toToken,
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public override returns (uint256 extraShare, uint256 shareReturned) {
{
(uint256 amountXbooFrom,) = bentoBox.withdraw(fromToken, address(this), address(this), 0, shareFrom);
xBOO.leave(amountXbooFrom);
}
uint256 amountFirst;
{
uint256 amountFrom = BOO.balanceOf(address(this));
BOO.transfer(address(BOO_FTM), amountFrom);
(address token0, ) = UniswapV2Library.sortTokens(address(BOO), address(WFTM));
(uint256 reserve0, uint256 reserve1, ) = BOO_FTM.getReserves();
(reserve0, reserve1) = address(BOO) == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountFirst = getAmountOut(amountFrom, reserve0, reserve1);
(uint256 amount0Out, uint256 amount1Out) = address(BOO) == token0
? (uint256(0), amountFirst)
: (amountFirst, uint256(0));
BOO_FTM.swap(amount0Out, amount1Out, address(USDC_WFTM), new bytes(0));
}
uint256 amountIntermediate;
{
(address token0, ) = UniswapV2Library.sortTokens(address(WFTM), address(USDC));
(uint256 reserve0, uint256 reserve1, ) = USDC_WFTM.getReserves();
(reserve0, reserve1) = address(WFTM) == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountIntermediate = getAmountOut(amountFirst, reserve0, reserve1);
(uint256 amount0Out, uint256 amount1Out) = address(WFTM) == token0
? (uint256(0), amountIntermediate)
: (amountIntermediate, uint256(0));
USDC_WFTM.swap(amount0Out, amount1Out, address(this), new bytes(0));
}
uint256 amountTo = ThreeCrypto.exchange(2, 0, amountIntermediate, 0, address(bentoBox));
(, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
// Swaps to an exact amount, from a flexible input amount
/// @inheritdoc ISwapper
function swapExact(
IERC20 fromToken,
IERC20 toToken,
address recipient,
address refundTo,
uint256 shareFromSupplied,
uint256 shareToExact
) public override returns (uint256 shareUsed, uint256 shareReturned) {
return (0,0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol";
import "../../interfaces/ISwapper.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
import "../../libraries/UniswapV2Library.sol";
interface CurvePool {
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
}
interface IWMEMO is IERC20 {
function wrap( uint _amount ) external returns ( uint );
function unwrap( uint _amount ) external returns ( uint );
function transfer(address _to, uint256 _value) external returns (bool success);
}
interface ITIME is IERC20 {
function transfer(address _to, uint256 _value) external returns (bool success);
}
interface IStakingManager {
function unstake( uint _amount, bool _trigger ) external;
function stake( uint _amount, address _recipient ) external returns ( bool );
}
contract wMEMOSwapper is ISwapper {
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xf4F46382C2bE1603Dc817551Ff9A7b333Ed1D18f);
IUniswapV2Pair constant WMEMO_MIM = IUniswapV2Pair(0x4d308C46EA9f234ea515cC51F16fba776451cac8);
IERC20 public constant MIM = IERC20(0x130966628846BFd36ff31a822705796e8cb8C18D);
IERC20 public constant MEMO = IERC20(0x136Acd46C134E8269052c62A67042D6bDeDde3C9);
IWMEMO public constant WMEMO = IWMEMO(0x0da67235dD5787D67955420C84ca1cEcd4E5Bb3b);
IStakingManager public constant STAKING_MANAGER = IStakingManager(0x4456B87Af11e87E329AB7d7C7A246ed1aC2168B9);
ITIME public constant TIME = ITIME(0xb54f16fB19478766A268F172C9480f8da1a7c9C3);
address private constant WAVAX = 0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7;
constructor(
) public {
MEMO.approve(address(STAKING_MANAGER), type(uint256).max);
}
// Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// Given an outpxut amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// Swaps to a flexible amount, from an exact input amount
/// @inheritdoc ISwapper
function swap(
IERC20 fromToken,
IERC20 toToken,
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public override returns (uint256 extraShare, uint256 shareReturned) {
(uint256 amountFrom, ) = bentoBox.withdraw(fromToken, address(this), address(WMEMO_MIM), 0, shareFrom);
(address token0, ) = UniswapV2Library.sortTokens(address(WMEMO), address(WMEMO_MIM));
(uint256 reserve0, uint256 reserve1, ) = WMEMO_MIM.getReserves();
(reserve0, reserve1) = address(WMEMO) == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
uint256 amountTo = getAmountOut(amountFrom, reserve0, reserve1);
(uint256 amount0Out, uint256 amount1Out) = address(WMEMO) == token0
? (uint256(0), amountTo)
: (amountTo, uint256(0));
WMEMO_MIM.swap(amount0Out, amount1Out, address(bentoBox), new bytes(0));
(, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
// Swaps to an exact amount, from a flexible input amount
/// @inheritdoc ISwapper
function swapExact(
IERC20 fromToken,
IERC20 toToken,
address recipient,
address refundTo,
uint256 shareFromSupplied,
uint256 shareToExact
) public override returns (uint256 shareUsed, uint256 shareReturned) {
return (0,0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol";
import "../../interfaces/ISwapper.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
import "../../libraries/UniswapV2Library.sol";
interface CurvePool {
function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
}
contract ICESwapper is ISwapper {
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966);
IERC20 public constant WFTM = IERC20(0x21be370D5312f44cB42ce377BC9b8a0cEF1A4C83);
IUniswapV2Pair public constant ICE_FTM = IUniswapV2Pair(0x84311ECC54D7553378c067282940b0fdfb913675);
IUniswapV2Pair public constant USDC_FTM = IUniswapV2Pair(0x2b4C76d0dc16BE1C31D4C1DC53bF9B45987Fc75c);
IERC20 public constant ICE = IERC20(0xf16e81dce15B08F326220742020379B855B87DF9);
IERC20 public constant USDC = IERC20(0x04068DA6C83AFCFA0e13ba15A6696662335D5B75);
IERC20 public constant MIM = IERC20(0x82f0B8B456c1A451378467398982d4834b6829c1);
CurvePool public constant threePool = CurvePool(0x2dd7C9371965472E5A5fD28fbE165007c61439E1);
uint8 private constant USDC_COIN = 2;
uint8 private constant MIM_COIN = 0;
constructor(
) public {
USDC.approve(address(threePool), type(uint256).max);
}
// Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// Given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// Swaps to a flexible amount, from an exact input amount
/// @inheritdoc ISwapper
function swap(
IERC20 fromToken,
IERC20 toToken,
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public override returns (uint256 extraShare, uint256 shareReturned) {
(uint256 amountFrom, ) = bentoBox.withdraw(ICE, address(this), address(ICE_FTM), 0, shareFrom);
uint256 amountIntermediate;
{
(address token0, ) = UniswapV2Library.sortTokens(address(ICE), address(WFTM));
(uint256 reserve0, uint256 reserve1, ) = ICE_FTM.getReserves();
(reserve0, reserve1) = address(ICE) == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountIntermediate = getAmountOut(amountFrom, reserve0, reserve1);
(uint256 amount0Out, uint256 amount1Out) = address(ICE) == token0
? (uint256(0), amountIntermediate)
: (amountIntermediate, uint256(0));
ICE_FTM.swap(amount0Out, amount1Out, address(USDC_FTM), new bytes(0));
}
uint256 amountIntermediate2;
{
(address token0, ) = UniswapV2Library.sortTokens(address(USDC), address(WFTM));
(uint256 reserve0, uint256 reserve1, ) = USDC_FTM.getReserves();
(reserve0, reserve1) = address(WFTM) == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountIntermediate2 = getAmountOut(amountIntermediate, reserve0, reserve1);
(uint256 amount0Out, uint256 amount1Out) = address(WFTM) == token0
? (uint256(0), amountIntermediate2)
: (amountIntermediate2, uint256(0));
USDC_FTM.swap(amount0Out, amount1Out, address(this), new bytes(0));
}
uint256 amountTo = threePool.exchange(USDC_COIN, MIM_COIN, amountIntermediate2, 0, address(bentoBox));
(, shareReturned) = bentoBox.deposit(MIM, address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
// Swaps to an exact amount, from a flexible input amount
/// @inheritdoc ISwapper
function swapExact(
IERC20 fromToken,
IERC20 toToken,
address recipient,
address refundTo,
uint256 shareFromSupplied,
uint256 shareToExact
) public override returns (uint256 shareUsed, uint256 shareReturned) {
return (0,0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol";
import "../../interfaces/ISwapper.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
import "../../libraries/UniswapV2Library.sol";
interface ICurvePool {
function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
}
contract FTMDegenSwapper is ISwapper {
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0x74A0BcA2eeEdf8883cb91E37e9ff49430f20a616);
IUniswapV2Pair constant USDC_WFTM = IUniswapV2Pair(0x2b4C76d0dc16BE1C31D4C1DC53bF9B45987Fc75c);
IERC20 constant WFTM = IERC20(0x21be370D5312f44cB42ce377BC9b8a0cEF1A4C83);
IERC20 constant USDC = IERC20(0x04068DA6C83AFCFA0e13ba15A6696662335D5B75);
IERC20 public constant MIM = IERC20(0x82f0B8B456c1A451378467398982d4834b6829c1);
ICurvePool public constant ThreeCrypto = ICurvePool(0x2dd7C9371965472E5A5fD28fbE165007c61439E1);
constructor() public {
USDC.approve(address(ThreeCrypto), type(uint256).max);
}
// Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// Given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// Swaps to a flexible amount, from an exact input amount
/// @inheritdoc ISwapper
function swap(
IERC20 fromToken,
IERC20 toToken,
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public override returns (uint256 extraShare, uint256 shareReturned) {
(uint256 amountFrom,) = bentoBox.withdraw(fromToken, address(this), address(USDC_WFTM), 0, shareFrom);
uint256 amountFirst;
{
(address token0, ) = UniswapV2Library.sortTokens(address(WFTM), address(USDC));
(uint256 reserve0, uint256 reserve1, ) = USDC_WFTM.getReserves();
(reserve0, reserve1) = address(WFTM) == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountFirst = getAmountOut(amountFrom, reserve0, reserve1);
(uint256 amount0Out, uint256 amount1Out) = address(WFTM) == token0
? (uint256(0), amountFirst)
: (amountFirst, uint256(0));
USDC_WFTM.swap(amount0Out, amount1Out, address(this), new bytes(0));
}
uint256 amountTo = ThreeCrypto.exchange(2, 0, amountFirst, 0, address(bentoBox));
(, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
// Swaps to an exact amount, from a flexible input amount
/// @inheritdoc ISwapper
function swapExact(
IERC20 fromToken,
IERC20 toToken,
address recipient,
address refundTo,
uint256 shareFromSupplied,
uint256 shareToExact
) public override returns (uint256 shareUsed, uint256 shareReturned) {
return (0,0);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol";
import "../../interfaces/ISwapper.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
import "../../libraries/UniswapV2Library.sol";
contract ArbEthSwapper is ISwapper {
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0x74c764D41B77DBbb4fe771daB1939B00b146894A);
IUniswapV2Pair constant pair = IUniswapV2Pair(0xb6DD51D5425861C808Fd60827Ab6CFBfFE604959);
IERC20 constant WETH = IERC20(0x82aF49447D8a07e3bd95BD0d56f35241523fBab1);
IERC20 public constant MIM = IERC20(0xFEa7a6a0B346362BF88A9e4A88416B77a57D6c2A);
// Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// Given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// Swaps to a flexible amount, from an exact input amount
/// @inheritdoc ISwapper
function swap(
IERC20 fromToken,
IERC20 toToken,
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public override returns (uint256 extraShare, uint256 shareReturned) {
(uint256 amountFrom,) = bentoBox.withdraw(fromToken, address(this), address(pair), 0, shareFrom);
(address token0, ) = UniswapV2Library.sortTokens(address(MIM), address(WETH));
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
(reserve0, reserve1) = address(WETH) == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
uint256 amountTo = getAmountOut(amountFrom, reserve0, reserve1);
(uint256 amount0Out, uint256 amount1Out) = address(WETH) == token0
? (uint256(0), amountTo)
: (amountTo, uint256(0));
pair.swap(amount0Out, amount1Out, address(bentoBox), new bytes(0));
(, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
// Swaps to an exact amount, from a flexible input amount
/// @inheritdoc ISwapper
function swapExact(
IERC20 fromToken,
IERC20 toToken,
address recipient,
address refundTo,
uint256 shareFromSupplied,
uint256 shareToExact
) public override returns (uint256 shareUsed, uint256 shareReturned) {
return (0,0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
import "../../libraries/UniswapV2Library.sol";
interface ICurvePool {
function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
}
interface IxBOO is IERC20 {
function leave(uint256 share) external;
function enter(uint256 amount) external;
function transfer(address _to, uint256 _value) external returns (bool success);
}
contract xBooLevSwapper {
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0x74A0BcA2eeEdf8883cb91E37e9ff49430f20a616);
IUniswapV2Pair constant USDC_WFTM = IUniswapV2Pair(0x2b4C76d0dc16BE1C31D4C1DC53bF9B45987Fc75c);
IERC20 constant WFTM = IERC20(0x21be370D5312f44cB42ce377BC9b8a0cEF1A4C83);
IERC20 constant USDC = IERC20(0x04068DA6C83AFCFA0e13ba15A6696662335D5B75);
IxBOO constant xBOO = IxBOO(0xa48d959AE2E88f1dAA7D5F611E01908106dE7598);
IERC20 constant BOO = IERC20(0x841FAD6EAe12c286d1Fd18d1d525DFfA75C7EFFE);
IUniswapV2Pair constant BOO_FTM = IUniswapV2Pair(0xEc7178F4C41f346b2721907F5cF7628E388A7a58);
IERC20 public constant MIM = IERC20(0x82f0B8B456c1A451378467398982d4834b6829c1);
ICurvePool public constant ThreeCrypto = ICurvePool(0x2dd7C9371965472E5A5fD28fbE165007c61439E1);
constructor() public {
MIM.approve(address(ThreeCrypto), type(uint256).max);
BOO.approve(address(xBOO), type(uint256).max);
}
// Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// Given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// Swaps to a flexible amount, from an exact input amount
function swap(
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public returns (uint256 extraShare, uint256 shareReturned) {
(uint256 amountFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom);
uint256 amountIntermediate;
{
uint256 amountFirst = ThreeCrypto.exchange(0, 2, amountFrom, 0, address(USDC_WFTM));
(address token0, ) = UniswapV2Library.sortTokens(address(USDC), address(WFTM));
(uint256 reserve0, uint256 reserve1, ) = USDC_WFTM.getReserves();
(reserve0, reserve1) = address(USDC) == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountIntermediate = getAmountOut(amountFirst, reserve0, reserve1);
(uint256 amount0Out, uint256 amount1Out) = address(USDC) == token0
? (uint256(0), amountIntermediate)
: (amountIntermediate, uint256(0));
USDC_WFTM.swap(amount0Out, amount1Out, address(BOO_FTM), new bytes(0));
}
uint256 amountIntermediate2;
{
(address token0, ) = UniswapV2Library.sortTokens(address(BOO), address(WFTM));
(uint256 reserve0, uint256 reserve1, ) = BOO_FTM.getReserves();
(reserve0, reserve1) = address(WFTM) == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountIntermediate2 = getAmountOut(amountIntermediate, reserve0, reserve1);
(uint256 amount0Out, uint256 amount1Out) = address(WFTM) == token0
? (uint256(0), amountIntermediate2)
: (amountIntermediate2, uint256(0));
BOO_FTM.swap(amount0Out, amount1Out, address(this), new bytes(0));
}
xBOO.enter(amountIntermediate2);
uint256 amountTo = xBOO.balanceOf(address(this));
xBOO.transfer(address(bentoBox), amountTo);
(, shareReturned) = bentoBox.deposit(xBOO, address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
import "../../libraries/UniswapV2Library.sol";
interface IWMEMO is IERC20 {
function wrap( uint _amount ) external returns ( uint );
function unwrap( uint _amount ) external returns ( uint );
function transfer(address _to, uint256 _value) external returns (bool success);
}
interface IStakingManager {
function unstake( uint _amount, bool _trigger ) external;
function stake( uint _amount, address _recipient ) external returns ( bool );
function claim ( address _recipient ) external;
}
contract wMEMOLevSwapper {
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xf4F46382C2bE1603Dc817551Ff9A7b333Ed1D18f);
IUniswapV2Pair constant WMEMO_MIM = IUniswapV2Pair(0x4d308C46EA9f234ea515cC51F16fba776451cac8);
IERC20 public constant MIM = IERC20(0x130966628846BFd36ff31a822705796e8cb8C18D);
IERC20 public constant MEMO = IERC20(0x136Acd46C134E8269052c62A67042D6bDeDde3C9);
IWMEMO public constant WMEMO = IWMEMO(0x0da67235dD5787D67955420C84ca1cEcd4E5Bb3b);
IStakingManager public constant STAKING_MANAGER = IStakingManager(0x4456B87Af11e87E329AB7d7C7A246ed1aC2168B9);
IERC20 public constant TIME = IERC20(0xb54f16fB19478766A268F172C9480f8da1a7c9C3);
address private constant WAVAX = 0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7;
constructor(
) public {
TIME.approve(address(STAKING_MANAGER), type(uint256).max);
MEMO.approve(address(WMEMO), type(uint256).max);
}
// Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// Given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// Swaps to a flexible amount, from an exact input amount
function swap(
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public returns (uint256 extraShare, uint256 shareReturned) {
(uint256 amountMIMFrom, ) = bentoBox.withdraw(MIM, address(this), address(WMEMO_MIM), 0, shareFrom);
(address token0, ) = UniswapV2Library.sortTokens(address(WMEMO), address(MIM));
(uint256 reserve0, uint256 reserve1, ) = WMEMO_MIM.getReserves();
(reserve0, reserve1) = address(MIM) == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
uint256 amountTo = getAmountOut(amountMIMFrom, reserve0, reserve1);
(uint256 amount0Out, uint256 amount1Out) = address(MIM) == token0
? (uint256(0), amountTo)
: (amountTo, uint256(0));
WMEMO_MIM.swap(amount0Out, amount1Out, address(bentoBox), new bytes(0));
(, shareReturned) = bentoBox.deposit(WMEMO, address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol";
import "../../interfaces/ISwapper.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
import "../../libraries/UniswapV2Library.sol";
interface CurvePool {
function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
}
contract ICELevSwapper {
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966);
IERC20 public constant WFTM = IERC20(0x21be370D5312f44cB42ce377BC9b8a0cEF1A4C83);
IUniswapV2Pair public constant ICE_FTM = IUniswapV2Pair(0x84311ECC54D7553378c067282940b0fdfb913675);
IUniswapV2Pair public constant USDC_FTM = IUniswapV2Pair(0x2b4C76d0dc16BE1C31D4C1DC53bF9B45987Fc75c);
IERC20 public constant ICE = IERC20(0xf16e81dce15B08F326220742020379B855B87DF9);
IERC20 public constant USDC = IERC20(0x04068DA6C83AFCFA0e13ba15A6696662335D5B75);
IERC20 public constant MIM = IERC20(0x82f0B8B456c1A451378467398982d4834b6829c1);
CurvePool public constant threePool = CurvePool(0x2dd7C9371965472E5A5fD28fbE165007c61439E1);
uint8 private constant USDC_COIN = 2;
uint8 private constant MIM_COIN = 0;
constructor(
) public {
MIM.approve(address(threePool), type(uint256).max);
}
// Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// Given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// Swaps to a flexible amount, from an exact input amount
function swap(
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public returns (uint256 extraShare, uint256 shareReturned) {
(uint256 amountFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom);
uint256 amountIntermediate = threePool.exchange(MIM_COIN, USDC_COIN, amountFrom, 0, address(USDC_FTM));
uint256 amountIntermediate2;
{
(address token0, ) = UniswapV2Library.sortTokens(address(USDC), address(WFTM));
(uint256 reserve0, uint256 reserve1, ) = USDC_FTM.getReserves();
(reserve0, reserve1) = address(USDC) == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountIntermediate2 = getAmountOut(amountIntermediate, reserve0, reserve1);
(uint256 amount0Out, uint256 amount1Out) = address(USDC) == token0
? (uint256(0), amountIntermediate2)
: (amountIntermediate2, uint256(0));
USDC_FTM.swap(amount0Out, amount1Out, address(ICE_FTM), new bytes(0));
}
uint256 amountTo;
{
(address token0, ) = UniswapV2Library.sortTokens(address(ICE), address(WFTM));
(uint256 reserve0, uint256 reserve1, ) = ICE_FTM.getReserves();
(reserve0, reserve1) = address(WFTM) == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountTo = getAmountOut(amountIntermediate2, reserve0, reserve1);
(uint256 amount0Out, uint256 amount1Out) = address(WFTM) == token0
? (uint256(0), amountTo)
: (amountTo, uint256(0));
ICE_FTM.swap(amount0Out, amount1Out, address(bentoBox), new bytes(0));
}
(, shareReturned) = bentoBox.deposit(ICE, address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
import "../../libraries/UniswapV2Library.sol";
interface ICurvePool {
function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
}
contract FTMLevDegenSwapper {
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0x74A0BcA2eeEdf8883cb91E37e9ff49430f20a616);
IUniswapV2Pair constant USDC_WFTM = IUniswapV2Pair(0x2b4C76d0dc16BE1C31D4C1DC53bF9B45987Fc75c);
IERC20 constant WFTM = IERC20(0x21be370D5312f44cB42ce377BC9b8a0cEF1A4C83);
IERC20 constant USDC = IERC20(0x04068DA6C83AFCFA0e13ba15A6696662335D5B75);
IERC20 public constant MIM = IERC20(0x82f0B8B456c1A451378467398982d4834b6829c1);
ICurvePool public constant ThreeCrypto = ICurvePool(0x2dd7C9371965472E5A5fD28fbE165007c61439E1);
constructor() public {
MIM.approve(address(ThreeCrypto), type(uint256).max);
}
// Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// Given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// Swaps to a flexible amount, from an exact input amount
function swap(
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public returns (uint256 extraShare, uint256 shareReturned) {
uint256 amountFirst;
{
(uint256 amountFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom);
amountFirst = ThreeCrypto.exchange(0, 2, amountFrom, 0, address(USDC_WFTM));
}
uint256 amountTo;
{
(address token0, ) = UniswapV2Library.sortTokens(address(USDC), address(WFTM));
(uint256 reserve0, uint256 reserve1, ) = USDC_WFTM.getReserves();
(reserve0, reserve1) = address(USDC) == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountTo = getAmountOut(amountFirst, reserve0, reserve1);
(uint256 amount0Out, uint256 amount1Out) = address(USDC) == token0
? (uint256(0), amountTo)
: (amountTo, uint256(0));
USDC_WFTM.swap(amount0Out, amount1Out, address(bentoBox), new bytes(0));
}
(, shareReturned) = bentoBox.deposit(WFTM, address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
import "../../libraries/UniswapV2Library.sol";
contract ArbEthLevSwapper {
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0x74c764D41B77DBbb4fe771daB1939B00b146894A);
IUniswapV2Pair constant pair = IUniswapV2Pair(0xb6DD51D5425861C808Fd60827Ab6CFBfFE604959);
IERC20 constant WETH = IERC20(0x82aF49447D8a07e3bd95BD0d56f35241523fBab1);
IERC20 public constant MIM = IERC20(0xFEa7a6a0B346362BF88A9e4A88416B77a57D6c2A);
// Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// Given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// Swaps to a flexible amount, from an exact input amount
function swap(
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public returns (uint256 extraShare, uint256 shareReturned) {
(uint256 amountFrom, ) = bentoBox.withdraw(MIM, address(this), address(pair), 0, shareFrom);
(address token0, ) = UniswapV2Library.sortTokens(address(MIM), address(WETH));
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
(reserve0, reserve1) = address(MIM) == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
uint256 amountTo = getAmountOut(amountFrom, reserve0, reserve1);
(uint256 amount0Out, uint256 amount1Out) = address(MIM) == token0
? (uint256(0), amountTo)
: (amountTo, uint256(0));
pair.swap(amount0Out, amount1Out, address(bentoBox), new bytes(0));
(, shareReturned) = bentoBox.deposit(WETH, address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity =0.6.12;
import './libraries/SafeMath.sol';
contract UniswapV2ERC20 {
using SafeMathUniswap for uint;
string public constant name = 'SushiSwap LP Token';
string public constant symbol = 'SLP';
uint8 public constant decimals = 18;
uint public totalSupply;
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public nonces;
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
constructor() public {
uint chainId;
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
function _mint(address to, uint value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external returns (bool) {
if (allowance[from][msg.sender] != uint(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
require(deadline >= block.timestamp, 'UniswapV2: EXPIRED');
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE');
_approve(owner, spender, value);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity =0.6.12;
import './UniswapV2ERC20.sol';
import './libraries/Math.sol';
import './libraries/UQ112x112.sol';
import './interfaces/IERC20.sol';
import './interfaces/IUniswapV2Factory.sol';
import './interfaces/IUniswapV2Callee.sol';
interface IMigrator {
// Return the desired amount of liquidity token that the migrator wants.
function desiredLiquidity() external view returns (uint256);
}
contract UniswapV2Pair is UniswapV2ERC20 {
using SafeMathUniswap for uint;
using UQ112x112 for uint224;
uint public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'UniswapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED');
}
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);
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
// update reserves and, on the first call per block, price accumulators
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IUniswapV2Factory(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(5).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20Uniswap(token0).balanceOf(address(this));
uint balance1 = IERC20Uniswap(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
address migrator = IUniswapV2Factory(factory).migrator();
if (msg.sender == migrator) {
liquidity = IMigrator(migrator).desiredLiquidity();
require(liquidity > 0 && liquidity != uint256(-1), "Bad desired liquidity");
} else {
require(migrator == address(0), "Must not have migrator");
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
}
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20Uniswap(_token0).balanceOf(address(this));
uint balance1 = IERC20Uniswap(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20Uniswap(_token0).balanceOf(address(this));
balance1 = IERC20Uniswap(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20Uniswap(_token0).balanceOf(address(this));
balance1 = IERC20Uniswap(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20Uniswap(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20Uniswap(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(IERC20Uniswap(token0).balanceOf(address(this)), IERC20Uniswap(token1).balanceOf(address(this)), reserve0, reserve1);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity =0.6.12;
// a library for performing various math operations
library Math {
function min(uint x, uint y) internal pure returns (uint z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity =0.6.12;
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
library UQ112x112 {
uint224 constant Q112 = 2**112;
// encode a uint112 as a UQ112x112
function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x / uint224(y);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IERC20Uniswap {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
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 (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);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IUniswapV2Callee {
function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@sushiswap/core/contracts/uniswapv2/UniswapV2Pair.sol";
contract SushiSwapPairMock is UniswapV2Pair {
constructor() public UniswapV2Pair() {
return;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity =0.6.12;
import './interfaces/IUniswapV2Factory.sol';
import './UniswapV2Pair.sol';
contract UniswapV2Factory is IUniswapV2Factory {
address public override feeTo;
address public override feeToSetter;
address public override migrator;
mapping(address => mapping(address => address)) public override getPair;
address[] public override allPairs;
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
constructor(address _feeToSetter) public {
feeToSetter = _feeToSetter;
}
function allPairsLength() external override view returns (uint) {
return allPairs.length;
}
function pairCodeHash() external pure returns (bytes32) {
return keccak256(type(UniswapV2Pair).creationCode);
}
function createPair(address tokenA, address tokenB) external override returns (address pair) {
require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES');
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS');
require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient
bytes memory bytecode = type(UniswapV2Pair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1));
assembly {
pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
UniswapV2Pair(pair).initialize(token0, token1);
getPair[token0][token1] = pair;
getPair[token1][token0] = pair; // populate mapping in the reverse direction
allPairs.push(pair);
emit PairCreated(token0, token1, pair, allPairs.length);
}
function setFeeTo(address _feeTo) external override {
require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');
feeTo = _feeTo;
}
function setMigrator(address _migrator) external override {
require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');
migrator = _migrator;
}
function setFeeToSetter(address _feeToSetter) external override {
require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');
feeToSetter = _feeToSetter;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol";
import "@sushiswap/core/contracts/uniswapv2/UniswapV2Factory.sol";
contract SushiSwapFactoryMock is UniswapV2Factory {
constructor() public UniswapV2Factory(msg.sender) {
return;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol";
import "../../interfaces/ISwapper.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
interface CurvePool {
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
}
interface IWOHM {
function wrap( uint _amount ) external returns ( uint );
function unwrap( uint _amount ) external returns ( uint );
}
interface IOHM is IERC20 {
function transfer(address _to, uint256 _value) external returns (bool success);
}
interface IStakingManager {
function unstake( uint _amount, bool _trigger ) external;
function stake( uint _amount, address _recipient ) external returns ( bool );
}
contract wOHMSwapper is ISwapper {
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966);
CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B);
IERC20 public constant DAI = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F);
IUniswapV2Pair constant OHM_DAI = IUniswapV2Pair(0x34d7d7Aaf50AD4944B70B320aCB24C95fa2def7c);
IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3);
IERC20 public constant SOHM = IERC20(0x04F2694C8fcee23e8Fd0dfEA1d4f5Bb8c352111F);
IWOHM public constant WOHM = IWOHM(0xCa76543Cf381ebBB277bE79574059e32108e3E65);
IStakingManager public constant STAKING_MANAGER = IStakingManager(0xFd31c7d00Ca47653c6Ce64Af53c1571f9C36566a);
IOHM public constant OHM = IOHM(0x383518188C0C6d7730D91b2c03a03C837814a899);
constructor(
) public {
DAI.approve(address(MIM3POOL), type(uint256).max);
SOHM.approve(address(STAKING_MANAGER), type(uint256).max);
}
// Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// Given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// Swaps to a flexible amount, from an exact input amount
/// @inheritdoc ISwapper
function swap(
IERC20 fromToken,
IERC20 toToken,
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public override returns (uint256 extraShare, uint256 shareReturned) {
uint256 amountFirst;
{
(uint256 amountFrom, ) = bentoBox.withdraw(fromToken, address(this), address(this), 0, shareFrom);
amountFirst = WOHM.unwrap(amountFrom);
}
STAKING_MANAGER.unstake(amountFirst, false);
OHM.transfer(address(OHM_DAI), amountFirst);
(uint256 reserve0, uint256 reserve1, ) = OHM_DAI.getReserves();
uint256 amountDAI = getAmountOut(amountFirst, reserve0, reserve1);
OHM_DAI.swap(0, amountDAI, address(this), new bytes(0));
uint256 amountTo = MIM3POOL.exchange_underlying(1, 0, amountDAI, 0, address(bentoBox));
(, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
// Swaps to an exact amount, from a flexible input amount
/// @inheritdoc ISwapper
function swapExact(
IERC20 fromToken,
IERC20 toToken,
address recipient,
address refundTo,
uint256 shareFromSupplied,
uint256 shareToExact
) public override returns (uint256 shareUsed, uint256 shareReturned) {
return (0,0);
}
}
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "../../interfaces/ISwapper.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
interface CurvePool {
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
function approve(address _spender, uint256 _value) external returns (bool);
function remove_liquidity_one_coin(uint256 tokenAmount, int128 i, uint256 min_amount) external;
}
interface IThreeCrypto is CurvePool {
function exchange(uint256 i, uint256 j, uint256 dx, uint256 min_dy) external;
}
interface YearnVault {
function withdraw() external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
}
interface TetherToken {
function approve(address _spender, uint256 _value) external;
function balanceOf(address user) external view returns (uint256);
}
interface IConvex is IERC20{
function withdrawAndUnwrap(uint256 _amount) external;
}
contract WethSwapper is ISwapper {
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public constant degenBox = IBentoBoxV1(0xd96f48665a1410C0cd669A88898ecA36B9Fc2cce);
CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B);
IThreeCrypto constant public threecrypto = IThreeCrypto(0xD51a44d3FaE010294C616388b506AcdA1bfAAE46);
TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7);
IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3);
IERC20 public constant WETH = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
constructor() public {
MIM.approve(address(MIM3POOL), type(uint256).max);
TETHER.approve(address(MIM3POOL), type(uint256).max);
WETH.approve(address(threecrypto), type(uint256).max);
}
// Swaps to a flexible amount, from an exact input amount
/// @inheritdoc ISwapper
function swap(
IERC20 fromToken,
IERC20 toToken,
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public override returns (uint256 extraShare, uint256 shareReturned) {
(uint256 amountFrom, ) = degenBox.withdraw(fromToken, address(this), address(this), 0, shareFrom);
threecrypto.exchange(2, 0, amountFrom, 0);
uint256 amountIntermediate = TETHER.balanceOf(address(this));
uint256 amountTo = MIM3POOL.exchange_underlying(3, 0, amountIntermediate, 0, address(degenBox));
(, shareReturned) = degenBox.deposit(toToken, address(degenBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
// Swaps to an exact amount, from a flexible input amount
/// @inheritdoc ISwapper
function swapExact(
IERC20 fromToken,
IERC20 toToken,
address recipient,
address refundTo,
uint256 shareFromSupplied,
uint256 shareToExact
) public override returns (uint256 shareUsed, uint256 shareReturned) {
return (0,0);
}
}
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "../../interfaces/ISwapper.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
interface CurvePool {
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
function approve(address _spender, uint256 _value) external returns (bool);
function remove_liquidity_one_coin(uint256 tokenAmount, int128 i, uint256 min_amount) external;
}
interface IThreeCrypto is CurvePool {
function exchange(uint256 i, uint256 j, uint256 dx, uint256 min_dy) external;
}
interface YearnVault {
function withdraw() external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
}
interface TetherToken {
function approve(address _spender, uint256 _value) external;
function balanceOf(address user) external view returns (uint256);
}
interface IConvex is IERC20{
function withdrawAndUnwrap(uint256 _amount) external;
}
contract WbtcSwapper is ISwapper {
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public constant degenBox = IBentoBoxV1(0xd96f48665a1410C0cd669A88898ecA36B9Fc2cce);
CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B);
IThreeCrypto constant public threecrypto = IThreeCrypto(0xD51a44d3FaE010294C616388b506AcdA1bfAAE46);
TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7);
IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3);
IERC20 public constant WBTC = IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599);
constructor() public {
MIM.approve(address(MIM3POOL), type(uint256).max);
TETHER.approve(address(MIM3POOL), type(uint256).max);
WBTC.approve(address(threecrypto), type(uint256).max);
}
// Swaps to a flexible amount, from an exact input amount
/// @inheritdoc ISwapper
function swap(
IERC20 fromToken,
IERC20 toToken,
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public override returns (uint256 extraShare, uint256 shareReturned) {
(uint256 amountFrom, ) = degenBox.withdraw(fromToken, address(this), address(this), 0, shareFrom);
threecrypto.exchange(1, 0, amountFrom, 0);
uint256 amountIntermediate = TETHER.balanceOf(address(this));
uint256 amountTo = MIM3POOL.exchange_underlying(3, 0, amountIntermediate, 0, address(degenBox));
(, shareReturned) = degenBox.deposit(toToken, address(degenBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
// Swaps to an exact amount, from a flexible input amount
/// @inheritdoc ISwapper
function swapExact(
IERC20 fromToken,
IERC20 toToken,
address recipient,
address refundTo,
uint256 shareFromSupplied,
uint256 shareToExact
) public override returns (uint256 shareUsed, uint256 shareReturned) {
return (0,0);
}
}
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "../../interfaces/ISwapper.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
interface CurvePool {
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
function approve(address _spender, uint256 _value) external returns (bool);
function remove_liquidity_one_coin(uint256 tokenAmount, uint256 i, uint256 min_amount) external;
}
interface YearnVault {
function withdraw() external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
}
interface TetherToken {
function approve(address _spender, uint256 _value) external;
function balanceOf(address user) external view returns (uint256);
}
interface IConvex is IERC20{
function withdrawAndUnwrap(uint256 _amount) external;
}
contract ThreeCryptoSwapper is ISwapper {
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966);
CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B);
CurvePool constant public threecrypto = CurvePool(0xD51a44d3FaE010294C616388b506AcdA1bfAAE46);
IConvex public constant cvx3Crypto = IConvex(0x5958A8DB7dfE0CC49382209069b00F54e17929C2);
TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7);
IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3);
constructor() public {
MIM.approve(address(MIM3POOL), type(uint256).max);
TETHER.approve(address(MIM3POOL), type(uint256).max);
}
// Swaps to a flexible amount, from an exact input amount
/// @inheritdoc ISwapper
function swap(
IERC20 fromToken,
IERC20 toToken,
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public override returns (uint256 extraShare, uint256 shareReturned) {
(uint256 amountFrom, ) = bentoBox.withdraw(fromToken, address(this), address(this), 0, shareFrom);
cvx3Crypto.withdrawAndUnwrap(amountFrom);
threecrypto.remove_liquidity_one_coin(amountFrom, 0, 0);
uint256 amountIntermediate = TETHER.balanceOf(address(this));
uint256 amountTo = MIM3POOL.exchange_underlying(3, 0, amountIntermediate, 0, address(bentoBox));
(, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
// Swaps to an exact amount, from a flexible input amount
/// @inheritdoc ISwapper
function swapExact(
IERC20 fromToken,
IERC20 toToken,
address recipient,
address refundTo,
uint256 shareFromSupplied,
uint256 shareToExact
) public override returns (uint256 shareUsed, uint256 shareReturned) {
return (0,0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
import "../../interfaces/ISwapper.sol";
interface CurvePool {
function exchange_underlying(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy,
address receiver
) external returns (uint256);
function approve(address _spender, uint256 _value) external returns (bool);
function remove_liquidity_one_coin(
address pool,
uint256 tokenAmount,
int128 i,
uint256 min_amount
) external returns (uint256);
}
interface YearnVault {
function withdraw() external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
}
interface TetherToken {
function approve(address _spender, uint256 _value) external;
function balanceOf(address user) external view returns (uint256);
}
interface IConvex is IERC20 {
function withdrawAndUnwrap(uint256 _amount) external;
}
contract StkFrax3CrvSwapper is ISwapper {
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966);
CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B);
address public constant FRAX3CRVPOOL = 0xd632f22692FaC7611d2AA1C0D552930D43CAEd3B;
CurvePool public constant threePool = CurvePool(0xA79828DF1850E8a3A3064576f380D90aECDD3359);
IConvex public immutable stkFrax3Crv;
TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7);
IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3);
IERC20 public constant FRAX3CRV = IERC20(0xd632f22692FaC7611d2AA1C0D552930D43CAEd3B);
constructor(IConvex _stkFrax3Crv) public {
stkFrax3Crv = _stkFrax3Crv;
MIM.approve(address(MIM3POOL), type(uint256).max);
TETHER.approve(address(MIM3POOL), type(uint256).max);
FRAX3CRV.approve(address(threePool), type(uint256).max);
}
// Swaps to a flexible amount, from an exact input amount
/// @inheritdoc ISwapper
function swap(
IERC20,
IERC20,
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public override returns (uint256 extraShare, uint256 shareReturned) {
(uint256 amountFrom, ) = bentoBox.withdraw(IERC20(stkFrax3Crv), address(this), address(this), 0, shareFrom);
stkFrax3Crv.withdrawAndUnwrap(amountFrom);
// Pool token order is FRAX, DAI, USDC, USDT
uint256 amountUSDT = threePool.remove_liquidity_one_coin(FRAX3CRVPOOL, amountFrom, 3, 0);
uint256 amountTo = MIM3POOL.exchange_underlying(3, 0, amountUSDT, 0, address(bentoBox));
(, shareReturned) = bentoBox.deposit(MIM, address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
// Swaps to an exact amount, from a flexible input amount
/// @inheritdoc ISwapper
function swapExact(
IERC20,
IERC20,
address,
address,
uint256,
uint256
) public override returns (uint256 shareUsed, uint256 shareReturned) {
return (0, 0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol";
import "../../interfaces/ISwapper.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
interface CurvePool {
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
}
interface IsSpell {
function burn(address to, uint256 shares) external returns (bool);
}
interface ISpell is IERC20 {
function transfer(address _to, uint256 _value) external returns (bool success);
}
interface TetherToken {
function approve(address _spender, uint256 _value) external;
}
contract SSpellSwapper is ISwapper {
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966);
CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B);
TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7);
IsSpell public constant sSpell = IsSpell(0x26FA3fFFB6EfE8c1E69103aCb4044C26B9A106a9);
ISpell public constant SPELL = ISpell(0x090185f2135308BaD17527004364eBcC2D37e5F6);
IUniswapV2Pair constant SPELL_ETH = IUniswapV2Pair(0xb5De0C3753b6E1B4dBA616Db82767F17513E6d4E);
IUniswapV2Pair constant pair = IUniswapV2Pair(0x06da0fd433C1A5d7a4faa01111c044910A184553);
constructor(
) public {
TETHER.approve(address(MIM3POOL), type(uint256).max);
}
// Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// Given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// Swaps to a flexible amount, from an exact input amount
/// @inheritdoc ISwapper
function swap(
IERC20 fromToken,
IERC20 toToken,
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public override returns (uint256 extraShare, uint256 shareReturned) {
{
(uint256 amountSSpellFrom, ) = bentoBox.withdraw(fromToken, address(this), address(this), 0, shareFrom);
sSpell.burn(address(this), amountSSpellFrom);
}
uint256 amountFirst;
{
uint256 amountFrom = SPELL.balanceOf(address(this));
SPELL.transfer(address(SPELL_ETH), amountFrom);
(uint256 reserve0, uint256 reserve1, ) = SPELL_ETH.getReserves();
amountFirst = getAmountOut(amountFrom, reserve0, reserve1);
}
SPELL_ETH.swap(0, amountFirst, address(pair), new bytes(0));
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 amountIntermediate = getAmountOut(amountFirst, reserve0, reserve1);
pair.swap(0, amountIntermediate, address(this), new bytes(0));
uint256 amountTo = MIM3POOL.exchange_underlying(3, 0, amountIntermediate, 0, address(bentoBox));
(, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
// Swaps to an exact amount, from a flexible input amount
/// @inheritdoc ISwapper
function swapExact(
IERC20 fromToken,
IERC20 toToken,
address recipient,
address refundTo,
uint256 shareFromSupplied,
uint256 shareToExact
) public override returns (uint256 shareUsed, uint256 shareReturned) {
return (0,0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol";
import "../../interfaces/ISwapper.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
interface CurvePool {
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
}
interface IsSpell {
function burn(address to, uint256 shares) external returns (bool);
}
interface ISpell is IERC20 {
function transfer(address _to, uint256 _value) external returns (bool success);
}
interface TetherToken {
function approve(address _spender, uint256 _value) external;
}
contract SpellSuperSwapper is ISwapper {
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xd96f48665a1410C0cd669A88898ecA36B9Fc2cce);
CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B);
TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7);
IsSpell public constant sSpell = IsSpell(0x26FA3fFFB6EfE8c1E69103aCb4044C26B9A106a9);
ISpell public constant SPELL = ISpell(0x090185f2135308BaD17527004364eBcC2D37e5F6);
IUniswapV2Pair constant SPELL_ETH = IUniswapV2Pair(0xb5De0C3753b6E1B4dBA616Db82767F17513E6d4E);
IUniswapV2Pair constant pair = IUniswapV2Pair(0x06da0fd433C1A5d7a4faa01111c044910A184553);
constructor(
) public {
TETHER.approve(address(MIM3POOL), type(uint256).max);
}
// Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// Given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// Swaps to a flexible amount, from an exact input amount
/// @inheritdoc ISwapper
function swap(
IERC20 fromToken,
IERC20 toToken,
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public override returns (uint256 extraShare, uint256 shareReturned) {
(uint256 amountFrom, ) = bentoBox.withdraw(fromToken, address(this), address(SPELL_ETH), 0, shareFrom);
uint256 amountFirst;
{
(uint256 reserve0, uint256 reserve1, ) = SPELL_ETH.getReserves();
amountFirst = getAmountOut(amountFrom, reserve0, reserve1);
}
SPELL_ETH.swap(0, amountFirst, address(pair), new bytes(0));
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 amountIntermediate = getAmountOut(amountFirst, reserve0, reserve1);
pair.swap(0, amountIntermediate, address(this), new bytes(0));
uint256 amountTo = MIM3POOL.exchange_underlying(3, 0, amountIntermediate, 0, address(bentoBox));
(, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
// Swaps to an exact amount, from a flexible input amount
/// @inheritdoc ISwapper
function swapExact(
IERC20 fromToken,
IERC20 toToken,
address recipient,
address refundTo,
uint256 shareFromSupplied,
uint256 shareToExact
) public override returns (uint256 shareUsed, uint256 shareReturned) {
return (0,0);
}
}
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "../../interfaces/ISwapper.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
interface CurvePool {
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
function approve(address _spender, uint256 _value) external returns (bool);
function remove_liquidity_one_coin(uint256 tokenAmount, int128 i, uint256 min_amount) external;
}
interface IThreeCrypto is CurvePool {
function exchange(uint256 i, uint256 j, uint256 dx, uint256 min_dy) external;
}
interface YearnVault {
function withdraw() external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
}
interface TetherToken {
function approve(address _spender, uint256 _value) external;
function balanceOf(address user) external view returns (uint256);
}
interface IConvex is IERC20{
function withdrawAndUnwrap(uint256 _amount) external;
}
contract RenCrvSwapper is ISwapper {
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966);
CurvePool constant public renCrv = CurvePool(0x93054188d876f558f4a66B2EF1d97d16eDf0895B);
CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B);
IThreeCrypto constant public threecrypto = IThreeCrypto(0xD51a44d3FaE010294C616388b506AcdA1bfAAE46);
IConvex public constant cvxRen = IConvex(0xB65eDE134521F0EFD4E943c835F450137dC6E83e);
TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7);
IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3);
IERC20 public constant CurveToken = IERC20(0x49849C98ae39Fff122806C06791Fa73784FB3675);
IERC20 public constant WBTC = IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599);
constructor() public {
MIM.approve(address(MIM3POOL), type(uint256).max);
TETHER.approve(address(MIM3POOL), type(uint256).max);
WBTC.approve(address(threecrypto), type(uint256).max);
}
// Swaps to a flexible amount, from an exact input amount
/// @inheritdoc ISwapper
function swap(
IERC20 fromToken,
IERC20 toToken,
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public override returns (uint256 extraShare, uint256 shareReturned) {
(uint256 amountFrom, ) = bentoBox.withdraw(fromToken, address(this), address(this), 0, shareFrom);
cvxRen.withdrawAndUnwrap(amountFrom);
renCrv.remove_liquidity_one_coin(amountFrom, 1, 0);
uint256 amountOne = WBTC.balanceOf(address(this));
threecrypto.exchange(1, 0, amountOne, 0);
uint256 amountIntermediate = TETHER.balanceOf(address(this));
uint256 amountTo = MIM3POOL.exchange_underlying(3, 0, amountIntermediate, 0, address(bentoBox));
(, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
// Swaps to an exact amount, from a flexible input amount
/// @inheritdoc ISwapper
function swapExact(
IERC20 fromToken,
IERC20 toToken,
address recipient,
address refundTo,
uint256 shareFromSupplied,
uint256 shareToExact
) public override returns (uint256 shareUsed, uint256 shareReturned) {
return (0,0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol";
import "../../interfaces/ISwapper.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
contract FTMSwapper is ISwapper {
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966);
IUniswapV2Pair constant pair = IUniswapV2Pair(0xB32b31DfAfbD53E310390F641C7119b5B9Ea0488);
IERC20 constant WFTM = IERC20(0x21be370D5312f44cB42ce377BC9b8a0cEF1A4C83);
IERC20 public constant MIM = IERC20(0x82f0B8B456c1A451378467398982d4834b6829c1);
// Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// Given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// Swaps to a flexible amount, from an exact input amount
/// @inheritdoc ISwapper
function swap(
IERC20 fromToken,
IERC20 toToken,
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public override returns (uint256 extraShare, uint256 shareReturned) {
(uint256 amountFrom,) = bentoBox.withdraw(fromToken, address(this), address(pair), 0, shareFrom);
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 amountTo = getAmountOut(amountFrom, reserve0, reserve1);
pair.swap(0, amountTo, address(bentoBox), new bytes(0));
(, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
// Swaps to an exact amount, from a flexible input amount
/// @inheritdoc ISwapper
function swapExact(
IERC20 fromToken,
IERC20 toToken,
address recipient,
address refundTo,
uint256 shareFromSupplied,
uint256 shareToExact
) public override returns (uint256 shareUsed, uint256 shareReturned) {
return (0,0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol";
import "../../interfaces/ISwapper.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
interface CurvePool {
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
}
interface TetherToken {
function approve(address _spender, uint256 _value) external;
}
contract ALCXSwapper is ISwapper {
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966);
CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B);
TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7);
IERC20 public constant ALCX = IERC20(0xdBdb4d16EdA451D0503b854CF79D55697F90c8DF);
IUniswapV2Pair constant ALCX_WETH = IUniswapV2Pair(0xC3f279090a47e80990Fe3a9c30d24Cb117EF91a8);
IUniswapV2Pair constant pair = IUniswapV2Pair(0x06da0fd433C1A5d7a4faa01111c044910A184553);
constructor() public {
TETHER.approve(address(MIM3POOL), type(uint256).max);
}
// Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// Given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// Swaps to a flexible amount, from an exact input amount
/// @inheritdoc ISwapper
function swap(
IERC20 fromToken,
IERC20 toToken,
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public override returns (uint256 extraShare, uint256 shareReturned) {
(uint256 amountFrom, ) = bentoBox.withdraw(fromToken, address(this), address(ALCX_WETH), 0, shareFrom);
(uint256 reserve0, uint256 reserve1, ) = ALCX_WETH.getReserves();
uint256 amountFirst = getAmountOut(amountFrom, reserve1, reserve0);
ALCX_WETH.swap(amountFirst, 0, address(pair), new bytes(0));
(reserve0, reserve1, ) = pair.getReserves();
uint256 amountIntermediate = getAmountOut(amountFirst, reserve0, reserve1);
pair.swap(0, amountIntermediate, address(this), new bytes(0));
uint256 amountTo = MIM3POOL.exchange_underlying(3, 0, amountIntermediate, 0, address(bentoBox));
(, shareReturned) = bentoBox.deposit(toToken, address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
// Swaps to an exact amount, from a flexible input amount
/// @inheritdoc ISwapper
function swapExact(
IERC20 fromToken,
IERC20 toToken,
address recipient,
address refundTo,
uint256 shareFromSupplied,
uint256 shareToExact
) public override returns (uint256 shareUsed, uint256 shareReturned) {
return (0,0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
interface CurvePool {
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
}
interface YearnVault {
function withdraw() external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
}
interface TetherToken {
function approve(address _spender, uint256 _value) external;
}
contract YVYFILevSwapper {
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public immutable bentoBox;
CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B);
YearnVault public constant YFI_VAULT = YearnVault(0xE14d13d8B3b85aF791b2AADD661cDBd5E6097Db1);
TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7);
IUniswapV2Pair constant YFI_WETH = IUniswapV2Pair(0x088ee5007C98a9677165D78dD2109AE4a3D04d0C);
IUniswapV2Pair constant pair = IUniswapV2Pair(0x06da0fd433C1A5d7a4faa01111c044910A184553);
IERC20 constant YFI = IERC20(0x0bc529c00C6401aEF6D220BE8C6Ea1667F6Ad93e);
IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3);
constructor(
IBentoBoxV1 bentoBox_
) public {
bentoBox = bentoBox_;
MIM.approve(address(MIM3POOL), type(uint256).max);
YFI.approve(address(YFI_VAULT), type(uint256).max);
}
// Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// Given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// Swaps to a flexible amount, from an exact input amount
function swap(
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public returns (uint256 extraShare, uint256 shareReturned) {
uint256 amountFirst;
{
(uint256 amountFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom);
amountFirst = MIM3POOL.exchange_underlying(0, 3, amountFrom, 0, address(pair));
}
uint256 amountIntermediate;
{
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
amountIntermediate = getAmountOut(amountFirst, reserve1, reserve0);
pair.swap(amountIntermediate, 0, address(YFI_WETH), new bytes(0));
}
(uint256 reserve0, uint256 reserve1, ) = YFI_WETH.getReserves();
uint256 amountInt2 = getAmountOut(amountIntermediate, reserve1, reserve0);
YFI_WETH.swap(amountInt2, 0, address(this), new bytes(0));
uint256 amountTo = YFI_VAULT.deposit(type(uint256).max, address(bentoBox));
(, shareReturned) = bentoBox.deposit(IERC20(address(YFI_VAULT)), address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
interface CurvePool {
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
}
interface SushiBar is IERC20 {
function leave(uint256 share) external;
function enter(uint256 amount) external;
function transfer(address _to, uint256 _value) external returns (bool success);
}
interface TetherToken {
function approve(address _spender, uint256 _value) external;
}
contract YVXSushiLevSwapper {
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public immutable bentoBox;
CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B);
TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7);
SushiBar public constant xSushi = SushiBar(0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272);
IERC20 public constant SUSHI = IERC20(0x6B3595068778DD592e39A122f4f5a5cF09C90fE2);
IUniswapV2Pair constant SUSHI_WETH = IUniswapV2Pair(0x795065dCc9f64b5614C407a6EFDC400DA6221FB0);
IUniswapV2Pair constant pair = IUniswapV2Pair(0x06da0fd433C1A5d7a4faa01111c044910A184553);
IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3);
constructor(
IBentoBoxV1 bentoBox_
) public {
bentoBox = bentoBox_;
SUSHI.approve(address(xSushi), type(uint256).max);
MIM.approve(address(MIM3POOL), type(uint256).max);
}
// Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// Given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// Swaps to a flexible amount, from an exact input amount
function swap(
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public returns (uint256 extraShare, uint256 shareReturned) {
uint256 amountFirst;
uint256 amountIntermediate;
{
(uint256 amountMIMFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom);
amountFirst = MIM3POOL.exchange_underlying(0, 3, amountMIMFrom, 0, address(pair));
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
amountIntermediate = getAmountOut(amountFirst, reserve1, reserve0);
}
uint256 amountThird;
{
pair.swap(amountIntermediate, 0, address(SUSHI_WETH), new bytes(0));
(uint256 reserve0, uint256 reserve1, ) = SUSHI_WETH.getReserves();
amountThird = getAmountOut(amountIntermediate, reserve1, reserve0);
}
SUSHI_WETH.swap(amountThird, 0, address(this), new bytes(0));
xSushi.enter(amountThird);
uint256 amountTo = xSushi.balanceOf(address(this));
xSushi.transfer(address(bentoBox), amountTo);
(, shareReturned) = bentoBox.deposit(xSushi, address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
interface CurvePool {
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
}
interface YearnVault {
function withdraw() external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
}
interface TetherToken {
function approve(address _spender, uint256 _value) external;
}
contract YVWETHLevSwapper{
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public immutable bentoBox;
CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B);
TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7);
YearnVault public constant WETH_VAULT = YearnVault(0xa258C4606Ca8206D8aA700cE2143D7db854D168c);
IUniswapV2Pair constant pair = IUniswapV2Pair(0x06da0fd433C1A5d7a4faa01111c044910A184553);
IERC20 constant WETH = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3);
constructor(
IBentoBoxV1 bentoBox_
) public {
bentoBox = bentoBox_;
WETH.approve(address(WETH_VAULT), type(uint256).max);
MIM.approve(address(MIM3POOL), type(uint256).max);
}
// Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// Given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// Swaps to a flexible amount, from an exact input amount
function swap(
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public returns (uint256 extraShare, uint256 shareReturned) {
(uint256 amountFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom);
uint256 amountIntermediate = MIM3POOL.exchange_underlying(0, 3, amountFrom, 0, address(pair));
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 amountInt2 = getAmountOut(amountIntermediate, reserve1, reserve0);
pair.swap(amountInt2, 0, address(this), new bytes(0));
uint256 amountTo = WETH_VAULT.deposit(type(uint256).max, address(bentoBox));
(, shareReturned) = bentoBox.deposit(IERC20(address(WETH_VAULT)), address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
interface CurvePool {
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
}
interface IWOHM is IERC20 {
function wrap( uint _amount ) external returns ( uint );
function unwrap( uint _amount ) external returns ( uint );
function transfer(address _to, uint256 _value) external returns (bool success);
}
interface IStakingManager {
function unstake( uint _amount, bool _trigger ) external;
function stake( uint _amount, address _recipient ) external returns ( bool );
function claim ( address _recipient ) external;
}
contract wOHMLevSwapper {
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966);
CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B);
IUniswapV2Pair constant OHM_DAI = IUniswapV2Pair(0x34d7d7Aaf50AD4944B70B320aCB24C95fa2def7c);
IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3);
IERC20 public constant SOHM = IERC20(0x04F2694C8fcee23e8Fd0dfEA1d4f5Bb8c352111F);
IWOHM public constant WOHM = IWOHM(0xCa76543Cf381ebBB277bE79574059e32108e3E65);
IStakingManager public constant STAKING_MANAGER = IStakingManager(0xFd31c7d00Ca47653c6Ce64Af53c1571f9C36566a);
IERC20 public constant OHM = IERC20(0x383518188C0C6d7730D91b2c03a03C837814a899);
constructor(
) public {
MIM.approve(address(MIM3POOL), type(uint256).max);
OHM.approve(address(STAKING_MANAGER), type(uint256).max);
SOHM.approve(address(WOHM), type(uint256).max);
}
// Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// Given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// Swaps to a flexible amount, from an exact input amount
function swap(
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public returns (uint256 extraShare, uint256 shareReturned) {
uint256 amountFirst;
uint256 amountIntermediate;
{
(uint256 amountMIMFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom);
amountFirst = MIM3POOL.exchange_underlying(0, 1, amountMIMFrom, 0, address(OHM_DAI));
(uint256 reserve0, uint256 reserve1, ) = OHM_DAI.getReserves();
amountIntermediate = getAmountOut(amountFirst, reserve1, reserve0);
}
OHM_DAI.swap(amountIntermediate, 0, address(this), new bytes(0));
STAKING_MANAGER.stake(amountIntermediate, address(this));
STAKING_MANAGER.claim(address(this));
uint256 amountTo = WOHM.wrap(amountIntermediate);
WOHM.transfer(address(bentoBox), amountTo);
(, shareReturned) = bentoBox.deposit(WOHM, address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
interface CurvePool {
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
}
interface TetherToken {
function approve(address _spender, uint256 _value) external;
}
contract SpellLevSwapper {
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xd96f48665a1410C0cd669A88898ecA36B9Fc2cce);
CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B);
TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7);
IERC20 public constant SPELL = IERC20(0x090185f2135308BaD17527004364eBcC2D37e5F6);
IUniswapV2Pair constant SPELL_ETH = IUniswapV2Pair(0xb5De0C3753b6E1B4dBA616Db82767F17513E6d4E);
IUniswapV2Pair constant pair = IUniswapV2Pair(0x06da0fd433C1A5d7a4faa01111c044910A184553);
IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3);
// Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// Given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
constructor() public {
MIM.approve(address(MIM3POOL), type(uint256).max);
}
// Swaps to a flexible amount, from an exact input amount
function swap(
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public returns (uint256 extraShare, uint256 shareReturned) {
(uint256 amountFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom);
uint256 amountFirst = MIM3POOL.exchange_underlying(0, 3, amountFrom, 0, address(pair));
uint256 amountIntermediate;
{
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
amountIntermediate = getAmountOut(amountFirst, reserve1, reserve0);
pair.swap(amountIntermediate, 0, address(SPELL_ETH), new bytes(0));
}
uint256 amountTo;
{
(uint256 reserve0, uint256 reserve1, ) = SPELL_ETH.getReserves();
amountTo = getAmountOut(amountIntermediate, reserve1, reserve0);
}
SPELL_ETH.swap(amountTo, 0, address(bentoBox), new bytes(0));
(, shareReturned) = bentoBox.deposit(SPELL, address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
contract FTMLevSwapper{
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966);
IUniswapV2Pair constant pair = IUniswapV2Pair(0xB32b31DfAfbD53E310390F641C7119b5B9Ea0488);
IERC20 constant WFTM = IERC20(0x21be370D5312f44cB42ce377BC9b8a0cEF1A4C83);
IERC20 public constant MIM = IERC20(0x82f0B8B456c1A451378467398982d4834b6829c1);
// Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// Given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// Swaps to a flexible amount, from an exact input amount
function swap(
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public returns (uint256 extraShare, uint256 shareReturned) {
(uint256 amountFrom, ) = bentoBox.withdraw(MIM, address(this), address(pair), 0, shareFrom);
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 amountTo = getAmountOut(amountFrom, reserve1, reserve0);
pair.swap(amountTo, 0, address(bentoBox), new bytes(0));
(, shareReturned) = bentoBox.deposit(WFTM, address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
interface CurvePool {
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
}
interface TetherToken {
function approve(address _spender, uint256 _value) external;
}
contract ALCXLevSwapper {
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966);
CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B);
TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7);
IERC20 public constant ALCX = IERC20(0xdBdb4d16EdA451D0503b854CF79D55697F90c8DF);
IUniswapV2Pair constant ALCX_WETH = IUniswapV2Pair(0xC3f279090a47e80990Fe3a9c30d24Cb117EF91a8);
IUniswapV2Pair constant pair = IUniswapV2Pair(0x06da0fd433C1A5d7a4faa01111c044910A184553);
IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3);
constructor() public {
MIM.approve(address(MIM3POOL), type(uint256).max);
}
// Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// Given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// Swaps to a flexible amount, from an exact input amount
function swap(
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public returns (uint256 extraShare, uint256 shareReturned) {
uint256 amountFirst;
uint256 amountIntermediate;
{
(uint256 amountMIMFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom);
amountFirst = MIM3POOL.exchange_underlying(0, 3, amountMIMFrom, 0, address(pair));
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
amountIntermediate = getAmountOut(amountFirst, reserve1, reserve0);
}
pair.swap(amountIntermediate, 0, address(ALCX_WETH), new bytes(0));
(uint256 reserve0, uint256 reserve1, ) = ALCX_WETH.getReserves();
uint256 amountThird = getAmountOut(amountIntermediate, reserve0, reserve1);
ALCX_WETH.swap(0, amountThird, address(bentoBox), new bytes(0));
(, shareReturned) = bentoBox.deposit(ALCX, address(bentoBox), recipient, amountThird, 0);
extraShare = shareReturned.sub(shareToMin);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "../interfaces/IOracle.sol";
// Chainlink Aggregator
interface IAggregator {
function latestAnswer() external view returns (int256 answer);
}
interface IYearnVault {
function pricePerShare() external view returns (uint256 price);
}
contract YearnChainlinkOracle is IOracle {
using BoringMath for uint256; // Keep everything in uint256
// Calculates the lastest exchange rate
// Uses both divide and multiply only for tokens not supported directly by Chainlink, for example MKR/USD
function _get(
address multiply,
address divide,
uint256 decimals,
address yearnVault
) internal view returns (uint256) {
uint256 price = uint256(1e36);
if (multiply != address(0)) {
price = price.mul(uint256(IAggregator(multiply).latestAnswer()));
} else {
price = price.mul(1e18);
}
if (divide != address(0)) {
price = price / uint256(IAggregator(divide).latestAnswer());
}
// @note decimals have to take into account the decimals of the vault asset
return price / decimals.mul(IYearnVault(yearnVault).pricePerShare());
}
function getDataParameter(
address multiply,
address divide,
uint256 decimals,
address yearnVault
) public pure returns (bytes memory) {
return abi.encode(multiply, divide, decimals, yearnVault);
}
// Get the latest exchange rate
/// @inheritdoc IOracle
function get(bytes calldata data) public override returns (bool, uint256) {
(address multiply, address divide, uint256 decimals, address yearnVault) = abi.decode(data, (address, address, uint256, address));
return (true, _get(multiply, divide, decimals, yearnVault));
}
// Check the last exchange rate without any state changes
/// @inheritdoc IOracle
function peek(bytes calldata data) public view override returns (bool, uint256) {
(address multiply, address divide, uint256 decimals, address yearnVault) = abi.decode(data, (address, address, uint256, address));
return (true, _get(multiply, divide, decimals, yearnVault));
}
// Check the current spot exchange rate without any state changes
/// @inheritdoc IOracle
function peekSpot(bytes calldata data) external view override returns (uint256 rate) {
(, rate) = peek(data);
}
/// @inheritdoc IOracle
function name(bytes calldata) public view override returns (string memory) {
return "Chainlink";
}
/// @inheritdoc IOracle
function symbol(bytes calldata) public view override returns (string memory) {
return "LINK";
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "../interfaces/IOracle.sol";
import "@boringcrypto/boring-solidity/contracts/interfaces/IERC20.sol";
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
interface IAggregator {
function latestAnswer() external view returns (int256 answer);
}
/// @title xSUSHIOracle
/// @author BoringCrypto
/// @notice Oracle used for getting the price of xSUSHI based on Chainlink
/// @dev
contract xSUSHIOracle is IOracle {
using BoringMath for uint256; // Keep everything in uint256
IERC20 public immutable sushi;
IERC20 public immutable bar;
IAggregator public immutable sushiOracle;
constructor(
IERC20 sushi_,
IERC20 bar_,
IAggregator sushiOracle_
) public {
sushi = sushi_;
bar = bar_;
sushiOracle = sushiOracle_;
}
// Calculates the lastest exchange rate
// Uses sushi rate and xSUSHI conversion and divide for any conversion other than from SUSHI to ETH
function _get(address divide, uint256 decimals) internal view returns (uint256) {
uint256 price = uint256(1e36);
price = (price.mul(uint256(sushiOracle.latestAnswer())) / bar.totalSupply()).mul(sushi.balanceOf(address(bar)));
if (divide != address(0)) {
price = price / uint256(IAggregator(divide).latestAnswer());
}
return price / decimals;
}
function getDataParameter(address divide, uint256 decimals) public pure returns (bytes memory) {
return abi.encode(divide, decimals);
}
// Get the latest exchange rate
/// @inheritdoc IOracle
function get(bytes calldata data) public override returns (bool, uint256) {
(address divide, uint256 decimals) = abi.decode(data, (address, uint256));
return (true, _get(divide, decimals));
}
// Check the last exchange rate without any state changes
/// @inheritdoc IOracle
function peek(bytes calldata data) public view override returns (bool, uint256) {
(address divide, uint256 decimals) = abi.decode(data, (address, uint256));
return (true, _get(divide, decimals));
}
// Check the current spot exchange rate without any state changes
/// @inheritdoc IOracle
function peekSpot(bytes calldata data) external view override returns (uint256 rate) {
(, rate) = peek(data);
}
/// @inheritdoc IOracle
function name(bytes calldata) public view override returns (string memory) {
return "xSUSHI Chainlink";
}
/// @inheritdoc IOracle
function symbol(bytes calldata) public view override returns (string memory) {
return "xSUSHI-LINK";
}
}
// SPDX-License-Identifier: AGPL-3.0-only
// Using the same Copyleft License as in the original Repository
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../interfaces/IOracle.sol";
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@boringcrypto/boring-solidity/contracts/interfaces/IERC20.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol";
import "../libraries/FixedPoint.sol";
import "hardhat/console.sol";
// solhint-disable not-rely-on-time
// adapted from https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/examples/ExampleSlidingWindowOracle.sol
interface IAggregator {
function latestAnswer() external view returns (int256 answer);
}
contract xBooOracle is IOracle {
using FixedPoint for *;
using BoringMath for uint256;
uint256 public constant PERIOD = 10 minutes;
IAggregator public constant FTM_USD = IAggregator(0xf4766552D15AE4d256Ad41B6cf2933482B0680dc);
IUniswapV2Pair public constant BOO_FTM = IUniswapV2Pair(0xEc7178F4C41f346b2721907F5cF7628E388A7a58);
IERC20 public constant BOO = IERC20(0x841FAD6EAe12c286d1Fd18d1d525DFfA75C7EFFE);
IERC20 public constant XBOO = IERC20(0xa48d959AE2E88f1dAA7D5F611E01908106dE7598);
struct PairInfo {
uint256 priceCumulativeLast;
uint32 blockTimestampLast;
uint144 priceAverage;
}
PairInfo public pairInfo;
function _get(uint32 blockTimestamp) public view returns (uint256) {
uint256 priceCumulative = BOO_FTM.price1CumulativeLast();
// if time has elapsed since the last update on the pair, mock the accumulated price values
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(BOO_FTM).getReserves();
priceCumulative += uint256(FixedPoint.fraction(reserve0, reserve1)._x) * (blockTimestamp - blockTimestampLast); // overflows ok
// overflow is desired, casting never truncates
// cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
return priceCumulative;
}
function toXBOO(uint256 amount) internal view returns (uint256) {
return amount.mul(BOO.balanceOf(address(XBOO))) / XBOO.totalSupply();
}
// Get the latest exchange rate, if no valid (recent) rate is available, return false
/// @inheritdoc IOracle
function get(bytes calldata) external override returns (bool, uint256) {
uint32 blockTimestamp = uint32(block.timestamp);
if (pairInfo.blockTimestampLast == 0) {
pairInfo.blockTimestampLast = blockTimestamp;
pairInfo.priceCumulativeLast = _get(blockTimestamp);
return (false, 0);
}
uint32 timeElapsed = blockTimestamp - pairInfo.blockTimestampLast; // overflow is desired
console.log(timeElapsed);
if (timeElapsed < PERIOD) {
return (true, pairInfo.priceAverage);
}
uint256 priceCumulative = _get(blockTimestamp);
pairInfo.priceAverage = uint144(1e44 / toXBOO(uint256(FixedPoint
.uq112x112(uint224((priceCumulative - pairInfo.priceCumulativeLast) / timeElapsed))
.mul(1e18)
.decode144())).mul(uint256(FTM_USD.latestAnswer())));
pairInfo.blockTimestampLast = blockTimestamp;
pairInfo.priceCumulativeLast = priceCumulative;
return (true, pairInfo.priceAverage);
}
// Check the last exchange rate without any state changes
/// @inheritdoc IOracle
function peek(bytes calldata) public view override returns (bool, uint256) {
uint32 blockTimestamp = uint32(block.timestamp);
if (pairInfo.blockTimestampLast == 0) {
return (false, 0);
}
uint32 timeElapsed = blockTimestamp - pairInfo.blockTimestampLast; // overflow is desired
if (timeElapsed < PERIOD) {
return (true, pairInfo.priceAverage);
}
uint256 priceCumulative = _get(blockTimestamp);
uint144 priceAverage = uint144(1e44 / toXBOO(uint256(FixedPoint
.uq112x112(uint224((priceCumulative - pairInfo.priceCumulativeLast) / timeElapsed))
.mul(1e18)
.decode144())).mul(uint256(FTM_USD.latestAnswer())));
return (true, priceAverage);
}
// Check the current spot exchange rate without any state changes
/// @inheritdoc IOracle
function peekSpot(bytes calldata) external view override returns (uint256 rate) {
(uint256 reserve0, uint256 reserve1, ) = BOO_FTM.getReserves();
rate = 1e44 / toXBOO(reserve0.mul(1e18) / reserve1).mul(uint256(FTM_USD.latestAnswer()));
}
/// @inheritdoc IOracle
function name(bytes calldata) public view override returns (string memory) {
return "xBOO TWAP";
}
/// @inheritdoc IOracle
function symbol(bytes calldata) public view override returns (string memory) {
return "xBOO";
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.6.12;
import "./FullMath_v06_12.sol";
// solhint-disable
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
library FixedPoint {
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
struct uq112x112 {
uint224 _x;
}
// range: [0, 2**144 - 1]
// resolution: 1 / 2**112
struct uq144x112 {
uint256 _x;
}
uint8 private constant RESOLUTION = 112;
uint256 private constant Q112 = 0x10000000000000000000000000000;
uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000;
uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits)
// decode a UQ144x112 into a uint144 by truncating after the radix point
function decode144(uq144x112 memory self) internal pure returns (uint144) {
return uint144(self._x >> RESOLUTION);
}
// multiply a UQ112x112 by a uint256, returning a UQ144x112
// reverts on overflow
function mul(uq112x112 memory self, uint256 y) internal pure returns (uq144x112 memory) {
uint256 z = 0;
require(y == 0 || (z = self._x * y) / y == self._x, "FixedPoint::mul: overflow");
return uq144x112(z);
}
// returns a UQ112x112 which represents the ratio of the numerator to the denominator
// lossy if either numerator or denominator is greater than 112 bits
function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, "FixedPoint::fraction: div by 0");
if (numerator == 0) return FixedPoint.uq112x112(0);
if (numerator <= uint144(-1)) {
uint256 result = (numerator << RESOLUTION) / denominator;
require(result <= uint224(-1), "FixedPoint::fraction: overflow");
return uq112x112(uint224(result));
} else {
uint256 result = FullMath.mulDiv(numerator, Q112, denominator);
require(result <= uint224(-1), "FixedPoint::fraction: overflow");
return uq112x112(uint224(result));
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// SPDX-License-Identifier: CC-BY-4.0
pragma solidity 0.6.12;
// solhint-disable
// taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1
// license is CC-BY-4.0
library FullMath {
function fullMul(uint256 x, uint256 y) private pure returns (uint256 l, uint256 h) {
uint256 mm = mulmod(x, y, uint256(-1));
l = x * y;
h = mm - l;
if (mm < l) h -= 1;
}
function fullDiv(
uint256 l,
uint256 h,
uint256 d
) private pure returns (uint256) {
uint256 pow2 = d & -d;
d /= pow2;
l /= pow2;
l += h * ((-pow2) / pow2 + 1);
uint256 r = 1;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
return l * r;
}
function mulDiv(
uint256 x,
uint256 y,
uint256 d
) internal pure returns (uint256) {
(uint256 l, uint256 h) = fullMul(x, y);
uint256 mm = mulmod(x, y, d);
if (mm > l) h -= 1;
l -= mm;
require(h < d, "FullMath::mulDiv: overflow");
return fullDiv(l, h, d);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
// Using the same Copyleft License as in the original Repository
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../interfaces/IOracle.sol";
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@boringcrypto/boring-solidity/contracts/interfaces/IERC20.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol";
import "../libraries/FixedPoint.sol";
import "hardhat/console.sol";
// solhint-disable not-rely-on-time
// adapted from https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/examples/ExampleSlidingWindowOracle.sol
interface IAggregator {
function latestAnswer() external view returns (int256 answer);
}
contract ICEOracleFTM is IOracle {
using FixedPoint for *;
using BoringMath for uint256;
uint256 public constant PERIOD = 10 minutes;
IAggregator public constant FTM_USD = IAggregator(0xf4766552D15AE4d256Ad41B6cf2933482B0680dc);
IUniswapV2Pair public constant ICE_FTM = IUniswapV2Pair(0x84311ECC54D7553378c067282940b0fdfb913675);
IERC20 public constant ICE = IERC20(0xf16e81dce15B08F326220742020379B855B87DF9);
struct PairInfo {
uint256 priceCumulativeLast;
uint32 blockTimestampLast;
uint144 priceAverage;
}
PairInfo public pairInfo;
function _get(uint32 blockTimestamp) public view returns (uint256) {
uint256 priceCumulative = ICE_FTM.price1CumulativeLast();
// if time has elapsed since the last update on the pair, mock the accumulated price values
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(ICE_FTM).getReserves();
priceCumulative += uint256(FixedPoint.fraction(reserve0, reserve1)._x) * (blockTimestamp - blockTimestampLast); // overflows ok
// overflow is desired, casting never truncates
// cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
return priceCumulative;
}
// Get the latest exchange rate, if no valid (recent) rate is available, return false
/// @inheritdoc IOracle
function get(bytes calldata) external override returns (bool, uint256) {
uint32 blockTimestamp = uint32(block.timestamp);
if (pairInfo.blockTimestampLast == 0) {
pairInfo.blockTimestampLast = blockTimestamp;
pairInfo.priceCumulativeLast = _get(blockTimestamp);
return (false, 0);
}
uint32 timeElapsed = blockTimestamp - pairInfo.blockTimestampLast; // overflow is desired
console.log(timeElapsed);
if (timeElapsed < PERIOD) {
return (true, pairInfo.priceAverage);
}
uint256 priceCumulative = _get(blockTimestamp);
pairInfo.priceAverage = uint144(1e44 / uint256(FixedPoint
.uq112x112(uint224((priceCumulative - pairInfo.priceCumulativeLast) / timeElapsed))
.mul(1e18)
.decode144()).mul(uint256(FTM_USD.latestAnswer())));
pairInfo.blockTimestampLast = blockTimestamp;
pairInfo.priceCumulativeLast = priceCumulative;
return (true, pairInfo.priceAverage);
}
// Check the last exchange rate without any state changes
/// @inheritdoc IOracle
function peek(bytes calldata) public view override returns (bool, uint256) {
uint32 blockTimestamp = uint32(block.timestamp);
if (pairInfo.blockTimestampLast == 0) {
return (false, 0);
}
uint32 timeElapsed = blockTimestamp - pairInfo.blockTimestampLast; // overflow is desired
if (timeElapsed < PERIOD) {
return (true, pairInfo.priceAverage);
}
uint256 priceCumulative = _get(blockTimestamp);
uint144 priceAverage = uint144(1e44 / uint256(FixedPoint
.uq112x112(uint224((priceCumulative - pairInfo.priceCumulativeLast) / timeElapsed))
.mul(1e18)
.decode144()).mul(uint256(FTM_USD.latestAnswer())));
return (true, priceAverage);
}
// Check the current spot exchange rate without any state changes
/// @inheritdoc IOracle
function peekSpot(bytes calldata) external view override returns (uint256 rate) {
(uint256 reserve0, uint256 reserve1, ) = ICE_FTM.getReserves();
rate = 1e44 / (reserve0.mul(1e18) / reserve1).mul(uint256(FTM_USD.latestAnswer()));
}
/// @inheritdoc IOracle
function name(bytes calldata) public view override returns (string memory) {
return "ICE TWAP";
}
/// @inheritdoc IOracle
function symbol(bytes calldata) public view override returns (string memory) {
return "ICE";
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "../interfaces/IOracle.sol";
// Chainlink Aggregator
interface IAggregator {
function latestAnswer() external view returns (int256 answer);
}
interface IWOHM {
function sOHMTowOHM(uint256 _amount) external view returns (uint256);
}
contract wOHMOracle is IOracle {
using BoringMath for uint256; // Keep everything in uint256
IAggregator public constant ohmOracle = IAggregator(0x90c2098473852E2F07678Fe1B6d595b1bd9b16Ed);
IAggregator public constant ethUSDOracle = IAggregator(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);
IWOHM public constant WOHM = IWOHM(0xCa76543Cf381ebBB277bE79574059e32108e3E65);
// Calculates the lastest exchange rate
// Uses both divide and multiply only for tokens not supported directly by Chainlink, for example MKR/USD
function _get() internal view returns (uint256) {
return
1e44 / (uint256(1e18).mul(uint256(ohmOracle.latestAnswer()).mul(uint256(ethUSDOracle.latestAnswer()))) / WOHM.sOHMTowOHM(1e9));
}
// Get the latest exchange rate
/// @inheritdoc IOracle
function get(bytes calldata) public override returns (bool, uint256) {
return (true, _get());
}
// Check the last exchange rate without any state changes
/// @inheritdoc IOracle
function peek(bytes calldata) public view override returns (bool, uint256) {
return (true, _get());
}
// Check the current spot exchange rate without any state changes
/// @inheritdoc IOracle
function peekSpot(bytes calldata data) external view override returns (uint256 rate) {
(, rate) = peek(data);
}
/// @inheritdoc IOracle
function name(bytes calldata) public view override returns (string memory) {
return "wOHM Chainlink";
}
/// @inheritdoc IOracle
function symbol(bytes calldata) public view override returns (string memory) {
return "LINK/wOHM";
}
}
// SPDX-License-Identifier: MIT
import "../interfaces/IOracle.sol";
import "@boringcrypto/boring-solidity/contracts/interfaces/IERC20.sol";
import "@boringcrypto/boring-solidity/contracts/BoringOwnable.sol";
/// @title ProxyOracle
/// @author 0xMerlin
/// @notice Oracle used for getting the price of an oracle implementation
contract ProxyOracle is IOracle, BoringOwnable {
IOracle public oracleImplementation;
event LogOracleImplementationChange(IOracle indexed oldOracle, IOracle indexed newOracle);
constructor() public {}
function changeOracleImplementation(IOracle newOracle) external onlyOwner {
IOracle oldOracle = oracleImplementation;
oracleImplementation = newOracle;
emit LogOracleImplementationChange(oldOracle, newOracle);
}
// Get the latest exchange rate
/// @inheritdoc IOracle
function get(bytes calldata data) public override returns (bool, uint256) {
return oracleImplementation.get(data);
}
// Check the last exchange rate without any state changes
/// @inheritdoc IOracle
function peek(bytes calldata data) public view override returns (bool, uint256) {
return oracleImplementation.peek(data);
}
// Check the current spot exchange rate without any state changes
/// @inheritdoc IOracle
function peekSpot(bytes calldata data) external view override returns (uint256 rate) {
return oracleImplementation.peekSpot(data);
}
/// @inheritdoc IOracle
function name(bytes calldata) public view override returns (string memory) {
return "Proxy Oracle";
}
/// @inheritdoc IOracle
function symbol(bytes calldata) public view override returns (string memory) {
return "Proxy";
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "../interfaces/IOracle.sol";
/// @title PeggedOracle
/// @author BoringCrypto
/// @notice Oracle used for pegged prices that don't change
/// @dev
contract PeggedOracle is IOracle {
/// @notice
/// @dev
/// @param rate (uint256) The fixed exchange rate
/// @return (bytes)
function getDataParameter(uint256 rate) public pure returns (bytes memory) {
return abi.encode(rate);
}
// Get the exchange rate
/// @inheritdoc IOracle
function get(bytes calldata data) public override returns (bool, uint256) {
uint256 rate = abi.decode(data, (uint256));
return (rate != 0, rate);
}
// Check the exchange rate without any state changes
/// @inheritdoc IOracle
function peek(bytes calldata data) public view override returns (bool, uint256) {
uint256 rate = abi.decode(data, (uint256));
return (rate != 0, rate);
}
// Check the current spot exchange rate without any state changes
/// @inheritdoc IOracle
function peekSpot(bytes calldata data) external view override returns (uint256 rate) {
(, rate) = peek(data);
}
/// @inheritdoc IOracle
function name(bytes calldata) public view override returns (string memory) {
return "Pegged";
}
/// @inheritdoc IOracle
function symbol(bytes calldata) public view override returns (string memory) {
return "PEG";
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "../interfaces/IOracle.sol";
import "@boringcrypto/boring-solidity/contracts/interfaces/IERC20.sol";
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
interface IAggregator {
function latestAnswer() external view returns (int256 answer);
}
/// @title xSUSHIOracle
/// @author BoringCrypto
/// @notice Oracle used for getting the price of xSUSHI based on Chainlink
/// @dev
contract xSUSHIOracle is IOracle {
using BoringMath for uint256; // Keep everything in uint256
IERC20 public immutable sushi;
IERC20 public immutable bar;
IAggregator public immutable sushiOracle;
constructor(
IERC20 sushi_,
IERC20 bar_,
IAggregator sushiOracle_
) public {
sushi = sushi_;
bar = bar_;
sushiOracle = sushiOracle_;
}
// Calculates the lastest exchange rate
// Uses sushi rate and xSUSHI conversion and divide for any conversion other than from SUSHI to ETH
function _get(address divide, uint256 decimals) internal view returns (uint256) {
uint256 price = uint256(1e36);
price = (price.mul(uint256(sushiOracle.latestAnswer())) / bar.totalSupply()).mul(sushi.balanceOf(address(bar)));
if (divide != address(0)) {
price = price / uint256(IAggregator(divide).latestAnswer());
}
return price / decimals;
}
function getDataParameter(address divide, uint256 decimals) public pure returns (bytes memory) {
return abi.encode(divide, decimals);
}
// Get the latest exchange rate
/// @inheritdoc IOracle
function get(bytes calldata data) public override returns (bool, uint256) {
(address divide, uint256 decimals) = abi.decode(data, (address, uint256));
return (true, _get(divide, decimals));
}
// Check the last exchange rate without any state changes
/// @inheritdoc IOracle
function peek(bytes calldata data) public view override returns (bool, uint256) {
(address divide, uint256 decimals) = abi.decode(data, (address, uint256));
return (true, _get(divide, decimals));
}
// Check the current spot exchange rate without any state changes
/// @inheritdoc IOracle
function peekSpot(bytes calldata data) external view override returns (uint256 rate) {
(, rate) = peek(data);
}
/// @inheritdoc IOracle
function name(bytes calldata) public view override returns (string memory) {
return "xSUSHI Chainlink";
}
/// @inheritdoc IOracle
function symbol(bytes calldata) public view override returns (string memory) {
return "xSUSHI-LINK";
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "../interfaces/IOracle.sol";
interface IUniswapAnchoredView {
function price(string memory symbol) external view returns (uint256);
}
contract CompoundOracle is IOracle {
using BoringMath for uint256;
IUniswapAnchoredView private constant ORACLE = IUniswapAnchoredView(0x922018674c12a7F0D394ebEEf9B58F186CdE13c1);
struct PriceInfo {
uint128 price;
uint128 blockNumber;
}
mapping(string => PriceInfo) public prices;
function _peekPrice(string memory symbol) internal view returns (uint256) {
if (bytes(symbol).length == 0) {
return 1000000;
} // To allow only using collateralSymbol or assetSymbol if paired against USDx
PriceInfo memory info = prices[symbol];
if (block.number > info.blockNumber + 8) {
return uint128(ORACLE.price(symbol)); // Prices are denominated with 6 decimals, so will fit in uint128
}
return info.price;
}
function _getPrice(string memory symbol) internal returns (uint256) {
if (bytes(symbol).length == 0) {
return 1000000;
} // To allow only using collateralSymbol or assetSymbol if paired against USDx
PriceInfo memory info = prices[symbol];
if (block.number > info.blockNumber + 8) {
info.price = uint128(ORACLE.price(symbol)); // Prices are denominated with 6 decimals, so will fit in uint128
info.blockNumber = uint128(block.number); // Blocknumber will fit in uint128
prices[symbol] = info;
}
return info.price;
}
function getDataParameter(
string memory collateralSymbol,
string memory assetSymbol,
uint256 division
) public pure returns (bytes memory) {
return abi.encode(collateralSymbol, assetSymbol, division);
}
// Get the latest exchange rate
/// @inheritdoc IOracle
function get(bytes calldata data) public override returns (bool, uint256) {
(string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256));
return (true, uint256(1e36).mul(_getPrice(assetSymbol)) / _getPrice(collateralSymbol) / division);
}
// Check the last exchange rate without any state changes
/// @inheritdoc IOracle
function peek(bytes calldata data) public view override returns (bool, uint256) {
(string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256));
return (true, uint256(1e36).mul(_peekPrice(assetSymbol)) / _peekPrice(collateralSymbol) / division);
}
// Check the current spot exchange rate without any state changes
/// @inheritdoc IOracle
function peekSpot(bytes calldata data) external view override returns (uint256 rate) {
(, rate) = peek(data);
}
/// @inheritdoc IOracle
function name(bytes calldata) public view override returns (string memory) {
return "Compound";
}
/// @inheritdoc IOracle
function symbol(bytes calldata) public view override returns (string memory) {
return "COMP";
}
}
// SPDX-License-Identifier: MIT
// Using the same Copyleft License as in the original Repository
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "../interfaces/IOracle.sol";
contract CompositeOracle is IOracle {
using BoringMath for uint256;
function getDataParameter(
IOracle oracle1,
IOracle oracle2,
bytes memory data1,
bytes memory data2
) public pure returns (bytes memory) {
return abi.encode(oracle1, oracle2, data1, data2);
}
// Get the latest exchange rate, if no valid (recent) rate is available, return false
/// @inheritdoc IOracle
function get(bytes calldata data) external override returns (bool, uint256) {
(IOracle oracle1, IOracle oracle2, bytes memory data1, bytes memory data2) = abi.decode(data, (IOracle, IOracle, bytes, bytes));
(bool success1, uint256 price1) = oracle1.get(data1);
(bool success2, uint256 price2) = oracle2.get(data2);
return (success1 && success2, price1.mul(price2) / 10**18);
}
// Check the last exchange rate without any state changes
/// @inheritdoc IOracle
function peek(bytes calldata data) public view override returns (bool, uint256) {
(IOracle oracle1, IOracle oracle2, bytes memory data1, bytes memory data2) = abi.decode(data, (IOracle, IOracle, bytes, bytes));
(bool success1, uint256 price1) = oracle1.peek(data1);
(bool success2, uint256 price2) = oracle2.peek(data2);
return (success1 && success2, price1.mul(price2) / 10**18);
}
// Check the current spot exchange rate without any state changes
/// @inheritdoc IOracle
function peekSpot(bytes calldata data) external view override returns (uint256 rate) {
(IOracle oracle1, IOracle oracle2, bytes memory data1, bytes memory data2) = abi.decode(data, (IOracle, IOracle, bytes, bytes));
uint256 price1 = oracle1.peekSpot(data1);
uint256 price2 = oracle2.peekSpot(data2);
return price1.mul(price2) / 10**18;
}
/// @inheritdoc IOracle
function name(bytes calldata data) public view override returns (string memory) {
(IOracle oracle1, IOracle oracle2, bytes memory data1, bytes memory data2) = abi.decode(data, (IOracle, IOracle, bytes, bytes));
return string(abi.encodePacked(oracle1.name(data1), "+", oracle2.name(data2)));
}
/// @inheritdoc IOracle
function symbol(bytes calldata data) public view override returns (string memory) {
(IOracle oracle1, IOracle oracle2, bytes memory data1, bytes memory data2) = abi.decode(data, (IOracle, IOracle, bytes, bytes));
return string(abi.encodePacked(oracle1.symbol(data1), "+", oracle2.symbol(data2)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "../interfaces/IOracle.sol";
// Chainlink Aggregator
interface IAggregator {
function latestAnswer() external view returns (int256 answer);
}
contract ChainlinkOracle is IOracle {
using BoringMath for uint256; // Keep everything in uint256
// Calculates the lastest exchange rate
// Uses both divide and multiply only for tokens not supported directly by Chainlink, for example MKR/USD
function _get(
address multiply,
address divide,
uint256 decimals
) internal view returns (uint256) {
uint256 price = uint256(1e36);
if (multiply != address(0)) {
price = price.mul(uint256(IAggregator(multiply).latestAnswer()));
} else {
price = price.mul(1e18);
}
if (divide != address(0)) {
price = price / uint256(IAggregator(divide).latestAnswer());
}
return price / decimals;
}
function getDataParameter(
address multiply,
address divide,
uint256 decimals
) public pure returns (bytes memory) {
return abi.encode(multiply, divide, decimals);
}
// Get the latest exchange rate
/// @inheritdoc IOracle
function get(bytes calldata data) public override returns (bool, uint256) {
(address multiply, address divide, uint256 decimals) = abi.decode(data, (address, address, uint256));
return (true, _get(multiply, divide, decimals));
}
// Check the last exchange rate without any state changes
/// @inheritdoc IOracle
function peek(bytes calldata data) public view override returns (bool, uint256) {
(address multiply, address divide, uint256 decimals) = abi.decode(data, (address, address, uint256));
return (true, _get(multiply, divide, decimals));
}
// Check the current spot exchange rate without any state changes
/// @inheritdoc IOracle
function peekSpot(bytes calldata data) external view override returns (uint256 rate) {
(, rate) = peek(data);
}
/// @inheritdoc IOracle
function name(bytes calldata) public view override returns (string memory) {
return "Chainlink";
}
/// @inheritdoc IOracle
function symbol(bytes calldata) public view override returns (string memory) {
return "LINK";
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "../interfaces/IOracle.sol";
// Band
interface IStdReference {
/// A structure returned whenever someone requests for standard reference data.
struct ReferenceData {
uint256 rate; // base/quote exchange rate, multiplied by 1e18.
uint256 lastUpdatedBase; // UNIX epoch of the last time when base price gets updated.
uint256 lastUpdatedQuote; // UNIX epoch of the last time when quote price gets updated.
}
/// Returns the price data for the given base/quote pair. Revert if not available.
function getReferenceData(string memory _base, string memory _quote) external view returns (ReferenceData memory);
/// Similar to getReferenceData, but with multiple base/quote pairs at once.
function getReferenceDataBulk(string[] memory _bases, string[] memory _quotes) external view returns (ReferenceData[] memory);
}
contract BandOracleFTMV1 is IOracle {
using BoringMath for uint256; // Keep everything in uint256
IStdReference constant ftmOracle = IStdReference(0x56E2898E0ceFF0D1222827759B56B28Ad812f92F);
// Calculates the lastest exchange rate
function _get() internal view returns (uint256 rate) {
IStdReference.ReferenceData memory referenceData = ftmOracle.getReferenceData("USD", "FTM");
return referenceData.rate;
}
// Get the latest exchange rate
/// @inheritdoc IOracle
function get(bytes calldata) public override returns (bool, uint256) {
return (true, _get());
}
// Check the last exchange rate without any state changes
/// @inheritdoc IOracle
function peek(bytes calldata) public view override returns (bool, uint256) {
return (true, _get());
}
// Check the current spot exchange rate without any state changes
/// @inheritdoc IOracle
function peekSpot(bytes calldata data) external view override returns (uint256 rate) {
(, rate) = peek(data);
}
/// @inheritdoc IOracle
function name(bytes calldata) public view override returns (string memory) {
return "BAND FTM/USD";
}
/// @inheritdoc IOracle
function symbol(bytes calldata) public view override returns (string memory) {
return "BAND";
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "../interfaces/IOracle.sol";
// Chainlink Aggregator
interface IAggregator {
function latestAnswer() external view returns (int256 answer);
}
contract AVAXOracle is IOracle {
using BoringMath for uint256; // Keep everything in uint256
IAggregator public constant avaxOracle = IAggregator(0x0A77230d17318075983913bC2145DB16C7366156);
// Calculates the lastest exchange rate
// Uses both divide and multiply only for tokens not supported directly by Chainlink, for example MKR/USD
function _get() internal view returns (uint256) {
return 1e26 / uint256(avaxOracle.latestAnswer());
}
// Get the latest exchange rate
/// @inheritdoc IOracle
function get(bytes calldata) public override returns (bool, uint256) {
return (true, _get());
}
// Check the last exchange rate without any state changes
/// @inheritdoc IOracle
function peek(bytes calldata) public view override returns (bool, uint256) {
return (true, _get());
}
// Check the current spot exchange rate without any state changes
/// @inheritdoc IOracle
function peekSpot(bytes calldata data) external view override returns (uint256 rate) {
(, rate) = peek(data);
}
/// @inheritdoc IOracle
function name(bytes calldata) public view override returns (string memory) {
return "AVAX Chainlink";
}
/// @inheritdoc IOracle
function symbol(bytes calldata) public view override returns (string memory) {
return "LINK/AVAX";
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "../interfaces/IOracle.sol";
// Chainlink Aggregator
interface IAggregator {
function latestAnswer() external view returns (int256 answer);
}
contract ALCXOracle is IOracle {
using BoringMath for uint256; // Keep everything in uint256
IAggregator public constant alcxOracle = IAggregator(0x194a9AaF2e0b67c35915cD01101585A33Fe25CAa);
IAggregator public constant ethUSDOracle = IAggregator(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);
// Calculates the lastest exchange rate
// Uses both divide and multiply only for tokens not supported directly by Chainlink, for example MKR/USD
function _get() internal view returns (uint256) {
return 1e44 / uint256(alcxOracle.latestAnswer()).mul(uint256(ethUSDOracle.latestAnswer()));
}
// Get the latest exchange rate
/// @inheritdoc IOracle
function get(bytes calldata) public override returns (bool, uint256) {
return (true, _get());
}
// Check the last exchange rate without any state changes
/// @inheritdoc IOracle
function peek(bytes calldata) public view override returns (bool, uint256) {
return (true, _get());
}
// Check the current spot exchange rate without any state changes
/// @inheritdoc IOracle
function peekSpot(bytes calldata data) external view override returns (uint256 rate) {
(, rate) = peek(data);
}
/// @inheritdoc IOracle
function name(bytes calldata) public view override returns (string memory) {
return "ALCX Chainlink";
}
/// @inheritdoc IOracle
function symbol(bytes calldata) public view override returns (string memory) {
return "LINK/ALCX";
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "../interfaces/IOracle.sol";
// WARNING: This oracle is only for testing, please use PeggedOracle for a fixed value oracle
contract OracleMock is IOracle {
using BoringMath for uint256;
uint256 public rate;
bool public success;
constructor() public {
success = true;
}
function set(uint256 rate_) public {
// The rate can be updated.
rate = rate_;
}
function setSuccess(bool val) public {
success = val;
}
function getDataParameter() public pure returns (bytes memory) {
return abi.encode("0x0");
}
// Get the latest exchange rate
function get(bytes calldata) public override returns (bool, uint256) {
return (success, rate);
}
// Check the last exchange rate without any state changes
function peek(bytes calldata) public view override returns (bool, uint256) {
return (success, rate);
}
function peekSpot(bytes calldata) public view override returns (uint256) {
return rate;
}
function name(bytes calldata) public view override returns (string memory) {
return "Test";
}
function symbol(bytes calldata) public view override returns (string memory) {
return "TEST";
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@boringcrypto/boring-solidity/contracts/interfaces/IERC20.sol";
import "@sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol";
import "./IOracle.sol";
import "./ISwapper.sol";
interface IKashiPair {
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event LogAccrue(uint256 accruedAmount, uint256 feeFraction, uint64 rate, uint256 utilization);
event LogAddAsset(address indexed from, address indexed to, uint256 share, uint256 fraction);
event LogAddCollateral(address indexed from, address indexed to, uint256 share);
event LogBorrow(address indexed from, address indexed to, uint256 amount, uint256 part);
event LogExchangeRate(uint256 rate);
event LogFeeTo(address indexed newFeeTo);
event LogRemoveAsset(address indexed from, address indexed to, uint256 share, uint256 fraction);
event LogRemoveCollateral(address indexed from, address indexed to, uint256 share);
event LogRepay(address indexed from, address indexed to, uint256 amount, uint256 part);
event LogWithdrawFees(address indexed feeTo, uint256 feesEarnedFraction);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function accrue() external;
function accrueInfo()
external
view
returns (
uint64 interestPerBlock,
uint64 lastBlockAccrued,
uint128 feesEarnedFraction
);
function addAsset(
address to,
bool skim,
uint256 share
) external returns (uint256 fraction);
function addCollateral(
address to,
bool skim,
uint256 share
) external;
function allowance(address, address) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function asset() external view returns (IERC20);
function balanceOf(address) external view returns (uint256);
function bentoBox() external view returns (IBentoBoxV1);
function borrow(address to, uint256 amount) external returns (uint256 part, uint256 share);
function claimOwnership() external;
function collateral() external view returns (IERC20);
function cook(
uint8[] calldata actions,
uint256[] calldata values,
bytes[] calldata datas
) external payable returns (uint256 value1, uint256 value2);
function decimals() external view returns (uint8);
function exchangeRate() external view returns (uint256);
function feeTo() external view returns (address);
function getInitData(
IERC20 collateral_,
IERC20 asset_,
IOracle oracle_,
bytes calldata oracleData_
) external pure returns (bytes memory data);
function init(bytes calldata data) external payable;
function isSolvent(address user, bool open) external view returns (bool);
function liquidate(
address[] calldata users,
uint256[] calldata borrowParts,
address to,
ISwapper swapper,
bool open
) external;
function masterContract() external view returns (address);
function name() external view returns (string memory);
function nonces(address) external view returns (uint256);
function oracle() external view returns (IOracle);
function oracleData() external view returns (bytes memory);
function owner() external view returns (address);
function pendingOwner() external view returns (address);
function permit(
address owner_,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function removeAsset(address to, uint256 fraction) external returns (uint256 share);
function removeCollateral(address to, uint256 share) external;
function repay(
address to,
bool skim,
uint256 part
) external returns (uint256 amount);
function setFeeTo(address newFeeTo) external;
function setSwapper(ISwapper swapper, bool enable) external;
function swappers(ISwapper) external view returns (bool);
function symbol() external view returns (string memory);
function totalAsset() external view returns (uint128 elastic, uint128 base);
function totalBorrow() external view returns (uint128 elastic, uint128 base);
function totalCollateralShare() external view returns (uint256);
function totalSupply() external view returns (uint256);
function transfer(address to, uint256 amount) external returns (bool);
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
function transferOwnership(
address newOwner,
bool direct,
bool renounce
) external;
function updateExchangeRate() external returns (bool updated, uint256 rate);
function userBorrowPart(address) external view returns (uint256);
function userCollateralShare(address) external view returns (uint256);
function withdrawFees() external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
contract ExternalFunctionMock {
using BoringMath for uint256;
event Result(uint256 output);
function sum(uint256 a, uint256 b) external returns (uint256 c) {
c = a.add(b);
emit Result(c);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@boringcrypto/boring-solidity/contracts/ERC20.sol";
contract ERC20Mock is ERC20 {
uint256 public override totalSupply;
string public symbol;
string public name;
uint8 public decimals;
constructor(uint256 _initialAmount) public {
// Give the creator all initial tokens
balanceOf[msg.sender] = _initialAmount;
// Update total supply
totalSupply = _initialAmount;
}
}
//SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import "@boringcrypto/boring-solidity/contracts/BoringOwnable.sol";
// Modified from https://etherscan.io/address/0x6d903f6003cca6255d85cca4d3b5e5146dc33925#code and https://github.com/boringcrypto/dictator-dao/blob/main/contracts/DictatorDAO.sol#L225
contract MinimalTimeLock is BoringOwnable {
event QueueTransaction(bytes32 indexed txHash, address indexed target, uint256 value, bytes data, uint256 eta);
event CancelTransaction(bytes32 indexed txHash, address indexed target, uint256 value, bytes data);
event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint256 value, bytes data);
uint256 public constant GRACE_PERIOD = 14 days;
uint256 public constant DELAY = 2 days;
mapping(bytes32 => uint256) public queuedTransactions;
function queueTransaction(
address target,
uint256 value,
bytes memory data
) public onlyOwner returns (bytes32) {
bytes32 txHash = keccak256(abi.encode(target, value, data));
uint256 eta = block.timestamp + DELAY;
queuedTransactions[txHash] = eta;
emit QueueTransaction(txHash, target, value, data, eta);
return txHash;
}
function cancelTransaction(
address target,
uint256 value,
bytes memory data
) public onlyOwner {
bytes32 txHash = keccak256(abi.encode(target, value, data));
queuedTransactions[txHash] = 0;
emit CancelTransaction(txHash, target, value, data);
}
function executeTransaction(
address target,
uint256 value,
bytes memory data
) public onlyOwner payable returns (bytes memory) {
bytes32 txHash = keccak256(abi.encode(target, value, data));
uint256 eta = queuedTransactions[txHash];
require(block.timestamp >= eta, "Too early");
require(block.timestamp <= eta + GRACE_PERIOD, "Tx stale");
queuedTransactions[txHash] = 0;
// solium-disable-next-line security/no-call-value
(bool success, bytes memory returnData) = target.call{value: value}(data);
require(success, "Tx reverted :(");
emit ExecuteTransaction(txHash, target, value, data);
return returnData;
}
} | Swaps to a flexible amount, from an exact input amount | function swap(
address recipient,
uint256 shareToMin,
uint256 shareFrom
) public returns (uint256 extraShare, uint256 shareReturned) {
(uint256 amountFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom);
uint256 amountIntermediate;
{
uint256 amountFirst = ThreeCrypto.exchange(0, 2, amountFrom, 0, address(USDC_WFTM));
(address token0, ) = UniswapV2Library.sortTokens(address(USDC), address(WFTM));
(uint256 reserve0, uint256 reserve1, ) = USDC_WFTM.getReserves();
(reserve0, reserve1) = address(USDC) == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountIntermediate = getAmountOut(amountFirst, reserve0, reserve1);
(uint256 amount0Out, uint256 amount1Out) = address(USDC) == token0
? (uint256(0), amountIntermediate)
: (amountIntermediate, uint256(0));
USDC_WFTM.swap(amount0Out, amount1Out, address(BOO_FTM), new bytes(0));
}
uint256 amountIntermediate2;
{
(address token0, ) = UniswapV2Library.sortTokens(address(BOO), address(WFTM));
(uint256 reserve0, uint256 reserve1, ) = BOO_FTM.getReserves();
(reserve0, reserve1) = address(WFTM) == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountIntermediate2 = getAmountOut(amountIntermediate, reserve0, reserve1);
(uint256 amount0Out, uint256 amount1Out) = address(WFTM) == token0
? (uint256(0), amountIntermediate2)
: (amountIntermediate2, uint256(0));
BOO_FTM.swap(amount0Out, amount1Out, address(this), new bytes(0));
}
xBOO.enter(amountIntermediate2);
uint256 amountTo = xBOO.balanceOf(address(this));
xBOO.transfer(address(bentoBox), amountTo);
(, shareReturned) = bentoBox.deposit(xBOO, address(bentoBox), recipient, amountTo, 0);
extraShare = shareReturned.sub(shareToMin);
}
| 6,036,747 | [
1,
6050,
6679,
358,
279,
16600,
1523,
3844,
16,
628,
392,
5565,
810,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7720,
12,
203,
3639,
1758,
8027,
16,
203,
3639,
2254,
5034,
7433,
774,
2930,
16,
203,
3639,
2254,
5034,
7433,
1265,
203,
565,
262,
1071,
1135,
261,
11890,
5034,
2870,
9535,
16,
2254,
5034,
7433,
22360,
13,
288,
203,
203,
3639,
261,
11890,
5034,
3844,
1265,
16,
262,
273,
324,
29565,
3514,
18,
1918,
9446,
12,
49,
3445,
16,
1758,
12,
2211,
3631,
1758,
12,
2211,
3631,
374,
16,
7433,
1265,
1769,
203,
540,
203,
3639,
2254,
5034,
3844,
2465,
6785,
31,
203,
203,
3639,
288,
203,
5411,
2254,
5034,
3844,
3759,
273,
935,
992,
18048,
18,
16641,
12,
20,
16,
576,
16,
3844,
1265,
16,
374,
16,
1758,
12,
3378,
5528,
67,
59,
4464,
49,
10019,
203,
203,
5411,
261,
2867,
1147,
20,
16,
262,
273,
1351,
291,
91,
438,
58,
22,
9313,
18,
3804,
5157,
12,
2867,
12,
3378,
5528,
3631,
1758,
12,
59,
4464,
49,
10019,
203,
203,
5411,
261,
11890,
5034,
20501,
20,
16,
2254,
5034,
20501,
21,
16,
262,
273,
11836,
5528,
67,
59,
4464,
49,
18,
588,
607,
264,
3324,
5621,
203,
203,
5411,
261,
455,
6527,
20,
16,
20501,
21,
13,
273,
1758,
12,
3378,
5528,
13,
422,
1147,
20,
692,
261,
455,
6527,
20,
16,
20501,
21,
13,
294,
261,
455,
6527,
21,
16,
20501,
20,
1769,
203,
2398,
203,
5411,
3844,
2465,
6785,
273,
24418,
1182,
12,
8949,
3759,
16,
20501,
20,
16,
20501,
21,
1769,
203,
203,
5411,
261,
11890,
5034,
3844,
20,
1182,
16,
2254,
5034,
3844,
21,
1182,
13,
273,
2
] |
./full_match/42220/0x2A0d7fA85666441cDd9bFE2B4e42F413Ab4ce684/sources/contracts/core/PriceAware.sol | We iterate directly through call data to extract the values for symbols | function _readFromCallData(
bytes32[] memory symbols,
uint256 dataSize,
uint16 messageLength
) private pure returns (uint256[] memory) {
uint256[] memory values;
uint256 i;
uint256 j;
uint256 readyAssets;
bytes32 currentSymbol;
assembly {
let start := sub(calldatasize(), add(messageLength, 66))
values := msize()
mstore(values, mload(symbols))
mstore(0x40, add(add(values, 0x20), mul(mload(symbols), 0x20)))
for {
i := 0
i := add(i, 1)
currentSymbol := calldataload(add(start, mul(i, 64)))
for {
j := 0
j := add(j, 1)
if eq(mload(add(add(symbols, 32), mul(j, 32))), currentSymbol) {
mstore(
add(add(values, 32), mul(j, 32)),
calldataload(add(add(start, mul(i, 64)), 32))
)
readyAssets := add(readyAssets, 1)
}
if eq(readyAssets, mload(symbols)) {
i := dataSize
}
}
}
}
return (values);
}
| 16,312,538 | [
1,
3218,
7401,
5122,
3059,
745,
501,
358,
2608,
326,
924,
364,
7963,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
389,
896,
1265,
1477,
751,
12,
203,
565,
1731,
1578,
8526,
3778,
7963,
16,
203,
565,
2254,
5034,
30216,
16,
203,
565,
2254,
2313,
883,
1782,
203,
225,
262,
3238,
16618,
1135,
261,
11890,
5034,
8526,
3778,
13,
288,
203,
565,
2254,
5034,
8526,
3778,
924,
31,
203,
565,
2254,
5034,
277,
31,
203,
565,
2254,
5034,
525,
31,
203,
565,
2254,
5034,
5695,
10726,
31,
203,
565,
1731,
1578,
783,
5335,
31,
203,
203,
565,
19931,
288,
203,
1377,
2231,
787,
519,
720,
12,
1991,
13178,
554,
9334,
527,
12,
2150,
1782,
16,
22342,
3719,
203,
203,
1377,
924,
519,
312,
1467,
1435,
203,
1377,
312,
2233,
12,
2372,
16,
312,
945,
12,
15536,
3719,
203,
1377,
312,
2233,
12,
20,
92,
7132,
16,
527,
12,
1289,
12,
2372,
16,
374,
92,
3462,
3631,
14064,
12,
81,
945,
12,
15536,
3631,
374,
92,
3462,
20349,
203,
203,
1377,
364,
288,
203,
3639,
277,
519,
374,
203,
3639,
277,
519,
527,
12,
77,
16,
404,
13,
203,
3639,
783,
5335,
519,
745,
72,
3145,
6189,
12,
1289,
12,
1937,
16,
14064,
12,
77,
16,
5178,
20349,
203,
203,
3639,
364,
288,
203,
1850,
525,
519,
374,
203,
1850,
525,
519,
527,
12,
78,
16,
404,
13,
203,
1850,
309,
7555,
12,
81,
945,
12,
1289,
12,
1289,
12,
15536,
16,
3847,
3631,
14064,
12,
78,
16,
3847,
3719,
3631,
783,
5335,
13,
288,
203,
5411,
312,
2233,
12,
203,
2868,
527,
12,
1289,
12,
2372,
16,
3847,
3631,
14064,
12,
78,
16,
2
] |
pragma solidity ^0.5.16;
// Inheritance
import "./FuturesMarketBase.sol";
/**
* A mixin that implements vairous useful views that are used externally but
* aren't used inside the core contract (so don't need to clutter the contract file)
*/
contract MixinFuturesViews is FuturesMarketBase {
/*
* Sizes of the long and short sides of the market (in sUSD)
*/
function marketSizes() public view returns (uint long, uint short) {
int size = int(marketSize);
int skew = marketSkew;
return (_abs(size.add(skew).div(2)), _abs(size.sub(skew).div(2)));
}
/*
* The debt contributed by this market to the overall system.
* The total market debt is equivalent to the sum of remaining margins in all open positions.
*/
function marketDebt() external view returns (uint debt, bool invalid) {
(uint price, bool isInvalid) = assetPrice();
return (_marketDebt(price), isInvalid);
}
/*
* The current funding rate as determined by the market skew; this is returned as a percentage per day.
* If this is positive, shorts pay longs, if it is negative, longs pay shorts.
*/
function currentFundingRate() external view returns (int) {
(uint price, ) = assetPrice();
return _currentFundingRate(price);
}
/*
* The funding per base unit accrued since the funding rate was last recomputed, which has not yet
* been persisted in the funding sequence.
*/
function unrecordedFunding() external view returns (int funding, bool invalid) {
(uint price, bool isInvalid) = assetPrice();
return (_unrecordedFunding(price), isInvalid);
}
/*
* The number of entries in the funding sequence.
*/
function fundingSequenceLength() external view returns (uint) {
return fundingSequence.length;
}
/*
* The notional value of a position is its size multiplied by the current price. Margin and leverage are ignored.
*/
function notionalValue(address account) external view returns (int value, bool invalid) {
(uint price, bool isInvalid) = assetPrice();
return (_notionalValue(positions[account].size, price), isInvalid);
}
/*
* The PnL of a position is the change in its notional value. Funding is not taken into account.
*/
function profitLoss(address account) external view returns (int pnl, bool invalid) {
(uint price, bool isInvalid) = assetPrice();
return (_profitLoss(positions[account], price), isInvalid);
}
/*
* The funding accrued in a position since it was opened; this does not include PnL.
*/
function accruedFunding(address account) external view returns (int funding, bool invalid) {
(uint price, bool isInvalid) = assetPrice();
return (_accruedFunding(positions[account], price), isInvalid);
}
/*
* The initial margin plus profit and funding; returns zero balance if losses exceed the initial margin.
*/
function remainingMargin(address account) external view returns (uint marginRemaining, bool invalid) {
(uint price, bool isInvalid) = assetPrice();
return (_remainingMargin(positions[account], price), isInvalid);
}
/*
* The approximate amount of margin the user may withdraw given their current position; this underestimates the
* true value slightly.
*/
function accessibleMargin(address account) external view returns (uint marginAccessible, bool invalid) {
(uint price, bool isInvalid) = assetPrice();
return (_accessibleMargin(positions[account], price), isInvalid);
}
/*
* The price at which a position is subject to liquidation; otherwise the price at which the user's remaining
* margin has run out. When they have just enough margin left to pay a liquidator, then they are liquidated.
* If a position is long, then it is safe as long as the current price is above the liquidation price; if it is
* short, then it is safe whenever the current price is below the liquidation price.
* A position's accurate liquidation price can move around slightly due to accrued funding.
*/
function liquidationPrice(address account) external view returns (uint price, bool invalid) {
(uint aPrice, bool isInvalid) = assetPrice();
uint liqPrice = _approxLiquidationPrice(positions[account], aPrice);
return (liqPrice, isInvalid);
}
/**
* The fee paid to liquidator in the event of successful liquidation of an account at current price.
* Returns 0 if account cannot be liquidated right now.
* @param account address of the trader's account
* @return fee that will be paid for liquidating the account if it can be liquidated
* in sUSD fixed point decimal units or 0 if account is not liquidatable.
*/
function liquidationFee(address account) external view returns (uint) {
(uint price, bool invalid) = assetPrice();
if (!invalid && _canLiquidate(positions[account], price)) {
return _liquidationFee(int(positions[account].size), price);
} else {
// theoretically we can calculate a value, but this value is always incorrect because
// it's for a price at which liquidation cannot happen - so is misleading, because
// it won't be paid, and what will be paid is a different fee (for a different price)
return 0;
}
}
/*
* True if and only if a position is ready to be liquidated.
*/
function canLiquidate(address account) external view returns (bool) {
(uint price, bool invalid) = assetPrice();
return !invalid && _canLiquidate(positions[account], price);
}
/*
* Reports the fee for submitting an order of a given size. Orders that increase the skew will be more
* expensive than ones that decrease it. Dynamic fee is added according to the recent volatility
* according to SIP-184.
* @param sizeDelta size of the order in baseAsset units (negative numbers for shorts / selling)
* @return fee in sUSD decimal, and invalid boolean flag for invalid rates or dynamic fee that is
* too high due to recent volatility.
*/
function orderFee(int sizeDelta) external view returns (uint fee, bool invalid) {
(uint price, bool isInvalid) = assetPrice();
(uint dynamicFeeRate, bool tooVolatile) = _dynamicFeeRate();
TradeParams memory params =
TradeParams({
sizeDelta: sizeDelta,
price: price,
takerFee: _takerFee(marketKey),
makerFee: _makerFee(marketKey),
trackingCode: bytes32("")
});
return (_orderFee(params, dynamicFeeRate), isInvalid || tooVolatile);
}
/*
* Returns all new position details if a given order from `sender` was confirmed at the current price.
*/
function postTradeDetails(int sizeDelta, address sender)
external
view
returns (
uint margin,
int size,
uint price,
uint liqPrice,
uint fee,
Status status
)
{
bool invalid;
(price, invalid) = assetPrice();
if (invalid) {
return (0, 0, 0, 0, 0, Status.InvalidPrice);
}
TradeParams memory params =
TradeParams({
sizeDelta: sizeDelta,
price: price,
takerFee: _takerFee(marketKey),
makerFee: _makerFee(marketKey),
trackingCode: bytes32("")
});
(Position memory newPosition, uint fee_, Status status_) = _postTradeDetails(positions[sender], params);
liqPrice = _approxLiquidationPrice(newPosition, newPosition.lastPrice);
return (newPosition.margin, newPosition.size, newPosition.lastPrice, liqPrice, fee_, status_);
}
/// helper methods calculates the approximate liquidation price
function _approxLiquidationPrice(Position memory position, uint currentPrice) internal view returns (uint) {
int positionSize = int(position.size);
// short circuit
if (positionSize == 0) {
return 0;
}
// price = lastPrice + (liquidationMargin - margin) / positionSize - netAccrued
int fundingPerUnit = _netFundingPerUnit(position.lastFundingIndex, currentPrice);
// minimum margin beyond which position can be liqudiated
uint liqMargin = _liquidationMargin(positionSize, currentPrice);
// A position can be liquidated whenever:
// remainingMargin <= liquidationMargin
// Hence, expanding the definition of remainingMargin the exact price
// at which a position can first be liquidated is:
// margin + profitLoss + funding = liquidationMargin
// substitute with: profitLoss = (price - last-price) * positionSize
// and also with: funding = netFundingPerUnit * positionSize
// we get: margin + (price - last-price) * positionSize + netFundingPerUnit * positionSize = liquidationMargin
// moving around: price = lastPrice + (liquidationMargin - margin) / positionSize - netFundingPerUnit
int result =
int(position.lastPrice).add(int(liqMargin).sub(int(position.margin)).divideDecimal(positionSize)).sub(
fundingPerUnit
);
// If the user has leverage less than 1, their liquidation price may actually be negative; return 0 instead.
return uint(_max(0, result));
}
}
| If the user has leverage less than 1, their liquidation price may actually be negative; return 0 instead. | return uint(_max(0, result));
| 12,548,826 | [
1,
2047,
326,
729,
711,
884,
5682,
5242,
2353,
404,
16,
3675,
4501,
26595,
367,
6205,
2026,
6013,
506,
6092,
31,
327,
374,
3560,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
327,
2254,
24899,
1896,
12,
20,
16,
563,
10019,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "./INFTree.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
// ,@@@@@@@,
// ,,,. ,@@@@@@/@@, .oo8888o.
// ,&%%&%&&%,@@@@@/@@@@@@,8888\88/8o
// ,%&\%&&%&&%,@@@\@@@/@@@88\88888/88'
// %&&%&%&/%&&%@@\@@/ /@@@88888\88888'
// %&&%/ %&%%&&@@\ V /@@' `88\8 `/88'
// `&%\ ` /%&' |.| \ '|8'
// |o| | | | |
// |.| | | | |
// \\/ ._\//_/__/ ,\_//__\\/. \_//__/_
/**
@title NFTreeFactory
@author Lorax + Bebop
@notice Enables the purchase/minting of Genesis Colletion NFTrees.
*/
contract NFTreeFactory is Ownable {
INFTree nftree;
address treasury;
uint256[] levels;
string[] coins;
bool public isLocked;
mapping(uint256 => Level) levelMap;
mapping(string => Coin) coinMap;
struct Level {
bool isValid;
uint256 cost;
uint256 carbonValue;
uint256 numMinted;
string tokenURI;
}
struct Coin {
bool isValid;
IERC20 coinContract;
}
/**
@dev Sets values for {nftree} and {treasury}.
@param _nftreeAddress NFTree contract address.
@param _treasuryAddress NFTrees vault wallet address.
*/
constructor(address _nftreeAddress, address _treasuryAddress)
{
nftree = INFTree(_nftreeAddress);
treasury = _treasuryAddress;
isLocked = false;
}
/**
@dev Locks/unlocks minting.
*/
function toggleLock() external onlyOwner {
isLocked = !isLocked;
}
/**
@dev Updates {nftree} contract address.
@param _nftreeAddress New NFTree contract address.
*/
function setNFTreeContract(address _nftreeAddress) external {
nftree = INFTree(_nftreeAddress);
}
/**
@dev Retrieves current NFTree contract instance.
@return INFTree {nftree}.
*/
function getNFTreeContract() external view returns(INFTree) {
return nftree;
}
/**
@dev Updates {treasury} wallet address.
@param _address New NFTrees vault wallet address.
*/
function setTreasury(address _address) external onlyOwner {
treasury = _address;
}
/**
@dev Retrieves current NFtree vault wallet address.
@return address {treasury}.
*/
function getTreasury() external view onlyOwner returns(address) {
return treasury;
}
/**
@dev Creates new Level instance and maps to the {levels} array. If the level already exists,
the function updates the struct but does not push to the levels array.
@param _level Carbon value.
@param _cost Cost of level.
@param _tokenURI IPFS hash of token metadata.
*/
function addLevel(uint256 _level, uint256 _cost, string memory _tokenURI) external onlyOwner {
if (!levelMap[_level].isValid) {
levels.push(_level);
}
levelMap[_level] = Level(true, _cost, _level, 0, _tokenURI);
}
/**
@dev Deletes Level instance and removes from {levels} array.
@param _level Carbon value of level to be removed.
requirements:
- {_level} must be a valid level.
*/
function removeLevel(uint256 _level) external onlyOwner {
require(levelMap[_level].isValid, 'Not a valid level.');
uint256 index;
for (uint256 i = 0; i < levels.length; i++) {
if (levels[i] == _level){
index = i;
}
}
levels[index] = levels[levels.length - 1];
levels.pop();
delete levelMap[_level];
}
/**
@dev Retrieves variables in that carbon value's Level struct.
@param _level Carbon value of level to be returned.
@return uint256 {levelMap[_level].cost}.
@return uint256 {levelMap[_level].carbonValue}.
@return uint256 {levelMap[_level].numMinted}.
requirements:
- {_level} must be a valid level.
*/
function getLevel(uint256 _level) external view returns(uint256, uint256, uint256, string memory) {
require(levelMap[_level].isValid, 'Not a valid level');
return (levelMap[_level].carbonValue, levelMap[_level].cost, levelMap[_level].numMinted, levelMap[_level].tokenURI);
}
/**
@dev Retrieves array of valid levels.
@return uint256[] {levels}.
*/
function getValidLevels() external view returns(uint256[] memory) {
return sort_array(levels);
}
/**
@dev Creates new Coin instance and maps to the {coins} array.
@param _coin Coin name.
@param _address Contract address for the coin.
Requirements:
- {_coin} must not already be a valid coin.
*/
function addCoin(string memory _coin, address _address) external onlyOwner {
require(!coinMap[_coin].isValid, 'Already a valid coin.');
coins.push(_coin);
coinMap[_coin] = Coin(true, IERC20(_address));
}
/**
@dev Deletes Coin instance and removes from {coins} array.
@param _coin Name of coin.
requirements:
- {_coin} must be a valid coin.
*/
function removeCoin(string memory _coin) external onlyOwner {
require(coinMap[_coin].isValid, 'Not a valid coin.');
uint256 index;
for (uint256 i = 0; i < coins.length; i++) {
if (keccak256(abi.encodePacked(coins[i])) == keccak256(abi.encodePacked(_coin))) {
index = i;
}
}
coins[index] = coins[coins.length - 1];
coins.pop();
delete coinMap[_coin];
}
/**
@dev Retrieves array of valid coins.
@return uint256[] {coins}.
*/
function getValidCoins() external view returns(string[] memory) {
return coins;
}
/**
@dev Mints NFTree to {msg.sender} and transfers payment to {treasury}.
@param _tonnes Carbon value of NFTree to purchase.
@param _amount Dollar value to be transferred to {treasury} from {msg.sender}.
@param _coin Coin to be used to purchase.
Requirements:
- {isLocked} must be false, mint lock must be off.
- {msg.sender} can not be the zero address.
- {_level} must be a valid level.
- {_coin} must be a valid coin.
- {_amount} must be creater than the cost to mint that level.
- {msg.sender} must have a balance of {_coin} that is greater than or equal to {_amount}.
- Allowance of {address(this)} to spend {msg.sender}'s {_coin} must be greater than or equal to {_amount}.
*/
function mintNFTree(uint256 _tonnes, uint256 _amount, string memory _coin) external {
// check requirements
require(!isLocked, 'Minting is locked.');
require(msg.sender != address(0) && msg.sender != address(this), 'Sending from zero address.');
require(levelMap[_tonnes].isValid, 'Not a valid level.');
require(coinMap[_coin].isValid, 'Not a valid coin.');
require(_amount >= levelMap[_tonnes].cost, 'Not enough value.');
require(coinMap[_coin].coinContract.balanceOf(msg.sender) >= _amount, 'Not enough balance.');
require(coinMap[_coin].coinContract.allowance(msg.sender, address(this)) >= _amount, 'Not enough allowance.');
// transfer tokens
coinMap[_coin].coinContract.transferFrom(msg.sender, treasury, _amount * 1e18);
nftree.mintNFTree(msg.sender, levelMap[_tonnes].tokenURI, _tonnes, "Genesis");
// log purchase
levelMap[_tonnes].numMinted += 1;
}
/**
@dev Sorts array.
@return uint256[] {arr}.
*/
function sort_array(uint256[] memory arr) private pure returns (uint256[] memory) {
uint256 l = arr.length;
for(uint i = 0; i < l; i++) {
for(uint j = i+1; j < l ;j++) {
if(arr[i] > arr[j]) {
uint256 temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
interface INFTree is IERC721{
/**
@dev see {NFTree-mintNFTree}
*/
function mintNFTree(address _recipient, string memory _tokenURI, uint256 _carbonOffset, string memory _collection) external;
}
// 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 "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../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;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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;
}
} | / check requirements transfer tokens log purchase | function mintNFTree(uint256 _tonnes, uint256 _amount, string memory _coin) external {
require(!isLocked, 'Minting is locked.');
require(msg.sender != address(0) && msg.sender != address(this), 'Sending from zero address.');
require(levelMap[_tonnes].isValid, 'Not a valid level.');
require(coinMap[_coin].isValid, 'Not a valid coin.');
require(_amount >= levelMap[_tonnes].cost, 'Not enough value.');
require(coinMap[_coin].coinContract.balanceOf(msg.sender) >= _amount, 'Not enough balance.');
require(coinMap[_coin].coinContract.allowance(msg.sender, address(this)) >= _amount, 'Not enough allowance.');
coinMap[_coin].coinContract.transferFrom(msg.sender, treasury, _amount * 1e18);
nftree.mintNFTree(msg.sender, levelMap[_tonnes].tokenURI, _tonnes, "Genesis");
levelMap[_tonnes].numMinted += 1;
}
| 6,221,423 | [
1,
19,
866,
8433,
7412,
2430,
613,
23701,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
312,
474,
26473,
2471,
12,
11890,
5034,
389,
1917,
23712,
16,
2254,
5034,
389,
8949,
16,
533,
3778,
389,
12645,
13,
3903,
288,
203,
3639,
2583,
12,
5,
291,
8966,
16,
296,
49,
474,
310,
353,
8586,
1093,
1769,
203,
3639,
2583,
12,
3576,
18,
15330,
480,
1758,
12,
20,
13,
597,
1234,
18,
15330,
480,
1758,
12,
2211,
3631,
296,
16322,
628,
3634,
1758,
1093,
1769,
7010,
3639,
2583,
12,
2815,
863,
63,
67,
1917,
23712,
8009,
26810,
16,
296,
1248,
279,
923,
1801,
1093,
1769,
203,
3639,
2583,
12,
12645,
863,
63,
67,
12645,
8009,
26810,
16,
296,
1248,
279,
923,
13170,
1093,
1769,
203,
3639,
2583,
24899,
8949,
1545,
1801,
863,
63,
67,
1917,
23712,
8009,
12398,
16,
296,
1248,
7304,
460,
1093,
1769,
203,
3639,
2583,
12,
12645,
863,
63,
67,
12645,
8009,
12645,
8924,
18,
12296,
951,
12,
3576,
18,
15330,
13,
1545,
389,
8949,
16,
296,
1248,
7304,
11013,
1093,
1769,
203,
3639,
2583,
12,
12645,
863,
63,
67,
12645,
8009,
12645,
8924,
18,
5965,
1359,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3719,
1545,
389,
8949,
16,
296,
1248,
7304,
1699,
1359,
1093,
1769,
203,
540,
203,
3639,
13170,
863,
63,
67,
12645,
8009,
12645,
8924,
18,
13866,
1265,
12,
3576,
18,
15330,
16,
9787,
345,
22498,
16,
389,
8949,
380,
404,
73,
2643,
1769,
203,
3639,
290,
1222,
992,
18,
81,
474,
26473,
2471,
12,
3576,
18,
15330,
16,
1801,
863,
63,
67,
1917,
23712,
8009,
2316,
3098,
16,
389,
1917,
23712,
16,
2
] |
./full_match/42/0x9978Bc141d6fb9E9b3E0E63EfEAaa359c8355081/sources/contracts/FRToken.sol | We calculate the new borrower and liquidator token balances, failing on underflow/overflow: borrowerTokensNew = accountTokens[borrower] - seizeTokens liquidatorTokensNew = accountTokens[liquidator] + seizeTokens/ | borrowerTokensNew = subUInt(accountTokens[borrower], seizeTokens);
| 16,224,231 | [
1,
3218,
4604,
326,
394,
29759,
264,
471,
4501,
26595,
639,
1147,
324,
26488,
16,
21311,
603,
3613,
2426,
19,
11512,
30,
225,
29759,
264,
5157,
1908,
273,
2236,
5157,
63,
70,
15318,
264,
65,
300,
695,
554,
5157,
225,
4501,
26595,
639,
5157,
1908,
273,
2236,
5157,
63,
549,
26595,
639,
65,
397,
695,
554,
5157,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
29759,
264,
5157,
1908,
273,
720,
14342,
12,
4631,
5157,
63,
70,
15318,
264,
6487,
695,
554,
5157,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {IRealmFacet} from "./interfaces/IRealmFacet.sol";
import "./libraries/LibSignature.sol";
import "hardhat/console.sol";
contract TransferPortals is Ownable, IERC721Receiver {
// contract address for voucher erc1155
address voucherContract;
address erc721TokenAddress;
uint256 voucherId;
bytes backendPubKey;
bool isPaused = false;
event VoucherContractSet(address voucherContract);
event TokenAddressSet(address tokenAddress);
constructor(
address _voucherContract,
address _tokenAddress,
uint256 _voucherId,
bytes memory _backendPubKey
) {
voucherContract = _voucherContract;
erc721TokenAddress = _tokenAddress;
voucherId = _voucherId;
backendPubKey = _backendPubKey;
}
function setVoucherContract(address _voucherContract) external onlyOwner {
voucherContract = _voucherContract;
emit VoucherContractSet(voucherContract);
}
function setTokenAddress(address _tokenAddress) external onlyOwner {
erc721TokenAddress = _tokenAddress;
emit TokenAddressSet(_tokenAddress);
}
function togglePause(bool _pause) external onlyOwner {
isPaused = _pause;
}
function paused() external view returns (bool) {
return isPaused;
}
function transferERC721FromVoucher(uint256 _amount, bytes memory _signature) external {
address sender = msg.sender;
require(tx.origin == sender, "Not authorized, fren");
uint256 voucherBalance = IERC1155(voucherContract).balanceOf(sender, voucherId);
//check signature
bytes32 messageHash = keccak256(abi.encodePacked(msg.sender, _amount, voucherBalance));
require(LibSignature.isValid(messageHash, _signature, backendPubKey), "Not authorized, fren");
require(!isPaused, "Portal transfer is paused");
require(_amount <= 20, "Can't mint more than 20 at once");
require(voucherBalance >= _amount, "Not enough ERC1155");
uint256 balance = IERC721(erc721TokenAddress).balanceOf(address(this));
require(balance >= _amount, "Not enough Portals");
// burn erc1155 first
IERC1155(voucherContract).safeTransferFrom(sender, address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF), voucherId, _amount, new bytes(0));
transferPortals(sender, _amount);
}
//If portals need to be withdrawn
function withdrawPortals(uint256 _amount) external onlyOwner {
address sender = msg.sender; //LibMeta.msgSender();
uint256 balance = IERC721(erc721TokenAddress).balanceOf(address(this));
require(balance >= _amount, "Not enough Portals");
transferPortals(sender, _amount);
}
function onERC721Received(
address,
address _from,
uint256,
bytes calldata
) external view override returns (bytes4) {
require(_from == owner(), "Can only receive from contract owner");
return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"));
}
function transferPortals(address _sender, uint256 _amount) internal {
uint256 transferredAmount;
uint256 j;
//Get all the tokenIds of this contract (shouldn't revert)
uint256[] memory tokenIds = IRealmFacet(erc721TokenAddress).tokenIdsOfOwner(address(this));
//Loop through the tokenIds and transfer to sender
do {
uint256 tokenId = tokenIds[j];
IERC721(erc721TokenAddress).safeTransferFrom(address(this), _sender, tokenId);
transferredAmount++;
j++;
} while (transferredAmount < _amount);
}
}
| Get all the tokenIds of this contract (shouldn't revert)Loop through the tokenIds and transfer to sender | function transferPortals(address _sender, uint256 _amount) internal {
uint256 transferredAmount;
uint256 j;
uint256[] memory tokenIds = IRealmFacet(erc721TokenAddress).tokenIdsOfOwner(address(this));
do {
uint256 tokenId = tokenIds[j];
IERC721(erc721TokenAddress).safeTransferFrom(address(this), _sender, tokenId);
transferredAmount++;
j++;
} while (transferredAmount < _amount);
}
| 12,888,055 | [
1,
967,
777,
326,
1147,
2673,
434,
333,
6835,
261,
13139,
82,
1404,
15226,
13,
6452,
3059,
326,
1147,
2673,
471,
7412,
358,
5793,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7412,
2617,
1031,
12,
2867,
389,
15330,
16,
2254,
5034,
389,
8949,
13,
2713,
288,
203,
3639,
2254,
5034,
906,
4193,
6275,
31,
203,
3639,
2254,
5034,
525,
31,
203,
203,
3639,
2254,
5034,
8526,
3778,
1147,
2673,
273,
467,
22545,
11137,
12,
12610,
27,
5340,
1345,
1887,
2934,
2316,
2673,
951,
5541,
12,
2867,
12,
2211,
10019,
203,
203,
3639,
741,
288,
203,
5411,
2254,
5034,
1147,
548,
273,
1147,
2673,
63,
78,
15533,
203,
5411,
467,
654,
39,
27,
5340,
12,
12610,
27,
5340,
1345,
1887,
2934,
4626,
5912,
1265,
12,
2867,
12,
2211,
3631,
389,
15330,
16,
1147,
548,
1769,
203,
5411,
906,
4193,
6275,
9904,
31,
203,
203,
5411,
525,
9904,
31,
203,
3639,
289,
1323,
261,
2338,
4193,
6275,
411,
389,
8949,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
import "../../TransferManager/ITransferManager.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
contract LockUpTransferManager is ITransferManager {
using SafeMath for uint256;
// permission definition
bytes32 public constant ADMIN = "ADMIN";
// a per-user lockup
struct LockUp {
uint256 lockupAmount; // Amount to be locked
uint256 startTime; // when this lockup starts (seconds)
uint256 lockUpPeriodSeconds; // total period of lockup (seconds)
uint256 releaseFrequencySeconds; // how often to release a tranche of tokens (seconds)
}
// mapping use to store the lockup details corresponds to lockup name
mapping (bytes32 => LockUp) public lockups;
// mapping user addresses to an array of lockups name for that user
mapping (address => bytes32[]) internal userToLockups;
// get list of the addresses for a particular lockupName
mapping (bytes32 => address[]) internal lockupToUsers;
// holds lockup index corresponds to user address. userAddress => lockupName => lockupIndex
mapping (address => mapping(bytes32 => uint256)) internal userToLockupIndex;
// holds the user address index corresponds to the lockup. lockupName => userAddress => userIndex
mapping (bytes32 => mapping(address => uint256)) internal lockupToUserIndex;
bytes32[] lockupArray;
event AddLockUpToUser(
address indexed _userAddress,
bytes32 indexed _lockupName
);
event RemoveLockUpFromUser(
address indexed _userAddress,
bytes32 indexed _lockupName
);
event ModifyLockUpType(
uint256 _lockupAmount,
uint256 _startTime,
uint256 _lockUpPeriodSeconds,
uint256 _releaseFrequencySeconds,
bytes32 indexed _lockupName
);
event AddNewLockUpType(
bytes32 indexed _lockupName,
uint256 _lockupAmount,
uint256 _startTime,
uint256 _lockUpPeriodSeconds,
uint256 _releaseFrequencySeconds
);
event RemoveLockUpType(bytes32 indexed _lockupName);
/**
* @notice Constructor
* @param _securityToken Address of the security token
* @param _polyAddress Address of the polytoken
*/
constructor (address _securityToken, address _polyAddress)
public
Module(_securityToken, _polyAddress)
{
}
/** @notice Used to verify the transfer transaction and prevent locked up tokens from being transferred
* @param _from Address of the sender
* @param _amount The amount of tokens to transfer
*/
function verifyTransfer(address _from, address /* _to*/, uint256 _amount, bytes /* _data */, bool /*_isTransfer*/) public returns(Result) {
// only attempt to verify the transfer if the token is unpaused, this isn't a mint txn, and there exists a lockup for this user
if (!paused && _from != address(0) && userToLockups[_from].length != 0) {
// check if this transfer is valid
return _checkIfValidTransfer(_from, _amount);
}
return Result.NA;
}
/**
* @notice Use to add the new lockup type
* @param _lockupAmount Amount of tokens that need to lock.
* @param _startTime When this lockup starts (seconds)
* @param _lockUpPeriodSeconds Total period of lockup (seconds)
* @param _releaseFrequencySeconds How often to release a tranche of tokens (seconds)
* @param _lockupName Name of the lockup
*/
function addNewLockUpType(
uint256 _lockupAmount,
uint256 _startTime,
uint256 _lockUpPeriodSeconds,
uint256 _releaseFrequencySeconds,
bytes32 _lockupName
)
public
withPerm(ADMIN)
{
_addNewLockUpType(
_lockupAmount,
_startTime,
_lockUpPeriodSeconds,
_releaseFrequencySeconds,
_lockupName
);
}
/**
* @notice Use to add the new lockup type
* @param _lockupAmounts Array of amount of tokens that need to lock.
* @param _startTimes Array of startTimes when this lockup starts (seconds)
* @param _lockUpPeriodsSeconds Array of total period of lockup (seconds)
* @param _releaseFrequenciesSeconds Array of how often to release a tranche of tokens (seconds)
* @param _lockupNames Array of names of the lockup
*/
function addNewLockUpTypeMulti(
uint256[] _lockupAmounts,
uint256[] _startTimes,
uint256[] _lockUpPeriodsSeconds,
uint256[] _releaseFrequenciesSeconds,
bytes32[] _lockupNames
)
external
withPerm(ADMIN)
{
require(
_lockupNames.length == _lockUpPeriodsSeconds.length && /*solium-disable-line operator-whitespace*/
_lockupNames.length == _releaseFrequenciesSeconds.length && /*solium-disable-line operator-whitespace*/
_lockupNames.length == _startTimes.length && /*solium-disable-line operator-whitespace*/
_lockupNames.length == _lockupAmounts.length,
"Input array length mismatch"
);
for (uint256 i = 0; i < _lockupNames.length; i++) {
_addNewLockUpType(
_lockupAmounts[i],
_startTimes[i],
_lockUpPeriodsSeconds[i],
_releaseFrequenciesSeconds[i],
_lockupNames[i]
);
}
}
/**
* @notice Add the lockup to a user
* @param _userAddress Address of the user
* @param _lockupName Name of the lockup
*/
function addLockUpByName(
address _userAddress,
bytes32 _lockupName
)
public
withPerm(ADMIN)
{
_addLockUpByName(_userAddress, _lockupName);
}
/**
* @notice Add the lockup to a user
* @param _userAddresses Address of the user
* @param _lockupNames Name of the lockup
*/
function addLockUpByNameMulti(
address[] _userAddresses,
bytes32[] _lockupNames
)
external
withPerm(ADMIN)
{
require(_userAddresses.length == _lockupNames.length, "Length mismatch");
for (uint256 i = 0; i < _userAddresses.length; i++) {
_addLockUpByName(_userAddresses[i], _lockupNames[i]);
}
}
/**
* @notice Lets the admin create a volume restriction lockup for a given address.
* @param _userAddress Address of the user whose tokens should be locked up
* @param _lockupAmount Amount of tokens that need to lock.
* @param _startTime When this lockup starts (seconds)
* @param _lockUpPeriodSeconds Total period of lockup (seconds)
* @param _releaseFrequencySeconds How often to release a tranche of tokens (seconds)
* @param _lockupName Name of the lockup
*/
function addNewLockUpToUser(
address _userAddress,
uint256 _lockupAmount,
uint256 _startTime,
uint256 _lockUpPeriodSeconds,
uint256 _releaseFrequencySeconds,
bytes32 _lockupName
)
external
withPerm(ADMIN)
{
_addNewLockUpToUser(
_userAddress,
_lockupAmount,
_startTime,
_lockUpPeriodSeconds,
_releaseFrequencySeconds,
_lockupName
);
}
/**
* @notice Lets the admin create multiple volume restriction lockups for multiple given addresses.
* @param _userAddresses Array of address of the user whose tokens should be locked up
* @param _lockupAmounts Array of the amounts that need to be locked for the different addresses.
* @param _startTimes Array of When this lockup starts (seconds)
* @param _lockUpPeriodsSeconds Array of total periods of lockup (seconds)
* @param _releaseFrequenciesSeconds Array of how often to release a tranche of tokens (seconds)
* @param _lockupNames Array of names of the lockup
*/
function addNewLockUpToUserMulti(
address[] _userAddresses,
uint256[] _lockupAmounts,
uint256[] _startTimes,
uint256[] _lockUpPeriodsSeconds,
uint256[] _releaseFrequenciesSeconds,
bytes32[] _lockupNames
)
public
withPerm(ADMIN)
{
require(
_userAddresses.length == _lockUpPeriodsSeconds.length && /*solium-disable-line operator-whitespace*/
_userAddresses.length == _releaseFrequenciesSeconds.length && /*solium-disable-line operator-whitespace*/
_userAddresses.length == _startTimes.length && /*solium-disable-line operator-whitespace*/
_userAddresses.length == _lockupAmounts.length &&
_userAddresses.length == _lockupNames.length,
"Input array length mismatch"
);
for (uint256 i = 0; i < _userAddresses.length; i++) {
_addNewLockUpToUser(_userAddresses[i], _lockupAmounts[i], _startTimes[i], _lockUpPeriodsSeconds[i], _releaseFrequenciesSeconds[i], _lockupNames[i]);
}
}
/**
* @notice Lets the admin remove a user's lock up
* @param _userAddress Address of the user whose tokens are locked up
* @param _lockupName Name of the lockup need to be removed.
*/
function removeLockUpFromUser(address _userAddress, bytes32 _lockupName) external withPerm(ADMIN) {
_removeLockUpFromUser(_userAddress, _lockupName);
}
/**
* @notice Used to remove the lockup type
* @param _lockupName Name of the lockup
*/
function removeLockupType(bytes32 _lockupName) external withPerm(ADMIN) {
_removeLockupType(_lockupName);
}
/**
* @notice Used to remove the multiple lockup type
* @param _lockupNames Array of the lockup names.
*/
function removeLockupTypeMulti(bytes32[] _lockupNames) external withPerm(ADMIN) {
for (uint256 i = 0; i < _lockupNames.length; i++) {
_removeLockupType(_lockupNames[i]);
}
}
/**
* @notice Use to remove the lockup for multiple users
* @param _userAddresses Array of addresses of the user whose tokens are locked up
* @param _lockupNames Array of the names of the lockup that needs to be removed.
*/
function removeLockUpFromUserMulti(address[] _userAddresses, bytes32[] _lockupNames) external withPerm(ADMIN) {
require(_userAddresses.length == _lockupNames.length, "Array length mismatch");
for (uint256 i = 0; i < _userAddresses.length; i++) {
_removeLockUpFromUser(_userAddresses[i], _lockupNames[i]);
}
}
/**
* @notice Lets the admin modify a lockup.
* @param _lockupAmount Amount of tokens that needs to be locked
* @param _startTime When this lockup starts (seconds)
* @param _lockUpPeriodSeconds Total period of lockup (seconds)
* @param _releaseFrequencySeconds How often to release a tranche of tokens (seconds)
* @param _lockupName name of the lockup that needs to be modified.
*/
function modifyLockUpType(
uint256 _lockupAmount,
uint256 _startTime,
uint256 _lockUpPeriodSeconds,
uint256 _releaseFrequencySeconds,
bytes32 _lockupName
)
external
withPerm(ADMIN)
{
_modifyLockUpType(
_lockupAmount,
_startTime,
_lockUpPeriodSeconds,
_releaseFrequencySeconds,
_lockupName
);
}
/**
* @notice Lets the admin modify a volume restriction lockup for a multiple address.
* @param _lockupAmounts Array of the amount of tokens that needs to be locked for the respective addresses.
* @param _startTimes Array of the start time of the lockups (seconds)
* @param _lockUpPeriodsSeconds Array of unix timestamp for the list of lockups (seconds).
* @param _releaseFrequenciesSeconds How often to release a tranche of tokens (seconds)
* @param _lockupNames Array of the lockup names that needs to be modified
*/
function modifyLockUpTypeMulti(
uint256[] _lockupAmounts,
uint256[] _startTimes,
uint256[] _lockUpPeriodsSeconds,
uint256[] _releaseFrequenciesSeconds,
bytes32[] _lockupNames
)
public
withPerm(ADMIN)
{
require(
_lockupNames.length == _lockUpPeriodsSeconds.length && /*solium-disable-line operator-whitespace*/
_lockupNames.length == _releaseFrequenciesSeconds.length && /*solium-disable-line operator-whitespace*/
_lockupNames.length == _startTimes.length && /*solium-disable-line operator-whitespace*/
_lockupNames.length == _lockupAmounts.length,
"Input array length mismatch"
);
for (uint256 i = 0; i < _lockupNames.length; i++) {
_modifyLockUpType(
_lockupAmounts[i],
_startTimes[i],
_lockUpPeriodsSeconds[i],
_releaseFrequenciesSeconds[i],
_lockupNames[i]
);
}
}
/**
* @notice Get a specific element in a user's lockups array given the user's address and the element index
* @param _lockupName The name of the lockup
*/
function getLockUp(bytes32 _lockupName) public view returns (
uint256 lockupAmount,
uint256 startTime,
uint256 lockUpPeriodSeconds,
uint256 releaseFrequencySeconds,
uint256 unlockedAmount
) {
if (lockups[_lockupName].lockupAmount != 0) {
return (
lockups[_lockupName].lockupAmount,
lockups[_lockupName].startTime,
lockups[_lockupName].lockUpPeriodSeconds,
lockups[_lockupName].releaseFrequencySeconds,
_getUnlockedAmountForLockup(_lockupName)
);
}
return (uint256(0), uint256(0), uint256(0), uint256(0), uint256(0));
}
/**
* @notice get the list of the users of a lockup type
* @param _lockupName Name of the lockup type
* @return address List of users associated with the blacklist
*/
function getListOfAddresses(bytes32 _lockupName) external view returns(address[]) {
require(lockups[_lockupName].startTime != 0, "Blacklist type doesn't exist");
return lockupToUsers[_lockupName];
}
/**
* @notice get the list of lockups names
* @return bytes32 Array of lockups names
*/
function getAllLockups() external view returns(bytes32[]) {
return lockupArray;
}
/**
* @notice Return the data of the lockups
*/
function getAllLockupData() external view returns(
bytes32[] memory,
uint256[] memory,
uint256[] memory,
uint256[] memory,
uint256[] memory,
uint256[] memory
)
{
uint256[] memory lockupAmounts = new uint256[](lockupArray.length);
uint256[] memory startTimes = new uint256[](lockupArray.length);
uint256[] memory lockUpPeriodSeconds = new uint256[](lockupArray.length);
uint256[] memory releaseFrequencySeconds = new uint256[](lockupArray.length);
uint256[] memory unlockedAmounts = new uint256[](lockupArray.length);
for (uint256 i = 0; i < lockupArray.length; i++) {
(lockupAmounts[i], startTimes[i], lockUpPeriodSeconds[i], releaseFrequencySeconds[i], unlockedAmounts[i]) = getLockUp(lockupArray[i]);
}
return (
lockupArray,
lockupAmounts,
startTimes,
lockUpPeriodSeconds,
releaseFrequencySeconds,
unlockedAmounts
);
}
/**
* @notice get the list of the lockups for a given user
* @param _user Address of the user
* @return bytes32 List of lockups names associated with the given address
*/
function getLockupsNamesToUser(address _user) external view returns(bytes32[]) {
return userToLockups[_user];
}
/**
* @notice Use to get the total locked tokens for a given user
* @param _userAddress Address of the user
* @return uint256 Total locked tokens amount
*/
function getLockedTokenToUser(address _userAddress) public view returns(uint256) {
require(_userAddress != address(0), "Invalid address");
bytes32[] memory userLockupNames = userToLockups[_userAddress];
uint256 totalRemainingLockedAmount = 0;
for (uint256 i = 0; i < userLockupNames.length; i++) {
// Find out the remaining locked amount for a given lockup
uint256 remainingLockedAmount = lockups[userLockupNames[i]].lockupAmount.sub(_getUnlockedAmountForLockup(userLockupNames[i]));
// aggregating all the remaining locked amount for all the lockups for a given address
totalRemainingLockedAmount = totalRemainingLockedAmount.add(remainingLockedAmount);
}
return totalRemainingLockedAmount;
}
/**
* @notice Checks whether the transfer is allowed
* @param _userAddress Address of the user whose lock ups should be checked
* @param _amount Amount of tokens that need to transact
*/
function _checkIfValidTransfer(address _userAddress, uint256 _amount) internal view returns (Result) {
uint256 totalRemainingLockedAmount = getLockedTokenToUser(_userAddress);
// Present balance of the user
uint256 currentBalance = ISecurityToken(securityToken).balanceOf(_userAddress);
if ((currentBalance.sub(_amount)) >= totalRemainingLockedAmount) {
return Result.NA;
}
return Result.INVALID;
}
/**
* @notice Provide the unlock amount for the given lockup for a particular user
*/
function _getUnlockedAmountForLockup(bytes32 _lockupName) internal view returns (uint256) {
/*solium-disable-next-line security/no-block-members*/
if (lockups[_lockupName].startTime > now) {
return 0;
} else if (lockups[_lockupName].startTime.add(lockups[_lockupName].lockUpPeriodSeconds) <= now) {
return lockups[_lockupName].lockupAmount;
} else {
// Calculate the no. of periods for a lockup
uint256 noOfPeriods = (lockups[_lockupName].lockUpPeriodSeconds).div(lockups[_lockupName].releaseFrequencySeconds);
// Calculate the transaction time lies in which period
/*solium-disable-next-line security/no-block-members*/
uint256 elapsedPeriod = (now.sub(lockups[_lockupName].startTime)).div(lockups[_lockupName].releaseFrequencySeconds);
// Find out the unlocked amount for a given lockup
uint256 unLockedAmount = (lockups[_lockupName].lockupAmount.mul(elapsedPeriod)).div(noOfPeriods);
return unLockedAmount;
}
}
function _removeLockupType(bytes32 _lockupName) internal {
require(lockups[_lockupName].startTime != 0, "Lockup type doesn’t exist");
require(lockupToUsers[_lockupName].length == 0, "Users are associated with the lockup");
// delete lockup type
delete(lockups[_lockupName]);
uint256 i = 0;
for (i = 0; i < lockupArray.length; i++) {
if (lockupArray[i] == _lockupName) {
break;
}
}
if (i != lockupArray.length -1) {
lockupArray[i] = lockupArray[lockupArray.length -1];
}
lockupArray.length--;
emit RemoveLockUpType(_lockupName);
}
function _modifyLockUpType(
uint256 _lockupAmount,
uint256 _startTime,
uint256 _lockUpPeriodSeconds,
uint256 _releaseFrequencySeconds,
bytes32 _lockupName
)
internal
{
/*solium-disable-next-line security/no-block-members*/
uint256 startTime = _startTime;
if (_startTime == 0) {
startTime = now;
}
require(startTime >= now, "Invalid start time");
require(lockups[_lockupName].lockupAmount != 0, "Doesn't exist");
_checkLockUpParams(
_lockupAmount,
_lockUpPeriodSeconds,
_releaseFrequencySeconds
);
lockups[_lockupName] = LockUp(
_lockupAmount,
startTime,
_lockUpPeriodSeconds,
_releaseFrequencySeconds
);
emit ModifyLockUpType(
_lockupAmount,
startTime,
_lockUpPeriodSeconds,
_releaseFrequencySeconds,
_lockupName
);
}
function _removeLockUpFromUser(address _userAddress, bytes32 _lockupName) internal {
require(_userAddress != address(0), "Invalid address");
require(_lockupName != bytes32(0), "Invalid lockup name");
require(
userToLockups[_userAddress][userToLockupIndex[_userAddress][_lockupName]] == _lockupName,
"User not assosicated with given lockup"
);
// delete the user from the lockup type
uint256 _lockupIndex = lockupToUserIndex[_lockupName][_userAddress];
uint256 _len = lockupToUsers[_lockupName].length;
if ( _lockupIndex != _len) {
lockupToUsers[_lockupName][_lockupIndex] = lockupToUsers[_lockupName][_len - 1];
lockupToUserIndex[_lockupName][lockupToUsers[_lockupName][_lockupIndex]] = _lockupIndex;
}
lockupToUsers[_lockupName].length--;
// delete the user index from the lockup
delete(lockupToUserIndex[_lockupName][_userAddress]);
// delete the lockup from the user
uint256 _userIndex = userToLockupIndex[_userAddress][_lockupName];
_len = userToLockups[_userAddress].length;
if ( _userIndex != _len) {
userToLockups[_userAddress][_userIndex] = userToLockups[_userAddress][_len - 1];
userToLockupIndex[_userAddress][userToLockups[_userAddress][_userIndex]] = _userIndex;
}
userToLockups[_userAddress].length--;
// delete the lockup index from the user
delete(userToLockupIndex[_userAddress][_lockupName]);
emit RemoveLockUpFromUser(_userAddress, _lockupName);
}
function _addNewLockUpToUser(
address _userAddress,
uint256 _lockupAmount,
uint256 _startTime,
uint256 _lockUpPeriodSeconds,
uint256 _releaseFrequencySeconds,
bytes32 _lockupName
)
internal
{
require(_userAddress != address(0), "Invalid address");
_addNewLockUpType(
_lockupAmount,
_startTime,
_lockUpPeriodSeconds,
_releaseFrequencySeconds,
_lockupName
);
_addLockUpByName(_userAddress, _lockupName);
}
function _addLockUpByName(
address _userAddress,
bytes32 _lockupName
)
internal
{
require(_userAddress != address(0), "Invalid address");
require(lockups[_lockupName].startTime >= now, "Lockup expired");
userToLockupIndex[_userAddress][_lockupName] = userToLockups[_userAddress].length;
lockupToUserIndex[_lockupName][_userAddress] = lockupToUsers[_lockupName].length;
userToLockups[_userAddress].push(_lockupName);
lockupToUsers[_lockupName].push(_userAddress);
emit AddLockUpToUser(_userAddress, _lockupName);
}
function _addNewLockUpType(
uint256 _lockupAmount,
uint256 _startTime,
uint256 _lockUpPeriodSeconds,
uint256 _releaseFrequencySeconds,
bytes32 _lockupName
)
internal
{
uint256 startTime = _startTime;
require(_lockupName != bytes32(0), "Invalid name");
require(lockups[_lockupName].lockupAmount == 0, "Already exist");
/*solium-disable-next-line security/no-block-members*/
if (_startTime == 0) {
startTime = now;
}
require(startTime >= now, "Invalid start time");
_checkLockUpParams(_lockupAmount, _lockUpPeriodSeconds, _releaseFrequencySeconds);
lockups[_lockupName] = LockUp(_lockupAmount, startTime, _lockUpPeriodSeconds, _releaseFrequencySeconds);
lockupArray.push(_lockupName);
emit AddNewLockUpType(_lockupName, _lockupAmount, startTime, _lockUpPeriodSeconds, _releaseFrequencySeconds);
}
/**
* @notice Parameter checking function for creating or editing a lockup.
* This function will cause an exception if any of the parameters are bad.
* @param _lockupAmount Amount that needs to be locked
* @param _lockUpPeriodSeconds Total period of lockup (seconds)
* @param _releaseFrequencySeconds How often to release a tranche of tokens (seconds)
*/
function _checkLockUpParams(
uint256 _lockupAmount,
uint256 _lockUpPeriodSeconds,
uint256 _releaseFrequencySeconds
)
internal
pure
{
require(_lockUpPeriodSeconds != 0, "lockUpPeriodSeconds cannot be zero");
require(_releaseFrequencySeconds != 0, "releaseFrequencySeconds cannot be zero");
require(_lockupAmount != 0, "lockupAmount cannot be zero");
}
/**
* @notice This function returns the signature of configure function
*/
function getInitFunction() public pure returns (bytes4) {
return bytes4(0);
}
/**
* @notice Returns the permissions flag that are associated with Percentage transfer Manager
*/
function getPermissions() public view returns(bytes32[]) {
bytes32[] memory allPermissions = new bytes32[](1);
allPermissions[0] = ADMIN;
return allPermissions;
}
}
| holds lockup index corresponds to user address. userAddress => lockupName => lockupIndex | mapping (address => mapping(bytes32 => uint256)) internal userToLockupIndex;
| 1,084,358 | [
1,
21056,
87,
2176,
416,
770,
13955,
358,
729,
1758,
18,
729,
1887,
516,
2176,
416,
461,
516,
2176,
416,
1016,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
261,
2867,
516,
2874,
12,
3890,
1578,
516,
2254,
5034,
3719,
2713,
729,
774,
2531,
416,
1016,
31,
7010,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x32bA720A38dcD3a9d4c04Aa398F4D7E65a7547f5/sources/https_/github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20Burnable.sol | * @dev Destroys `amount` tokens from `account`, deducting from the caller's allowance. See {ERC20-_burn} and {ERC20-allowance}. Requirements: - the caller must have allowance for ``accounts``'s tokens of at least `amount`./ | function burnFrom(address account, uint256 amount) public virtual {
require(allowance(account, _msgSender()) >= amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), allowance(account, _msgSender()) - amount);
_burn(account, amount);
}
| 4,879,952 | [
1,
9378,
28599,
1375,
8949,
68,
2430,
628,
1375,
4631,
9191,
11140,
853,
310,
628,
326,
4894,
1807,
1699,
1359,
18,
2164,
288,
654,
39,
3462,
17,
67,
70,
321,
97,
471,
288,
654,
39,
3462,
17,
5965,
1359,
5496,
29076,
30,
300,
326,
4894,
1297,
1240,
1699,
1359,
364,
12176,
13739,
10335,
11,
87,
2430,
434,
622,
4520,
1375,
8949,
8338,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
18305,
1265,
12,
2867,
2236,
16,
2254,
5034,
3844,
13,
1071,
5024,
288,
203,
3639,
2583,
12,
5965,
1359,
12,
4631,
16,
389,
3576,
12021,
10756,
1545,
3844,
16,
315,
654,
39,
3462,
30,
18305,
3844,
14399,
1699,
1359,
8863,
203,
3639,
389,
12908,
537,
12,
4631,
16,
389,
3576,
12021,
9334,
1699,
1359,
12,
4631,
16,
389,
3576,
12021,
10756,
300,
3844,
1769,
203,
3639,
389,
70,
321,
12,
4631,
16,
3844,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.0;
import '../../contracts/auth/Authorised.sol';
// Authorised contract for testing
contract AuthorisedTest1 is Authorised {
bytes32 constant public ACTION_SET_INT = keccak256("action: set int");
bytes32 constant public ACTION_SET_INT_ONCE = keccak256("action: set int once");
uint256 public intValue = 0;
function hash() public view returns (bytes32) {
return keccak256(abi.encodePacked(msg.sender, ACTION_SET_INT, uint256(8)));
}
event Mark(bool);
function setInt(uint256 _intValue, bytes memory _signature) public {
// check general authorisation
if (!authorise(keccak256(abi.encodePacked(msg.sender, ACTION_SET_INT)), _signature, true)) {
// check single-use authorisation
if(!authorise(keccak256(abi.encodePacked(msg.sender, ACTION_SET_INT_ONCE)), _signature, false)) {
// check general authorisation with value
if (!authorise(keccak256(abi.encodePacked(msg.sender, ACTION_SET_INT, _intValue)), _signature, true)) {
// Check single-use authorisation with value
require(authorise(keccak256(abi.encodePacked(msg.sender, ACTION_SET_INT_ONCE, _intValue)), _signature, false));
}
}
}
intValue = _intValue;
}
}
| Authorised contract for testing | contract AuthorisedTest1 is Authorised {
bytes32 constant public ACTION_SET_INT = keccak256("action: set int");
bytes32 constant public ACTION_SET_INT_ONCE = keccak256("action: set int once");
uint256 public intValue = 0;
function hash() public view returns (bytes32) {
return keccak256(abi.encodePacked(msg.sender, ACTION_SET_INT, uint256(8)));
}
event Mark(bool);
function setInt(uint256 _intValue, bytes memory _signature) public {
if (!authorise(keccak256(abi.encodePacked(msg.sender, ACTION_SET_INT)), _signature, true)) {
if(!authorise(keccak256(abi.encodePacked(msg.sender, ACTION_SET_INT_ONCE)), _signature, false)) {
if (!authorise(keccak256(abi.encodePacked(msg.sender, ACTION_SET_INT, _intValue)), _signature, true)) {
require(authorise(keccak256(abi.encodePacked(msg.sender, ACTION_SET_INT_ONCE, _intValue)), _signature, false));
}
}
}
intValue = _intValue;
}
function setInt(uint256 _intValue, bytes memory _signature) public {
if (!authorise(keccak256(abi.encodePacked(msg.sender, ACTION_SET_INT)), _signature, true)) {
if(!authorise(keccak256(abi.encodePacked(msg.sender, ACTION_SET_INT_ONCE)), _signature, false)) {
if (!authorise(keccak256(abi.encodePacked(msg.sender, ACTION_SET_INT, _intValue)), _signature, true)) {
require(authorise(keccak256(abi.encodePacked(msg.sender, ACTION_SET_INT_ONCE, _intValue)), _signature, false));
}
}
}
intValue = _intValue;
}
function setInt(uint256 _intValue, bytes memory _signature) public {
if (!authorise(keccak256(abi.encodePacked(msg.sender, ACTION_SET_INT)), _signature, true)) {
if(!authorise(keccak256(abi.encodePacked(msg.sender, ACTION_SET_INT_ONCE)), _signature, false)) {
if (!authorise(keccak256(abi.encodePacked(msg.sender, ACTION_SET_INT, _intValue)), _signature, true)) {
require(authorise(keccak256(abi.encodePacked(msg.sender, ACTION_SET_INT_ONCE, _intValue)), _signature, false));
}
}
}
intValue = _intValue;
}
function setInt(uint256 _intValue, bytes memory _signature) public {
if (!authorise(keccak256(abi.encodePacked(msg.sender, ACTION_SET_INT)), _signature, true)) {
if(!authorise(keccak256(abi.encodePacked(msg.sender, ACTION_SET_INT_ONCE)), _signature, false)) {
if (!authorise(keccak256(abi.encodePacked(msg.sender, ACTION_SET_INT, _intValue)), _signature, true)) {
require(authorise(keccak256(abi.encodePacked(msg.sender, ACTION_SET_INT_ONCE, _intValue)), _signature, false));
}
}
}
intValue = _intValue;
}
}
| 12,723,597 | [
1,
3594,
5918,
6835,
364,
7769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
6712,
5918,
4709,
21,
353,
6712,
5918,
288,
203,
565,
1731,
1578,
5381,
1071,
11385,
67,
4043,
67,
3217,
273,
417,
24410,
581,
5034,
2932,
1128,
30,
444,
509,
8863,
203,
565,
1731,
1578,
5381,
1071,
11385,
67,
4043,
67,
3217,
67,
673,
1441,
273,
417,
24410,
581,
5034,
2932,
1128,
30,
444,
509,
3647,
8863,
203,
203,
565,
2254,
5034,
1071,
9307,
273,
374,
31,
203,
203,
565,
445,
1651,
1435,
1071,
1476,
1135,
261,
3890,
1578,
13,
288,
203,
3639,
327,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
3576,
18,
15330,
16,
11385,
67,
4043,
67,
3217,
16,
2254,
5034,
12,
28,
3719,
1769,
203,
565,
289,
203,
203,
565,
871,
6622,
12,
6430,
1769,
203,
565,
445,
21089,
12,
11890,
5034,
389,
474,
620,
16,
1731,
3778,
389,
8195,
13,
1071,
288,
203,
3639,
309,
16051,
4161,
784,
12,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
3576,
18,
15330,
16,
11385,
67,
4043,
67,
3217,
13,
3631,
389,
8195,
16,
638,
3719,
288,
203,
5411,
309,
12,
5,
4161,
784,
12,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
3576,
18,
15330,
16,
11385,
67,
4043,
67,
3217,
67,
673,
1441,
13,
3631,
389,
8195,
16,
629,
3719,
288,
203,
7734,
309,
16051,
4161,
784,
12,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
3576,
18,
15330,
16,
11385,
67,
4043,
67,
3217,
16,
389,
474,
620,
13,
3631,
389,
8195,
16,
638,
3719,
288,
203,
2
] |
./full_match/44787/0x3a111Ca2d73697e77e5E898C5029df443E46df83/sources/contracts/StarFarm.sol | MasterChef is the master of Star. He can make Star 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 STAR is sufficiently distributed and the community can show to govern itself. Have fun reading it. Hopefully it's bug-free. God bless. Info of each user. | contract MasterChef is Initializable, OwnableUpgradeable {
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
struct UserInfo {
uint256 reward;
uint256 userRewardDebt;
uint256 lastDeposit;
uint256 nftAmount;
uint256 nftRewardDebt;
uint256 nftReward;
uint256 nftUserRewardDebt;
uint256 nftLastDeposit;
}
struct PoolInfo {
uint256 lpSupply;
uint256 fee;
uint256 size;
}
struct SlotInfo {
PoolInfo pool;
uint256 _self_parentGain;
uint256 _selfGain;
uint256 _parentGain;
uint256 _nftAmountGain;
uint256 accStarPerShare;
uint256 lpSupply;
uint256 multiplier;
uint256 starReward;
uint256 i;
uint256 _amount;
}
mapping (uint256 => mapping (uint256 => address)) public userIndex;
mapping (uint256 => mapping (address => bool)) public isPoolUser;
address public lockAddr;
address public teamAddr;
address public rewardAddr;
uint256 public lockRatio;
uint256 public teamRatio;
uint256 public rewardRatio;
mapping (address => uint256[]) public userNFTs;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount, bool isNodeUser);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, bool isNodeUser);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, bool isNodeUser);
IERC20Upgradeable public starToken;
IStarNode public starNode;
address public bonusAddr;
IERC721Upgradeable public starNFT;
INFTLogic public nftLogic;
uint256 public starPerBlock;
uint256 public BONUS_MULTIPLIER;
IMigratorChef public migrator;
PoolInfo[] public poolInfo;
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
uint256 public totalAllocPoint;
uint256 public startBlock;
mapping (address => bool) public isNodeUser;
function initialize(address _starToken, address _bonus, address _node, uint256 _starPerBlock, uint256 _startBlock) public initializer {
__farm_init(_starToken, _bonus, _node, _starPerBlock, _startBlock);
}
function __farm_init(address _starToken, address _bonus, address _node, uint256 _starPerBlock, uint256 _startBlock) internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
__farm_init_unchained(_starToken, _bonus, _node, _starPerBlock, _startBlock);
}
function __farm_init_unchained(address _starToken, address _bonus, address _node, uint256 _starPerBlock, uint256 _startBlock) internal initializer {
starToken = IERC20Upgradeable(_starToken);
bonusAddr = _bonus;
starNode = IStarNode(_node);
starPerBlock = _starPerBlock;
startBlock = _startBlock;
poolInfo.push(PoolInfo({
lpToken: IERC20Upgradeable(_starToken),
lpSupply: 0,
allocPoint: 1000,
lastRewardBlock: startBlock,
accStarPerShare: 0,
extraAmount: 0,
fee: 0,
size: 0
}));
totalAllocPoint = 1000;
}
function __farm_init_unchained(address _starToken, address _bonus, address _node, uint256 _starPerBlock, uint256 _startBlock) internal initializer {
starToken = IERC20Upgradeable(_starToken);
bonusAddr = _bonus;
starNode = IStarNode(_node);
starPerBlock = _starPerBlock;
startBlock = _startBlock;
poolInfo.push(PoolInfo({
lpToken: IERC20Upgradeable(_starToken),
lpSupply: 0,
allocPoint: 1000,
lastRewardBlock: startBlock,
accStarPerShare: 0,
extraAmount: 0,
fee: 0,
size: 0
}));
totalAllocPoint = 1000;
}
function updateMultiplier(uint256 multiplierNumber) public onlyOwner {
BONUS_MULTIPLIER = multiplierNumber;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
function add(uint256 _allocPoint, IERC20Upgradeable _lpToken, uint256 _fee, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
lpSupply: 0,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accStarPerShare: 0,
extraAmount: 0,
fee: _fee,
size: 0
}));
updateStakingPool();
}
function add(uint256 _allocPoint, IERC20Upgradeable _lpToken, uint256 _fee, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
lpSupply: 0,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accStarPerShare: 0,
extraAmount: 0,
fee: _fee,
size: 0
}));
updateStakingPool();
}
function add(uint256 _allocPoint, IERC20Upgradeable _lpToken, uint256 _fee, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
lpSupply: 0,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accStarPerShare: 0,
extraAmount: 0,
fee: _fee,
size: 0
}));
updateStakingPool();
}
function set(uint256 _pid, uint256 _allocPoint, uint256 _fee, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
uint256 prevAllocPoint = poolInfo[_pid].allocPoint;
poolInfo[_pid].allocPoint = _allocPoint;
poolInfo[_pid].fee = _fee;
if (prevAllocPoint != _allocPoint) {
updateStakingPool();
}
}
function set(uint256 _pid, uint256 _allocPoint, uint256 _fee, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
uint256 prevAllocPoint = poolInfo[_pid].allocPoint;
poolInfo[_pid].allocPoint = _allocPoint;
poolInfo[_pid].fee = _fee;
if (prevAllocPoint != _allocPoint) {
updateStakingPool();
}
}
function set(uint256 _pid, uint256 _allocPoint, uint256 _fee, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
uint256 prevAllocPoint = poolInfo[_pid].allocPoint;
poolInfo[_pid].allocPoint = _allocPoint;
poolInfo[_pid].fee = _fee;
if (prevAllocPoint != _allocPoint) {
updateStakingPool();
}
}
function updateStakingPool() internal {
uint256 length = poolInfo.length;
uint256 points = 0;
for (uint256 pid = 1; pid < length; ++pid) {
points = points.add(poolInfo[pid].allocPoint);
}
if (points != 0) {
points = points.div(3);
totalAllocPoint = totalAllocPoint.sub(poolInfo[0].allocPoint).add(points);
poolInfo[0].allocPoint = points;
}
}
function updateStakingPool() internal {
uint256 length = poolInfo.length;
uint256 points = 0;
for (uint256 pid = 1; pid < length; ++pid) {
points = points.add(poolInfo[pid].allocPoint);
}
if (points != 0) {
points = points.div(3);
totalAllocPoint = totalAllocPoint.sub(poolInfo[0].allocPoint).add(points);
poolInfo[0].allocPoint = points;
}
}
function updateStakingPool() internal {
uint256 length = poolInfo.length;
uint256 points = 0;
for (uint256 pid = 1; pid < length; ++pid) {
points = points.add(poolInfo[pid].allocPoint);
}
if (points != 0) {
points = points.div(3);
totalAllocPoint = totalAllocPoint.sub(poolInfo[0].allocPoint).add(points);
poolInfo[0].allocPoint = points;
}
}
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20Upgradeable lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20Upgradeable newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
}
function pendingStar(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
}
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(_msgSender());
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain.add(_parentGain)).div(100));
uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12);
_amountpendingStar = user.reward.add(_amountpendingStar);
if(_amountpendingStar > 0) {
_amountpendingStar = _amountpendingStar.sub(_amountpendingStar.mul(lockRatio.add(teamRatio)).div(100));
_amountpendingStar = _amountpendingStar.sub(_amountpendingStar.mul(rewardRatio).div(100));
_amountpendingStar = _amountpendingStar.mul(100).div(_selfGain.add(_parentGain).add(100));
_amountpendingStar = _amountpendingStar.mul(_selfGain.add(100)).div(100);
}
return _amountpendingStar;
}
function pendingStar(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
}
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(_msgSender());
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain.add(_parentGain)).div(100));
uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12);
_amountpendingStar = user.reward.add(_amountpendingStar);
if(_amountpendingStar > 0) {
_amountpendingStar = _amountpendingStar.sub(_amountpendingStar.mul(lockRatio.add(teamRatio)).div(100));
_amountpendingStar = _amountpendingStar.sub(_amountpendingStar.mul(rewardRatio).div(100));
_amountpendingStar = _amountpendingStar.mul(100).div(_selfGain.add(_parentGain).add(100));
_amountpendingStar = _amountpendingStar.mul(_selfGain.add(100)).div(100);
}
return _amountpendingStar;
}
function pendingStar(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
}
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(_msgSender());
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain.add(_parentGain)).div(100));
uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12);
_amountpendingStar = user.reward.add(_amountpendingStar);
if(_amountpendingStar > 0) {
_amountpendingStar = _amountpendingStar.sub(_amountpendingStar.mul(lockRatio.add(teamRatio)).div(100));
_amountpendingStar = _amountpendingStar.sub(_amountpendingStar.mul(rewardRatio).div(100));
_amountpendingStar = _amountpendingStar.mul(100).div(_selfGain.add(_parentGain).add(100));
_amountpendingStar = _amountpendingStar.mul(_selfGain.add(100)).div(100);
}
return _amountpendingStar;
}
function nftPendingStar(address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][_user];
uint256 accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
}
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(_msgSender());
uint256 _amountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12);
_amountpendingStar = user.nftReward.add(_amountpendingStar);
if(_amountpendingStar > 0) {
_amountpendingStar = _amountpendingStar.sub(_amountpendingStar.mul(lockRatio.add(teamRatio)).div(100));
_amountpendingStar = _amountpendingStar.sub(_amountpendingStar.mul(rewardRatio).div(100));
_amountpendingStar = _amountpendingStar.mul(100).div(_selfGain.add(_parentGain).add(100));
_amountpendingStar = _amountpendingStar.mul(_selfGain.add(100)).div(100);
}
return _amountpendingStar;
}
function nftPendingStar(address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][_user];
uint256 accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
}
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(_msgSender());
uint256 _amountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12);
_amountpendingStar = user.nftReward.add(_amountpendingStar);
if(_amountpendingStar > 0) {
_amountpendingStar = _amountpendingStar.sub(_amountpendingStar.mul(lockRatio.add(teamRatio)).div(100));
_amountpendingStar = _amountpendingStar.sub(_amountpendingStar.mul(rewardRatio).div(100));
_amountpendingStar = _amountpendingStar.mul(100).div(_selfGain.add(_parentGain).add(100));
_amountpendingStar = _amountpendingStar.mul(_selfGain.add(100)).div(100);
}
return _amountpendingStar;
}
function nftPendingStar(address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][_user];
uint256 accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
}
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(_msgSender());
uint256 _amountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12);
_amountpendingStar = user.nftReward.add(_amountpendingStar);
if(_amountpendingStar > 0) {
_amountpendingStar = _amountpendingStar.sub(_amountpendingStar.mul(lockRatio.add(teamRatio)).div(100));
_amountpendingStar = _amountpendingStar.sub(_amountpendingStar.mul(rewardRatio).div(100));
_amountpendingStar = _amountpendingStar.mul(100).div(_selfGain.add(_parentGain).add(100));
_amountpendingStar = _amountpendingStar.mul(_selfGain.add(100)).div(100);
}
return _amountpendingStar;
}
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
if (pool.lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
for(uint256 unumber = 0; unumber < pool.size; ++unumber){
address userAddr = userIndex[_pid][unumber];
if(userIndex[_pid][unumber] == address(0)||userAddr == _msgSender()){
continue;
}
UserInfo storage user = userInfo[_pid][userAddr];
if(user.amount >0){
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(userAddr);
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain.add(_parentGain)).div(100));
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain.add(_parentGain)).div(100));
uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12);
uint256 _nftAmountpendingStar = _nftAmountGain.mul(accStarPerShare).div(1e12);
user.reward = user.reward.add(_amountpendingStar);
user.nftReward = user.nftReward.add(_nftAmountpendingStar);
}
}
pool.accStarPerShare = accStarPerShare;
pool.lastRewardBlock = block.number;
}
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
if (pool.lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
for(uint256 unumber = 0; unumber < pool.size; ++unumber){
address userAddr = userIndex[_pid][unumber];
if(userIndex[_pid][unumber] == address(0)||userAddr == _msgSender()){
continue;
}
UserInfo storage user = userInfo[_pid][userAddr];
if(user.amount >0){
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(userAddr);
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain.add(_parentGain)).div(100));
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain.add(_parentGain)).div(100));
uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12);
uint256 _nftAmountpendingStar = _nftAmountGain.mul(accStarPerShare).div(1e12);
user.reward = user.reward.add(_amountpendingStar);
user.nftReward = user.nftReward.add(_nftAmountpendingStar);
}
}
pool.accStarPerShare = accStarPerShare;
pool.lastRewardBlock = block.number;
}
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
if (pool.lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
for(uint256 unumber = 0; unumber < pool.size; ++unumber){
address userAddr = userIndex[_pid][unumber];
if(userIndex[_pid][unumber] == address(0)||userAddr == _msgSender()){
continue;
}
UserInfo storage user = userInfo[_pid][userAddr];
if(user.amount >0){
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(userAddr);
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain.add(_parentGain)).div(100));
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain.add(_parentGain)).div(100));
uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12);
uint256 _nftAmountpendingStar = _nftAmountGain.mul(accStarPerShare).div(1e12);
user.reward = user.reward.add(_amountpendingStar);
user.nftReward = user.nftReward.add(_nftAmountpendingStar);
}
}
pool.accStarPerShare = accStarPerShare;
pool.lastRewardBlock = block.number;
}
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
if (pool.lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
for(uint256 unumber = 0; unumber < pool.size; ++unumber){
address userAddr = userIndex[_pid][unumber];
if(userIndex[_pid][unumber] == address(0)||userAddr == _msgSender()){
continue;
}
UserInfo storage user = userInfo[_pid][userAddr];
if(user.amount >0){
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(userAddr);
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain.add(_parentGain)).div(100));
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain.add(_parentGain)).div(100));
uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12);
uint256 _nftAmountpendingStar = _nftAmountGain.mul(accStarPerShare).div(1e12);
user.reward = user.reward.add(_amountpendingStar);
user.nftReward = user.nftReward.add(_nftAmountpendingStar);
}
}
pool.accStarPerShare = accStarPerShare;
pool.lastRewardBlock = block.number;
}
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
if (pool.lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
for(uint256 unumber = 0; unumber < pool.size; ++unumber){
address userAddr = userIndex[_pid][unumber];
if(userIndex[_pid][unumber] == address(0)||userAddr == _msgSender()){
continue;
}
UserInfo storage user = userInfo[_pid][userAddr];
if(user.amount >0){
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(userAddr);
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain.add(_parentGain)).div(100));
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain.add(_parentGain)).div(100));
uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12);
uint256 _nftAmountpendingStar = _nftAmountGain.mul(accStarPerShare).div(1e12);
user.reward = user.reward.add(_amountpendingStar);
user.nftReward = user.nftReward.add(_nftAmountpendingStar);
}
}
pool.accStarPerShare = accStarPerShare;
pool.lastRewardBlock = block.number;
}
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
if (pool.lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
for(uint256 unumber = 0; unumber < pool.size; ++unumber){
address userAddr = userIndex[_pid][unumber];
if(userIndex[_pid][unumber] == address(0)||userAddr == _msgSender()){
continue;
}
UserInfo storage user = userInfo[_pid][userAddr];
if(user.amount >0){
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(userAddr);
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain.add(_parentGain)).div(100));
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain.add(_parentGain)).div(100));
uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12);
uint256 _nftAmountpendingStar = _nftAmountGain.mul(accStarPerShare).div(1e12);
user.reward = user.reward.add(_amountpendingStar);
user.nftReward = user.nftReward.add(_nftAmountpendingStar);
}
}
pool.accStarPerShare = accStarPerShare;
pool.lastRewardBlock = block.number;
}
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
if (pool.lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
for(uint256 unumber = 0; unumber < pool.size; ++unumber){
address userAddr = userIndex[_pid][unumber];
if(userIndex[_pid][unumber] == address(0)||userAddr == _msgSender()){
continue;
}
UserInfo storage user = userInfo[_pid][userAddr];
if(user.amount >0){
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(userAddr);
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain.add(_parentGain)).div(100));
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain.add(_parentGain)).div(100));
uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12);
uint256 _nftAmountpendingStar = _nftAmountGain.mul(accStarPerShare).div(1e12);
user.reward = user.reward.add(_amountpendingStar);
user.nftReward = user.nftReward.add(_nftAmountpendingStar);
}
}
pool.accStarPerShare = accStarPerShare;
pool.lastRewardBlock = block.number;
}
}
function testpendingStar(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
}
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(_msgSender());
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain.add(_parentGain)).div(100));
uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12);
_amountpendingStar = user.reward.add(_amountpendingStar);
return _amountpendingStar;
}
function testpendingStar(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
}
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(_msgSender());
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain.add(_parentGain)).div(100));
uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12);
_amountpendingStar = user.reward.add(_amountpendingStar);
return _amountpendingStar;
}
function testdeposit(uint256 _pid, uint256 _amount) view public returns(uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(_msgSender());
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain.add(_parentGain)).div(100));
uint256 accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
}
uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12);
if(user.amount >0){
_amountpendingStar = user.reward.add(_amountpendingStar);
}
return _amountpendingStar;
}
function testdeposit(uint256 _pid, uint256 _amount) view public returns(uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(_msgSender());
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain.add(_parentGain)).div(100));
uint256 accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
}
uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12);
if(user.amount >0){
_amountpendingStar = user.reward.add(_amountpendingStar);
}
return _amountpendingStar;
}
function testdeposit(uint256 _pid, uint256 _amount) view public returns(uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(_msgSender());
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain.add(_parentGain)).div(100));
uint256 accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
}
uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12);
if(user.amount >0){
_amountpendingStar = user.reward.add(_amountpendingStar);
}
return _amountpendingStar;
}
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
updatePool(_pid);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(_msgSender());
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain.add(_parentGain)).div(100));
uint256 accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
}
if(_amountGain >0){
uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12);
user.reward = user.reward.add(_amountpendingStar);
}
uint256 pending = user.reward;
if(pending > 0) {
starToken.safeTransfer(lockAddr,pending.mul(lockRatio).div(100));
starToken.safeTransfer(teamAddr,pending.mul(teamRatio).div(100));
pending = pending.sub(pending.mul(lockRatio.add(teamRatio)).div(100));
starToken.safeTransfer(rewardAddr,pending.mul(rewardRatio).div(100));
pending = pending.sub(pending.mul(rewardRatio).div(100));
pending = pending.mul(100).div(_selfGain.add(_parentGain).add(100));
starToken.safeTransfer(_msgSender(), pending.mul(_selfGain.add(100)).div(100));
user.rewardDebt = user.rewardDebt.add(pending.mul(_selfGain.add(100)).div(100));
starNode.settleNode(_msgSender(), pending.mul(_parentGain).div(100));
user.reward = 0;
pool.accStarPerShare = accStarPerShare;
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(_msgSender(), address(this), _amount);
user.amount = user.amount.add(_amount);
user.lastDeposit = block.timestamp;
uint256 _extraAmount = _amount.mul(_selfGain.add(_parentGain)).div(100);
pool.extraAmount = pool.extraAmount.add(_extraAmount);
pool.lpSupply = pool.lpSupply.add(_amount);
if(isPoolUser[_pid][_msgSender()] == false){
userIndex[_pid][pool.size] = _msgSender();
pool.size += 1;
isPoolUser[_pid][_msgSender()] = true;
}
}
emit Deposit(_msgSender(), _pid, _amount, isNodeUser[_msgSender()]);
}
event WidthdrawLog(uint256 _amount, uint256 _reward, uint256 _amountpendingStar, uint256 _amountGain,uint256 _extraAmount, uint256 _starReward);
event GetReward(uint256 _lpSupply, uint256 multiplier,uint256 starReward,uint256 accStarPerShare,uint256 allocPoint, uint256 totalAllocPoint, uint256 _lastRewardBlock, uint256 _blockNumber);
event widthLog(uint256 amountGain,uint256 accStarPerShare,uint256 lpSupply,uint256 amountpendingStar,uint256 reward);
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
updatePool(_pid);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(_msgSender());
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain.add(_parentGain)).div(100));
uint256 accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
}
if(_amountGain >0){
uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12);
user.reward = user.reward.add(_amountpendingStar);
}
uint256 pending = user.reward;
if(pending > 0) {
starToken.safeTransfer(lockAddr,pending.mul(lockRatio).div(100));
starToken.safeTransfer(teamAddr,pending.mul(teamRatio).div(100));
pending = pending.sub(pending.mul(lockRatio.add(teamRatio)).div(100));
starToken.safeTransfer(rewardAddr,pending.mul(rewardRatio).div(100));
pending = pending.sub(pending.mul(rewardRatio).div(100));
pending = pending.mul(100).div(_selfGain.add(_parentGain).add(100));
starToken.safeTransfer(_msgSender(), pending.mul(_selfGain.add(100)).div(100));
user.rewardDebt = user.rewardDebt.add(pending.mul(_selfGain.add(100)).div(100));
starNode.settleNode(_msgSender(), pending.mul(_parentGain).div(100));
user.reward = 0;
pool.accStarPerShare = accStarPerShare;
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(_msgSender(), address(this), _amount);
user.amount = user.amount.add(_amount);
user.lastDeposit = block.timestamp;
uint256 _extraAmount = _amount.mul(_selfGain.add(_parentGain)).div(100);
pool.extraAmount = pool.extraAmount.add(_extraAmount);
pool.lpSupply = pool.lpSupply.add(_amount);
if(isPoolUser[_pid][_msgSender()] == false){
userIndex[_pid][pool.size] = _msgSender();
pool.size += 1;
isPoolUser[_pid][_msgSender()] = true;
}
}
emit Deposit(_msgSender(), _pid, _amount, isNodeUser[_msgSender()]);
}
event WidthdrawLog(uint256 _amount, uint256 _reward, uint256 _amountpendingStar, uint256 _amountGain,uint256 _extraAmount, uint256 _starReward);
event GetReward(uint256 _lpSupply, uint256 multiplier,uint256 starReward,uint256 accStarPerShare,uint256 allocPoint, uint256 totalAllocPoint, uint256 _lastRewardBlock, uint256 _blockNumber);
event widthLog(uint256 amountGain,uint256 accStarPerShare,uint256 lpSupply,uint256 amountpendingStar,uint256 reward);
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
updatePool(_pid);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(_msgSender());
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain.add(_parentGain)).div(100));
uint256 accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
}
if(_amountGain >0){
uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12);
user.reward = user.reward.add(_amountpendingStar);
}
uint256 pending = user.reward;
if(pending > 0) {
starToken.safeTransfer(lockAddr,pending.mul(lockRatio).div(100));
starToken.safeTransfer(teamAddr,pending.mul(teamRatio).div(100));
pending = pending.sub(pending.mul(lockRatio.add(teamRatio)).div(100));
starToken.safeTransfer(rewardAddr,pending.mul(rewardRatio).div(100));
pending = pending.sub(pending.mul(rewardRatio).div(100));
pending = pending.mul(100).div(_selfGain.add(_parentGain).add(100));
starToken.safeTransfer(_msgSender(), pending.mul(_selfGain.add(100)).div(100));
user.rewardDebt = user.rewardDebt.add(pending.mul(_selfGain.add(100)).div(100));
starNode.settleNode(_msgSender(), pending.mul(_parentGain).div(100));
user.reward = 0;
pool.accStarPerShare = accStarPerShare;
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(_msgSender(), address(this), _amount);
user.amount = user.amount.add(_amount);
user.lastDeposit = block.timestamp;
uint256 _extraAmount = _amount.mul(_selfGain.add(_parentGain)).div(100);
pool.extraAmount = pool.extraAmount.add(_extraAmount);
pool.lpSupply = pool.lpSupply.add(_amount);
if(isPoolUser[_pid][_msgSender()] == false){
userIndex[_pid][pool.size] = _msgSender();
pool.size += 1;
isPoolUser[_pid][_msgSender()] = true;
}
}
emit Deposit(_msgSender(), _pid, _amount, isNodeUser[_msgSender()]);
}
event WidthdrawLog(uint256 _amount, uint256 _reward, uint256 _amountpendingStar, uint256 _amountGain,uint256 _extraAmount, uint256 _starReward);
event GetReward(uint256 _lpSupply, uint256 multiplier,uint256 starReward,uint256 accStarPerShare,uint256 allocPoint, uint256 totalAllocPoint, uint256 _lastRewardBlock, uint256 _blockNumber);
event widthLog(uint256 amountGain,uint256 accStarPerShare,uint256 lpSupply,uint256 amountpendingStar,uint256 reward);
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
updatePool(_pid);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(_msgSender());
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain.add(_parentGain)).div(100));
uint256 accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
}
if(_amountGain >0){
uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12);
user.reward = user.reward.add(_amountpendingStar);
}
uint256 pending = user.reward;
if(pending > 0) {
starToken.safeTransfer(lockAddr,pending.mul(lockRatio).div(100));
starToken.safeTransfer(teamAddr,pending.mul(teamRatio).div(100));
pending = pending.sub(pending.mul(lockRatio.add(teamRatio)).div(100));
starToken.safeTransfer(rewardAddr,pending.mul(rewardRatio).div(100));
pending = pending.sub(pending.mul(rewardRatio).div(100));
pending = pending.mul(100).div(_selfGain.add(_parentGain).add(100));
starToken.safeTransfer(_msgSender(), pending.mul(_selfGain.add(100)).div(100));
user.rewardDebt = user.rewardDebt.add(pending.mul(_selfGain.add(100)).div(100));
starNode.settleNode(_msgSender(), pending.mul(_parentGain).div(100));
user.reward = 0;
pool.accStarPerShare = accStarPerShare;
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(_msgSender(), address(this), _amount);
user.amount = user.amount.add(_amount);
user.lastDeposit = block.timestamp;
uint256 _extraAmount = _amount.mul(_selfGain.add(_parentGain)).div(100);
pool.extraAmount = pool.extraAmount.add(_extraAmount);
pool.lpSupply = pool.lpSupply.add(_amount);
if(isPoolUser[_pid][_msgSender()] == false){
userIndex[_pid][pool.size] = _msgSender();
pool.size += 1;
isPoolUser[_pid][_msgSender()] = true;
}
}
emit Deposit(_msgSender(), _pid, _amount, isNodeUser[_msgSender()]);
}
event WidthdrawLog(uint256 _amount, uint256 _reward, uint256 _amountpendingStar, uint256 _amountGain,uint256 _extraAmount, uint256 _starReward);
event GetReward(uint256 _lpSupply, uint256 multiplier,uint256 starReward,uint256 accStarPerShare,uint256 allocPoint, uint256 totalAllocPoint, uint256 _lastRewardBlock, uint256 _blockNumber);
event widthLog(uint256 amountGain,uint256 accStarPerShare,uint256 lpSupply,uint256 amountpendingStar,uint256 reward);
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
updatePool(_pid);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(_msgSender());
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain.add(_parentGain)).div(100));
uint256 accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
}
if(_amountGain >0){
uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12);
user.reward = user.reward.add(_amountpendingStar);
}
uint256 pending = user.reward;
if(pending > 0) {
starToken.safeTransfer(lockAddr,pending.mul(lockRatio).div(100));
starToken.safeTransfer(teamAddr,pending.mul(teamRatio).div(100));
pending = pending.sub(pending.mul(lockRatio.add(teamRatio)).div(100));
starToken.safeTransfer(rewardAddr,pending.mul(rewardRatio).div(100));
pending = pending.sub(pending.mul(rewardRatio).div(100));
pending = pending.mul(100).div(_selfGain.add(_parentGain).add(100));
starToken.safeTransfer(_msgSender(), pending.mul(_selfGain.add(100)).div(100));
user.rewardDebt = user.rewardDebt.add(pending.mul(_selfGain.add(100)).div(100));
starNode.settleNode(_msgSender(), pending.mul(_parentGain).div(100));
user.reward = 0;
pool.accStarPerShare = accStarPerShare;
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(_msgSender(), address(this), _amount);
user.amount = user.amount.add(_amount);
user.lastDeposit = block.timestamp;
uint256 _extraAmount = _amount.mul(_selfGain.add(_parentGain)).div(100);
pool.extraAmount = pool.extraAmount.add(_extraAmount);
pool.lpSupply = pool.lpSupply.add(_amount);
if(isPoolUser[_pid][_msgSender()] == false){
userIndex[_pid][pool.size] = _msgSender();
pool.size += 1;
isPoolUser[_pid][_msgSender()] = true;
}
}
emit Deposit(_msgSender(), _pid, _amount, isNodeUser[_msgSender()]);
}
event WidthdrawLog(uint256 _amount, uint256 _reward, uint256 _amountpendingStar, uint256 _amountGain,uint256 _extraAmount, uint256 _starReward);
event GetReward(uint256 _lpSupply, uint256 multiplier,uint256 starReward,uint256 accStarPerShare,uint256 allocPoint, uint256 totalAllocPoint, uint256 _lastRewardBlock, uint256 _blockNumber);
event widthLog(uint256 amountGain,uint256 accStarPerShare,uint256 lpSupply,uint256 amountpendingStar,uint256 reward);
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
updatePool(_pid);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(_msgSender());
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain.add(_parentGain)).div(100));
uint256 accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
}
if(_amountGain >0){
uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12);
user.reward = user.reward.add(_amountpendingStar);
}
uint256 pending = user.reward;
if(pending > 0) {
starToken.safeTransfer(lockAddr,pending.mul(lockRatio).div(100));
starToken.safeTransfer(teamAddr,pending.mul(teamRatio).div(100));
pending = pending.sub(pending.mul(lockRatio.add(teamRatio)).div(100));
starToken.safeTransfer(rewardAddr,pending.mul(rewardRatio).div(100));
pending = pending.sub(pending.mul(rewardRatio).div(100));
pending = pending.mul(100).div(_selfGain.add(_parentGain).add(100));
starToken.safeTransfer(_msgSender(), pending.mul(_selfGain.add(100)).div(100));
user.rewardDebt = user.rewardDebt.add(pending.mul(_selfGain.add(100)).div(100));
starNode.settleNode(_msgSender(), pending.mul(_parentGain).div(100));
user.reward = 0;
pool.accStarPerShare = accStarPerShare;
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(_msgSender(), address(this), _amount);
user.amount = user.amount.add(_amount);
user.lastDeposit = block.timestamp;
uint256 _extraAmount = _amount.mul(_selfGain.add(_parentGain)).div(100);
pool.extraAmount = pool.extraAmount.add(_extraAmount);
pool.lpSupply = pool.lpSupply.add(_amount);
if(isPoolUser[_pid][_msgSender()] == false){
userIndex[_pid][pool.size] = _msgSender();
pool.size += 1;
isPoolUser[_pid][_msgSender()] = true;
}
}
emit Deposit(_msgSender(), _pid, _amount, isNodeUser[_msgSender()]);
}
event WidthdrawLog(uint256 _amount, uint256 _reward, uint256 _amountpendingStar, uint256 _amountGain,uint256 _extraAmount, uint256 _starReward);
event GetReward(uint256 _lpSupply, uint256 multiplier,uint256 starReward,uint256 accStarPerShare,uint256 allocPoint, uint256 totalAllocPoint, uint256 _lastRewardBlock, uint256 _blockNumber);
event widthLog(uint256 amountGain,uint256 accStarPerShare,uint256 lpSupply,uint256 amountpendingStar,uint256 reward);
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
require(user.amount >= _amount, "withdraw: amount error");
updatePool(_pid);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(_msgSender());
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain.add(_parentGain)).div(100));
uint256 accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
}
if(_amountGain >0){
uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12);
user.reward = user.reward.add(_amountpendingStar);
}
if(pending > 0) {
starToken.safeTransfer(lockAddr,pending.mul(lockRatio).div(100));
starToken.safeTransfer(teamAddr,pending.mul(teamRatio).div(100));
pending = pending.sub(pending.mul(lockRatio.add(teamRatio)).div(100));
starToken.safeTransfer(rewardAddr,pending.mul(rewardRatio).div(100));
pending = pending.sub(pending.mul(rewardRatio).div(100));
pending = pending.div(_selfGain.add(_parentGain).add(100)).mul(100);
if (user.lastDeposit > block.timestamp.sub(604800)) {
starToken.safeTransfer(_msgSender(), pending.mul(_selfGain.add(100)).div(100).sub(pending.mul(pool.fee).div(10000)));
starNode.settleNode(_msgSender(), pending.mul(_parentGain).div(100));
user.rewardDebt = user.rewardDebt.add(pending.mul(_selfGain.add(100)).div(100).sub(pending.mul(pool.fee).div(10000)));
if(pool.fee > 0){
pending = pending.mul(pool.fee).div(10000);
starToken.safeTransfer(bonusAddr, pending.mul(70).div(100));
starToken.safeTransfer(lockAddr, pending.mul(30).div(100));
}
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), pending.mul(_parentGain).div(100));
user.rewardDebt = user.rewardDebt.add(pending);
}
user.reward = 0;
pool.accStarPerShare = accStarPerShare;
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
uint256 _extraAmount = _amount.mul(_selfGain.add(_parentGain)).div(100);
pool.extraAmount = pool.extraAmount.sub(_extraAmount);
pool.lpSupply = pool.lpSupply.sub(_amount);
pool.lpToken.safeTransfer(_msgSender(), _amount);
}
emit Withdraw(_msgSender(), _pid, _amount, isNodeUser[_msgSender()]);
}
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
require(user.amount >= _amount, "withdraw: amount error");
updatePool(_pid);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(_msgSender());
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain.add(_parentGain)).div(100));
uint256 accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
}
if(_amountGain >0){
uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12);
user.reward = user.reward.add(_amountpendingStar);
}
if(pending > 0) {
starToken.safeTransfer(lockAddr,pending.mul(lockRatio).div(100));
starToken.safeTransfer(teamAddr,pending.mul(teamRatio).div(100));
pending = pending.sub(pending.mul(lockRatio.add(teamRatio)).div(100));
starToken.safeTransfer(rewardAddr,pending.mul(rewardRatio).div(100));
pending = pending.sub(pending.mul(rewardRatio).div(100));
pending = pending.div(_selfGain.add(_parentGain).add(100)).mul(100);
if (user.lastDeposit > block.timestamp.sub(604800)) {
starToken.safeTransfer(_msgSender(), pending.mul(_selfGain.add(100)).div(100).sub(pending.mul(pool.fee).div(10000)));
starNode.settleNode(_msgSender(), pending.mul(_parentGain).div(100));
user.rewardDebt = user.rewardDebt.add(pending.mul(_selfGain.add(100)).div(100).sub(pending.mul(pool.fee).div(10000)));
if(pool.fee > 0){
pending = pending.mul(pool.fee).div(10000);
starToken.safeTransfer(bonusAddr, pending.mul(70).div(100));
starToken.safeTransfer(lockAddr, pending.mul(30).div(100));
}
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), pending.mul(_parentGain).div(100));
user.rewardDebt = user.rewardDebt.add(pending);
}
user.reward = 0;
pool.accStarPerShare = accStarPerShare;
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
uint256 _extraAmount = _amount.mul(_selfGain.add(_parentGain)).div(100);
pool.extraAmount = pool.extraAmount.sub(_extraAmount);
pool.lpSupply = pool.lpSupply.sub(_amount);
pool.lpToken.safeTransfer(_msgSender(), _amount);
}
emit Withdraw(_msgSender(), _pid, _amount, isNodeUser[_msgSender()]);
}
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
require(user.amount >= _amount, "withdraw: amount error");
updatePool(_pid);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(_msgSender());
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain.add(_parentGain)).div(100));
uint256 accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
}
if(_amountGain >0){
uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12);
user.reward = user.reward.add(_amountpendingStar);
}
if(pending > 0) {
starToken.safeTransfer(lockAddr,pending.mul(lockRatio).div(100));
starToken.safeTransfer(teamAddr,pending.mul(teamRatio).div(100));
pending = pending.sub(pending.mul(lockRatio.add(teamRatio)).div(100));
starToken.safeTransfer(rewardAddr,pending.mul(rewardRatio).div(100));
pending = pending.sub(pending.mul(rewardRatio).div(100));
pending = pending.div(_selfGain.add(_parentGain).add(100)).mul(100);
if (user.lastDeposit > block.timestamp.sub(604800)) {
starToken.safeTransfer(_msgSender(), pending.mul(_selfGain.add(100)).div(100).sub(pending.mul(pool.fee).div(10000)));
starNode.settleNode(_msgSender(), pending.mul(_parentGain).div(100));
user.rewardDebt = user.rewardDebt.add(pending.mul(_selfGain.add(100)).div(100).sub(pending.mul(pool.fee).div(10000)));
if(pool.fee > 0){
pending = pending.mul(pool.fee).div(10000);
starToken.safeTransfer(bonusAddr, pending.mul(70).div(100));
starToken.safeTransfer(lockAddr, pending.mul(30).div(100));
}
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), pending.mul(_parentGain).div(100));
user.rewardDebt = user.rewardDebt.add(pending);
}
user.reward = 0;
pool.accStarPerShare = accStarPerShare;
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
uint256 _extraAmount = _amount.mul(_selfGain.add(_parentGain)).div(100);
pool.extraAmount = pool.extraAmount.sub(_extraAmount);
pool.lpSupply = pool.lpSupply.sub(_amount);
pool.lpToken.safeTransfer(_msgSender(), _amount);
}
emit Withdraw(_msgSender(), _pid, _amount, isNodeUser[_msgSender()]);
}
uint256 pending = user.reward;
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
require(user.amount >= _amount, "withdraw: amount error");
updatePool(_pid);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(_msgSender());
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain.add(_parentGain)).div(100));
uint256 accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
}
if(_amountGain >0){
uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12);
user.reward = user.reward.add(_amountpendingStar);
}
if(pending > 0) {
starToken.safeTransfer(lockAddr,pending.mul(lockRatio).div(100));
starToken.safeTransfer(teamAddr,pending.mul(teamRatio).div(100));
pending = pending.sub(pending.mul(lockRatio.add(teamRatio)).div(100));
starToken.safeTransfer(rewardAddr,pending.mul(rewardRatio).div(100));
pending = pending.sub(pending.mul(rewardRatio).div(100));
pending = pending.div(_selfGain.add(_parentGain).add(100)).mul(100);
if (user.lastDeposit > block.timestamp.sub(604800)) {
starToken.safeTransfer(_msgSender(), pending.mul(_selfGain.add(100)).div(100).sub(pending.mul(pool.fee).div(10000)));
starNode.settleNode(_msgSender(), pending.mul(_parentGain).div(100));
user.rewardDebt = user.rewardDebt.add(pending.mul(_selfGain.add(100)).div(100).sub(pending.mul(pool.fee).div(10000)));
if(pool.fee > 0){
pending = pending.mul(pool.fee).div(10000);
starToken.safeTransfer(bonusAddr, pending.mul(70).div(100));
starToken.safeTransfer(lockAddr, pending.mul(30).div(100));
}
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), pending.mul(_parentGain).div(100));
user.rewardDebt = user.rewardDebt.add(pending);
}
user.reward = 0;
pool.accStarPerShare = accStarPerShare;
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
uint256 _extraAmount = _amount.mul(_selfGain.add(_parentGain)).div(100);
pool.extraAmount = pool.extraAmount.sub(_extraAmount);
pool.lpSupply = pool.lpSupply.sub(_amount);
pool.lpToken.safeTransfer(_msgSender(), _amount);
}
emit Withdraw(_msgSender(), _pid, _amount, isNodeUser[_msgSender()]);
}
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
require(user.amount >= _amount, "withdraw: amount error");
updatePool(_pid);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(_msgSender());
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain.add(_parentGain)).div(100));
uint256 accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
}
if(_amountGain >0){
uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12);
user.reward = user.reward.add(_amountpendingStar);
}
if(pending > 0) {
starToken.safeTransfer(lockAddr,pending.mul(lockRatio).div(100));
starToken.safeTransfer(teamAddr,pending.mul(teamRatio).div(100));
pending = pending.sub(pending.mul(lockRatio.add(teamRatio)).div(100));
starToken.safeTransfer(rewardAddr,pending.mul(rewardRatio).div(100));
pending = pending.sub(pending.mul(rewardRatio).div(100));
pending = pending.div(_selfGain.add(_parentGain).add(100)).mul(100);
if (user.lastDeposit > block.timestamp.sub(604800)) {
starToken.safeTransfer(_msgSender(), pending.mul(_selfGain.add(100)).div(100).sub(pending.mul(pool.fee).div(10000)));
starNode.settleNode(_msgSender(), pending.mul(_parentGain).div(100));
user.rewardDebt = user.rewardDebt.add(pending.mul(_selfGain.add(100)).div(100).sub(pending.mul(pool.fee).div(10000)));
if(pool.fee > 0){
pending = pending.mul(pool.fee).div(10000);
starToken.safeTransfer(bonusAddr, pending.mul(70).div(100));
starToken.safeTransfer(lockAddr, pending.mul(30).div(100));
}
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), pending.mul(_parentGain).div(100));
user.rewardDebt = user.rewardDebt.add(pending);
}
user.reward = 0;
pool.accStarPerShare = accStarPerShare;
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
uint256 _extraAmount = _amount.mul(_selfGain.add(_parentGain)).div(100);
pool.extraAmount = pool.extraAmount.sub(_extraAmount);
pool.lpSupply = pool.lpSupply.sub(_amount);
pool.lpToken.safeTransfer(_msgSender(), _amount);
}
emit Withdraw(_msgSender(), _pid, _amount, isNodeUser[_msgSender()]);
}
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
require(user.amount >= _amount, "withdraw: amount error");
updatePool(_pid);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(_msgSender());
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain.add(_parentGain)).div(100));
uint256 accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
}
if(_amountGain >0){
uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12);
user.reward = user.reward.add(_amountpendingStar);
}
if(pending > 0) {
starToken.safeTransfer(lockAddr,pending.mul(lockRatio).div(100));
starToken.safeTransfer(teamAddr,pending.mul(teamRatio).div(100));
pending = pending.sub(pending.mul(lockRatio.add(teamRatio)).div(100));
starToken.safeTransfer(rewardAddr,pending.mul(rewardRatio).div(100));
pending = pending.sub(pending.mul(rewardRatio).div(100));
pending = pending.div(_selfGain.add(_parentGain).add(100)).mul(100);
if (user.lastDeposit > block.timestamp.sub(604800)) {
starToken.safeTransfer(_msgSender(), pending.mul(_selfGain.add(100)).div(100).sub(pending.mul(pool.fee).div(10000)));
starNode.settleNode(_msgSender(), pending.mul(_parentGain).div(100));
user.rewardDebt = user.rewardDebt.add(pending.mul(_selfGain.add(100)).div(100).sub(pending.mul(pool.fee).div(10000)));
if(pool.fee > 0){
pending = pending.mul(pool.fee).div(10000);
starToken.safeTransfer(bonusAddr, pending.mul(70).div(100));
starToken.safeTransfer(lockAddr, pending.mul(30).div(100));
}
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), pending.mul(_parentGain).div(100));
user.rewardDebt = user.rewardDebt.add(pending);
}
user.reward = 0;
pool.accStarPerShare = accStarPerShare;
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
uint256 _extraAmount = _amount.mul(_selfGain.add(_parentGain)).div(100);
pool.extraAmount = pool.extraAmount.sub(_extraAmount);
pool.lpSupply = pool.lpSupply.sub(_amount);
pool.lpToken.safeTransfer(_msgSender(), _amount);
}
emit Withdraw(_msgSender(), _pid, _amount, isNodeUser[_msgSender()]);
}
}else{
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
require(user.amount >= _amount, "withdraw: amount error");
updatePool(_pid);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(_msgSender());
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain.add(_parentGain)).div(100));
uint256 accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
}
if(_amountGain >0){
uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12);
user.reward = user.reward.add(_amountpendingStar);
}
if(pending > 0) {
starToken.safeTransfer(lockAddr,pending.mul(lockRatio).div(100));
starToken.safeTransfer(teamAddr,pending.mul(teamRatio).div(100));
pending = pending.sub(pending.mul(lockRatio.add(teamRatio)).div(100));
starToken.safeTransfer(rewardAddr,pending.mul(rewardRatio).div(100));
pending = pending.sub(pending.mul(rewardRatio).div(100));
pending = pending.div(_selfGain.add(_parentGain).add(100)).mul(100);
if (user.lastDeposit > block.timestamp.sub(604800)) {
starToken.safeTransfer(_msgSender(), pending.mul(_selfGain.add(100)).div(100).sub(pending.mul(pool.fee).div(10000)));
starNode.settleNode(_msgSender(), pending.mul(_parentGain).div(100));
user.rewardDebt = user.rewardDebt.add(pending.mul(_selfGain.add(100)).div(100).sub(pending.mul(pool.fee).div(10000)));
if(pool.fee > 0){
pending = pending.mul(pool.fee).div(10000);
starToken.safeTransfer(bonusAddr, pending.mul(70).div(100));
starToken.safeTransfer(lockAddr, pending.mul(30).div(100));
}
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), pending.mul(_parentGain).div(100));
user.rewardDebt = user.rewardDebt.add(pending);
}
user.reward = 0;
pool.accStarPerShare = accStarPerShare;
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
uint256 _extraAmount = _amount.mul(_selfGain.add(_parentGain)).div(100);
pool.extraAmount = pool.extraAmount.sub(_extraAmount);
pool.lpSupply = pool.lpSupply.sub(_amount);
pool.lpToken.safeTransfer(_msgSender(), _amount);
}
emit Withdraw(_msgSender(), _pid, _amount, isNodeUser[_msgSender()]);
}
function enterStakingNFT(uint256 _tokenId) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][_msgSender()];
require(starNFT.ownerOf(_tokenId) == _msgSender(), "error NFT user");
updatePool(0);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(_msgSender());
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain.add(_parentGain)).div(100));
uint256 accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
}
if(user.amount >0){
uint256 _nftAmountpendingStar = _nftAmountGain.mul(accStarPerShare).div(1e12);
user.nftReward = user.nftReward.add(_nftAmountpendingStar);
}
uint256 pending = user.nftReward;
if(pending > 0) {
starToken.safeTransfer(lockAddr,pending.mul(lockRatio).div(100));
starToken.safeTransfer(teamAddr,pending.mul(teamRatio).div(100));
pending = pending.sub(pending.mul(lockRatio.add(teamRatio)).div(100));
starToken.safeTransfer(rewardAddr,pending.mul(rewardRatio).div(100));
pending = pending.sub(pending.mul(rewardRatio).div(100));
pending = pending.mul(100).div(_selfGain.add(_parentGain).add(100));
starToken.safeTransfer(_msgSender(), pending.mul(_selfGain.add(100)).div(100));
user.nftRewardDebt = user.nftRewardDebt.add(pending.mul(_selfGain.add(100)).div(100));
starNode.settleNode(_msgSender(), pending.mul(_parentGain).div(100));
user.nftReward = 0;
pool.accStarPerShare = accStarPerShare;
}
if (_tokenId > 0) {
starNFT.transferFrom(_msgSender(), address(this), _tokenId);
userNFTs[_msgSender()].push(_tokenId);
(, , uint256 _price, uint256 _multi) = nftLogic.starMeta(_tokenId);
uint256 _amount = _price.mul(_multi).div(100);
uint256 _extraAmount = _amount.add(_amount.mul(_selfGain.add(_parentGain)).div(100));
pool.extraAmount = pool.extraAmount.add(_extraAmount);
pool.lpSupply = pool.lpSupply.add(_amount);
user.nftAmount = user.nftAmount.add(_amount);
user.nftLastDeposit = block.timestamp;
if(isPoolUser[0][_msgSender()] == false){
userIndex[0][pool.size] = _msgSender();
pool.size += 1;
isPoolUser[0][_msgSender()] = true;
}
}
emit Deposit(_msgSender(), 0, _tokenId, isNodeUser[_msgSender()]);
}
function enterStakingNFT(uint256 _tokenId) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][_msgSender()];
require(starNFT.ownerOf(_tokenId) == _msgSender(), "error NFT user");
updatePool(0);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(_msgSender());
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain.add(_parentGain)).div(100));
uint256 accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
}
if(user.amount >0){
uint256 _nftAmountpendingStar = _nftAmountGain.mul(accStarPerShare).div(1e12);
user.nftReward = user.nftReward.add(_nftAmountpendingStar);
}
uint256 pending = user.nftReward;
if(pending > 0) {
starToken.safeTransfer(lockAddr,pending.mul(lockRatio).div(100));
starToken.safeTransfer(teamAddr,pending.mul(teamRatio).div(100));
pending = pending.sub(pending.mul(lockRatio.add(teamRatio)).div(100));
starToken.safeTransfer(rewardAddr,pending.mul(rewardRatio).div(100));
pending = pending.sub(pending.mul(rewardRatio).div(100));
pending = pending.mul(100).div(_selfGain.add(_parentGain).add(100));
starToken.safeTransfer(_msgSender(), pending.mul(_selfGain.add(100)).div(100));
user.nftRewardDebt = user.nftRewardDebt.add(pending.mul(_selfGain.add(100)).div(100));
starNode.settleNode(_msgSender(), pending.mul(_parentGain).div(100));
user.nftReward = 0;
pool.accStarPerShare = accStarPerShare;
}
if (_tokenId > 0) {
starNFT.transferFrom(_msgSender(), address(this), _tokenId);
userNFTs[_msgSender()].push(_tokenId);
(, , uint256 _price, uint256 _multi) = nftLogic.starMeta(_tokenId);
uint256 _amount = _price.mul(_multi).div(100);
uint256 _extraAmount = _amount.add(_amount.mul(_selfGain.add(_parentGain)).div(100));
pool.extraAmount = pool.extraAmount.add(_extraAmount);
pool.lpSupply = pool.lpSupply.add(_amount);
user.nftAmount = user.nftAmount.add(_amount);
user.nftLastDeposit = block.timestamp;
if(isPoolUser[0][_msgSender()] == false){
userIndex[0][pool.size] = _msgSender();
pool.size += 1;
isPoolUser[0][_msgSender()] = true;
}
}
emit Deposit(_msgSender(), 0, _tokenId, isNodeUser[_msgSender()]);
}
function enterStakingNFT(uint256 _tokenId) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][_msgSender()];
require(starNFT.ownerOf(_tokenId) == _msgSender(), "error NFT user");
updatePool(0);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(_msgSender());
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain.add(_parentGain)).div(100));
uint256 accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
}
if(user.amount >0){
uint256 _nftAmountpendingStar = _nftAmountGain.mul(accStarPerShare).div(1e12);
user.nftReward = user.nftReward.add(_nftAmountpendingStar);
}
uint256 pending = user.nftReward;
if(pending > 0) {
starToken.safeTransfer(lockAddr,pending.mul(lockRatio).div(100));
starToken.safeTransfer(teamAddr,pending.mul(teamRatio).div(100));
pending = pending.sub(pending.mul(lockRatio.add(teamRatio)).div(100));
starToken.safeTransfer(rewardAddr,pending.mul(rewardRatio).div(100));
pending = pending.sub(pending.mul(rewardRatio).div(100));
pending = pending.mul(100).div(_selfGain.add(_parentGain).add(100));
starToken.safeTransfer(_msgSender(), pending.mul(_selfGain.add(100)).div(100));
user.nftRewardDebt = user.nftRewardDebt.add(pending.mul(_selfGain.add(100)).div(100));
starNode.settleNode(_msgSender(), pending.mul(_parentGain).div(100));
user.nftReward = 0;
pool.accStarPerShare = accStarPerShare;
}
if (_tokenId > 0) {
starNFT.transferFrom(_msgSender(), address(this), _tokenId);
userNFTs[_msgSender()].push(_tokenId);
(, , uint256 _price, uint256 _multi) = nftLogic.starMeta(_tokenId);
uint256 _amount = _price.mul(_multi).div(100);
uint256 _extraAmount = _amount.add(_amount.mul(_selfGain.add(_parentGain)).div(100));
pool.extraAmount = pool.extraAmount.add(_extraAmount);
pool.lpSupply = pool.lpSupply.add(_amount);
user.nftAmount = user.nftAmount.add(_amount);
user.nftLastDeposit = block.timestamp;
if(isPoolUser[0][_msgSender()] == false){
userIndex[0][pool.size] = _msgSender();
pool.size += 1;
isPoolUser[0][_msgSender()] = true;
}
}
emit Deposit(_msgSender(), 0, _tokenId, isNodeUser[_msgSender()]);
}
function enterStakingNFT(uint256 _tokenId) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][_msgSender()];
require(starNFT.ownerOf(_tokenId) == _msgSender(), "error NFT user");
updatePool(0);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(_msgSender());
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain.add(_parentGain)).div(100));
uint256 accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
}
if(user.amount >0){
uint256 _nftAmountpendingStar = _nftAmountGain.mul(accStarPerShare).div(1e12);
user.nftReward = user.nftReward.add(_nftAmountpendingStar);
}
uint256 pending = user.nftReward;
if(pending > 0) {
starToken.safeTransfer(lockAddr,pending.mul(lockRatio).div(100));
starToken.safeTransfer(teamAddr,pending.mul(teamRatio).div(100));
pending = pending.sub(pending.mul(lockRatio.add(teamRatio)).div(100));
starToken.safeTransfer(rewardAddr,pending.mul(rewardRatio).div(100));
pending = pending.sub(pending.mul(rewardRatio).div(100));
pending = pending.mul(100).div(_selfGain.add(_parentGain).add(100));
starToken.safeTransfer(_msgSender(), pending.mul(_selfGain.add(100)).div(100));
user.nftRewardDebt = user.nftRewardDebt.add(pending.mul(_selfGain.add(100)).div(100));
starNode.settleNode(_msgSender(), pending.mul(_parentGain).div(100));
user.nftReward = 0;
pool.accStarPerShare = accStarPerShare;
}
if (_tokenId > 0) {
starNFT.transferFrom(_msgSender(), address(this), _tokenId);
userNFTs[_msgSender()].push(_tokenId);
(, , uint256 _price, uint256 _multi) = nftLogic.starMeta(_tokenId);
uint256 _amount = _price.mul(_multi).div(100);
uint256 _extraAmount = _amount.add(_amount.mul(_selfGain.add(_parentGain)).div(100));
pool.extraAmount = pool.extraAmount.add(_extraAmount);
pool.lpSupply = pool.lpSupply.add(_amount);
user.nftAmount = user.nftAmount.add(_amount);
user.nftLastDeposit = block.timestamp;
if(isPoolUser[0][_msgSender()] == false){
userIndex[0][pool.size] = _msgSender();
pool.size += 1;
isPoolUser[0][_msgSender()] = true;
}
}
emit Deposit(_msgSender(), 0, _tokenId, isNodeUser[_msgSender()]);
}
function enterStakingNFT(uint256 _tokenId) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][_msgSender()];
require(starNFT.ownerOf(_tokenId) == _msgSender(), "error NFT user");
updatePool(0);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(_msgSender());
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain.add(_parentGain)).div(100));
uint256 accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
}
if(user.amount >0){
uint256 _nftAmountpendingStar = _nftAmountGain.mul(accStarPerShare).div(1e12);
user.nftReward = user.nftReward.add(_nftAmountpendingStar);
}
uint256 pending = user.nftReward;
if(pending > 0) {
starToken.safeTransfer(lockAddr,pending.mul(lockRatio).div(100));
starToken.safeTransfer(teamAddr,pending.mul(teamRatio).div(100));
pending = pending.sub(pending.mul(lockRatio.add(teamRatio)).div(100));
starToken.safeTransfer(rewardAddr,pending.mul(rewardRatio).div(100));
pending = pending.sub(pending.mul(rewardRatio).div(100));
pending = pending.mul(100).div(_selfGain.add(_parentGain).add(100));
starToken.safeTransfer(_msgSender(), pending.mul(_selfGain.add(100)).div(100));
user.nftRewardDebt = user.nftRewardDebt.add(pending.mul(_selfGain.add(100)).div(100));
starNode.settleNode(_msgSender(), pending.mul(_parentGain).div(100));
user.nftReward = 0;
pool.accStarPerShare = accStarPerShare;
}
if (_tokenId > 0) {
starNFT.transferFrom(_msgSender(), address(this), _tokenId);
userNFTs[_msgSender()].push(_tokenId);
(, , uint256 _price, uint256 _multi) = nftLogic.starMeta(_tokenId);
uint256 _amount = _price.mul(_multi).div(100);
uint256 _extraAmount = _amount.add(_amount.mul(_selfGain.add(_parentGain)).div(100));
pool.extraAmount = pool.extraAmount.add(_extraAmount);
pool.lpSupply = pool.lpSupply.add(_amount);
user.nftAmount = user.nftAmount.add(_amount);
user.nftLastDeposit = block.timestamp;
if(isPoolUser[0][_msgSender()] == false){
userIndex[0][pool.size] = _msgSender();
pool.size += 1;
isPoolUser[0][_msgSender()] = true;
}
}
emit Deposit(_msgSender(), 0, _tokenId, isNodeUser[_msgSender()]);
}
function enterStakingNFT(uint256 _tokenId) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][_msgSender()];
require(starNFT.ownerOf(_tokenId) == _msgSender(), "error NFT user");
updatePool(0);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(_msgSender());
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain.add(_parentGain)).div(100));
uint256 accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accStarPerShare = starReward.mul(1e12).div(pool.lpSupply);
}
if(user.amount >0){
uint256 _nftAmountpendingStar = _nftAmountGain.mul(accStarPerShare).div(1e12);
user.nftReward = user.nftReward.add(_nftAmountpendingStar);
}
uint256 pending = user.nftReward;
if(pending > 0) {
starToken.safeTransfer(lockAddr,pending.mul(lockRatio).div(100));
starToken.safeTransfer(teamAddr,pending.mul(teamRatio).div(100));
pending = pending.sub(pending.mul(lockRatio.add(teamRatio)).div(100));
starToken.safeTransfer(rewardAddr,pending.mul(rewardRatio).div(100));
pending = pending.sub(pending.mul(rewardRatio).div(100));
pending = pending.mul(100).div(_selfGain.add(_parentGain).add(100));
starToken.safeTransfer(_msgSender(), pending.mul(_selfGain.add(100)).div(100));
user.nftRewardDebt = user.nftRewardDebt.add(pending.mul(_selfGain.add(100)).div(100));
starNode.settleNode(_msgSender(), pending.mul(_parentGain).div(100));
user.nftReward = 0;
pool.accStarPerShare = accStarPerShare;
}
if (_tokenId > 0) {
starNFT.transferFrom(_msgSender(), address(this), _tokenId);
userNFTs[_msgSender()].push(_tokenId);
(, , uint256 _price, uint256 _multi) = nftLogic.starMeta(_tokenId);
uint256 _amount = _price.mul(_multi).div(100);
uint256 _extraAmount = _amount.add(_amount.mul(_selfGain.add(_parentGain)).div(100));
pool.extraAmount = pool.extraAmount.add(_extraAmount);
pool.lpSupply = pool.lpSupply.add(_amount);
user.nftAmount = user.nftAmount.add(_amount);
user.nftLastDeposit = block.timestamp;
if(isPoolUser[0][_msgSender()] == false){
userIndex[0][pool.size] = _msgSender();
pool.size += 1;
isPoolUser[0][_msgSender()] = true;
}
}
emit Deposit(_msgSender(), 0, _tokenId, isNodeUser[_msgSender()]);
}
function leaveStakingNFT(uint256 _tokenId) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][_msgSender()];
SlotInfo memory slot;
require(userNFTs[_msgSender()].length > 0, "no NFT");
updatePool(0);
(slot._selfGain, slot._parentGain) = starNode.nodeGain(_msgSender());
slot._self_parentGain = slot._selfGain.add(slot._parentGain);
slot._nftAmountGain = user.nftAmount.add(user.nftAmount.mul(slot._self_parentGain).div(100));
slot.accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
slot.multiplier = getMultiplier(pool.lastRewardBlock, block.number);
slot.starReward = slot.multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
slot.accStarPerShare = slot.starReward.mul(1e12).div(pool.lpSupply);
}
if(user.amount >0){
uint256 _nftAmountpendingStar = slot._nftAmountGain.mul(slot.accStarPerShare).div(1e12);
user.nftReward = user.nftReward.add(_nftAmountpendingStar);
}
uint256 pending = user.nftReward;
if(pending > 0) {
starToken.safeTransfer(lockAddr,pending.mul(lockRatio).div(100));
starToken.safeTransfer(teamAddr,pending.mul(teamRatio).div(100));
pending = pending.sub(pending.mul(lockRatio.add(teamRatio)).div(100));
starToken.safeTransfer(rewardAddr,pending.mul(rewardRatio).div(100));
pending = pending.sub(pending.mul(rewardRatio).div(100));
pending = pending.mul(100).div(slot._self_parentGain.add(100));
if (user.lastDeposit > block.timestamp.sub(604800)) {
starToken.safeTransfer(_msgSender(), pending.mul(slot._selfGain.add(100)).div(100).sub(pending.mul(pool.fee).div(10000)));
starNode.settleNode(_msgSender(), pending.mul(slot._parentGain).div(100));
user.nftRewardDebt = user.nftRewardDebt.add(pending.mul(slot._selfGain.add(100)).div(100).sub(pending.mul(pool.fee).div(10000)));
pending = pending.mul(pool.fee).div(10000);
starToken.safeTransfer(bonusAddr, pending.mul(70).div(100));
starToken.safeTransfer(lockAddr, pending.mul(30).div(100));
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), pending.mul(slot._parentGain).div(100));
user.nftRewardDebt = user.nftRewardDebt.add(pending);
}
user.nftReward = 0;
pool.accStarPerShare = slot.accStarPerShare;
}
if (_tokenId > 0) {
uint256[] storage _userNFTs = userNFTs[_msgSender()];
for (slot.i = 0; slot.i < _userNFTs.length; slot.i ++) {
if(_userNFTs[slot.i] == _tokenId) {
(, , uint256 _price, uint256 _multi) = nftLogic.starMeta(_tokenId);
slot._amount = _price.mul(_multi).div(100);
if(slot._amount > 0) {
uint256 _extraAmount = slot._amount.add(slot._amount.mul(slot._self_parentGain).div(100));
pool.extraAmount = pool.extraAmount.sub(_extraAmount);
pool.lpSupply = pool.lpSupply.sub(slot._amount);
user.amount = user.amount.sub(slot._amount);
user.nftAmount = user.nftAmount.sub(slot._amount);
_userNFTs[slot.i] = _userNFTs[_userNFTs.length - 1];
_userNFTs.pop();
}
starNFT.transferFrom(address(this), _msgSender(), _tokenId);
slot._nftAmountGain = user.nftAmount.add(user.nftAmount.mul(slot._selfGain).div(100));
user.nftRewardDebt = slot._nftAmountGain.mul(pool.accStarPerShare).div(1e12);
emit Withdraw(_msgSender(), 0, _price.mul(_multi).div(100), isNodeUser[_msgSender()]);
break;
}
}
}
}
function leaveStakingNFT(uint256 _tokenId) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][_msgSender()];
SlotInfo memory slot;
require(userNFTs[_msgSender()].length > 0, "no NFT");
updatePool(0);
(slot._selfGain, slot._parentGain) = starNode.nodeGain(_msgSender());
slot._self_parentGain = slot._selfGain.add(slot._parentGain);
slot._nftAmountGain = user.nftAmount.add(user.nftAmount.mul(slot._self_parentGain).div(100));
slot.accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
slot.multiplier = getMultiplier(pool.lastRewardBlock, block.number);
slot.starReward = slot.multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
slot.accStarPerShare = slot.starReward.mul(1e12).div(pool.lpSupply);
}
if(user.amount >0){
uint256 _nftAmountpendingStar = slot._nftAmountGain.mul(slot.accStarPerShare).div(1e12);
user.nftReward = user.nftReward.add(_nftAmountpendingStar);
}
uint256 pending = user.nftReward;
if(pending > 0) {
starToken.safeTransfer(lockAddr,pending.mul(lockRatio).div(100));
starToken.safeTransfer(teamAddr,pending.mul(teamRatio).div(100));
pending = pending.sub(pending.mul(lockRatio.add(teamRatio)).div(100));
starToken.safeTransfer(rewardAddr,pending.mul(rewardRatio).div(100));
pending = pending.sub(pending.mul(rewardRatio).div(100));
pending = pending.mul(100).div(slot._self_parentGain.add(100));
if (user.lastDeposit > block.timestamp.sub(604800)) {
starToken.safeTransfer(_msgSender(), pending.mul(slot._selfGain.add(100)).div(100).sub(pending.mul(pool.fee).div(10000)));
starNode.settleNode(_msgSender(), pending.mul(slot._parentGain).div(100));
user.nftRewardDebt = user.nftRewardDebt.add(pending.mul(slot._selfGain.add(100)).div(100).sub(pending.mul(pool.fee).div(10000)));
pending = pending.mul(pool.fee).div(10000);
starToken.safeTransfer(bonusAddr, pending.mul(70).div(100));
starToken.safeTransfer(lockAddr, pending.mul(30).div(100));
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), pending.mul(slot._parentGain).div(100));
user.nftRewardDebt = user.nftRewardDebt.add(pending);
}
user.nftReward = 0;
pool.accStarPerShare = slot.accStarPerShare;
}
if (_tokenId > 0) {
uint256[] storage _userNFTs = userNFTs[_msgSender()];
for (slot.i = 0; slot.i < _userNFTs.length; slot.i ++) {
if(_userNFTs[slot.i] == _tokenId) {
(, , uint256 _price, uint256 _multi) = nftLogic.starMeta(_tokenId);
slot._amount = _price.mul(_multi).div(100);
if(slot._amount > 0) {
uint256 _extraAmount = slot._amount.add(slot._amount.mul(slot._self_parentGain).div(100));
pool.extraAmount = pool.extraAmount.sub(_extraAmount);
pool.lpSupply = pool.lpSupply.sub(slot._amount);
user.amount = user.amount.sub(slot._amount);
user.nftAmount = user.nftAmount.sub(slot._amount);
_userNFTs[slot.i] = _userNFTs[_userNFTs.length - 1];
_userNFTs.pop();
}
starNFT.transferFrom(address(this), _msgSender(), _tokenId);
slot._nftAmountGain = user.nftAmount.add(user.nftAmount.mul(slot._selfGain).div(100));
user.nftRewardDebt = slot._nftAmountGain.mul(pool.accStarPerShare).div(1e12);
emit Withdraw(_msgSender(), 0, _price.mul(_multi).div(100), isNodeUser[_msgSender()]);
break;
}
}
}
}
function leaveStakingNFT(uint256 _tokenId) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][_msgSender()];
SlotInfo memory slot;
require(userNFTs[_msgSender()].length > 0, "no NFT");
updatePool(0);
(slot._selfGain, slot._parentGain) = starNode.nodeGain(_msgSender());
slot._self_parentGain = slot._selfGain.add(slot._parentGain);
slot._nftAmountGain = user.nftAmount.add(user.nftAmount.mul(slot._self_parentGain).div(100));
slot.accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
slot.multiplier = getMultiplier(pool.lastRewardBlock, block.number);
slot.starReward = slot.multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
slot.accStarPerShare = slot.starReward.mul(1e12).div(pool.lpSupply);
}
if(user.amount >0){
uint256 _nftAmountpendingStar = slot._nftAmountGain.mul(slot.accStarPerShare).div(1e12);
user.nftReward = user.nftReward.add(_nftAmountpendingStar);
}
uint256 pending = user.nftReward;
if(pending > 0) {
starToken.safeTransfer(lockAddr,pending.mul(lockRatio).div(100));
starToken.safeTransfer(teamAddr,pending.mul(teamRatio).div(100));
pending = pending.sub(pending.mul(lockRatio.add(teamRatio)).div(100));
starToken.safeTransfer(rewardAddr,pending.mul(rewardRatio).div(100));
pending = pending.sub(pending.mul(rewardRatio).div(100));
pending = pending.mul(100).div(slot._self_parentGain.add(100));
if (user.lastDeposit > block.timestamp.sub(604800)) {
starToken.safeTransfer(_msgSender(), pending.mul(slot._selfGain.add(100)).div(100).sub(pending.mul(pool.fee).div(10000)));
starNode.settleNode(_msgSender(), pending.mul(slot._parentGain).div(100));
user.nftRewardDebt = user.nftRewardDebt.add(pending.mul(slot._selfGain.add(100)).div(100).sub(pending.mul(pool.fee).div(10000)));
pending = pending.mul(pool.fee).div(10000);
starToken.safeTransfer(bonusAddr, pending.mul(70).div(100));
starToken.safeTransfer(lockAddr, pending.mul(30).div(100));
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), pending.mul(slot._parentGain).div(100));
user.nftRewardDebt = user.nftRewardDebt.add(pending);
}
user.nftReward = 0;
pool.accStarPerShare = slot.accStarPerShare;
}
if (_tokenId > 0) {
uint256[] storage _userNFTs = userNFTs[_msgSender()];
for (slot.i = 0; slot.i < _userNFTs.length; slot.i ++) {
if(_userNFTs[slot.i] == _tokenId) {
(, , uint256 _price, uint256 _multi) = nftLogic.starMeta(_tokenId);
slot._amount = _price.mul(_multi).div(100);
if(slot._amount > 0) {
uint256 _extraAmount = slot._amount.add(slot._amount.mul(slot._self_parentGain).div(100));
pool.extraAmount = pool.extraAmount.sub(_extraAmount);
pool.lpSupply = pool.lpSupply.sub(slot._amount);
user.amount = user.amount.sub(slot._amount);
user.nftAmount = user.nftAmount.sub(slot._amount);
_userNFTs[slot.i] = _userNFTs[_userNFTs.length - 1];
_userNFTs.pop();
}
starNFT.transferFrom(address(this), _msgSender(), _tokenId);
slot._nftAmountGain = user.nftAmount.add(user.nftAmount.mul(slot._selfGain).div(100));
user.nftRewardDebt = slot._nftAmountGain.mul(pool.accStarPerShare).div(1e12);
emit Withdraw(_msgSender(), 0, _price.mul(_multi).div(100), isNodeUser[_msgSender()]);
break;
}
}
}
}
function leaveStakingNFT(uint256 _tokenId) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][_msgSender()];
SlotInfo memory slot;
require(userNFTs[_msgSender()].length > 0, "no NFT");
updatePool(0);
(slot._selfGain, slot._parentGain) = starNode.nodeGain(_msgSender());
slot._self_parentGain = slot._selfGain.add(slot._parentGain);
slot._nftAmountGain = user.nftAmount.add(user.nftAmount.mul(slot._self_parentGain).div(100));
slot.accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
slot.multiplier = getMultiplier(pool.lastRewardBlock, block.number);
slot.starReward = slot.multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
slot.accStarPerShare = slot.starReward.mul(1e12).div(pool.lpSupply);
}
if(user.amount >0){
uint256 _nftAmountpendingStar = slot._nftAmountGain.mul(slot.accStarPerShare).div(1e12);
user.nftReward = user.nftReward.add(_nftAmountpendingStar);
}
uint256 pending = user.nftReward;
if(pending > 0) {
starToken.safeTransfer(lockAddr,pending.mul(lockRatio).div(100));
starToken.safeTransfer(teamAddr,pending.mul(teamRatio).div(100));
pending = pending.sub(pending.mul(lockRatio.add(teamRatio)).div(100));
starToken.safeTransfer(rewardAddr,pending.mul(rewardRatio).div(100));
pending = pending.sub(pending.mul(rewardRatio).div(100));
pending = pending.mul(100).div(slot._self_parentGain.add(100));
if (user.lastDeposit > block.timestamp.sub(604800)) {
starToken.safeTransfer(_msgSender(), pending.mul(slot._selfGain.add(100)).div(100).sub(pending.mul(pool.fee).div(10000)));
starNode.settleNode(_msgSender(), pending.mul(slot._parentGain).div(100));
user.nftRewardDebt = user.nftRewardDebt.add(pending.mul(slot._selfGain.add(100)).div(100).sub(pending.mul(pool.fee).div(10000)));
pending = pending.mul(pool.fee).div(10000);
starToken.safeTransfer(bonusAddr, pending.mul(70).div(100));
starToken.safeTransfer(lockAddr, pending.mul(30).div(100));
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), pending.mul(slot._parentGain).div(100));
user.nftRewardDebt = user.nftRewardDebt.add(pending);
}
user.nftReward = 0;
pool.accStarPerShare = slot.accStarPerShare;
}
if (_tokenId > 0) {
uint256[] storage _userNFTs = userNFTs[_msgSender()];
for (slot.i = 0; slot.i < _userNFTs.length; slot.i ++) {
if(_userNFTs[slot.i] == _tokenId) {
(, , uint256 _price, uint256 _multi) = nftLogic.starMeta(_tokenId);
slot._amount = _price.mul(_multi).div(100);
if(slot._amount > 0) {
uint256 _extraAmount = slot._amount.add(slot._amount.mul(slot._self_parentGain).div(100));
pool.extraAmount = pool.extraAmount.sub(_extraAmount);
pool.lpSupply = pool.lpSupply.sub(slot._amount);
user.amount = user.amount.sub(slot._amount);
user.nftAmount = user.nftAmount.sub(slot._amount);
_userNFTs[slot.i] = _userNFTs[_userNFTs.length - 1];
_userNFTs.pop();
}
starNFT.transferFrom(address(this), _msgSender(), _tokenId);
slot._nftAmountGain = user.nftAmount.add(user.nftAmount.mul(slot._selfGain).div(100));
user.nftRewardDebt = slot._nftAmountGain.mul(pool.accStarPerShare).div(1e12);
emit Withdraw(_msgSender(), 0, _price.mul(_multi).div(100), isNodeUser[_msgSender()]);
break;
}
}
}
}
function leaveStakingNFT(uint256 _tokenId) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][_msgSender()];
SlotInfo memory slot;
require(userNFTs[_msgSender()].length > 0, "no NFT");
updatePool(0);
(slot._selfGain, slot._parentGain) = starNode.nodeGain(_msgSender());
slot._self_parentGain = slot._selfGain.add(slot._parentGain);
slot._nftAmountGain = user.nftAmount.add(user.nftAmount.mul(slot._self_parentGain).div(100));
slot.accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
slot.multiplier = getMultiplier(pool.lastRewardBlock, block.number);
slot.starReward = slot.multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
slot.accStarPerShare = slot.starReward.mul(1e12).div(pool.lpSupply);
}
if(user.amount >0){
uint256 _nftAmountpendingStar = slot._nftAmountGain.mul(slot.accStarPerShare).div(1e12);
user.nftReward = user.nftReward.add(_nftAmountpendingStar);
}
uint256 pending = user.nftReward;
if(pending > 0) {
starToken.safeTransfer(lockAddr,pending.mul(lockRatio).div(100));
starToken.safeTransfer(teamAddr,pending.mul(teamRatio).div(100));
pending = pending.sub(pending.mul(lockRatio.add(teamRatio)).div(100));
starToken.safeTransfer(rewardAddr,pending.mul(rewardRatio).div(100));
pending = pending.sub(pending.mul(rewardRatio).div(100));
pending = pending.mul(100).div(slot._self_parentGain.add(100));
if (user.lastDeposit > block.timestamp.sub(604800)) {
starToken.safeTransfer(_msgSender(), pending.mul(slot._selfGain.add(100)).div(100).sub(pending.mul(pool.fee).div(10000)));
starNode.settleNode(_msgSender(), pending.mul(slot._parentGain).div(100));
user.nftRewardDebt = user.nftRewardDebt.add(pending.mul(slot._selfGain.add(100)).div(100).sub(pending.mul(pool.fee).div(10000)));
pending = pending.mul(pool.fee).div(10000);
starToken.safeTransfer(bonusAddr, pending.mul(70).div(100));
starToken.safeTransfer(lockAddr, pending.mul(30).div(100));
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), pending.mul(slot._parentGain).div(100));
user.nftRewardDebt = user.nftRewardDebt.add(pending);
}
user.nftReward = 0;
pool.accStarPerShare = slot.accStarPerShare;
}
if (_tokenId > 0) {
uint256[] storage _userNFTs = userNFTs[_msgSender()];
for (slot.i = 0; slot.i < _userNFTs.length; slot.i ++) {
if(_userNFTs[slot.i] == _tokenId) {
(, , uint256 _price, uint256 _multi) = nftLogic.starMeta(_tokenId);
slot._amount = _price.mul(_multi).div(100);
if(slot._amount > 0) {
uint256 _extraAmount = slot._amount.add(slot._amount.mul(slot._self_parentGain).div(100));
pool.extraAmount = pool.extraAmount.sub(_extraAmount);
pool.lpSupply = pool.lpSupply.sub(slot._amount);
user.amount = user.amount.sub(slot._amount);
user.nftAmount = user.nftAmount.sub(slot._amount);
_userNFTs[slot.i] = _userNFTs[_userNFTs.length - 1];
_userNFTs.pop();
}
starNFT.transferFrom(address(this), _msgSender(), _tokenId);
slot._nftAmountGain = user.nftAmount.add(user.nftAmount.mul(slot._selfGain).div(100));
user.nftRewardDebt = slot._nftAmountGain.mul(pool.accStarPerShare).div(1e12);
emit Withdraw(_msgSender(), 0, _price.mul(_multi).div(100), isNodeUser[_msgSender()]);
break;
}
}
}
}
}else{
function leaveStakingNFT(uint256 _tokenId) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][_msgSender()];
SlotInfo memory slot;
require(userNFTs[_msgSender()].length > 0, "no NFT");
updatePool(0);
(slot._selfGain, slot._parentGain) = starNode.nodeGain(_msgSender());
slot._self_parentGain = slot._selfGain.add(slot._parentGain);
slot._nftAmountGain = user.nftAmount.add(user.nftAmount.mul(slot._self_parentGain).div(100));
slot.accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
slot.multiplier = getMultiplier(pool.lastRewardBlock, block.number);
slot.starReward = slot.multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
slot.accStarPerShare = slot.starReward.mul(1e12).div(pool.lpSupply);
}
if(user.amount >0){
uint256 _nftAmountpendingStar = slot._nftAmountGain.mul(slot.accStarPerShare).div(1e12);
user.nftReward = user.nftReward.add(_nftAmountpendingStar);
}
uint256 pending = user.nftReward;
if(pending > 0) {
starToken.safeTransfer(lockAddr,pending.mul(lockRatio).div(100));
starToken.safeTransfer(teamAddr,pending.mul(teamRatio).div(100));
pending = pending.sub(pending.mul(lockRatio.add(teamRatio)).div(100));
starToken.safeTransfer(rewardAddr,pending.mul(rewardRatio).div(100));
pending = pending.sub(pending.mul(rewardRatio).div(100));
pending = pending.mul(100).div(slot._self_parentGain.add(100));
if (user.lastDeposit > block.timestamp.sub(604800)) {
starToken.safeTransfer(_msgSender(), pending.mul(slot._selfGain.add(100)).div(100).sub(pending.mul(pool.fee).div(10000)));
starNode.settleNode(_msgSender(), pending.mul(slot._parentGain).div(100));
user.nftRewardDebt = user.nftRewardDebt.add(pending.mul(slot._selfGain.add(100)).div(100).sub(pending.mul(pool.fee).div(10000)));
pending = pending.mul(pool.fee).div(10000);
starToken.safeTransfer(bonusAddr, pending.mul(70).div(100));
starToken.safeTransfer(lockAddr, pending.mul(30).div(100));
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), pending.mul(slot._parentGain).div(100));
user.nftRewardDebt = user.nftRewardDebt.add(pending);
}
user.nftReward = 0;
pool.accStarPerShare = slot.accStarPerShare;
}
if (_tokenId > 0) {
uint256[] storage _userNFTs = userNFTs[_msgSender()];
for (slot.i = 0; slot.i < _userNFTs.length; slot.i ++) {
if(_userNFTs[slot.i] == _tokenId) {
(, , uint256 _price, uint256 _multi) = nftLogic.starMeta(_tokenId);
slot._amount = _price.mul(_multi).div(100);
if(slot._amount > 0) {
uint256 _extraAmount = slot._amount.add(slot._amount.mul(slot._self_parentGain).div(100));
pool.extraAmount = pool.extraAmount.sub(_extraAmount);
pool.lpSupply = pool.lpSupply.sub(slot._amount);
user.amount = user.amount.sub(slot._amount);
user.nftAmount = user.nftAmount.sub(slot._amount);
_userNFTs[slot.i] = _userNFTs[_userNFTs.length - 1];
_userNFTs.pop();
}
starNFT.transferFrom(address(this), _msgSender(), _tokenId);
slot._nftAmountGain = user.nftAmount.add(user.nftAmount.mul(slot._selfGain).div(100));
user.nftRewardDebt = slot._nftAmountGain.mul(pool.accStarPerShare).div(1e12);
emit Withdraw(_msgSender(), 0, _price.mul(_multi).div(100), isNodeUser[_msgSender()]);
break;
}
}
}
}
function leaveStakingNFT(uint256 _tokenId) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][_msgSender()];
SlotInfo memory slot;
require(userNFTs[_msgSender()].length > 0, "no NFT");
updatePool(0);
(slot._selfGain, slot._parentGain) = starNode.nodeGain(_msgSender());
slot._self_parentGain = slot._selfGain.add(slot._parentGain);
slot._nftAmountGain = user.nftAmount.add(user.nftAmount.mul(slot._self_parentGain).div(100));
slot.accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
slot.multiplier = getMultiplier(pool.lastRewardBlock, block.number);
slot.starReward = slot.multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
slot.accStarPerShare = slot.starReward.mul(1e12).div(pool.lpSupply);
}
if(user.amount >0){
uint256 _nftAmountpendingStar = slot._nftAmountGain.mul(slot.accStarPerShare).div(1e12);
user.nftReward = user.nftReward.add(_nftAmountpendingStar);
}
uint256 pending = user.nftReward;
if(pending > 0) {
starToken.safeTransfer(lockAddr,pending.mul(lockRatio).div(100));
starToken.safeTransfer(teamAddr,pending.mul(teamRatio).div(100));
pending = pending.sub(pending.mul(lockRatio.add(teamRatio)).div(100));
starToken.safeTransfer(rewardAddr,pending.mul(rewardRatio).div(100));
pending = pending.sub(pending.mul(rewardRatio).div(100));
pending = pending.mul(100).div(slot._self_parentGain.add(100));
if (user.lastDeposit > block.timestamp.sub(604800)) {
starToken.safeTransfer(_msgSender(), pending.mul(slot._selfGain.add(100)).div(100).sub(pending.mul(pool.fee).div(10000)));
starNode.settleNode(_msgSender(), pending.mul(slot._parentGain).div(100));
user.nftRewardDebt = user.nftRewardDebt.add(pending.mul(slot._selfGain.add(100)).div(100).sub(pending.mul(pool.fee).div(10000)));
pending = pending.mul(pool.fee).div(10000);
starToken.safeTransfer(bonusAddr, pending.mul(70).div(100));
starToken.safeTransfer(lockAddr, pending.mul(30).div(100));
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), pending.mul(slot._parentGain).div(100));
user.nftRewardDebt = user.nftRewardDebt.add(pending);
}
user.nftReward = 0;
pool.accStarPerShare = slot.accStarPerShare;
}
if (_tokenId > 0) {
uint256[] storage _userNFTs = userNFTs[_msgSender()];
for (slot.i = 0; slot.i < _userNFTs.length; slot.i ++) {
if(_userNFTs[slot.i] == _tokenId) {
(, , uint256 _price, uint256 _multi) = nftLogic.starMeta(_tokenId);
slot._amount = _price.mul(_multi).div(100);
if(slot._amount > 0) {
uint256 _extraAmount = slot._amount.add(slot._amount.mul(slot._self_parentGain).div(100));
pool.extraAmount = pool.extraAmount.sub(_extraAmount);
pool.lpSupply = pool.lpSupply.sub(slot._amount);
user.amount = user.amount.sub(slot._amount);
user.nftAmount = user.nftAmount.sub(slot._amount);
_userNFTs[slot.i] = _userNFTs[_userNFTs.length - 1];
_userNFTs.pop();
}
starNFT.transferFrom(address(this), _msgSender(), _tokenId);
slot._nftAmountGain = user.nftAmount.add(user.nftAmount.mul(slot._selfGain).div(100));
user.nftRewardDebt = slot._nftAmountGain.mul(pool.accStarPerShare).div(1e12);
emit Withdraw(_msgSender(), 0, _price.mul(_multi).div(100), isNodeUser[_msgSender()]);
break;
}
}
}
}
function leaveStakingNFT(uint256 _tokenId) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][_msgSender()];
SlotInfo memory slot;
require(userNFTs[_msgSender()].length > 0, "no NFT");
updatePool(0);
(slot._selfGain, slot._parentGain) = starNode.nodeGain(_msgSender());
slot._self_parentGain = slot._selfGain.add(slot._parentGain);
slot._nftAmountGain = user.nftAmount.add(user.nftAmount.mul(slot._self_parentGain).div(100));
slot.accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
slot.multiplier = getMultiplier(pool.lastRewardBlock, block.number);
slot.starReward = slot.multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
slot.accStarPerShare = slot.starReward.mul(1e12).div(pool.lpSupply);
}
if(user.amount >0){
uint256 _nftAmountpendingStar = slot._nftAmountGain.mul(slot.accStarPerShare).div(1e12);
user.nftReward = user.nftReward.add(_nftAmountpendingStar);
}
uint256 pending = user.nftReward;
if(pending > 0) {
starToken.safeTransfer(lockAddr,pending.mul(lockRatio).div(100));
starToken.safeTransfer(teamAddr,pending.mul(teamRatio).div(100));
pending = pending.sub(pending.mul(lockRatio.add(teamRatio)).div(100));
starToken.safeTransfer(rewardAddr,pending.mul(rewardRatio).div(100));
pending = pending.sub(pending.mul(rewardRatio).div(100));
pending = pending.mul(100).div(slot._self_parentGain.add(100));
if (user.lastDeposit > block.timestamp.sub(604800)) {
starToken.safeTransfer(_msgSender(), pending.mul(slot._selfGain.add(100)).div(100).sub(pending.mul(pool.fee).div(10000)));
starNode.settleNode(_msgSender(), pending.mul(slot._parentGain).div(100));
user.nftRewardDebt = user.nftRewardDebt.add(pending.mul(slot._selfGain.add(100)).div(100).sub(pending.mul(pool.fee).div(10000)));
pending = pending.mul(pool.fee).div(10000);
starToken.safeTransfer(bonusAddr, pending.mul(70).div(100));
starToken.safeTransfer(lockAddr, pending.mul(30).div(100));
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), pending.mul(slot._parentGain).div(100));
user.nftRewardDebt = user.nftRewardDebt.add(pending);
}
user.nftReward = 0;
pool.accStarPerShare = slot.accStarPerShare;
}
if (_tokenId > 0) {
uint256[] storage _userNFTs = userNFTs[_msgSender()];
for (slot.i = 0; slot.i < _userNFTs.length; slot.i ++) {
if(_userNFTs[slot.i] == _tokenId) {
(, , uint256 _price, uint256 _multi) = nftLogic.starMeta(_tokenId);
slot._amount = _price.mul(_multi).div(100);
if(slot._amount > 0) {
uint256 _extraAmount = slot._amount.add(slot._amount.mul(slot._self_parentGain).div(100));
pool.extraAmount = pool.extraAmount.sub(_extraAmount);
pool.lpSupply = pool.lpSupply.sub(slot._amount);
user.amount = user.amount.sub(slot._amount);
user.nftAmount = user.nftAmount.sub(slot._amount);
_userNFTs[slot.i] = _userNFTs[_userNFTs.length - 1];
_userNFTs.pop();
}
starNFT.transferFrom(address(this), _msgSender(), _tokenId);
slot._nftAmountGain = user.nftAmount.add(user.nftAmount.mul(slot._selfGain).div(100));
user.nftRewardDebt = slot._nftAmountGain.mul(pool.accStarPerShare).div(1e12);
emit Withdraw(_msgSender(), 0, _price.mul(_multi).div(100), isNodeUser[_msgSender()]);
break;
}
}
}
}
function leaveStakingNFT(uint256 _tokenId) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][_msgSender()];
SlotInfo memory slot;
require(userNFTs[_msgSender()].length > 0, "no NFT");
updatePool(0);
(slot._selfGain, slot._parentGain) = starNode.nodeGain(_msgSender());
slot._self_parentGain = slot._selfGain.add(slot._parentGain);
slot._nftAmountGain = user.nftAmount.add(user.nftAmount.mul(slot._self_parentGain).div(100));
slot.accStarPerShare = pool.accStarPerShare;
if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) {
slot.multiplier = getMultiplier(pool.lastRewardBlock, block.number);
slot.starReward = slot.multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
slot.accStarPerShare = slot.starReward.mul(1e12).div(pool.lpSupply);
}
if(user.amount >0){
uint256 _nftAmountpendingStar = slot._nftAmountGain.mul(slot.accStarPerShare).div(1e12);
user.nftReward = user.nftReward.add(_nftAmountpendingStar);
}
uint256 pending = user.nftReward;
if(pending > 0) {
starToken.safeTransfer(lockAddr,pending.mul(lockRatio).div(100));
starToken.safeTransfer(teamAddr,pending.mul(teamRatio).div(100));
pending = pending.sub(pending.mul(lockRatio.add(teamRatio)).div(100));
starToken.safeTransfer(rewardAddr,pending.mul(rewardRatio).div(100));
pending = pending.sub(pending.mul(rewardRatio).div(100));
pending = pending.mul(100).div(slot._self_parentGain.add(100));
if (user.lastDeposit > block.timestamp.sub(604800)) {
starToken.safeTransfer(_msgSender(), pending.mul(slot._selfGain.add(100)).div(100).sub(pending.mul(pool.fee).div(10000)));
starNode.settleNode(_msgSender(), pending.mul(slot._parentGain).div(100));
user.nftRewardDebt = user.nftRewardDebt.add(pending.mul(slot._selfGain.add(100)).div(100).sub(pending.mul(pool.fee).div(10000)));
pending = pending.mul(pool.fee).div(10000);
starToken.safeTransfer(bonusAddr, pending.mul(70).div(100));
starToken.safeTransfer(lockAddr, pending.mul(30).div(100));
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), pending.mul(slot._parentGain).div(100));
user.nftRewardDebt = user.nftRewardDebt.add(pending);
}
user.nftReward = 0;
pool.accStarPerShare = slot.accStarPerShare;
}
if (_tokenId > 0) {
uint256[] storage _userNFTs = userNFTs[_msgSender()];
for (slot.i = 0; slot.i < _userNFTs.length; slot.i ++) {
if(_userNFTs[slot.i] == _tokenId) {
(, , uint256 _price, uint256 _multi) = nftLogic.starMeta(_tokenId);
slot._amount = _price.mul(_multi).div(100);
if(slot._amount > 0) {
uint256 _extraAmount = slot._amount.add(slot._amount.mul(slot._self_parentGain).div(100));
pool.extraAmount = pool.extraAmount.sub(_extraAmount);
pool.lpSupply = pool.lpSupply.sub(slot._amount);
user.amount = user.amount.sub(slot._amount);
user.nftAmount = user.nftAmount.sub(slot._amount);
_userNFTs[slot.i] = _userNFTs[_userNFTs.length - 1];
_userNFTs.pop();
}
starNFT.transferFrom(address(this), _msgSender(), _tokenId);
slot._nftAmountGain = user.nftAmount.add(user.nftAmount.mul(slot._selfGain).div(100));
user.nftRewardDebt = slot._nftAmountGain.mul(pool.accStarPerShare).div(1e12);
emit Withdraw(_msgSender(), 0, _price.mul(_multi).div(100), isNodeUser[_msgSender()]);
break;
}
}
}
}
function getStakingNFTAmount(address _user) view public returns (uint256) {
return userNFTs[_user].length;
}
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
pool.lpToken.safeTransfer(_msgSender(), user.amount);
emit EmergencyWithdraw(_msgSender(), _pid, user.amount, isNodeUser[_msgSender()]);
user.amount = 0;
user.rewardDebt = 0;
}
function setBonus(address _addr) external onlyOwner {
require(address(0) != _addr, "bonus address can not be address 0");
bonusAddr = _addr;
}
function getAllocationInfo() view public returns(address ,address ,address ,uint256 ,uint256 ,uint256 ) {
return (lockAddr,teamAddr,rewardAddr,lockRatio,teamRatio,rewardRatio);
}
function setAllocationInfo(address _lockAddr,address _teamAddr,address _rewardAddr,uint256 _lockRatio,uint256 _teamRatio,uint256 _rewardRatio) public onlyOwner {
lockAddr = _lockAddr;
teamAddr = _teamAddr;
rewardAddr = _rewardAddr;
lockRatio = _lockRatio;
teamRatio = _teamRatio;
rewardRatio = _rewardRatio;
}
function setStarNFT(address _addr) external onlyOwner {
require(address(0) != _addr, "NFT address can not be address 0");
starNFT = IERC721Upgradeable(_addr);
}
function setNFTLogic(address _addr) external onlyOwner {
require(address(0) != _addr, "logic address can not be address 0");
nftLogic = INFTLogic(_addr);
}
function regNodeUser(address _user) external onlyNode {
require(address(0) != _user, '');
isNodeUser[_user] = true;
}
function setNode(address _node) public onlyOwner {
require(address(0) != _node, 'node can not be address 0');
starNode = IStarNode(_node);
}
modifier onlyNode() {
require(_msgSender() == address(starNode), "not node");
_;
}
} | 13,291,854 | [
1,
7786,
39,
580,
74,
353,
326,
4171,
434,
934,
297,
18,
8264,
848,
1221,
934,
297,
471,
3904,
353,
279,
284,
1826,
3058,
93,
18,
3609,
716,
518,
1807,
4953,
429,
471,
326,
3410,
341,
491,
87,
268,
2764,
409,
1481,
7212,
18,
1021,
23178,
903,
506,
906,
4193,
358,
279,
314,
1643,
82,
1359,
13706,
6835,
3647,
21807,
353,
18662,
715,
16859,
471,
326,
19833,
848,
2405,
358,
314,
1643,
82,
6174,
18,
21940,
9831,
6453,
518,
18,
670,
1306,
4095,
518,
1807,
7934,
17,
9156,
18,
611,
369,
324,
2656,
18,
3807,
434,
1517,
729,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
13453,
39,
580,
74,
353,
10188,
6934,
16,
14223,
6914,
10784,
429,
288,
203,
565,
1450,
14060,
10477,
10784,
429,
364,
2254,
5034,
31,
203,
565,
1450,
14060,
654,
39,
3462,
10784,
429,
364,
467,
654,
39,
3462,
10784,
429,
31,
203,
203,
565,
1958,
25003,
288,
203,
3639,
2254,
5034,
19890,
31,
203,
3639,
2254,
5034,
729,
17631,
1060,
758,
23602,
31,
203,
3639,
2254,
5034,
1142,
758,
1724,
31,
203,
3639,
2254,
5034,
290,
1222,
6275,
31,
203,
3639,
2254,
5034,
290,
1222,
17631,
1060,
758,
23602,
31,
203,
3639,
2254,
5034,
290,
1222,
17631,
1060,
31,
203,
3639,
2254,
5034,
290,
1222,
1299,
17631,
1060,
758,
23602,
31,
203,
3639,
2254,
5034,
290,
1222,
3024,
758,
1724,
31,
203,
565,
289,
203,
202,
203,
565,
1958,
8828,
966,
288,
203,
3639,
2254,
5034,
12423,
3088,
1283,
31,
203,
3639,
2254,
5034,
14036,
31,
203,
3639,
2254,
5034,
963,
31,
203,
565,
289,
203,
203,
565,
1958,
23195,
966,
288,
203,
3639,
8828,
966,
2845,
31,
203,
3639,
2254,
5034,
389,
2890,
67,
2938,
43,
530,
31,
203,
3639,
2254,
5034,
389,
2890,
43,
530,
31,
203,
3639,
2254,
5034,
389,
2938,
43,
530,
31,
203,
3639,
2254,
5034,
389,
82,
1222,
6275,
43,
530,
31,
7010,
3639,
2254,
5034,
4078,
18379,
2173,
9535,
31,
203,
3639,
2254,
5034,
12423,
3088,
1283,
31,
203,
3639,
2254,
5034,
15027,
31,
203,
3639,
2254,
5034,
10443,
17631,
1060,
31,
203,
3639,
2254,
5034,
277,
31,
203,
3639,
2254,
5034,
389,
8949,
31,
203,
2
] |
pragma solidity ^0.4.24;
import "./IERCMessagingSystemProtocol.sol";
/**
* @title EthMessaging.
* @notice Contract for sending messages between accounts.
*/
contract EthMessaging is IERCMessagingSystemProtocol {
/**
* @notice Message struct.
*/
struct Message {
address from;
string hash;
uint256 time;
}
/**
* @notice Mapping for storing address last message index.
*/
mapping(address => uint256) private _lastMsgIndex;
/**
* @notice Mapping for storing address messages.
*/
mapping(address => mapping(uint256 => Message)) private _messages;
/**
* @notice Mapping for storing address public keys.
*/
mapping(address => string) private _keys;
/**
* @notice Sets public key for sender.
*
* @param key Public key for decrypting messages.
*/
function setPublicKey(string key) external {
require(bytes(key).length > 0, "key should not be empty.");
_keys[msg.sender] = key;
emit PublicKeyUpdated(msg.sender, key);
}
/**
* @notice Sends message hash to given address.
* The receiver needs to have public key.
*
* @param to Receiver address. Should not be address(0).
* @param hash Message hash. Should not be empty
*/
function sendMessage(address to, string hash) external {
require(to != address(0), "to should not be address(0).");
require(bytes(_keys[to]).length > 0, "to should have public key.");
require(bytes(hash).length > 0, "hash should not be empty.");
_messages[to][_lastMsgIndex[to]].from = msg.sender;
_messages[to][_lastMsgIndex[to]].hash = hash;
_messages[to][_lastMsgIndex[to]].time = now;
_lastMsgIndex[to]++;
emit MessageSent(
msg.sender,
to,
now,
hash
);
}
/**
* @notice Gets last message index.
*
* @param who Message owner.
*
* @return uint256 last message index.
*/
function lastIndex(address who) public view returns (uint256) {
return _lastMsgIndex[who];
}
/**
* @notice Gets last message.
*
* @param who Message owner. Should have some message.
*
* @return sender address, message hash and message date.
*/
function getLastMessage(address who) public view returns (address, string, uint256) {
require(_lastMsgIndex[who] > 0, "who does not have any message.");
return (
_messages[who][_lastMsgIndex[who] - 1].from,
_messages[who][_lastMsgIndex[who] - 1].hash,
_messages[who][_lastMsgIndex[who] - 1].time
);
}
/**
* @notice Gets message by index.
*
* @param who Message owner.
* @param index Message index. Should be a correct index.
*
* @return sender address, message hash and message date.
*/
function getMessageByIndex(address who, uint256 index) public view returns (address, string, uint256) {
require(index <= _lastMsgIndex[who], "index is bigger than last message index.");
return (
_messages[who][index - 1].from,
_messages[who][index - 1].hash,
_messages[who][index - 1].time
);
}
/**
* @notice Gets address public key.
*
* @param who Public key owner.
*
* @return adress public key.
*/
function getPublicKey(address who) public view returns (string key) {
return _keys[who];
}
}
| * @notice Gets message by index. @param who Message owner. @param index Message index. Should be a correct index. @return sender address, message hash and message date./ | function getMessageByIndex(address who, uint256 index) public view returns (address, string, uint256) {
require(index <= _lastMsgIndex[who], "index is bigger than last message index.");
return (
_messages[who][index - 1].from,
_messages[who][index - 1].hash,
_messages[who][index - 1].time
);
}
| 1,797,233 | [
1,
3002,
883,
635,
770,
18,
225,
10354,
2350,
3410,
18,
225,
770,
2350,
770,
18,
9363,
506,
279,
3434,
770,
18,
327,
5793,
1758,
16,
883,
1651,
471,
883,
1509,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2381,
21268,
12,
2867,
10354,
16,
2254,
5034,
770,
13,
1071,
1476,
1135,
261,
2867,
16,
533,
16,
2254,
5034,
13,
288,
203,
3639,
2583,
12,
1615,
1648,
389,
2722,
3332,
1016,
63,
3350,
83,
6487,
315,
1615,
353,
18983,
2353,
1142,
883,
770,
1199,
1769,
203,
3639,
327,
261,
203,
5411,
389,
6833,
63,
3350,
83,
6362,
1615,
300,
404,
8009,
2080,
16,
203,
5411,
389,
6833,
63,
3350,
83,
6362,
1615,
300,
404,
8009,
2816,
16,
203,
5411,
389,
6833,
63,
3350,
83,
6362,
1615,
300,
404,
8009,
957,
203,
3639,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/42/0x237DA1E545beAce435018a0E5a73B8ef302D60aC/sources/contracts/artifacts/treasure.sol | do not allow to drain core tokens | function governanceRecoverUnsupported(
IERC20 _token,
uint256 _amount,
address _to
) external onlyOperator {
require(address(_token) != address(ice), "ice");
require(address(_token) != address(ibond), "bond");
require(address(_token) != address(ishare), "share");
_token.safeTransfer(_to, _amount);
}
| 9,581,957 | [
1,
2896,
486,
1699,
358,
15427,
2922,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
314,
1643,
82,
1359,
27622,
8544,
12,
203,
3639,
467,
654,
39,
3462,
389,
2316,
16,
203,
3639,
2254,
5034,
389,
8949,
16,
203,
3639,
1758,
389,
869,
203,
565,
262,
3903,
1338,
5592,
288,
203,
3639,
2583,
12,
2867,
24899,
2316,
13,
480,
1758,
12,
1812,
3631,
315,
1812,
8863,
203,
3639,
2583,
12,
2867,
24899,
2316,
13,
480,
1758,
12,
495,
1434,
3631,
315,
26425,
8863,
203,
3639,
2583,
12,
2867,
24899,
2316,
13,
480,
1758,
12,
1468,
834,
3631,
315,
14419,
8863,
203,
3639,
389,
2316,
18,
4626,
5912,
24899,
869,
16,
389,
8949,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.6.12;
interface IERC20 {
function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD659(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB877(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB877(a, b, "SafeMath: subtraction overflow");
}
function SUB877(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL487(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV156(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV156(a, b, "SafeMath: division by zero");
}
function DIV156(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD860(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD860(a, b, "SafeMath: modulo by zero");
}
function MOD860(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT107(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function SENDVALUE513(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER239(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFER353.selector, to, value));
}
function SAFETRANSFERFROM64(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFERFROM954.selector, from, to, value));
}
function SAFEAPPROVE765(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.ALLOWANCE946(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, value));
}
function SAFEINCREASEALLOWANCE134(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE946(address(this), spender).ADD659(value);
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE546(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE946(address(this), spender).SUB877(value, "SafeERC20: decreased allowance below zero");
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance));
}
function _CALLOPTIONALRETURN137(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).ISCONTRACT107(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
function _ADD286(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING
if (!_CONTAINS837(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
function _REMOVE863(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
function _CONTAINS837(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING
return set._indexes[value] != 0;
}
function _LENGTH639(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING
return set._values.length;
}
function _AT524(Set storage set, uint256 index) private view returns (bytes32) { //inject NONSTANDARD NAMING
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
function ADD659(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING
return _ADD286(set._inner, bytes32(uint256(value)));
}
function REMOVE976(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING
return _REMOVE863(set._inner, bytes32(uint256(value)));
}
function CONTAINS600(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING
return _CONTAINS837(set._inner, bytes32(uint256(value)));
}
function LENGTH659(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING
return _LENGTH639(set._inner);
}
function AT450(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING
return address(uint256(_AT524(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
function ADD659(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING
return _ADD286(set._inner, bytes32(value));
}
function REMOVE976(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING
return _REMOVE863(set._inner, bytes32(value));
}
function CONTAINS600(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING
return _CONTAINS837(set._inner, bytes32(value));
}
function LENGTH659(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING
return _LENGTH639(set._inner);
}
function AT450(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING
return uint256(_AT524(set._inner, index));
}
}
contract Initializable {
bool private initialized;
bool private initializing;
modifier INITIALIZER933() { //inject NONSTANDARD NAMING
require(initializing || ISCONSTRUCTOR543() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
function ISCONSTRUCTOR543() private view returns (bool) { //inject NONSTANDARD NAMING
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
contract ContextUpgradeSafe is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __CONTEXT_INIT408() internal INITIALIZER933 { //inject NONSTANDARD NAMING
__CONTEXT_INIT_UNCHAINED28();
}
function __CONTEXT_INIT_UNCHAINED28() internal INITIALIZER933 { //inject NONSTANDARD NAMING
}
function _MSGSENDER195() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA356() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe {
address private _owner;
event OWNERSHIPTRANSFERRED637(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
function __OWNABLE_INIT503() internal INITIALIZER933 { //inject NONSTANDARD NAMING
__CONTEXT_INIT_UNCHAINED28();
__OWNABLE_INIT_UNCHAINED19();
}
function __OWNABLE_INIT_UNCHAINED19() internal INITIALIZER933 { //inject NONSTANDARD NAMING
address msgSender = _MSGSENDER195();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED637(address(0), msgSender);
}
function OWNER330() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER691() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER195(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP236() public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED637(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP889(address newOwner) public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED637(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
interface INBUNIERC20 {
function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
event LOG470(string log); //inject NONSTANDARD NAMING
}
library console {
address constant console_address243 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING
function _SENDLOGPAYLOAD647(bytes memory payload) private view { //inject NONSTANDARD NAMING
uint256 payloadLength = payload.length;
address consoleAddress = console_address243;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function LOG714() internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log()"));
}
function LOGINT241(int p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(int)", p0));
}
function LOGUINT442(uint p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0));
}
function LOGSTRING55(string memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0));
}
function LOGBOOL721(bool p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0));
}
function LOGADDRESS713(address p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0));
}
function LOGBYTES271(bytes memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes)", p0));
}
function LOGBYTE944(byte p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(byte)", p0));
}
function LOGBYTES1701(bytes1 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes1)", p0));
}
function LOGBYTES2946(bytes2 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes2)", p0));
}
function LOGBYTES314(bytes3 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes3)", p0));
}
function LOGBYTES4424(bytes4 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes4)", p0));
}
function LOGBYTES566(bytes5 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes5)", p0));
}
function LOGBYTES6220(bytes6 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes6)", p0));
}
function LOGBYTES7640(bytes7 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes7)", p0));
}
function LOGBYTES8995(bytes8 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes8)", p0));
}
function LOGBYTES9199(bytes9 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes9)", p0));
}
function LOGBYTES10336(bytes10 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes10)", p0));
}
function LOGBYTES11706(bytes11 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes11)", p0));
}
function LOGBYTES12632(bytes12 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes12)", p0));
}
function LOGBYTES13554(bytes13 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes13)", p0));
}
function LOGBYTES14593(bytes14 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes14)", p0));
}
function LOGBYTES15340(bytes15 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes15)", p0));
}
function LOGBYTES16538(bytes16 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes16)", p0));
}
function LOGBYTES17699(bytes17 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes17)", p0));
}
function LOGBYTES18607(bytes18 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes18)", p0));
}
function LOGBYTES19918(bytes19 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes19)", p0));
}
function LOGBYTES20388(bytes20 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes20)", p0));
}
function LOGBYTES21100(bytes21 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes21)", p0));
}
function LOGBYTES22420(bytes22 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes22)", p0));
}
function LOGBYTES238(bytes23 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes23)", p0));
}
function LOGBYTES24936(bytes24 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes24)", p0));
}
function LOGBYTES25750(bytes25 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes25)", p0));
}
function LOGBYTES26888(bytes26 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes26)", p0));
}
function LOGBYTES2749(bytes27 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes27)", p0));
}
function LOGBYTES28446(bytes28 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes28)", p0));
}
function LOGBYTES29383(bytes29 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes29)", p0));
}
function LOGBYTES30451(bytes30 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes30)", p0));
}
function LOGBYTES31456(bytes31 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes31)", p0));
}
function LOGBYTES32174(bytes32 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes32)", p0));
}
function LOG714(uint p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0));
}
function LOG714(string memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0));
}
function LOG714(bool p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0));
}
function LOG714(address p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0));
}
function LOG714(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function LOG714(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function LOG714(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function LOG714(uint p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function LOG714(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function LOG714(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function LOG714(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function LOG714(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function LOG714(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function LOG714(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function LOG714(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function LOG714(bool p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function LOG714(address p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function LOG714(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function LOG714(address p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function LOG714(address p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function LOG714(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function LOG714(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function LOG714(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function LOG714(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function LOG714(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function LOG714(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function LOG714(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function LOG714(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function LOG714(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function LOG714(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function LOG714(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function LOG714(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function LOG714(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function LOG714(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function LOG714(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function LOG714(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function LOG714(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function LOG714(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function LOG714(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function LOG714(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function LOG714(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function LOG714(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function LOG714(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function LOG714(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function LOG714(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function LOG714(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function LOG714(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function LOG714(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function LOG714(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function LOG714(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function LOG714(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function LOG714(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function LOG714(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function LOG714(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function LOG714(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function LOG714(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function LOG714(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function LOG714(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function LOG714(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function LOG714(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function LOG714(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function LOG714(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function LOG714(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function LOG714(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function LOG714(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function LOG714(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function LOG714(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function LOG714(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function LOG714(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function LOG714(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function LOG714(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function LOG714(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function LOG714(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function LOG714(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function LOG714(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function LOG714(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function LOG714(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function LOG714(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function LOG714(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function LOG714(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function LOG714(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function LOG714(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function LOG714(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function LOG714(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function LOG714(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// HDCore Vault distributes fees equally amongst staked pools
// Have fun reading it. Hopefully it's bug-free. God bless.
contract HdcoreVault is OwnableUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of HdCOREs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accHdcorePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws tokens to a pool. Here's what happens:
// 1. The pool's `accHdcorePerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 token; // Address of token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. HDCOREs to distribute per block.
uint256 accHdcorePerShare; // Accumulated HDCOREs per share, times 1e12. See below.
bool withdrawable; // Is this pool withdrawable?
mapping(address => mapping(address => uint256)) allowance;
}
// The HDCORE TOKEN!
INBUNIERC20 public hdcore;
// Dev address.
address public devaddr;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
uint256 public pendingRewards;
uint256 public contractStartBlock;
uint256 public epochCalculationStartBlock;
uint256 public cumulativeRewardsSinceStart;
uint256 public rewardsInThisEpoch;
uint public epoch;
// Returns fees generated since start of this contract
function AVERAGEFEESPERBLOCKSINCESTART533() external view returns (uint averagePerBlock) { //inject NONSTANDARD NAMING
averagePerBlock = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch).DIV156(block.number.SUB877(contractStartBlock));
}
// Returns averge fees in this epoch
function AVERAGEFEESPERBLOCKEPOCH880() external view returns (uint256 averagePerBlock) { //inject NONSTANDARD NAMING
averagePerBlock = rewardsInThisEpoch.DIV156(block.number.SUB877(epochCalculationStartBlock));
}
// For easy graphing historical epoch rewards
mapping(uint => uint256) public epochRewards;
//Starts a new calculation epoch
// Because averge since start will not be accurate
function STARTNEWEPOCH403() public { //inject NONSTANDARD NAMING
require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week
epochRewards[epoch] = rewardsInThisEpoch;
cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch);
rewardsInThisEpoch = 0;
epochCalculationStartBlock = block.number;
++epoch;
}
event DEPOSIT941(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING
event WITHDRAW483(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING
event EMERGENCYWITHDRAW770( //inject NONSTANDARD NAMING
address indexed user,
uint256 indexed pid,
uint256 amount
);
event APPROVAL172(address indexed owner, address indexed spender, uint256 _pid, uint256 value); //inject NONSTANDARD NAMING
function INITIALIZE896( //inject NONSTANDARD NAMING
INBUNIERC20 _hdcore
) public INITIALIZER933 {
OwnableUpgradeSafe.__OWNABLE_INIT503();
DEV_FEE = 724;
hdcore = _hdcore;
devaddr = msg.sender;
contractStartBlock = block.number;
_superAdmin = msg.sender;
}
function POOLLENGTH724() external view returns (uint256) { //inject NONSTANDARD NAMING
return poolInfo.length;
}
// Add a new token pool. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing HDCORE governance consensus
function ADD659( //inject NONSTANDARD NAMING
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate,
bool _withdrawable
) public ONLYOWNER691 {
if (_withUpdate) {
MASSUPDATEPOOLS941();
}
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].token != _token,"Error pool already added");
}
totalAllocPoint = totalAllocPoint.ADD659(_allocPoint);
poolInfo.push(
PoolInfo({
token: _token,
allocPoint: _allocPoint,
accHdcorePerShare: 0,
withdrawable : _withdrawable
})
);
}
// Update the given pool's HDCOREs allocation point. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing HDCORE governance consensus
function SET408( //inject NONSTANDARD NAMING
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public ONLYOWNER691 {
if (_withUpdate) {
MASSUPDATEPOOLS941();
}
totalAllocPoint = totalAllocPoint.SUB877(poolInfo[_pid].allocPoint).ADD659(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Update the given pool's ability to withdraw tokens
// Note contract owner is meant to be a governance contract allowing HDCORE governance consensus
function SETPOOLWITHDRAWABLE817( //inject NONSTANDARD NAMING
uint256 _pid,
bool _withdrawable
) public ONLYOWNER691 {
poolInfo[_pid].withdrawable = _withdrawable;
}
// Sets the dev fee for this contract
// defaults at 7.24%
// Note contract owner is meant to be a governance contract allowing HDCORE governance consensus
uint16 DEV_FEE;
function SETDEVFEE755(uint16 _DEV_FEE) public ONLYOWNER691 { //inject NONSTANDARD NAMING
require(_DEV_FEE <= 1000, 'Dev fee clamped at 10%');
DEV_FEE = _DEV_FEE;
}
uint256 pending_DEV_rewards;
// View function to see pending HDCOREs on frontend.
function PENDINGHDCORE546(uint256 _pid, address _user) //inject NONSTANDARD NAMING
external
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accHdcorePerShare = pool.accHdcorePerShare;
return user.amount.MUL487(accHdcorePerShare).DIV156(1e12).SUB877(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function MASSUPDATEPOOLS941() public { //inject NONSTANDARD NAMING
console.LOG714("Mass Updating Pools");
uint256 length = poolInfo.length;
uint allRewards;
for (uint256 pid = 0; pid < length; ++pid) {
allRewards = allRewards.ADD659(UPDATEPOOL374(pid));
}
pendingRewards = pendingRewards.SUB877(allRewards);
}
// ----
// Function that adds pending rewards, called by the HDCORE token.
// ----
uint256 private hdcoreBalance;
function ADDPENDINGREWARDS319(uint256 _) public { //inject NONSTANDARD NAMING
uint256 newRewards = hdcore.BALANCEOF536(address(this)).SUB877(hdcoreBalance);
if(newRewards > 0) {
hdcoreBalance = hdcore.BALANCEOF536(address(this)); // If there is no change the balance didn't change
pendingRewards = pendingRewards.ADD659(newRewards);
rewardsInThisEpoch = rewardsInThisEpoch.ADD659(newRewards);
}
}
// Update reward variables of the given pool to be up-to-date.
function UPDATEPOOL374(uint256 _pid) internal returns (uint256 hdcoreRewardWhole) { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
uint256 tokenSupply = pool.token.BALANCEOF536(address(this));
if (tokenSupply == 0) { // avoids division by 0 errors
return 0;
}
hdcoreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation
.MUL487(pool.allocPoint) // getting the percent of total pending rewards this pool should get
.DIV156(totalAllocPoint); // we can do this because pools are only mass updated
uint256 hdcoreRewardFee = hdcoreRewardWhole.MUL487(DEV_FEE).DIV156(10000);
uint256 hdcoreRewardToDistribute = hdcoreRewardWhole.SUB877(hdcoreRewardFee);
pending_DEV_rewards = pending_DEV_rewards.ADD659(hdcoreRewardFee);
pool.accHdcorePerShare = pool.accHdcorePerShare.ADD659(
hdcoreRewardToDistribute.MUL487(1e12).DIV156(tokenSupply)
);
}
// Deposit tokens to HdcoreVault for HDCORE allocation.
function DEPOSIT767(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
MASSUPDATEPOOLS941();
// Transfer pending tokens
// to user
UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender);
//Transfer in the amounts from user
// save gas
if(_amount > 0) {
pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount);
user.amount = user.amount.ADD659(_amount);
}
user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12);
emit DEPOSIT941(msg.sender, _pid, _amount);
}
// Test coverage
// [x] Does user get the deposited amounts?
// [x] Does user that its deposited for update correcty?
// [x] Does the depositor get their tokens decreased
function DEPOSITFOR318(address depositFor, uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING
// requires no allowances
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][depositFor];
MASSUPDATEPOOLS941();
// Transfer pending tokens
// to user
UPDATEANDPAYOUTPENDING193(_pid, pool, user, depositFor); // Update the balances of person that amount is being deposited for
if(_amount > 0) {
pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount);
user.amount = user.amount.ADD659(_amount); // This is depositedFor address
}
user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12);
emit DEPOSIT941(depositFor, _pid, _amount);
}
// Test coverage
// [x] Does allowance update correctly?
function SETALLOWANCEFORPOOLTOKEN927(address spender, uint256 _pid, uint256 value) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
pool.allowance[msg.sender][spender] = value;
emit APPROVAL172(msg.sender, spender, _pid, value);
}
// Test coverage
// [x] Does allowance decrease?
// [x] Do oyu need allowance
// [x] Withdraws to correct address
function WITHDRAWFROM678(address owner, uint256 _pid, uint256 _amount) public{ //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance");
pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].SUB877(_amount);
_WITHDRAW26(_pid, _amount, owner, msg.sender);
}
// Withdraw tokens from HdcoreVault.
function WITHDRAW844(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING
_WITHDRAW26(_pid, _amount, msg.sender, msg.sender);
}
// Low level withdraw function
function _WITHDRAW26(uint256 _pid, uint256 _amount, address from, address to) internal { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][from];
require(user.amount >= _amount, "withdraw: not good");
MASSUPDATEPOOLS941();
UPDATEANDPAYOUTPENDING193(_pid, pool, user, from); // Update balances of from this is not withdrawal but claiming HDCORE farmed
if(_amount > 0) {
user.amount = user.amount.SUB877(_amount);
pool.token.SAFETRANSFER239(address(to), _amount);
}
user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12);
emit WITHDRAW483(to, _pid, _amount);
}
function CLAIM95(uint256 _pid) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][msg.sender];
MASSUPDATEPOOLS941();
UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender);
}
function UPDATEANDPAYOUTPENDING193(uint256 _pid, PoolInfo storage pool, UserInfo storage user, address from) internal { //inject NONSTANDARD NAMING
if(user.amount == 0) return;
uint256 pending = user
.amount
.MUL487(pool.accHdcorePerShare)
.DIV156(1e12)
.SUB877(user.rewardDebt);
if(pending > 0) {
SAFEHDCORETRANSFER939(from, pending);
}
}
// function that lets owner/governance contract
// approve allowance for any token inside this contract
// This means all future UNI like airdrops are covered
// And at the same time allows us to give allowance to strategy contracts.
// Upcoming cYFI etc vaults strategy contracts will use this function to manage and farm yield on value locked
function SETSTRATEGYCONTRACTORDISTRIBUTIONCONTRACTALLOWANCE131(address tokenAddress, uint256 _amount, address contractAddress) public ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING
require(ISCONTRACT107(contractAddress), "Recipent is not a smart contract, BAD");
require(block.number > contractStartBlock.ADD659(95_000), "Governance setup grace period not over"); // about 2weeks
IERC20(tokenAddress).APPROVE926(contractAddress, _amount);
}
function ISCONTRACT107(address addr) public returns (bool) { //inject NONSTANDARD NAMING
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
// !Caution this will remove all your pending rewards!
function EMERGENCYWITHDRAW608(uint256 _pid) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][msg.sender];
pool.token.SAFETRANSFER239(address(msg.sender), user.amount);
emit EMERGENCYWITHDRAW770(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
// No mass update dont update pending rewards
}
// Safe hdcore transfer function, just in case if rounding error causes pool to not have enough HDCOREs.
function SAFEHDCORETRANSFER939(address _to, uint256 _amount) internal { //inject NONSTANDARD NAMING
if(_amount == 0) return;
uint256 hdcoreBal = hdcore.BALANCEOF536(address(this));
if (_amount > hdcoreBal) {
console.LOG714("transfering out for to person:", _amount);
console.LOG714("Balance of this address is :", hdcoreBal);
hdcore.TRANSFER353(_to, hdcoreBal);
hdcoreBalance = hdcore.BALANCEOF536(address(this));
} else {
hdcore.TRANSFER353(_to, _amount);
hdcoreBalance = hdcore.BALANCEOF536(address(this));
}
if(pending_DEV_rewards > 0) {
uint256 devSend = pending_DEV_rewards; // Avoid recursive loop
pending_DEV_rewards = 0;
SAFEHDCORETRANSFER939(devaddr, devSend);
}
}
// Update dev address by the previous dev.
// Note onlyOwner functions are meant for the governance contract
// allowing HDCORE governance token holders to do this functions.
function SETDEVFEERECIEVER7(address _devaddr) public ONLYOWNER691 { //inject NONSTANDARD NAMING
devaddr = _devaddr;
}
address private _superAdmin;
event SUPERADMINTRANSFERED362(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
function SUPERADMIN402() public view returns (address) { //inject NONSTANDARD NAMING
return _superAdmin;
}
modifier ONLYSUPERADMIN581() { //inject NONSTANDARD NAMING
require(_superAdmin == _MSGSENDER195(), "Super admin : caller is not super admin.");
_;
}
// Assisns super admint to address 0, making it unreachable forever
function BURNSUPERADMIN143() public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING
emit SUPERADMINTRANSFERED362(_superAdmin, address(0));
_superAdmin = address(0);
}
// Super admin can transfer its powers to another address
function NEWSUPERADMIN397(address newOwner) public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit SUPERADMINTRANSFERED362(_superAdmin, newOwner);
_superAdmin = newOwner;
}
} | inject NONSTANDARD NAMING
| function AVERAGEFEESPERBLOCKSINCESTART533() external view returns (uint averagePerBlock) { | 14,087,989 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
432,
2204,
2833,
8090,
41,
3118,
654,
11403,
55,
706,
1441,
7570,
25,
3707,
1435,
3903,
1476,
1135,
261,
11890,
8164,
2173,
1768,
13,
288,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
import "truffle/Assert.sol";
import "./MoneyMarketTest.sol";
/*
* @dev This tests the money market with tests for supply.
*/
contract MoneyMarketTest_Supply is MoneyMarketTest {
function testSupply_basicValidations() public {
address token = address(this); // must be this
address protocol = address(this); // must be this
uint err = supply(token, 10);
Assert.equal(uint(Error.MARKET_NOT_SUPPORTED), err, "should have returned Error.MARKET_NOT_SUPPORTED");
markets[token].isSupported = true;
err = supply(token, 10);
Assert.equal(uint(Error.TOKEN_INSUFFICIENT_ALLOWANCE), err, "should have returned Error.TOKEN_INSUFFICIENT_ALLOWANCE");
approve(protocol, 20); // allowed[customer][protocol] = 20; is not working. why not?
err = supply(token, 10);
Assert.equal(uint(Error.TOKEN_INSUFFICIENT_BALANCE), err, "should have returned Error.TOKEN_INSUFFICIENT_BALANCE");
}
} | @dev This tests the money market with tests for supply./ | contract MoneyMarketTest_Supply is MoneyMarketTest {
function testSupply_basicValidations() public {
uint err = supply(token, 10);
Assert.equal(uint(Error.MARKET_NOT_SUPPORTED), err, "should have returned Error.MARKET_NOT_SUPPORTED");
markets[token].isSupported = true;
err = supply(token, 10);
Assert.equal(uint(Error.TOKEN_INSUFFICIENT_ALLOWANCE), err, "should have returned Error.TOKEN_INSUFFICIENT_ALLOWANCE");
err = supply(token, 10);
Assert.equal(uint(Error.TOKEN_INSUFFICIENT_BALANCE), err, "should have returned Error.TOKEN_INSUFFICIENT_BALANCE");
}
} | 5,517,222 | [
1,
2503,
7434,
326,
15601,
13667,
598,
7434,
364,
14467,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
16892,
3882,
278,
4709,
67,
3088,
1283,
353,
16892,
3882,
278,
4709,
288,
203,
203,
565,
445,
1842,
3088,
1283,
67,
13240,
1556,
1012,
1435,
1071,
288,
203,
203,
3639,
2254,
393,
273,
14467,
12,
2316,
16,
1728,
1769,
203,
3639,
5452,
18,
9729,
12,
11890,
12,
668,
18,
12693,
1584,
67,
4400,
67,
21134,
3631,
393,
16,
315,
13139,
1240,
2106,
1068,
18,
12693,
1584,
67,
4400,
67,
21134,
8863,
203,
203,
3639,
2267,
2413,
63,
2316,
8009,
291,
7223,
273,
638,
31,
203,
203,
3639,
393,
273,
14467,
12,
2316,
16,
1728,
1769,
203,
3639,
5452,
18,
9729,
12,
11890,
12,
668,
18,
8412,
67,
706,
6639,
42,
1653,
7266,
2222,
67,
13511,
4722,
3631,
393,
16,
315,
13139,
1240,
2106,
1068,
18,
8412,
67,
706,
6639,
42,
1653,
7266,
2222,
67,
13511,
4722,
8863,
203,
203,
3639,
393,
273,
14467,
12,
2316,
16,
1728,
1769,
203,
3639,
5452,
18,
9729,
12,
11890,
12,
668,
18,
8412,
67,
706,
6639,
42,
1653,
7266,
2222,
67,
38,
1013,
4722,
3631,
393,
16,
315,
13139,
1240,
2106,
1068,
18,
8412,
67,
706,
6639,
42,
1653,
7266,
2222,
67,
38,
1013,
4722,
8863,
203,
565,
289,
203,
203,
97,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0xe02102a6a6B8CCC0a7fD2313823C8186A729fD38/sources/contracts/ThriftClubFactory.sol | Remove a consumer contract from the subscription. | function removeConsumer(address consumerAddress) public {
COORDINATOR.removeConsumer(s_subscriptionId, consumerAddress);
}
| 863,275 | [
1,
3288,
279,
4765,
6835,
628,
326,
4915,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1206,
5869,
12,
2867,
4765,
1887,
13,
1071,
288,
203,
3639,
7910,
916,
21329,
3575,
18,
4479,
5869,
12,
87,
67,
25218,
16,
4765,
1887,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xC4bfcAC43433C2435184c87aF26daDE9379b5B11/sources/project:/contracts/MtrollerUser.sol | old calculation (Compound version) | numerator = mul_(Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa}));
| 4,993,329 | [
1,
1673,
11096,
261,
16835,
1177,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
16730,
273,
14064,
67,
12,
2966,
12590,
81,
970,
21269,
30,
4501,
26595,
367,
382,
2998,
688,
49,
970,
21269,
97,
3631,
7784,
12590,
81,
970,
21269,
30,
6205,
38,
15318,
329,
49,
970,
21269,
6792,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x4452b85dE653D2c39f565Bba8f0CbebbF76fDc57/sources/EMPgov_default.sol | a function that stores the internal address of the decision-making contract to which we will transition The function can only be executed by the dictator (This function is needed because if there were a simple method of giving up power, anyone can subsequently specify an arbitrary, non-approved by the dictator, decision-making contract. Therefore, the dictator needs to approve a specific contract to which they surrender their power. | function initiateChange(address newDecisonContractAddr) external
onlyAuthorized() {
emit Log("The dictator is initiating change to a new contract!");
allowedContractAddr = newDecisonContractAddr;
}
| 9,785,340 | [
1,
69,
445,
716,
9064,
326,
2713,
1758,
434,
326,
14604,
17,
19718,
6835,
358,
1492,
732,
903,
6007,
1021,
445,
848,
1338,
506,
7120,
635,
326,
2065,
639,
261,
2503,
445,
353,
3577,
2724,
309,
1915,
4591,
279,
4143,
707,
434,
21057,
731,
7212,
16,
1281,
476,
848,
10815,
715,
4800,
392,
11078,
16,
1661,
17,
25990,
635,
326,
2065,
639,
16,
14604,
17,
19718,
6835,
18,
17189,
16,
326,
2065,
639,
4260,
358,
6617,
537,
279,
2923,
6835,
358,
1492,
2898,
5056,
5902,
3675,
7212,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
18711,
3043,
12,
2867,
394,
1799,
4530,
8924,
3178,
13,
3903,
203,
377,
1338,
15341,
1435,
288,
203,
3639,
3626,
1827,
2932,
1986,
2065,
639,
353,
1208,
22906,
2549,
358,
279,
394,
6835,
4442,
1769,
203,
3639,
2935,
8924,
3178,
273,
394,
1799,
4530,
8924,
3178,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x76DD4Ecc786aB0A027FF9A7DFf15eaE484085b7b/sources/AISexSimulator.sol | Set minimum tokens required to swap. | function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner {
_swapTokensAtAmount = swapTokensAtAmount;
}
| 4,268,078 | [
1,
694,
5224,
2430,
1931,
358,
7720,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
27724,
12521,
5157,
7614,
12,
11890,
5034,
7720,
5157,
861,
6275,
13,
1071,
1338,
5541,
288,
203,
1377,
389,
22270,
5157,
861,
6275,
273,
7720,
5157,
861,
6275,
31,
203,
225,
289,
203,
203,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xB0A1Cd3b31A8e3bbBaba15fEDdB88ABD932a677d/sources/contracts/mixins/nftMarket/NFTMarketOffer.sol | Record offer details | offer.buyer = sender;
| 8,357,013 | [
1,
2115,
10067,
3189,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
10067,
18,
70,
16213,
273,
5793,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./AtivVotes.sol";
import "./IPNFT.sol";
/**
* @title MasterChef
*
* As you know, MasterChef is the master of Sushi.
* He can make Sushi and he is a fair guy.
*
* However, He distributes ATIVs per NFT in this system.
*
* Master chef said:
* Have fun reading it. Hopefully it's bug-free. God bless.
*/
contract MasterChef is Ownable {
/// @dev The ATIV TOKEN!
AtivVotes public ativ;
/// @dev The IP NFT!
IPNFT public ipnft;
/// @dev Dev address.
address public devaddr;
// Fee. Default: 10%
uint256 public feeNumerator = 10;
uint256 public feeDenominator = 100;
event Harvest(address indexed user, uint256 indexed musicId, uint256 amount);
constructor(
AtivVotes ativ_,
IPNFT ipnft_,
address devaddr_
) {
ativ = ativ_;
ipnft = ipnft_;
devaddr = devaddr_;
}
/// @dev Update dev address by the previous dev.
function dev(address devaddr_) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = devaddr_;
}
/// @dev View function to see pending ATIVs on frontend.
function pendingAtiv(uint256 musicId_, uint256 tokenId_)
public
view
returns (uint256)
{
uint256 musicId;
uint256 gain;
uint256 lastUpdatedEpoch;
(musicId, gain, lastUpdatedEpoch) = ipnft.meta(tokenId_);
if (musicId != musicId_) { return 0; }
uint256 period = ipnft.epoch() - lastUpdatedEpoch;
if (period <= 0) { return 0; }
return period * gain;
}
/// @notice Harvest proceeds for transaction sender to `to`.
/// @param musicId_ The ID of the music.
/// @param tokenId_ The ID of the token.
/// @param to Receiver of ATIV rewards.
function harvest(uint256 musicId_, uint256 tokenId_, address to) public {
uint256 pendingAtiv_ = pendingAtiv(musicId_, tokenId_);
if (pendingAtiv_ == 0) { return; }
ipnft.updateNftEpoch(tokenId_);
ativ.mint(devaddr, pendingAtiv_ * feeNumerator / feeDenominator);
ativ.mint(to, pendingAtiv_);
emit Harvest(msg.sender, musicId_, pendingAtiv_);
}
}
| @dev View function to see pending ATIVs on frontend. | function pendingAtiv(uint256 musicId_, uint256 tokenId_)
public
view
returns (uint256)
{
uint256 musicId;
uint256 gain;
uint256 lastUpdatedEpoch;
(musicId, gain, lastUpdatedEpoch) = ipnft.meta(tokenId_);
uint256 period = ipnft.epoch() - lastUpdatedEpoch;
return period * gain;
}
| 12,585,988 | [
1,
1767,
445,
358,
2621,
4634,
14464,
8188,
87,
603,
15442,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4634,
861,
427,
12,
11890,
5034,
26225,
548,
67,
16,
2254,
5034,
1147,
548,
67,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
2254,
5034,
26225,
548,
31,
203,
3639,
2254,
5034,
17527,
31,
203,
3639,
2254,
5034,
1142,
7381,
14638,
31,
203,
540,
203,
3639,
261,
81,
14894,
548,
16,
17527,
16,
1142,
7381,
14638,
13,
273,
2359,
82,
1222,
18,
3901,
12,
2316,
548,
67,
1769,
203,
203,
3639,
2254,
5034,
3879,
273,
2359,
82,
1222,
18,
12015,
1435,
300,
1142,
7381,
14638,
31,
203,
203,
3639,
327,
3879,
380,
17527,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/137/0x3c25b96fF62D21E90556869272a277eE2E229747/sources/src/contracts/interfaces/ICrossChainReceiver.sol | * @notice emitted when a new timestamp for invalidations gets set @param invalidTimestamp timestamp to invalidate previous messages @param chainId id of the chain updated/ | event NewInvalidation(uint256 invalidTimestamp, uint256 indexed chainId);
| 4,674,709 | [
1,
351,
11541,
1347,
279,
394,
2858,
364,
2057,
1012,
5571,
444,
225,
2057,
4921,
2858,
358,
11587,
2416,
2743,
225,
2687,
548,
612,
434,
326,
2687,
3526,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
871,
1166,
27946,
12,
11890,
5034,
2057,
4921,
16,
2254,
5034,
8808,
2687,
548,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/42/0x3BFC680c17585281ab57A4C82b29F5390A5ce5f7/sources/browser/senetherSandy.sol | mapping(address => bool) public admins; | contract SendEther {
address payable public admin;
uint weekInterval;
mapping(address => uint) public deposits;
address[] public admins;
pragma solidity >=0.7.0 <0.8.0;
constructor() {
weekInterval = block.timestamp + 1 minutes;
admin = msg.sender;
}
receive() external payable {
deposits[msg.sender] += msg.value;
}
modifier onlyOwner() {
require(msg.sender == admin, 'only owner can do action');
_;
}
modifier weekIntervalReached() {
require(block.timestamp > weekInterval, 'admin can withdraw past 1 week');
_;
}
modifier onlyAdmins(){
for (uint i=0; i<= admins.length; i++){
if(admins[i] == msg.sender){
_;
}
}
}
modifier onlyAdmins(){
for (uint i=0; i<= admins.length; i++){
if(admins[i] == msg.sender){
_;
}
}
}
modifier onlyAdmins(){
for (uint i=0; i<= admins.length; i++){
if(admins[i] == msg.sender){
_;
}
}
}
function addAdmin(address _admin) public onlyOwner {
admins.push(_admin);
}
function withdraw() public onlyOwner {
require(block.timestamp > weekInterval, 'admin can withdraw past 1 week');
admin.transfer(address(this).balance);
}
function withdrawAdmin(uint _amount) public payable {
msg.sender.transfer(_amount);
}
function deposit() public payable {
deposits[msg.sender] = msg.value;
}
function sendViaTransfer(address payable _target, uint _amount) public payable {
require(deposits[msg.sender] >= _amount);
_target.transfer(_amount);
deposits[msg.sender] -= _amount;
}
function getBalance() public view returns(uint) {
return address(this).balance;
}
} | 9,590,837 | [
1,
6770,
12,
2867,
516,
1426,
13,
1071,
31116,
31,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
6835,
2479,
41,
1136,
288,
203,
377,
1758,
8843,
429,
1071,
3981,
31,
203,
377,
2254,
4860,
4006,
31,
203,
203,
377,
2874,
12,
2867,
516,
2254,
13,
1071,
443,
917,
1282,
31,
203,
1377,
203,
1377,
203,
377,
1758,
8526,
1071,
31116,
31,
203,
203,
203,
683,
9454,
18035,
560,
1545,
20,
18,
27,
18,
20,
411,
20,
18,
28,
18,
20,
31,
203,
7010,
377,
3885,
1435,
288,
203,
540,
4860,
4006,
273,
1203,
18,
5508,
397,
404,
6824,
31,
203,
540,
3981,
273,
1234,
18,
15330,
31,
203,
377,
289,
203,
203,
377,
6798,
1435,
3903,
8843,
429,
288,
203,
540,
443,
917,
1282,
63,
3576,
18,
15330,
65,
1011,
1234,
18,
1132,
31,
203,
377,
289,
203,
203,
377,
9606,
1338,
5541,
1435,
288,
203,
540,
2583,
12,
3576,
18,
15330,
422,
3981,
16,
296,
3700,
3410,
848,
741,
1301,
8284,
203,
540,
389,
31,
203,
377,
289,
203,
203,
1377,
9606,
4860,
4006,
23646,
1435,
288,
203,
540,
2583,
12,
2629,
18,
5508,
405,
4860,
4006,
16,
296,
3666,
848,
598,
9446,
8854,
404,
4860,
8284,
203,
540,
389,
31,
203,
377,
289,
203,
1377,
203,
377,
9606,
1338,
4446,
87,
1435,
95,
203,
540,
364,
261,
11890,
277,
33,
20,
31,
277,
32,
33,
31116,
18,
2469,
31,
277,
27245,
95,
203,
2398,
309,
12,
3666,
87,
63,
77,
65,
422,
1234,
18,
15330,
15329,
203,
1171,
389,
31,
203,
2398,
289,
203,
540,
289,
203,
377,
289,
203,
1377,
203,
377,
9606,
1338,
4446,
87,
1435,
95,
2
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.