file_name
stringlengths 71
779k
| comments
stringlengths 20
182k
| code_string
stringlengths 20
36.9M
| __index_level_0__
int64 0
17.2M
| input_ids
sequence | attention_mask
sequence | labels
sequence |
---|---|---|---|---|---|---|
./full_match/8453/0xaB2708ac44D567064Bc91b7f44f0447812a9431b/sources/project:/contracts/MiniChefV2.sol | @notice The (older) MasterChef contract gives out a constant number of SAM tokens per block. It is the only address with minting rights for SAM. The idea for this MasterChef V2 (MCV2) contract is therefore to be the owner of a dummy token that is deposited into the MasterChef V1 (MCV1) contract. The allocation point for this pool on MCV1 is the total allocation point for all pools that receive double incentives. | contract MiniChefV2 is BoringOwnable, BoringBatchable {
using BoringMath for uint256;
using BoringMath128 for uint128;
using BoringERC20 for IERC20;
using SignedSafeMath for int256;
struct UserInfo {
uint256 amount;
int256 rewardDebt;
uint256 releaseTime;
uint256 lockAmount;
}
struct PoolInfo {
uint128 accSamPerShare;
uint64 lastRewardTime;
uint64 allocPoint;
}
uint256 public samPerSecond;
uint256 private constant ACC_SAM_PRECISION = 1e12;
uint256 public unitLockTime = 14 days;
uint256 public boostMul = 10;
event Deposit(
address indexed user,
uint256 indexed pid,
uint256 amount,
address indexed to
);
event Withdraw(
address indexed user,
uint256 indexed pid,
uint256 amount,
address indexed to
);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount,
address indexed to
);
event Harvest(address indexed user, uint256 indexed pid, uint256 amount);
event LogPoolAddition(
uint256 indexed pid,
uint256 allocPoint,
IERC20 indexed lpToken,
IRewarder indexed rewarder
);
event LogSetPool(
uint256 indexed pid,
uint256 allocPoint,
IRewarder indexed rewarder,
bool overwrite
);
event LogUpdatePool(
uint256 indexed pid,
uint64 lastRewardTime,
uint256 lpSupply,
uint256 accSamPerShare
);
event LogSamPerSecond(uint256 samPerSecond);
IERC20 public immutable SAM;
IMigratorChef public migrator;
PoolInfo[] public poolInfo;
IERC20[] public lpToken;
IRewarder[] public rewarder;
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
mapping(address => bool) public addedTokens;
uint256 public totalAllocPoint;
constructor(IERC20 _sam) public {
SAM = _sam;
}
function poolLength() public view returns (uint256 pools) {
pools = poolInfo.length;
}
function add(
uint256 allocPoint,
IERC20 _lpToken,
IRewarder _rewarder
) public onlyOwner {
require(addedTokens[address(_lpToken)] == false, "Token already added");
totalAllocPoint = totalAllocPoint.add(allocPoint);
lpToken.push(_lpToken);
rewarder.push(_rewarder);
poolInfo.push(
PoolInfo({
allocPoint: allocPoint.to64(),
lastRewardTime: block.timestamp.to64(),
accSamPerShare: 0
})
);
addedTokens[address(_lpToken)] = true;
emit LogPoolAddition(
lpToken.length.sub(1),
allocPoint,
_lpToken,
_rewarder
);
}
function add(
uint256 allocPoint,
IERC20 _lpToken,
IRewarder _rewarder
) public onlyOwner {
require(addedTokens[address(_lpToken)] == false, "Token already added");
totalAllocPoint = totalAllocPoint.add(allocPoint);
lpToken.push(_lpToken);
rewarder.push(_rewarder);
poolInfo.push(
PoolInfo({
allocPoint: allocPoint.to64(),
lastRewardTime: block.timestamp.to64(),
accSamPerShare: 0
})
);
addedTokens[address(_lpToken)] = true;
emit LogPoolAddition(
lpToken.length.sub(1),
allocPoint,
_lpToken,
_rewarder
);
}
function set(
uint256 _pid,
uint256 _allocPoint,
IRewarder _rewarder,
bool overwrite
) public onlyOwner {
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint.to64();
if (overwrite) {
rewarder[_pid] = _rewarder;
}
emit LogSetPool(
_pid,
_allocPoint,
overwrite ? _rewarder : rewarder[_pid],
overwrite
);
}
function set(
uint256 _pid,
uint256 _allocPoint,
IRewarder _rewarder,
bool overwrite
) public onlyOwner {
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint.to64();
if (overwrite) {
rewarder[_pid] = _rewarder;
}
emit LogSetPool(
_pid,
_allocPoint,
overwrite ? _rewarder : rewarder[_pid],
overwrite
);
}
function setSamPerSecond(uint256 _samPerSecond) public onlyOwner {
samPerSecond = _samPerSecond;
emit LogSamPerSecond(_samPerSecond);
}
function setBoostMul(uint256 _boostMul) public onlyOwner {
boostMul = _boostMul;
}
function pendingSam(
uint256 _pid,
address _user
) external view returns (uint256 pending) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSamPerShare = pool.accSamPerShare;
uint256 lpSupply = lpToken[_pid].balanceOf(address(this));
if (block.timestamp > pool.lastRewardTime && lpSupply != 0) {
uint256 time = block.timestamp.sub(pool.lastRewardTime);
uint256 samReward = time.mul(samPerSecond).mul(pool.allocPoint) /
totalAllocPoint;
accSamPerShare = accSamPerShare.add(
samReward.mul(ACC_SAM_PRECISION) / lpSupply
);
}
pending = int256(user.amount.mul(accSamPerShare) / ACC_SAM_PRECISION)
.sub(user.rewardDebt)
.toUInt256();
}
function pendingSam(
uint256 _pid,
address _user
) external view returns (uint256 pending) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSamPerShare = pool.accSamPerShare;
uint256 lpSupply = lpToken[_pid].balanceOf(address(this));
if (block.timestamp > pool.lastRewardTime && lpSupply != 0) {
uint256 time = block.timestamp.sub(pool.lastRewardTime);
uint256 samReward = time.mul(samPerSecond).mul(pool.allocPoint) /
totalAllocPoint;
accSamPerShare = accSamPerShare.add(
samReward.mul(ACC_SAM_PRECISION) / lpSupply
);
}
pending = int256(user.amount.mul(accSamPerShare) / ACC_SAM_PRECISION)
.sub(user.rewardDebt)
.toUInt256();
}
function massUpdatePools(uint256[] calldata pids) external {
uint256 len = pids.length;
for (uint256 i = 0; i < len; ++i) {
updatePool(pids[i]);
}
}
function massUpdatePools(uint256[] calldata pids) external {
uint256 len = pids.length;
for (uint256 i = 0; i < len; ++i) {
updatePool(pids[i]);
}
}
function updatePool(uint256 pid) public returns (PoolInfo memory pool) {
pool = poolInfo[pid];
if (block.timestamp > pool.lastRewardTime) {
uint256 lpSupply = lpToken[pid].balanceOf(address(this));
if (lpSupply > 0) {
uint256 time = block.timestamp.sub(pool.lastRewardTime);
uint256 samReward = time.mul(samPerSecond).mul(
pool.allocPoint
) / totalAllocPoint;
pool.accSamPerShare = pool.accSamPerShare.add(
(samReward.mul(ACC_SAM_PRECISION) / lpSupply).to128()
);
}
pool.lastRewardTime = block.timestamp.to64();
poolInfo[pid] = pool;
emit LogUpdatePool(
pid,
pool.lastRewardTime,
lpSupply,
pool.accSamPerShare
);
}
}
function updatePool(uint256 pid) public returns (PoolInfo memory pool) {
pool = poolInfo[pid];
if (block.timestamp > pool.lastRewardTime) {
uint256 lpSupply = lpToken[pid].balanceOf(address(this));
if (lpSupply > 0) {
uint256 time = block.timestamp.sub(pool.lastRewardTime);
uint256 samReward = time.mul(samPerSecond).mul(
pool.allocPoint
) / totalAllocPoint;
pool.accSamPerShare = pool.accSamPerShare.add(
(samReward.mul(ACC_SAM_PRECISION) / lpSupply).to128()
);
}
pool.lastRewardTime = block.timestamp.to64();
poolInfo[pid] = pool;
emit LogUpdatePool(
pid,
pool.lastRewardTime,
lpSupply,
pool.accSamPerShare
);
}
}
function updatePool(uint256 pid) public returns (PoolInfo memory pool) {
pool = poolInfo[pid];
if (block.timestamp > pool.lastRewardTime) {
uint256 lpSupply = lpToken[pid].balanceOf(address(this));
if (lpSupply > 0) {
uint256 time = block.timestamp.sub(pool.lastRewardTime);
uint256 samReward = time.mul(samPerSecond).mul(
pool.allocPoint
) / totalAllocPoint;
pool.accSamPerShare = pool.accSamPerShare.add(
(samReward.mul(ACC_SAM_PRECISION) / lpSupply).to128()
);
}
pool.lastRewardTime = block.timestamp.to64();
poolInfo[pid] = pool;
emit LogUpdatePool(
pid,
pool.lastRewardTime,
lpSupply,
pool.accSamPerShare
);
}
}
function deposit(
uint256 pid,
uint256 amount,
address to,
bool enterLock
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
user.amount = user.amount.add(amount);
if (lpToken[pid] == SAM && enterLock) {
user.lockAmount = user.lockAmount.add(amount);
user.releaseTime = block.timestamp.add(unitLockTime);
}
user.rewardDebt = user.rewardDebt.add(
int256(amount.mul(pool.accSamPerShare) / ACC_SAM_PRECISION)
);
if (address(_rewarder) != address(0)) {
_rewarder.onSamReward(pid, to, to, 0, user.amount);
}
lpToken[pid].safeTransferFrom(msg.sender, address(this), amount);
if (lpToken[pid] == SAM && enterLock) {
lpToken[pid].safeTransfer(msg.sender, (amount * boostMul) / 100);
}
emit Deposit(msg.sender, pid, amount, to);
}
function deposit(
uint256 pid,
uint256 amount,
address to,
bool enterLock
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
user.amount = user.amount.add(amount);
if (lpToken[pid] == SAM && enterLock) {
user.lockAmount = user.lockAmount.add(amount);
user.releaseTime = block.timestamp.add(unitLockTime);
}
user.rewardDebt = user.rewardDebt.add(
int256(amount.mul(pool.accSamPerShare) / ACC_SAM_PRECISION)
);
if (address(_rewarder) != address(0)) {
_rewarder.onSamReward(pid, to, to, 0, user.amount);
}
lpToken[pid].safeTransferFrom(msg.sender, address(this), amount);
if (lpToken[pid] == SAM && enterLock) {
lpToken[pid].safeTransfer(msg.sender, (amount * boostMul) / 100);
}
emit Deposit(msg.sender, pid, amount, to);
}
IRewarder _rewarder = rewarder[pid];
function deposit(
uint256 pid,
uint256 amount,
address to,
bool enterLock
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
user.amount = user.amount.add(amount);
if (lpToken[pid] == SAM && enterLock) {
user.lockAmount = user.lockAmount.add(amount);
user.releaseTime = block.timestamp.add(unitLockTime);
}
user.rewardDebt = user.rewardDebt.add(
int256(amount.mul(pool.accSamPerShare) / ACC_SAM_PRECISION)
);
if (address(_rewarder) != address(0)) {
_rewarder.onSamReward(pid, to, to, 0, user.amount);
}
lpToken[pid].safeTransferFrom(msg.sender, address(this), amount);
if (lpToken[pid] == SAM && enterLock) {
lpToken[pid].safeTransfer(msg.sender, (amount * boostMul) / 100);
}
emit Deposit(msg.sender, pid, amount, to);
}
function deposit(
uint256 pid,
uint256 amount,
address to,
bool enterLock
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
user.amount = user.amount.add(amount);
if (lpToken[pid] == SAM && enterLock) {
user.lockAmount = user.lockAmount.add(amount);
user.releaseTime = block.timestamp.add(unitLockTime);
}
user.rewardDebt = user.rewardDebt.add(
int256(amount.mul(pool.accSamPerShare) / ACC_SAM_PRECISION)
);
if (address(_rewarder) != address(0)) {
_rewarder.onSamReward(pid, to, to, 0, user.amount);
}
lpToken[pid].safeTransferFrom(msg.sender, address(this), amount);
if (lpToken[pid] == SAM && enterLock) {
lpToken[pid].safeTransfer(msg.sender, (amount * boostMul) / 100);
}
emit Deposit(msg.sender, pid, amount, to);
}
function withdraw(uint256 pid, uint256 amount, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
if (lpToken[pid] == SAM) {
uint256 active = user.amount.sub(user.lockAmount);
if (block.timestamp < user.releaseTime) {
require(active >= amount, "err amount");
}
if (amount > active) {
user.lockAmount = user.lockAmount.sub(amount.sub(active));
}
}
int256(amount.mul(pool.accSamPerShare) / ACC_SAM_PRECISION)
);
user.amount = user.amount.sub(amount);
if (address(_rewarder) != address(0)) {
_rewarder.onSamReward(pid, msg.sender, to, 0, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
}
function withdraw(uint256 pid, uint256 amount, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
if (lpToken[pid] == SAM) {
uint256 active = user.amount.sub(user.lockAmount);
if (block.timestamp < user.releaseTime) {
require(active >= amount, "err amount");
}
if (amount > active) {
user.lockAmount = user.lockAmount.sub(amount.sub(active));
}
}
int256(amount.mul(pool.accSamPerShare) / ACC_SAM_PRECISION)
);
user.amount = user.amount.sub(amount);
if (address(_rewarder) != address(0)) {
_rewarder.onSamReward(pid, msg.sender, to, 0, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
}
function withdraw(uint256 pid, uint256 amount, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
if (lpToken[pid] == SAM) {
uint256 active = user.amount.sub(user.lockAmount);
if (block.timestamp < user.releaseTime) {
require(active >= amount, "err amount");
}
if (amount > active) {
user.lockAmount = user.lockAmount.sub(amount.sub(active));
}
}
int256(amount.mul(pool.accSamPerShare) / ACC_SAM_PRECISION)
);
user.amount = user.amount.sub(amount);
if (address(_rewarder) != address(0)) {
_rewarder.onSamReward(pid, msg.sender, to, 0, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
}
function withdraw(uint256 pid, uint256 amount, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
if (lpToken[pid] == SAM) {
uint256 active = user.amount.sub(user.lockAmount);
if (block.timestamp < user.releaseTime) {
require(active >= amount, "err amount");
}
if (amount > active) {
user.lockAmount = user.lockAmount.sub(amount.sub(active));
}
}
int256(amount.mul(pool.accSamPerShare) / ACC_SAM_PRECISION)
);
user.amount = user.amount.sub(amount);
if (address(_rewarder) != address(0)) {
_rewarder.onSamReward(pid, msg.sender, to, 0, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
}
user.rewardDebt = user.rewardDebt.sub(
IRewarder _rewarder = rewarder[pid];
function withdraw(uint256 pid, uint256 amount, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
if (lpToken[pid] == SAM) {
uint256 active = user.amount.sub(user.lockAmount);
if (block.timestamp < user.releaseTime) {
require(active >= amount, "err amount");
}
if (amount > active) {
user.lockAmount = user.lockAmount.sub(amount.sub(active));
}
}
int256(amount.mul(pool.accSamPerShare) / ACC_SAM_PRECISION)
);
user.amount = user.amount.sub(amount);
if (address(_rewarder) != address(0)) {
_rewarder.onSamReward(pid, msg.sender, to, 0, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
}
function harvest(uint256 pid, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
int256 accumulatedSam = int256(
user.amount.mul(pool.accSamPerShare) / ACC_SAM_PRECISION
);
uint256 _pendingSam = accumulatedSam.sub(user.rewardDebt).toUInt256();
user.rewardDebt = accumulatedSam;
if (_pendingSam != 0) {
SAM.safeTransfer(to, _pendingSam);
}
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSamReward(pid, to, to, _pendingSam, user.amount);
}
emit Harvest(to, pid, _pendingSam);
}
function harvest(uint256 pid, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
int256 accumulatedSam = int256(
user.amount.mul(pool.accSamPerShare) / ACC_SAM_PRECISION
);
uint256 _pendingSam = accumulatedSam.sub(user.rewardDebt).toUInt256();
user.rewardDebt = accumulatedSam;
if (_pendingSam != 0) {
SAM.safeTransfer(to, _pendingSam);
}
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSamReward(pid, to, to, _pendingSam, user.amount);
}
emit Harvest(to, pid, _pendingSam);
}
function harvest(uint256 pid, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
int256 accumulatedSam = int256(
user.amount.mul(pool.accSamPerShare) / ACC_SAM_PRECISION
);
uint256 _pendingSam = accumulatedSam.sub(user.rewardDebt).toUInt256();
user.rewardDebt = accumulatedSam;
if (_pendingSam != 0) {
SAM.safeTransfer(to, _pendingSam);
}
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSamReward(pid, to, to, _pendingSam, user.amount);
}
emit Harvest(to, pid, _pendingSam);
}
function withdrawAndHarvest(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
if (lpToken[pid] == SAM) {
uint256 active = user.amount.sub(user.lockAmount);
if (block.timestamp < user.releaseTime) {
require(active >= amount, "err amount");
}
if (amount > active) {
user.lockAmount = user.lockAmount.sub(amount.sub(active));
}
}
int256 accumulatedSam = int256(
user.amount.mul(pool.accSamPerShare) / ACC_SAM_PRECISION
);
uint256 _pendingSam = accumulatedSam.sub(user.rewardDebt).toUInt256();
int256(amount.mul(pool.accSamPerShare) / ACC_SAM_PRECISION)
);
user.amount = user.amount.sub(amount);
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSamReward(
pid,
msg.sender,
to,
_pendingSam,
user.amount
);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
emit Harvest(msg.sender, pid, _pendingSam);
}
function withdrawAndHarvest(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
if (lpToken[pid] == SAM) {
uint256 active = user.amount.sub(user.lockAmount);
if (block.timestamp < user.releaseTime) {
require(active >= amount, "err amount");
}
if (amount > active) {
user.lockAmount = user.lockAmount.sub(amount.sub(active));
}
}
int256 accumulatedSam = int256(
user.amount.mul(pool.accSamPerShare) / ACC_SAM_PRECISION
);
uint256 _pendingSam = accumulatedSam.sub(user.rewardDebt).toUInt256();
int256(amount.mul(pool.accSamPerShare) / ACC_SAM_PRECISION)
);
user.amount = user.amount.sub(amount);
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSamReward(
pid,
msg.sender,
to,
_pendingSam,
user.amount
);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
emit Harvest(msg.sender, pid, _pendingSam);
}
function withdrawAndHarvest(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
if (lpToken[pid] == SAM) {
uint256 active = user.amount.sub(user.lockAmount);
if (block.timestamp < user.releaseTime) {
require(active >= amount, "err amount");
}
if (amount > active) {
user.lockAmount = user.lockAmount.sub(amount.sub(active));
}
}
int256 accumulatedSam = int256(
user.amount.mul(pool.accSamPerShare) / ACC_SAM_PRECISION
);
uint256 _pendingSam = accumulatedSam.sub(user.rewardDebt).toUInt256();
int256(amount.mul(pool.accSamPerShare) / ACC_SAM_PRECISION)
);
user.amount = user.amount.sub(amount);
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSamReward(
pid,
msg.sender,
to,
_pendingSam,
user.amount
);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
emit Harvest(msg.sender, pid, _pendingSam);
}
function withdrawAndHarvest(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
if (lpToken[pid] == SAM) {
uint256 active = user.amount.sub(user.lockAmount);
if (block.timestamp < user.releaseTime) {
require(active >= amount, "err amount");
}
if (amount > active) {
user.lockAmount = user.lockAmount.sub(amount.sub(active));
}
}
int256 accumulatedSam = int256(
user.amount.mul(pool.accSamPerShare) / ACC_SAM_PRECISION
);
uint256 _pendingSam = accumulatedSam.sub(user.rewardDebt).toUInt256();
int256(amount.mul(pool.accSamPerShare) / ACC_SAM_PRECISION)
);
user.amount = user.amount.sub(amount);
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSamReward(
pid,
msg.sender,
to,
_pendingSam,
user.amount
);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
emit Harvest(msg.sender, pid, _pendingSam);
}
user.rewardDebt = accumulatedSam.sub(
SAM.safeTransfer(to, _pendingSam);
function withdrawAndHarvest(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
if (lpToken[pid] == SAM) {
uint256 active = user.amount.sub(user.lockAmount);
if (block.timestamp < user.releaseTime) {
require(active >= amount, "err amount");
}
if (amount > active) {
user.lockAmount = user.lockAmount.sub(amount.sub(active));
}
}
int256 accumulatedSam = int256(
user.amount.mul(pool.accSamPerShare) / ACC_SAM_PRECISION
);
uint256 _pendingSam = accumulatedSam.sub(user.rewardDebt).toUInt256();
int256(amount.mul(pool.accSamPerShare) / ACC_SAM_PRECISION)
);
user.amount = user.amount.sub(amount);
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSamReward(
pid,
msg.sender,
to,
_pendingSam,
user.amount
);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
emit Harvest(msg.sender, pid, _pendingSam);
}
}
| 11,554,862 | [
1,
1986,
261,
1498,
13,
13453,
39,
580,
74,
6835,
14758,
596,
279,
5381,
1300,
434,
30712,
2430,
1534,
1203,
18,
2597,
353,
326,
1338,
1758,
598,
312,
474,
310,
14989,
364,
30712,
18,
1021,
21463,
364,
333,
13453,
39,
580,
74,
776,
22,
261,
20022,
58,
22,
13,
6835,
353,
13526,
358,
506,
326,
3410,
434,
279,
9609,
1147,
716,
353,
443,
1724,
329,
1368,
326,
13453,
39,
580,
74,
776,
21,
261,
20022,
58,
21,
13,
6835,
18,
1021,
13481,
1634,
364,
333,
2845,
603,
490,
22007,
21,
353,
326,
2078,
13481,
1634,
364,
777,
16000,
716,
6798,
1645,
316,
2998,
3606,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
16351,
27987,
39,
580,
74,
58,
22,
353,
605,
6053,
5460,
429,
16,
605,
6053,
4497,
429,
288,
203,
565,
1450,
605,
6053,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
605,
6053,
10477,
10392,
364,
2254,
10392,
31,
203,
565,
1450,
605,
6053,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
565,
1450,
16724,
9890,
10477,
364,
509,
5034,
31,
203,
203,
565,
1958,
25003,
288,
203,
3639,
2254,
5034,
3844,
31,
203,
3639,
509,
5034,
19890,
758,
23602,
31,
203,
3639,
2254,
5034,
3992,
950,
31,
203,
3639,
2254,
5034,
2176,
6275,
31,
203,
565,
289,
203,
203,
565,
1958,
8828,
966,
288,
203,
3639,
2254,
10392,
4078,
55,
301,
2173,
9535,
31,
203,
3639,
2254,
1105,
1142,
17631,
1060,
950,
31,
203,
3639,
2254,
1105,
4767,
2148,
31,
203,
565,
289,
203,
203,
203,
203,
203,
203,
203,
565,
2254,
5034,
1071,
16260,
2173,
8211,
31,
203,
565,
2254,
5034,
3238,
5381,
18816,
67,
55,
2192,
67,
3670,
26913,
273,
404,
73,
2138,
31,
203,
565,
2254,
5034,
1071,
2836,
2531,
950,
273,
5045,
4681,
31,
203,
565,
2254,
5034,
1071,
14994,
27860,
273,
1728,
31,
203,
203,
565,
871,
4019,
538,
305,
12,
203,
3639,
1758,
8808,
729,
16,
203,
3639,
2254,
5034,
8808,
4231,
16,
203,
3639,
2254,
5034,
3844,
16,
203,
3639,
1758,
8808,
358,
203,
565,
11272,
203,
565,
871,
3423,
9446,
12,
203,
3639,
1758,
8808,
729,
16,
203,
3639,
2254,
5034,
8808,
4231,
16,
203,
3639,
2254,
5034,
3844,
16,
203,
3639,
1758,
2
] |
./full_match/1/0xef165820dEa2c24C2A61675d7B183b36255e10c8/sources/contracts/Awakened.sol | * @notice Set the maximum presale mints allowed per a given transaction/ | function setPresaleMintsAllowedPerTransaction(
uint256 _mintsAllowed
) external onlyOwner {
presaleMintsAllowedPerTransaction = _mintsAllowed;
}
| 2,910,216 | [
1,
694,
326,
4207,
4075,
5349,
312,
28142,
2935,
1534,
279,
864,
2492,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
444,
12236,
5349,
49,
28142,
5042,
2173,
3342,
12,
203,
3639,
2254,
5034,
389,
81,
28142,
5042,
203,
565,
262,
3903,
1338,
5541,
288,
203,
3639,
4075,
5349,
49,
28142,
5042,
2173,
3342,
273,
389,
81,
28142,
5042,
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
] |
/**
*Submitted for verification at Etherscan.io on 2021-01-18
*/
// Dependency file: /Users/present/code/super-sett/deps/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
function decimals() external view returns (uint8);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* // importANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// Dependency file: /Users/present/code/super-sett/deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol
// pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library 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;
}
}
// Dependency file: /Users/present/code/super-sett/deps/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol
// pragma solidity ^0.6.2;
/**
* @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);
}
}
}
}
// Dependency file: /Users/present/code/super-sett/deps/@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol
// pragma solidity ^0.6.0;
// import "/Users/present/code/super-sett/deps/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
// import "/Users/present/code/super-sett/deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
// import "/Users/present/code/super-sett/deps/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using 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");
}
}
}
// Dependency file: /Users/present/code/super-sett/interfaces/badger/IController.sol
// pragma solidity >=0.5.0 <0.8.0;
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);
}
// Dependency file: /Users/present/code/super-sett/interfaces/badger/IStrategy.sol
// pragma solidity >=0.5.0 <0.8.0;
interface IStrategy {
function want() external view returns (address);
function deposit() external;
// NOTE: must exclude any tokens used in the yield
// Controller role - withdraw should return to Controller
function withdrawOther(address) external returns (uint256 balance);
// Controller | Vault role - withdraw should always return to Vault
function withdraw(uint256) external;
// Controller | Vault role - withdraw should always return to Vault
function withdrawAll() external returns (uint256);
function balanceOf() external view returns (uint256);
function getName() external pure returns (string memory);
function setStrategist(address _strategist) external;
function setWithdrawalFee(uint256 _withdrawalFee) external;
function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist) external;
function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance) external;
function setGovernance(address _governance) external;
function setController(address _controller) external;
}
// Dependency file: /Users/present/code/super-sett/deps/@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol
// pragma solidity ^0.6.0;
/**
* @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);
}
}
// Dependency file: /Users/present/code/super-sett/deps/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol
// pragma solidity >=0.4.24 <0.7.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 0;
}
}
// Dependency file: /Users/present/code/super-sett/deps/@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol
// pragma solidity ^0.6.0;
// import "/Users/present/code/super-sett/deps/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// Dependency file: /Users/present/code/super-sett/deps/@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol
// pragma solidity ^0.6.0;
// import "/Users/present/code/super-sett/deps/@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol";
// import "/Users/present/code/super-sett/deps/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
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;
}
// Dependency file: contracts/badger-sett/SettAccessControl.sol
// pragma solidity ^0.6.11;
// import "deps/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
/*
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;
}
// Dependency file: contracts/badger-sett/strategies/BaseStrategy.sol
// pragma solidity ^0.6.11;
// import "/Users/present/code/super-sett/deps/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
// import "/Users/present/code/super-sett/deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
// import "/Users/present/code/super-sett/deps/@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol";
// import "/Users/present/code/super-sett/deps/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
// import "/Users/present/code/super-sett/deps/@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
// import "/Users/present/code/super-sett/deps/@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
// import "/Users/present/code/super-sett/deps/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
// import "/Users/present/code/super-sett/interfaces/uniswap/IUniswapRouterV2.sol";
// import "/Users/present/code/super-sett/interfaces/badger/IController.sol";
// import "/Users/present/code/super-sett/interfaces/badger/IStrategy.sol";
// import "contracts/badger-sett/SettAccessControl.sol";
/*
===== 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 constant uniswap = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // Uniswap Dex
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 pure 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 virtual view returns (uint256) {
return balanceOfWant().add(balanceOfPool());
}
function isTendable() public virtual pure returns (bool) {
return false;
}
/// ===== Permissioned Actions: Governance =====
function setGuardian(address _guardian) external {
_onlyGovernance();
guardian = _guardian;
}
function setWithdrawalFee(uint256 _withdrawalFee) external {
_onlyGovernance();
require(_withdrawalFee <= MAX_FEE, "base-strategy/excessive-withdrawal-fee");
withdrawalFee = _withdrawalFee;
}
function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist) external {
_onlyGovernance();
require(_performanceFeeStrategist <= MAX_FEE, "base-strategy/excessive-strategist-performance-fee");
performanceFeeStrategist = _performanceFeeStrategist;
}
function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance) external {
_onlyGovernance();
require(_performanceFeeGovernance <= MAX_FEE, "base-strategy/excessive-governance-performance-fee");
performanceFeeGovernance = _performanceFeeGovernance;
}
function setController(address _controller) external {
_onlyGovernance();
controller = _controller;
}
function setWithdrawalMaxDeviationThreshold(uint256 _threshold) external {
_onlyGovernance();
require(_threshold <= MAX_FEE, "base-strategy/excessive-max-deviation-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) {
_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), "base-strategy/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;
}
/// @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);
}
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() external virtual view returns (address[] memory);
/// @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 virtual pure returns (string memory);
/// @dev Balance of want currently held in strategy positions
function balanceOfPool() public virtual view returns (uint256);
uint256[49] private __gap;
}
// Root file: contracts/StabilizeStrategyDiggV1.sol
pragma solidity =0.6.11;
/*
This is a strategy to stabilize Digg with wBTC. It takes advantage of market momentum and accumulated collateral to
track Digg price with BTC price after rebase events. Users exposed in this strategy are somewhat protected from
a loss of value due to a negative rebase
Authorized parties include many different parties that can modify trade parameters and fees
*/
interface AggregatorV3Interface {
function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}
interface TradeRouter {
function swapExactETHForTokens(uint, address[] calldata, address, uint) external payable returns (uint[] memory);
function swapExactTokensForTokens(uint, uint, address[] calldata, address, uint) external returns (uint[] memory);
function getAmountsOut(uint, address[] calldata) external view returns (uint[] memory); // For a value in, it calculates value out
}
interface UniswapLikeLPToken {
function sync() external; // We need to call sync before Trading on Uniswap/Sushiswap due to rebase potential of Digg
}
interface DiggTreasury {
function exchangeWBTCForDigg(uint256, address) external;
}
contract StabilizeStrategyDiggV1 is BaseStrategy {
using SafeERC20Upgradeable for IERC20Upgradeable;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
// Variables
uint256 public stabilizeFee; // 10000 = 100%, this fee goes to Stabilize Treasury
address public stabilizeVault; // Address to the Stabilize treasury
uint256 public strategyLockedUntil; // The blocknumber that the strategy will prevent withdrawals until
bool public diggInExpansion;
uint256 public lastDiggTotalSupply; // The last recorded total supply of the digg token
uint256 public lastDiggPrice; // The price of Digg at last trade in BTC units
uint256 public diggSupplyChangeFactor = 50000; // This is a factor used by the strategy to determine how much digg to sell in expansion
uint256 public wbtcSupplyChangeFactor = 20000; // This is a factor used by the strategy to determine how much wbtc to sell in contraction
uint256 public wbtcSellAmplificationFactor = 2; // The higher this number the more aggressive the buyback in contraction
uint256 public maxGainedDiggSellPercent = 100000; // The maximum percent of sellable Digg gains through rebase
uint256 public maxWBTCSellPercent = 50000; // The maximum percent of sellable wBTC;
uint256 public tradeBatchSize = 10e18; // The normalized size of the trade batches, can be adjusted
uint256 public tradeAmountLeft = 0; // The amount left to trade
// Constants
uint256 constant DIVISION_FACTOR = 100000;
address constant SUSHISWAP_ROUTER_ADDRESS = address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // Sushi swap router
address constant UNISWAP_ROUTER_ADDRESS = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address constant SUSHISWAP_DIGG_LP = address(0x9a13867048e01c663ce8Ce2fE0cDAE69Ff9F35E3); // Will need to sync before trading
address constant UNISWAP_DIGG_LP = address(0xE86204c4eDDd2f70eE00EAd6805f917671F56c52);
address constant BTC_ORACLE_ADDRESS = address(0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c); // Chainlink BTC Oracle
address constant DIGG_ORACLE_ADDRESS = address(0x418a6C98CD5B8275955f08F0b8C1c6838c8b1685); // Chainlink DIGG Oracle
address constant DIGG_TREASURY = address(0); // TODO, place holder for digg treasury
struct TokenInfo {
IERC20Upgradeable token; // Reference of token
uint256 decimals; // Decimals of token
}
TokenInfo[] private tokenList; // An array of tokens accepted as deposits
event TradeState (
uint256 soldAmountNormalized,
int256 percentPriceChange,
uint256 soldPercent,
uint256 oldSupply,
uint256 newSupply,
uint256 blocknumber
);
event NoTrade(uint256 blocknumber);
function initialize(
address _governance,
address _strategist,
address _controller,
address _keeper,
address _guardian,
address _vaultConfig,
uint256[5] memory _feeConfig
) public initializer {
__BaseStrategy_init(_governance, _strategist, _controller, _keeper, _guardian);
stabilizeVault = _vaultConfig;
performanceFeeGovernance = _feeConfig[0];
performanceFeeStrategist = _feeConfig[1];
withdrawalFee = _feeConfig[2];
stabilizeFee = _feeConfig[3];
strategyLockedUntil = _feeConfig[4]; // Deployer can optionally lock strategy from withdrawing until a certain blocknumber
setupTradeTokens();
lastDiggPrice = getDiggPrice();
lastDiggTotalSupply = tokenList[0].token.totalSupply(); // The supply only changes at rebase
want = address(tokenList[0].token);
}
function setupTradeTokens() internal {
// Start with DIGG
IERC20Upgradeable _token = IERC20Upgradeable(address(0x798D1bE841a82a273720CE31c822C61a67a601C3));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals()
})
);
// WBTC
_token = IERC20Upgradeable(address(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals()
})
);
}
function _onlyAnyAuthorizedParties() internal view {
require(msg.sender == strategist
|| msg.sender == governance
|| msg.sender == controller
|| msg.sender == keeper
|| msg.sender == guardian, "Not an authorized party");
}
/// ===== View Functions =====
// Chainlink price grabbers
function getDiggUSDPrice() public view returns (uint256) {
AggregatorV3Interface priceOracle = AggregatorV3Interface(DIGG_ORACLE_ADDRESS);
( , int256 intPrice, , , ) = priceOracle.latestRoundData(); // We only want the answer
uint256 usdPrice = uint256(intPrice);
priceOracle = AggregatorV3Interface(BTC_ORACLE_ADDRESS);
( , intPrice, , , ) = priceOracle.latestRoundData(); // We only want the answer
usdPrice = usdPrice.mul(uint256(intPrice)).mul(10**2);
return usdPrice; // Digg Price in USD
}
function getDiggPrice() public view returns (uint256) {
AggregatorV3Interface priceOracle = AggregatorV3Interface(DIGG_ORACLE_ADDRESS);
( , int256 intPrice, , , ) = priceOracle.latestRoundData(); // We only want the answer
return uint256(intPrice).mul(10**10);
}
function getWBTCUSDPrice() public view returns (uint256) {
AggregatorV3Interface priceOracle = AggregatorV3Interface(BTC_ORACLE_ADDRESS);
( , int256 intPrice, , , ) = priceOracle.latestRoundData(); // We only want the answer
return uint256(intPrice).mul(10**10);
}
function getTokenAddress(uint256 _id) external view returns (address) {
require(_id < tokenList.length, "ID is too high");
return address(tokenList[_id].token);
}
function getName() external override pure returns (string memory) {
return "StabilizeStrategyDiggV1";
}
function version() external pure returns (string memory) {
return "1.0";
}
function balanceOf() public override view returns (uint256) {
// This will return the DIGG and DIGG equivalent of WBTC in Digg decimals
uint256 _diggAmount = tokenList[0].token.balanceOf(address(this));
uint256 _wBTCAmount = tokenList[1].token.balanceOf(address(this));
return _diggAmount.add(wbtcInDiggUnits(_wBTCAmount));
}
function wbtcInDiggUnits(uint256 amount) internal view returns (uint256) {
if(amount == 0) { return 0; }
amount = amount.mul(1e18).div(10**tokenList[1].decimals); // Normalize the wBTC amount
uint256 _digg = amount.mul(getWBTCUSDPrice()).div(1e18); // Get the USD value of wBtC
_digg = _digg.mul(1e18).div(getDiggUSDPrice());
_digg = _digg.mul(10**tokenList[0].decimals).div(1e18); // Convert to Digg units
return _digg;
}
function diggInWBTCUnits(uint256 amount) internal view returns (uint256) {
if(amount == 0) { return 0; }
// Converts digg into wbtc equivalent
amount = amount.mul(1e18).div(10**tokenList[0].decimals); // Normalize the digg amount
uint256 _wbtc = amount.mul(getDiggUSDPrice()).div(1e18); // Get the USD value of digg
_wbtc = _wbtc.mul(1e18).div(getWBTCUSDPrice());
_wbtc = _wbtc.mul(10**tokenList[1].decimals).div(1e18); // Convert to wbtc units
return _wbtc;
}
/// @dev Not used
function balanceOfPool() public override view returns (uint256) {
return 0;
}
function getProtectedTokens() external override view returns (address[] memory) {
address[] memory protectedTokens = new address[](2);
protectedTokens[0] = address(tokenList[0].token);
protectedTokens[1] = address(tokenList[1].token);
return protectedTokens;
}
// Customer active Strategy functions
function exchange(uint256 _inID, uint256 _outID, uint256 _amount) internal {
address _inputToken = address(tokenList[_inID].token);
address _outputToken = address(tokenList[_outID].token);
// One route, between DIGG and WBTC on Sushiswap and Uniswap, split based on liquidity
address[] memory path = new address[](2);
path[0] = _inputToken;
path[1] = _outputToken;
// Sync Sushiswap pool
UniswapLikeLPToken lpPool = UniswapLikeLPToken(SUSHISWAP_DIGG_LP);
lpPool.sync(); // Sync the pool amounts
// Sync Uniswap pool
lpPool = UniswapLikeLPToken(UNISWAP_DIGG_LP);
lpPool.sync(); // Sync the pool amounts
// Now determine the split between Uni and Sushi
uint256 uniPercent = tokenList[0].token.balanceOf(address(UNISWAP_DIGG_LP))
.mul(DIVISION_FACTOR)
.div(tokenList[0].token.balanceOf(address(UNISWAP_DIGG_LP)).add(tokenList[0].token.balanceOf(address(SUSHISWAP_DIGG_LP))));
uint256 uniAmount = _amount.mul(uniPercent).div(DIVISION_FACTOR);
_amount = _amount.sub(uniAmount);
// Make sure selling produces a growth in pooled tokens
TradeRouter router = TradeRouter(SUSHISWAP_ROUTER_ADDRESS);
uint256 minAmount = _amount.mul(10**tokenList[_outID].decimals).div(10**tokenList[_inID].decimals); // Trades should always increase balance
uint256[] memory estimates = router.getAmountsOut(_amount, path);
uint256 estimate = estimates[estimates.length - 1]; // This is the amount of expected output token
if(estimate > minAmount){
_safeApproveHelper(_inputToken, SUSHISWAP_ROUTER_ADDRESS, _amount);
router.swapExactTokensForTokens(_amount, minAmount, path, address(this), now.add(60)); // Get output token
}
if(uniAmount > 0){
// Now try the same on Uniswap
router = TradeRouter(UNISWAP_ROUTER_ADDRESS);
minAmount = uniAmount.mul(10**tokenList[_outID].decimals).div(10**tokenList[_inID].decimals); // Trades should always increase balance
estimates = router.getAmountsOut(uniAmount, path);
estimate = estimates[estimates.length - 1]; // This is the amount of expected output token
if(estimate > minAmount){
_safeApproveHelper(_inputToken, UNISWAP_ROUTER_ADDRESS, uniAmount);
router.swapExactTokensForTokens(uniAmount, minAmount, path, address(this), now.add(60)); // Get output token
}
}
return;
}
function governancePullSomeCollateral(uint256 _amount) external {
// This will pull wBTC from the contract by governance
_onlyGovernance();
IERC20Upgradeable wbtc = tokenList[1].token;
uint256 _balance = wbtc.balanceOf(address(this));
if(_amount <= _balance){
wbtc.safeTransfer(governance, _amount);
}
}
// Changeable variables by governance
function setTradingBatchSize(uint256 _size) external {
_onlyGovernance();
tradeBatchSize = _size;
}
function setStabilizeFee(uint256 _fee) external {
_onlyGovernance();
require(_fee <= MAX_FEE, "base-strategy/excessive-stabilize-fee");
stabilizeFee = _fee;
}
function setStabilizeVault(address _vault) external {
_onlyGovernance();
require(_vault != address(0), "No vault");
stabilizeVault = _vault;
}
function setSellFactorsAndPercents(uint256 _dFactor, uint256 _wFactor, uint256 _wAmplifier, uint256 _mPDigg, uint256 _mPWBTC) external {
_onlyGovernanceOrStrategist();
require(_mPDigg <= 100000 && _mPWBTC <= 100000, "Percents outside range");
diggSupplyChangeFactor = _dFactor;
wbtcSupplyChangeFactor = _wFactor;
wbtcSellAmplificationFactor = _wAmplifier;
maxGainedDiggSellPercent = _mPDigg;
maxWBTCSellPercent = _mPWBTC;
}
/// ===== Internal Core Implementations =====
function _onlyNotProtectedTokens(address _asset) internal override {
require(address(tokenList[0].token) != _asset, "DIGG");
require(address(tokenList[1].token) != _asset, "WBTC");
}
/// @notice No active position
function _deposit(uint256 _want) internal override {
// This strategy doesn't do anything when tokens are deposited
}
/// @dev No active position to exit, just send all want to controller as per wrapper withdrawAll() function
function _withdrawAll() internal override {
// This strategy doesn't do anything when tokens are withdrawn, wBTC stays in strategy until governance decides
// what to do with it
}
function _withdrawSome(uint256 _amount) internal override returns (uint256) {
require(block.number >= strategyLockedUntil, "Unable to withdraw from strategy until certain block");
// We only have idle DIGG, withdraw from the strategy directly
// Note: This value is in DIGG fragments
// Make sure that when the user withdraws, the vaults try to maintain a 1:1 ratio in value
uint256 _diggEquivalent = wbtcInDiggUnits(tokenList[1].token.balanceOf(address(this)));
uint256 _diggBalance = tokenList[0].token.balanceOf(address(this));
uint256 _extraDiggNeeded = 0;
if(_amount > _diggBalance){
_extraDiggNeeded = _amount.sub(_diggBalance);
_diggBalance = 0;
}else{
_diggBalance = _diggBalance.sub(_amount);
}
if(_extraDiggNeeded > 0){
// Calculate how much digg we need from digg vault
_diggEquivalent = _diggEquivalent.sub(_extraDiggNeeded);
}
if(_diggBalance < _diggEquivalent || _diggEquivalent == 0){
// Now balance the vaults
_extraDiggNeeded = _extraDiggNeeded.add(_diggEquivalent.sub(_diggBalance).div(2));
// Exchange with the digg treasury to keep this balanced
uint256 wbtcAmount = diggInWBTCUnits(_extraDiggNeeded);
if(wbtcAmount > tokenList[1].token.balanceOf(address(this))){
wbtcAmount = tokenList[1].token.balanceOf(address(this)); // Make sure we can actual spend it
}
_safeApproveHelper(address(tokenList[1].token), DIGG_TREASURY, wbtcAmount);
DiggTreasury(DIGG_TREASURY).exchangeWBTCForDigg(wbtcAmount, address(this)); // Internal no slip treasury exchange
}
return _amount;
}
// We will separate trades into batches to reduce market slippage
// Keepers can call this function after rebalancing to sell/buy slowly
function executeTradeBatch() public whenNotPaused {
_onlyAuthorizedActors();
if(tradeAmountLeft == 0) { return; }
// Reduce the trade amount left
uint256 batchSize = tradeBatchSize;
if(tradeAmountLeft < batchSize){
batchSize = tradeAmountLeft;
}
tradeAmountLeft = tradeAmountLeft.sub(batchSize);
if(diggInExpansion == true){
// We will be selling digg for wbtc, convert to digg units from normalized
batchSize = batchSize.mul(10**tokenList[0].decimals).div(1e18);
uint256 _earned = tokenList[1].token.balanceOf(address(this)); // Get the pre-exchange WBTC balance
if(batchSize > 0){
exchange(0,1,batchSize); // Sell Digg for wBTC
}
_earned = tokenList[1].token.balanceOf(address(this)).sub(_earned);
if(_earned > 0){
// We will distribute some of this wBTC to different parties
_processFee(address(tokenList[1].token), _earned, performanceFeeGovernance, IController(controller).rewards());
_processFee(address(tokenList[1].token), _earned, stabilizeFee, stabilizeVault);
}
}else{
// We will be selling wbtc for digg, convert to wbtc units from normalized
batchSize = batchSize.mul(10**tokenList[1].decimals).div(1e18);
uint256 _earned = tokenList[0].token.balanceOf(address(this)); // Get the pre-exchange Digg balance
if(batchSize > 0){
exchange(1,0,batchSize); // Sell WBTC for digg
}
_earned = tokenList[0].token.balanceOf(address(this)).sub(_earned);
}
}
function rebalance() external whenNotPaused {
// Modified the harvest function and called it rebalance
// This function is called by Keepers post rebase to evaluate what to do with the trade
// A percent of wbtc earned during expansion goes to rewards pool and stabilize vault
_onlyAuthorizedActors();
uint256 currentTotalSupply = tokenList[0].token.totalSupply();
if(currentTotalSupply != lastDiggTotalSupply){
// Rebase has taken place, act on it
int256 currentPrice = int256(getDiggPrice());
int256 percentChange = (currentPrice - int256(lastDiggPrice)) * int256(DIVISION_FACTOR) / int256(lastDiggPrice);
if(percentChange > 100000) {percentChange = 100000;} // We only act on at most 100% change
if(percentChange < -100000) {percentChange = -100000;}
if(currentTotalSupply > lastDiggTotalSupply){
diggInExpansion = true;
// Price is still positive
// We will sell digg for wbtc
// Our formula to calculate the amount of digg sold is below
// digg_supply_change_amount * (digg_supply_change_factor - price_change_percent)
// If amount is < 0, nothing is sold. The higher the price change, the less is sold
uint256 sellPercent;
if(int256(diggSupplyChangeFactor) <= percentChange){
sellPercent = 0;
}else if(percentChange > 0){
sellPercent = diggSupplyChangeFactor.sub(uint256(percentChange));
}else{
sellPercent = diggSupplyChangeFactor.add(uint256(-percentChange));
}
if(sellPercent > maxGainedDiggSellPercent){sellPercent = maxGainedDiggSellPercent;}
// Get the percentage amount the supply increased by
uint256 changedDigg = currentTotalSupply.sub(lastDiggTotalSupply).mul(DIVISION_FACTOR).div(lastDiggTotalSupply);
changedDigg = tokenList[0].token.balanceOf(address(this)).mul(changedDigg).div(DIVISION_FACTOR);
// This is the amount of Digg gain from the rebase returned
uint256 _amount = changedDigg.mul(sellPercent).div(DIVISION_FACTOR); // This the amount to sell
// Normalize sell amount
_amount = _amount.mul(1e18).div(10**tokenList[0].decimals);
tradeAmountLeft = _amount;
executeTradeBatch(); // This will start to trade in batches
emit TradeState(_amount, percentChange, sellPercent, lastDiggTotalSupply, currentTotalSupply, block.number);
}else{
diggInExpansion = false;
// Price is now negative
// We will sell wbtc for digg only if price begins to rise again
if(percentChange > 0){
// Our formula to calculate the percentage of wbtc sold is below
// -digg_supply_change_percent * (wbtc_supply_change_factor + price_change_percent * amplication_factor)
// First get the digg supply change in positive units
uint256 changedDiggPercent = lastDiggTotalSupply.sub(currentTotalSupply).mul(DIVISION_FACTOR).div(lastDiggTotalSupply);
// The faster the rise and the larger the negative rebase, the more that is bought
uint256 sellPercent = changedDiggPercent.mul(wbtcSupplyChangeFactor.add(uint256(percentChange).mul(wbtcSellAmplificationFactor))).div(DIVISION_FACTOR);
if(sellPercent > maxWBTCSellPercent){sellPercent = maxWBTCSellPercent;}
// We just sell this percentage of wbtc for digg gains
uint256 _amount = tokenList[1].token.balanceOf(address(this)).mul(sellPercent).div(DIVISION_FACTOR);
//Normalize the amount
_amount = _amount.mul(1e18).div(10**tokenList[1].decimals);
tradeAmountLeft = _amount;
executeTradeBatch();
emit TradeState(_amount, percentChange, sellPercent, lastDiggTotalSupply, currentTotalSupply, block.number);
}else{
tradeAmountLeft = 0; // Do not trade
emit NoTrade(block.number);
}
}
lastDiggPrice = uint256(currentPrice);
lastDiggTotalSupply = currentTotalSupply;
}else{
emit NoTrade(block.number);
}
}
} | Modified the harvest function and called it rebalance This function is called by Keepers post rebase to evaluate what to do with the trade A percent of wbtc earned during expansion goes to rewards pool and stabilize vault Rebase has taken place, act on it Price is still positive We will sell digg for wbtc Our formula to calculate the amount of digg sold is below digg_supply_change_amount * (digg_supply_change_factor - price_change_percent) If amount is < 0, nothing is sold. The higher the price change, the less is sold Price is now negative We will sell wbtc for digg only if price begins to rise again Our formula to calculate the percentage of wbtc sold is below -digg_supply_change_percent * (wbtc_supply_change_factor + price_change_percent * amplication_factor) First get the digg supply change in positive units The faster the rise and the larger the negative rebase, the more that is bought We just sell this percentage of wbtc for digg gainsNormalize the amount | function rebalance() external whenNotPaused {
_onlyAuthorizedActors();
uint256 currentTotalSupply = tokenList[0].token.totalSupply();
if(currentTotalSupply != lastDiggTotalSupply){
int256 currentPrice = int256(getDiggPrice());
int256 percentChange = (currentPrice - int256(lastDiggPrice)) * int256(DIVISION_FACTOR) / int256(lastDiggPrice);
if(currentTotalSupply > lastDiggTotalSupply){
diggInExpansion = true;
uint256 sellPercent;
if(int256(diggSupplyChangeFactor) <= percentChange){
sellPercent = 0;
sellPercent = diggSupplyChangeFactor.sub(uint256(percentChange));
sellPercent = diggSupplyChangeFactor.add(uint256(-percentChange));
}
changedDigg = tokenList[0].token.balanceOf(address(this)).mul(changedDigg).div(DIVISION_FACTOR);
tradeAmountLeft = _amount;
emit TradeState(_amount, percentChange, sellPercent, lastDiggTotalSupply, currentTotalSupply, block.number);
diggInExpansion = false;
if(percentChange > 0){
uint256 changedDiggPercent = lastDiggTotalSupply.sub(currentTotalSupply).mul(DIVISION_FACTOR).div(lastDiggTotalSupply);
uint256 sellPercent = changedDiggPercent.mul(wbtcSupplyChangeFactor.add(uint256(percentChange).mul(wbtcSellAmplificationFactor))).div(DIVISION_FACTOR);
uint256 _amount = tokenList[1].token.balanceOf(address(this)).mul(sellPercent).div(DIVISION_FACTOR);
_amount = _amount.mul(1e18).div(10**tokenList[1].decimals);
tradeAmountLeft = _amount;
executeTradeBatch();
emit TradeState(_amount, percentChange, sellPercent, lastDiggTotalSupply, currentTotalSupply, block.number);
emit NoTrade(block.number);
}
}
lastDiggPrice = uint256(currentPrice);
lastDiggTotalSupply = currentTotalSupply;
emit NoTrade(block.number);
}
}
| 12,547,743 | [
1,
4575,
326,
17895,
26923,
445,
471,
2566,
518,
283,
12296,
1220,
445,
353,
2566,
635,
10498,
414,
1603,
283,
1969,
358,
5956,
4121,
358,
741,
598,
326,
18542,
432,
5551,
434,
17298,
5111,
425,
1303,
329,
4982,
17965,
13998,
358,
283,
6397,
2845,
471,
384,
22681,
554,
9229,
868,
1969,
711,
9830,
3166,
16,
1328,
603,
518,
20137,
353,
4859,
6895,
1660,
903,
357,
80,
3097,
75,
364,
17298,
5111,
29613,
8013,
358,
4604,
326,
3844,
434,
3097,
75,
272,
1673,
353,
5712,
3097,
75,
67,
2859,
1283,
67,
3427,
67,
8949,
225,
261,
5606,
75,
67,
2859,
1283,
67,
3427,
67,
6812,
300,
6205,
67,
3427,
67,
8849,
13,
971,
3844,
353,
411,
374,
16,
5083,
353,
272,
1673,
18,
1021,
10478,
326,
6205,
2549,
16,
326,
5242,
353,
272,
1673,
20137,
353,
2037,
6092,
1660,
903,
357,
80,
17298,
5111,
364,
3097,
75,
1338,
309,
6205,
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,
283,
12296,
1435,
3903,
1347,
1248,
28590,
288,
203,
3639,
389,
3700,
15341,
2459,
1383,
5621,
203,
3639,
2254,
5034,
783,
5269,
3088,
1283,
273,
1147,
682,
63,
20,
8009,
2316,
18,
4963,
3088,
1283,
5621,
203,
3639,
309,
12,
2972,
5269,
3088,
1283,
480,
1142,
4907,
75,
5269,
3088,
1283,
15329,
203,
5411,
509,
5034,
783,
5147,
273,
509,
5034,
12,
588,
4907,
75,
5147,
10663,
203,
5411,
509,
5034,
5551,
3043,
273,
261,
2972,
5147,
300,
509,
5034,
12,
2722,
4907,
75,
5147,
3719,
380,
509,
5034,
12,
2565,
25216,
67,
26835,
13,
342,
509,
5034,
12,
2722,
4907,
75,
5147,
1769,
203,
5411,
309,
12,
2972,
5269,
3088,
1283,
405,
1142,
4907,
75,
5269,
3088,
1283,
15329,
203,
7734,
3097,
75,
382,
2966,
12162,
273,
638,
31,
203,
1171,
203,
7734,
2254,
5034,
357,
80,
8410,
31,
203,
7734,
309,
12,
474,
5034,
12,
5606,
75,
3088,
1283,
3043,
6837,
13,
1648,
5551,
3043,
15329,
203,
10792,
357,
80,
8410,
273,
374,
31,
203,
10792,
357,
80,
8410,
273,
3097,
75,
3088,
1283,
3043,
6837,
18,
1717,
12,
11890,
5034,
12,
8849,
3043,
10019,
203,
10792,
357,
80,
8410,
273,
3097,
75,
3088,
1283,
3043,
6837,
18,
1289,
12,
11890,
5034,
19236,
8849,
3043,
10019,
203,
7734,
289,
203,
1171,
203,
7734,
3550,
4907,
75,
273,
1147,
682,
63,
20,
8009,
2316,
18,
12296,
951,
12,
2867,
12,
2211,
13,
2934,
16411,
12,
6703,
4907,
75,
2934,
2892,
12,
2565,
25216,
67,
26835,
1769,
203,
1171,
203,
7734,
18542,
2
] |
pragma solidity ^0.4.23;
// File: contracts/WhitelistableConstraints.sol
/**
* @title WhitelistableConstraints
* @dev Contract encapsulating the constraints applicable to a Whitelistable contract.
*/
contract WhitelistableConstraints {
/**
* @dev Check if whitelist with specified parameters is allowed.
* @param _maxWhitelistLength The maximum length of whitelist. Zero means no whitelist.
* @param _weiWhitelistThresholdBalance The threshold balance triggering whitelist check.
* @return true if whitelist with specified parameters is allowed, false otherwise
*/
function isAllowedWhitelist(uint256 _maxWhitelistLength, uint256 _weiWhitelistThresholdBalance)
public pure returns(bool isReallyAllowedWhitelist) {
return _maxWhitelistLength > 0 || _weiWhitelistThresholdBalance > 0;
}
}
// File: contracts/Whitelistable.sol
/**
* @title Whitelistable
* @dev Base contract implementing a whitelist to keep track of investors.
* The construction parameters allow for both whitelisted and non-whitelisted contracts:
* 1) maxWhitelistLength = 0 and whitelistThresholdBalance > 0: whitelist disabled
* 2) maxWhitelistLength > 0 and whitelistThresholdBalance = 0: whitelist enabled, full whitelisting
* 3) maxWhitelistLength > 0 and whitelistThresholdBalance > 0: whitelist enabled, partial whitelisting
*/
contract Whitelistable is WhitelistableConstraints {
event LogMaxWhitelistLengthChanged(address indexed caller, uint256 indexed maxWhitelistLength);
event LogWhitelistThresholdBalanceChanged(address indexed caller, uint256 indexed whitelistThresholdBalance);
event LogWhitelistAddressAdded(address indexed caller, address indexed subscriber);
event LogWhitelistAddressRemoved(address indexed caller, address indexed subscriber);
mapping (address => bool) public whitelist;
uint256 public whitelistLength;
uint256 public maxWhitelistLength;
uint256 public whitelistThresholdBalance;
constructor(uint256 _maxWhitelistLength, uint256 _whitelistThresholdBalance) internal {
require(isAllowedWhitelist(_maxWhitelistLength, _whitelistThresholdBalance), "parameters not allowed");
maxWhitelistLength = _maxWhitelistLength;
whitelistThresholdBalance = _whitelistThresholdBalance;
}
/**
* @return true if whitelist is currently enabled, false otherwise
*/
function isWhitelistEnabled() public view returns(bool isReallyWhitelistEnabled) {
return maxWhitelistLength > 0;
}
/**
* @return true if subscriber is whitelisted, false otherwise
*/
function isWhitelisted(address _subscriber) public view returns(bool isReallyWhitelisted) {
return whitelist[_subscriber];
}
function setMaxWhitelistLengthInternal(uint256 _maxWhitelistLength) internal {
require(isAllowedWhitelist(_maxWhitelistLength, whitelistThresholdBalance),
"_maxWhitelistLength not allowed");
require(_maxWhitelistLength != maxWhitelistLength, "_maxWhitelistLength equal to current one");
maxWhitelistLength = _maxWhitelistLength;
emit LogMaxWhitelistLengthChanged(msg.sender, maxWhitelistLength);
}
function setWhitelistThresholdBalanceInternal(uint256 _whitelistThresholdBalance) internal {
require(isAllowedWhitelist(maxWhitelistLength, _whitelistThresholdBalance),
"_whitelistThresholdBalance not allowed");
require(whitelistLength == 0 || _whitelistThresholdBalance > whitelistThresholdBalance,
"_whitelistThresholdBalance not greater than current one");
whitelistThresholdBalance = _whitelistThresholdBalance;
emit LogWhitelistThresholdBalanceChanged(msg.sender, _whitelistThresholdBalance);
}
function addToWhitelistInternal(address _subscriber) internal {
require(_subscriber != address(0), "_subscriber is zero");
require(!whitelist[_subscriber], "already whitelisted");
require(whitelistLength < maxWhitelistLength, "max whitelist length reached");
whitelistLength++;
whitelist[_subscriber] = true;
emit LogWhitelistAddressAdded(msg.sender, _subscriber);
}
function removeFromWhitelistInternal(address _subscriber, uint256 _balance) internal {
require(_subscriber != address(0), "_subscriber is zero");
require(whitelist[_subscriber], "not whitelisted");
require(_balance <= whitelistThresholdBalance, "_balance greater than whitelist threshold");
assert(whitelistLength > 0);
whitelistLength--;
whitelist[_subscriber] = false;
emit LogWhitelistAddressRemoved(msg.sender, _subscriber);
}
/**
* @param _subscriber The subscriber for which the balance check is required.
* @param _balance The balance value to check for allowance.
* @return true if the balance is allowed for the subscriber, false otherwise
*/
function isAllowedBalance(address _subscriber, uint256 _balance) public view returns(bool isReallyAllowed) {
return !isWhitelistEnabled() || _balance <= whitelistThresholdBalance || whitelist[_subscriber];
}
}
// File: openzeppelin-solidity/contracts/AddressUtils.sol
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param addr address to check
* @return whether the target address is a contract
*/
function isContract(address addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
assembly { size := extcodesize(addr) } // solium-disable-line security/no-inline-assembly
return size > 0;
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @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);
}
// File: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) 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];
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol
/**
* @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;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/MintableToken.sol
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
// File: contracts/Presale.sol
/**
* @title Presale
* @dev A simple Presale Contract (PsC) for deposit collection during pre-sale events.
*/
contract Presale is Whitelistable, Pausable {
using AddressUtils for address;
using SafeMath for uint256;
event LogCreated(
address caller,
uint256 indexed startBlock,
uint256 indexed endBlock,
uint256 minDeposit,
address wallet,
address indexed providerWallet,
uint256 maxWhitelistLength,
uint256 whitelistThreshold
);
event LogMinDepositChanged(address indexed caller, uint256 indexed minDeposit);
event LogInvestmentReceived(
address indexed caller,
address indexed beneficiary,
uint256 indexed amount,
uint256 netAmount
);
event LogPresaleTokenChanged(
address indexed caller,
address indexed presaleToken,
uint256 indexed rate
);
// The start and end block where investments are allowed (both inclusive)
uint256 public startBlock;
uint256 public endBlock;
// Address where funds are collected
address public wallet;
// Presale minimum deposit in wei
uint256 public minDeposit;
// Presale balances (expressed in wei) deposited by each subscriber
mapping (address => uint256) public balanceOf;
// Amount of raised money in wei
uint256 public raisedFunds;
// Amount of service provider fees in wei
uint256 public providerFees;
// Address where service provider fees are collected
address public providerWallet;
// Two fee thresholds separating the raised money into three partitions
uint256 public feeThreshold1;
uint256 public feeThreshold2;
// Three percentage levels for fee calculation in each partition
uint256 public lowFeePercentage;
uint256 public mediumFeePercentage;
uint256 public highFeePercentage;
// Optional ERC20 presale token (0 means no presale token)
MintableToken public presaleToken;
// How many ERC20 presale token units a buyer gets per wei (0 means no presale token)
uint256 public rate;
constructor(
uint256 _startBlock,
uint256 _endBlock,
uint256 _minDeposit,
address _wallet,
address _providerWallet,
uint256 _maxWhitelistLength,
uint256 _whitelistThreshold,
uint256 _feeThreshold1,
uint256 _feeThreshold2,
uint256 _lowFeePercentage,
uint256 _mediumFeePercentage,
uint256 _highFeePercentage
)
Whitelistable(_maxWhitelistLength, _whitelistThreshold)
public
{
require(_startBlock >= block.number, "_startBlock is lower than current block number");
require(_endBlock >= _startBlock, "_endBlock is lower than _startBlock");
require(_minDeposit > 0, "_minDeposit is zero");
require(_wallet != address(0) && !_wallet.isContract(), "_wallet is zero or contract");
require(!_providerWallet.isContract(), "_providerWallet is contract");
require(_feeThreshold2 >= _feeThreshold1, "_feeThreshold2 is lower than _feeThreshold1");
require(0 <= _lowFeePercentage && _lowFeePercentage <= 100, "_lowFeePercentage not in range [0, 100]");
require(0 <= _mediumFeePercentage && _mediumFeePercentage <= 100, "_mediumFeePercentage not in range [0, 100]");
require(0 <= _highFeePercentage && _highFeePercentage <= 100, "_highFeePercentage not in range [0, 100]");
startBlock = _startBlock;
endBlock = _endBlock;
minDeposit = _minDeposit;
wallet = _wallet;
providerWallet = _providerWallet;
feeThreshold1 = _feeThreshold1;
feeThreshold2 = _feeThreshold2;
lowFeePercentage = _lowFeePercentage;
mediumFeePercentage = _mediumFeePercentage;
highFeePercentage = _highFeePercentage;
emit LogCreated(
msg.sender,
_startBlock,
_endBlock,
_minDeposit,
_wallet,
_providerWallet,
_maxWhitelistLength,
_whitelistThreshold
);
}
function hasStarted() public view returns (bool ended) {
return block.number >= startBlock;
}
// @return true if presale event has ended
function hasEnded() public view returns (bool ended) {
return block.number > endBlock;
}
// @return The current fee percentage based on raised funds
function currentFeePercentage() public view returns (uint256 feePercentage) {
return raisedFunds < feeThreshold1 ? lowFeePercentage :
raisedFunds < feeThreshold2 ? mediumFeePercentage : highFeePercentage;
}
/**
* Change the minimum deposit for each subscriber. New value shall be lower than previous.
* @param _minDeposit The minimum deposit for each subscriber, expressed in wei
*/
function setMinDeposit(uint256 _minDeposit) external onlyOwner {
require(0 < _minDeposit && _minDeposit < minDeposit, "_minDeposit not in range [0, minDeposit]");
require(!hasEnded(), "presale has ended");
minDeposit = _minDeposit;
emit LogMinDepositChanged(msg.sender, _minDeposit);
}
/**
* Change the maximum whitelist length. New value shall satisfy the #isAllowedWhitelist conditions.
* @param _maxWhitelistLength The maximum whitelist length
*/
function setMaxWhitelistLength(uint256 _maxWhitelistLength) external onlyOwner {
require(!hasEnded(), "presale has ended");
setMaxWhitelistLengthInternal(_maxWhitelistLength);
}
/**
* Change the whitelist threshold balance. New value shall satisfy the #isAllowedWhitelist conditions.
* @param _whitelistThreshold The threshold balance (in wei) above which whitelisting is required to invest
*/
function setWhitelistThresholdBalance(uint256 _whitelistThreshold) external onlyOwner {
require(!hasEnded(), "presale has ended");
setWhitelistThresholdBalanceInternal(_whitelistThreshold);
}
/**
* Add the subscriber to the whitelist.
* @param _subscriber The subscriber to add to the whitelist.
*/
function addToWhitelist(address _subscriber) external onlyOwner {
require(!hasEnded(), "presale has ended");
addToWhitelistInternal(_subscriber);
}
/**
* Removed the subscriber from the whitelist.
* @param _subscriber The subscriber to remove from the whitelist.
*/
function removeFromWhitelist(address _subscriber) external onlyOwner {
require(!hasEnded(), "presale has ended");
removeFromWhitelistInternal(_subscriber, balanceOf[_subscriber]);
}
/**
* Set the ERC20 presale token address and conversion rate.
* @param _presaleToken The ERC20 presale token.
* @param _rate How many ERC20 presale token units a buyer gets per wei.
*/
function setPresaleToken(MintableToken _presaleToken, uint256 _rate) external onlyOwner {
require(_presaleToken != presaleToken || _rate != rate, "both _presaleToken and _rate equal to current ones");
require(!hasEnded(), "presale has ended");
presaleToken = _presaleToken;
rate = _rate;
emit LogPresaleTokenChanged(msg.sender, _presaleToken, _rate);
}
function isAllowedBalance(address _beneficiary, uint256 _balance) public view returns (bool isReallyAllowed) {
bool hasMinimumBalance = _balance >= minDeposit;
return hasMinimumBalance && super.isAllowedBalance(_beneficiary, _balance);
}
function isValidInvestment(address _beneficiary, uint256 _amount) public view returns (bool isValid) {
bool withinPeriod = startBlock <= block.number && block.number <= endBlock;
bool nonZeroPurchase = _amount != 0;
bool isAllowedAmount = isAllowedBalance(_beneficiary, balanceOf[_beneficiary].add(_amount));
return withinPeriod && nonZeroPurchase && isAllowedAmount;
}
function invest(address _beneficiary) public payable whenNotPaused {
require(_beneficiary != address(0), "_beneficiary is zero");
require(_beneficiary != wallet, "_beneficiary is equal to wallet");
require(_beneficiary != providerWallet, "_beneficiary is equal to providerWallet");
require(isValidInvestment(_beneficiary, msg.value), "forbidden investment for _beneficiary");
balanceOf[_beneficiary] = balanceOf[_beneficiary].add(msg.value);
raisedFunds = raisedFunds.add(msg.value);
// Optionally distribute presale token to buyer, if configured
if (presaleToken != address(0) && rate != 0) {
uint256 tokenAmount = msg.value.mul(rate);
presaleToken.mint(_beneficiary, tokenAmount);
}
if (providerWallet == 0) {
wallet.transfer(msg.value);
emit LogInvestmentReceived(msg.sender, _beneficiary, msg.value, msg.value);
}
else {
uint256 feePercentage = currentFeePercentage();
uint256 fees = msg.value.mul(feePercentage).div(100);
uint256 netAmount = msg.value.sub(fees);
providerFees = providerFees.add(fees);
providerWallet.transfer(fees);
wallet.transfer(netAmount);
emit LogInvestmentReceived(msg.sender, _beneficiary, msg.value, netAmount);
}
}
function () external payable whenNotPaused {
invest(msg.sender);
}
}
// File: contracts/CappedPresale.sol
/**
* @title CappedPresale
* @dev Extension of Presale with a max amount of funds raised
*/
contract CappedPresale is Presale {
using SafeMath for uint256;
event LogMaxCapChanged(address indexed caller, uint256 indexed maxCap);
// Maximum cap in wei
uint256 public maxCap;
constructor(
uint256 _startBlock,
uint256 _endBlock,
uint256 _minDeposit,
address _wallet,
address _providerWallet,
uint256 _maxWhitelistLength,
uint256 _whitelistThreshold,
uint256 _feeThreshold1,
uint256 _feeThreshold2,
uint256 _lowFeePercentage,
uint256 _mediumFeePercentage,
uint256 _highFeePercentage,
uint256 _maxCap
)
Presale(
_startBlock,
_endBlock,
_minDeposit,
_wallet,
_providerWallet,
_maxWhitelistLength,
_whitelistThreshold,
_feeThreshold1,
_feeThreshold2,
_lowFeePercentage,
_mediumFeePercentage,
_highFeePercentage
)
public
{
require(_maxCap > 0, "_maxCap is zero");
require(_maxCap >= _feeThreshold2, "_maxCap is lower than _feeThreshold2");
maxCap = _maxCap;
}
/**
* Change the maximum cap of the presale. New value shall be greater than previous one.
* @param _maxCap The maximum cap of the presale, expressed in wei
*/
function setMaxCap(uint256 _maxCap) external onlyOwner {
require(_maxCap > maxCap, "_maxCap is not greater than current maxCap");
require(!hasEnded(), "presale has ended");
maxCap = _maxCap;
emit LogMaxCapChanged(msg.sender, _maxCap);
}
// overriding Presale#hasEnded to add cap logic
// @return true if presale event has ended
function hasEnded() public view returns (bool ended) {
bool capReached = raisedFunds >= maxCap;
return super.hasEnded() || capReached;
}
// overriding Presale#isValidInvestment to add extra cap logic
// @return true if beneficiary can buy at the moment
function isValidInvestment(address _beneficiary, uint256 _amount) public view returns (bool isValid) {
bool withinCap = raisedFunds.add(_amount) <= maxCap;
return super.isValidInvestment(_beneficiary, _amount) && withinCap;
}
}
// File: contracts/NokuCustomPresale.sol
/**
* @title NokuCustomPresale
* @dev Extension of CappedPresale.
*/
contract NokuCustomPresale is CappedPresale {
event LogNokuCustomPresaleCreated(
address caller,
uint256 indexed startBlock,
uint256 indexed endBlock,
uint256 minDeposit,
address wallet,
address indexed providerWallet,
uint256 maxWhitelistLength,
uint256 whitelistThreshold
);
constructor(
uint256 _startBlock,
uint256 _endBlock,
uint256 _minDeposit,
address _wallet,
address _providerWallet,
uint256 _maxWhitelistLength,
uint256 _whitelistThreshold,
uint256 _feeThreshold1,
uint256 _feeThreshold2,
uint256 _lowFeePercentage,
uint256 _mediumFeePercentage,
uint256 _highFeePercentage,
uint256 _maxCap
)
CappedPresale(
_startBlock,
_endBlock,
_minDeposit,
_wallet,
_providerWallet,
_maxWhitelistLength,
_whitelistThreshold,
_feeThreshold1,
_feeThreshold2,
_lowFeePercentage,
_mediumFeePercentage,
_highFeePercentage,
_maxCap
)
public {
emit LogNokuCustomPresaleCreated(
msg.sender,
_startBlock,
_endBlock,
_minDeposit,
_wallet,
_providerWallet,
_maxWhitelistLength,
_whitelistThreshold
);
}
}
// File: contracts/NokuPricingPlan.sol
/**
* @dev The NokuPricingPlan contract defines the responsibilities of a Noku pricing plan.
*/
contract NokuPricingPlan {
/**
* @dev Pay the fee for the service identified by the specified name.
* The fee amount shall already be approved by the client.
* @param serviceName The name of the target service.
* @param multiplier The multiplier of the base service fee to apply.
* @param client The client of the target service.
* @return true if fee has been paid.
*/
function payFee(bytes32 serviceName, uint256 multiplier, address client) public returns(bool paid);
/**
* @dev Get the usage fee for the service identified by the specified name.
* The returned fee amount shall be approved before using #payFee method.
* @param serviceName The name of the target service.
* @param multiplier The multiplier of the base service fee to apply.
* @return The amount to approve before really paying such fee.
*/
function usageFee(bytes32 serviceName, uint256 multiplier) public constant returns(uint fee);
}
// File: contracts/NokuCustomService.sol
contract NokuCustomService is Pausable {
using AddressUtils for address;
event LogPricingPlanChanged(address indexed caller, address indexed pricingPlan);
// The pricing plan determining the fee to be paid in NOKU tokens by customers
NokuPricingPlan public pricingPlan;
constructor(address _pricingPlan) internal {
require(_pricingPlan.isContract(), "_pricingPlan is not contract");
pricingPlan = NokuPricingPlan(_pricingPlan);
}
function setPricingPlan(address _pricingPlan) public onlyOwner {
require(_pricingPlan.isContract(), "_pricingPlan is not contract");
require(NokuPricingPlan(_pricingPlan) != pricingPlan, "_pricingPlan equal to current");
pricingPlan = NokuPricingPlan(_pricingPlan);
emit LogPricingPlanChanged(msg.sender, _pricingPlan);
}
}
// File: contracts/NokuCustomPresaleService.sol
/**
* @title NokuCustomPresaleService
* @dev Extension of NokuCustomService adding the fee payment in NOKU tokens.
*/
contract NokuCustomPresaleService is NokuCustomService {
event LogNokuCustomPresaleServiceCreated(address indexed caller);
bytes32 public constant SERVICE_NAME = "NokuCustomERC20.presale";
uint256 public constant CREATE_AMOUNT = 1 * 10**18;
constructor(address _pricingPlan) NokuCustomService(_pricingPlan) public {
emit LogNokuCustomPresaleServiceCreated(msg.sender);
}
function createCustomPresale(
uint256 _startBlock,
uint256 _endBlock,
uint256 _minDeposit,
address _wallet,
address _providerWallet,
uint256 _maxWhitelistLength,
uint256 _whitelistThreshold,
uint256 _feeThreshold1,
uint256 _feeThreshold2,
uint256 _lowFeePercentage,
uint256 _mediumFeePercentage,
uint256 _highFeePercentage,
uint256 _maxCap
)
public returns(NokuCustomPresale customPresale)
{
customPresale = new NokuCustomPresale(
_startBlock,
_endBlock,
_minDeposit,
_wallet,
_providerWallet,
_maxWhitelistLength,
_whitelistThreshold,
_feeThreshold1,
_feeThreshold2,
_lowFeePercentage,
_mediumFeePercentage,
_highFeePercentage,
_maxCap
);
// Transfer NokuCustomPresale ownership to the client
customPresale.transferOwnership(msg.sender);
require(pricingPlan.payFee(SERVICE_NAME, CREATE_AMOUNT, msg.sender), "fee payment failed");
}
} | * @return true if subscriber is whitelisted, false otherwise/ | function isWhitelisted(address _subscriber) public view returns(bool isReallyWhitelisted) {
return whitelist[_subscriber];
}
| 887,500 | [
1,
2463,
638,
309,
9467,
353,
26944,
16,
629,
3541,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
353,
18927,
329,
12,
2867,
389,
26410,
13,
1071,
1476,
1135,
12,
6430,
28627,
1230,
18927,
329,
13,
288,
203,
3639,
327,
10734,
63,
67,
26410,
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
] |
//Address: 0x14fbca95be7e99c15cc2996c6c9d841e54b79425
//Contract name: MatchingMarket
//Balance: 0 Ether
//Verification Date: 12/18/2017
//Transacion Count: 171303
// CODE STARTS HERE
pragma solidity ^0.4.18;
contract DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) public view returns (bool);
}
contract DSAuthEvents {
event LogSetAuthority (address indexed authority);
event LogSetOwner (address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
function DSAuth() public {
owner = msg.sender;
LogSetOwner(msg.sender);
}
function setOwner(address owner_)
public
auth
{
owner = owner_;
LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_)
public
auth
{
authority = authority_;
LogSetAuthority(authority);
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig));
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, this, sig);
}
}
}
contract DSMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x);
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x);
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x);
}
function min(uint x, uint y) internal pure returns (uint z) {
return x <= y ? x : y;
}
function max(uint x, uint y) internal pure returns (uint z) {
return x >= y ? x : y;
}
function imin(int x, int y) internal pure returns (int z) {
return x <= y ? x : y;
}
function imax(int x, int y) internal pure returns (int z) {
return x >= y ? x : y;
}
uint constant WAD = 10 ** 18;
uint constant RAY = 10 ** 27;
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, RAY), y / 2) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function rpow(uint x, uint n) internal pure returns (uint z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
contract ERC20Events {
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
}
contract ERC20 is ERC20Events {
function totalSupply() public view returns (uint);
function balanceOf(address guy) public view returns (uint);
function allowance(address src, address guy) public view returns (uint);
function approve(address guy, uint wad) public returns (bool);
function transfer(address dst, uint wad) public returns (bool);
function transferFrom(
address src, address dst, uint wad
) public returns (bool);
}
contract EventfulMarket {
event LogItemUpdate(uint id);
event LogTrade(uint pay_amt, address indexed pay_gem,
uint buy_amt, address indexed buy_gem);
event LogMake(
bytes32 indexed id,
bytes32 indexed pair,
address indexed maker,
ERC20 pay_gem,
ERC20 buy_gem,
uint128 pay_amt,
uint128 buy_amt,
uint64 timestamp
);
event LogBump(
bytes32 indexed id,
bytes32 indexed pair,
address indexed maker,
ERC20 pay_gem,
ERC20 buy_gem,
uint128 pay_amt,
uint128 buy_amt,
uint64 timestamp
);
event LogTake(
bytes32 id,
bytes32 indexed pair,
address indexed maker,
ERC20 pay_gem,
ERC20 buy_gem,
address indexed taker,
uint128 take_amt,
uint128 give_amt,
uint64 timestamp
);
event LogKill(
bytes32 indexed id,
bytes32 indexed pair,
address indexed maker,
ERC20 pay_gem,
ERC20 buy_gem,
uint128 pay_amt,
uint128 buy_amt,
uint64 timestamp
);
}
contract SimpleMarket is EventfulMarket, DSMath {
uint public last_offer_id;
mapping (uint => OfferInfo) public offers;
bool locked;
struct OfferInfo {
uint pay_amt;
ERC20 pay_gem;
uint buy_amt;
ERC20 buy_gem;
address owner;
uint64 timestamp;
}
modifier can_buy(uint id) {
require(isActive(id));
_;
}
modifier can_cancel(uint id) {
require(isActive(id));
require(getOwner(id) == msg.sender);
_;
}
modifier can_offer {
_;
}
modifier synchronized {
require(!locked);
locked = true;
_;
locked = false;
}
function isActive(uint id) public constant returns (bool active) {
return offers[id].timestamp > 0;
}
function getOwner(uint id) public constant returns (address owner) {
return offers[id].owner;
}
function getOffer(uint id) public constant returns (uint, ERC20, uint, ERC20) {
var offer = offers[id];
return (offer.pay_amt, offer.pay_gem,
offer.buy_amt, offer.buy_gem);
}
// ---- Public entrypoints ---- //
function bump(bytes32 id_)
public
can_buy(uint256(id_))
{
var id = uint256(id_);
LogBump(
id_,
keccak256(offers[id].pay_gem, offers[id].buy_gem),
offers[id].owner,
offers[id].pay_gem,
offers[id].buy_gem,
uint128(offers[id].pay_amt),
uint128(offers[id].buy_amt),
offers[id].timestamp
);
}
// Accept given `quantity` of an offer. Transfers funds from caller to
// offer maker, and from market to caller.
function buy(uint id, uint quantity)
public
can_buy(id)
synchronized
returns (bool)
{
OfferInfo memory offer = offers[id];
uint spend = mul(quantity, offer.buy_amt) / offer.pay_amt;
require(uint128(spend) == spend);
require(uint128(quantity) == quantity);
// For backwards semantic compatibility.
if (quantity == 0 || spend == 0 ||
quantity > offer.pay_amt || spend > offer.buy_amt)
{
return false;
}
offers[id].pay_amt = sub(offer.pay_amt, quantity);
offers[id].buy_amt = sub(offer.buy_amt, spend);
require( offer.buy_gem.transferFrom(msg.sender, offer.owner, spend) );
require( offer.pay_gem.transfer(msg.sender, quantity) );
LogItemUpdate(id);
LogTake(
bytes32(id),
keccak256(offer.pay_gem, offer.buy_gem),
offer.owner,
offer.pay_gem,
offer.buy_gem,
msg.sender,
uint128(quantity),
uint128(spend),
uint64(now)
);
LogTrade(quantity, offer.pay_gem, spend, offer.buy_gem);
if (offers[id].pay_amt == 0) {
delete offers[id];
}
return true;
}
// Cancel an offer. Refunds offer maker.
function cancel(uint id)
public
can_cancel(id)
synchronized
returns (bool success)
{
// read-only offer. Modify an offer by directly accessing offers[id]
OfferInfo memory offer = offers[id];
delete offers[id];
require( offer.pay_gem.transfer(offer.owner, offer.pay_amt) );
LogItemUpdate(id);
LogKill(
bytes32(id),
keccak256(offer.pay_gem, offer.buy_gem),
offer.owner,
offer.pay_gem,
offer.buy_gem,
uint128(offer.pay_amt),
uint128(offer.buy_amt),
uint64(now)
);
success = true;
}
function kill(bytes32 id)
public
{
require(cancel(uint256(id)));
}
function make(
ERC20 pay_gem,
ERC20 buy_gem,
uint128 pay_amt,
uint128 buy_amt
)
public
returns (bytes32 id)
{
return bytes32(offer(pay_amt, pay_gem, buy_amt, buy_gem));
}
// Make a new offer. Takes funds from the caller into market escrow.
function offer(uint pay_amt, ERC20 pay_gem, uint buy_amt, ERC20 buy_gem)
public
can_offer
synchronized
returns (uint id)
{
require(uint128(pay_amt) == pay_amt);
require(uint128(buy_amt) == buy_amt);
require(pay_amt > 0);
require(pay_gem != ERC20(0x0));
require(buy_amt > 0);
require(buy_gem != ERC20(0x0));
require(pay_gem != buy_gem);
OfferInfo memory info;
info.pay_amt = pay_amt;
info.pay_gem = pay_gem;
info.buy_amt = buy_amt;
info.buy_gem = buy_gem;
info.owner = msg.sender;
info.timestamp = uint64(now);
id = _next_id();
offers[id] = info;
require( pay_gem.transferFrom(msg.sender, this, pay_amt) );
LogItemUpdate(id);
LogMake(
bytes32(id),
keccak256(pay_gem, buy_gem),
msg.sender,
pay_gem,
buy_gem,
uint128(pay_amt),
uint128(buy_amt),
uint64(now)
);
}
function take(bytes32 id, uint128 maxTakeAmount)
public
{
require(buy(uint256(id), maxTakeAmount));
}
function _next_id()
internal
returns (uint)
{
last_offer_id++; return last_offer_id;
}
}
// Simple Market with a market lifetime. When the close_time has been reached,
// offers can only be cancelled (offer and buy will throw).
contract ExpiringMarket is DSAuth, SimpleMarket {
uint64 public close_time;
bool public stopped;
// after close_time has been reached, no new offers are allowed
modifier can_offer {
require(!isClosed());
_;
}
// after close, no new buys are allowed
modifier can_buy(uint id) {
require(isActive(id));
require(!isClosed());
_;
}
// after close, anyone can cancel an offer
modifier can_cancel(uint id) {
require(isActive(id));
require(isClosed() || (msg.sender == getOwner(id)));
_;
}
function ExpiringMarket(uint64 _close_time)
public
{
close_time = _close_time;
}
function isClosed() public constant returns (bool closed) {
return stopped || getTime() > close_time;
}
function getTime() public constant returns (uint64) {
return uint64(now);
}
function stop() public auth {
stopped = true;
}
}
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
assembly {
foo := calldataload(4)
bar := calldataload(36)
}
LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data);
_;
}
}
contract MatchingEvents {
event LogBuyEnabled(bool isEnabled);
event LogMinSell(address pay_gem, uint min_amount);
event LogMatchingEnabled(bool isEnabled);
event LogUnsortedOffer(uint id);
event LogSortedOffer(uint id);
event LogAddTokenPairWhitelist(ERC20 baseToken, ERC20 quoteToken);
event LogRemTokenPairWhitelist(ERC20 baseToken, ERC20 quoteToken);
event LogInsert(address keeper, uint id);
event LogDelete(address keeper, uint id);
}
contract MatchingMarket is MatchingEvents, ExpiringMarket, DSNote {
bool public buyEnabled = true; //buy enabled
bool public matchingEnabled = true; //true: enable matching,
//false: revert to expiring market
struct sortInfo {
uint next; //points to id of next higher offer
uint prev; //points to id of previous lower offer
uint delb; //the blocknumber where this entry was marked for delete
}
mapping(uint => sortInfo) public _rank; //doubly linked lists of sorted offer ids
mapping(address => mapping(address => uint)) public _best; //id of the highest offer for a token pair
mapping(address => mapping(address => uint)) public _span; //number of offers stored for token pair in sorted orderbook
mapping(address => uint) public _dust; //minimum sell amount for a token to avoid dust offers
mapping(uint => uint) public _near; //next unsorted offer id
mapping(bytes32 => bool) public _menu; //whitelist tracking which token pairs can be traded
uint _head; //first unsorted offer id
//check if token pair is enabled
modifier isWhitelist(ERC20 buy_gem, ERC20 pay_gem) {
require(_menu[keccak256(buy_gem, pay_gem)] || _menu[keccak256(pay_gem, buy_gem)]);
_;
}
function MatchingMarket(uint64 close_time) ExpiringMarket(close_time) public {
}
// ---- Public entrypoints ---- //
function make(
ERC20 pay_gem,
ERC20 buy_gem,
uint128 pay_amt,
uint128 buy_amt
)
public
returns (bytes32)
{
return bytes32(offer(pay_amt, pay_gem, buy_amt, buy_gem));
}
function take(bytes32 id, uint128 maxTakeAmount) public {
require(buy(uint256(id), maxTakeAmount));
}
function kill(bytes32 id) public {
require(cancel(uint256(id)));
}
// Make a new offer. Takes funds from the caller into market escrow.
//
// If matching is enabled:
// * creates new offer without putting it in
// the sorted list.
// * available to authorized contracts only!
// * keepers should call insert(id,pos)
// to put offer in the sorted list.
//
// If matching is disabled:
// * calls expiring market's offer().
// * available to everyone without authorization.
// * no sorting is done.
//
function offer(
uint pay_amt, //maker (ask) sell how much
ERC20 pay_gem, //maker (ask) sell which token
uint buy_amt, //taker (ask) buy how much
ERC20 buy_gem //taker (ask) buy which token
)
public
isWhitelist(pay_gem, buy_gem)
/* NOT synchronized!!! */
returns (uint)
{
var fn = matchingEnabled ? _offeru : super.offer;
return fn(pay_amt, pay_gem, buy_amt, buy_gem);
}
// Make a new offer. Takes funds from the caller into market escrow.
function offer(
uint pay_amt, //maker (ask) sell how much
ERC20 pay_gem, //maker (ask) sell which token
uint buy_amt, //maker (ask) buy how much
ERC20 buy_gem, //maker (ask) buy which token
uint pos //position to insert offer, 0 should be used if unknown
)
public
isWhitelist(pay_gem, buy_gem)
/*NOT synchronized!!! */
can_offer
returns (uint)
{
return offer(pay_amt, pay_gem, buy_amt, buy_gem, pos, false);
}
function offer(
uint pay_amt, //maker (ask) sell how much
ERC20 pay_gem, //maker (ask) sell which token
uint buy_amt, //maker (ask) buy how much
ERC20 buy_gem, //maker (ask) buy which token
uint pos, //position to insert offer, 0 should be used if unknown
bool rounding //match "close enough" orders?
)
public
isWhitelist(pay_gem, buy_gem)
/*NOT synchronized!!! */
can_offer
returns (uint)
{
require(_dust[pay_gem] <= pay_amt);
if (matchingEnabled) {
return _matcho(pay_amt, pay_gem, buy_amt, buy_gem, pos, rounding);
}
return super.offer(pay_amt, pay_gem, buy_amt, buy_gem);
}
//Transfers funds from caller to offer maker, and from market to caller.
function buy(uint id, uint amount)
public
/*NOT synchronized!!! */
can_buy(id)
returns (bool)
{
var fn = matchingEnabled ? _buys : super.buy;
return fn(id, amount);
}
// Cancel an offer. Refunds offer maker.
function cancel(uint id)
public
/*NOT synchronized!!! */
can_cancel(id)
returns (bool success)
{
if (matchingEnabled) {
if (isOfferSorted(id)) {
require(_unsort(id));
} else {
require(_hide(id));
}
}
return super.cancel(id); //delete the offer.
}
//insert offer into the sorted list
//keepers need to use this function
function insert(
uint id, //maker (ask) id
uint pos //position to insert into
)
public
returns (bool)
{
require(!isOfferSorted(id)); //make sure offers[id] is not yet sorted
require(isActive(id)); //make sure offers[id] is active
_hide(id); //remove offer from unsorted offers list
_sort(id, pos); //put offer into the sorted offers list
LogInsert(msg.sender, id);
return true;
}
//deletes _rank [id]
// Function should be called by keepers.
function del_rank(uint id)
public
returns (bool)
{
require(!isActive(id) && _rank[id].delb != 0 && _rank[id].delb < block.number - 10);
delete _rank[id];
LogDelete(msg.sender, id);
return true;
}
//returns true if token is succesfully added to whitelist
// Function is used to add a token pair to the whitelist
// All incoming offers are checked against the whitelist.
function addTokenPairWhitelist(
ERC20 baseToken,
ERC20 quoteToken
)
public
auth
note
returns (bool)
{
require(!isTokenPairWhitelisted(baseToken, quoteToken));
require(address(baseToken) != 0x0 && address(quoteToken) != 0x0);
_menu[keccak256(baseToken, quoteToken)] = true;
LogAddTokenPairWhitelist(baseToken, quoteToken);
return true;
}
//returns true if token is successfully removed from whitelist
// Function is used to remove a token pair from the whitelist.
// All incoming offers are checked against the whitelist.
function remTokenPairWhitelist(
ERC20 baseToken,
ERC20 quoteToken
)
public
auth
note
returns (bool)
{
require(isTokenPairWhitelisted(baseToken, quoteToken));
delete _menu[keccak256(baseToken, quoteToken)];
delete _menu[keccak256(quoteToken, baseToken)];
LogRemTokenPairWhitelist(baseToken, quoteToken);
return true;
}
function isTokenPairWhitelisted(
ERC20 baseToken,
ERC20 quoteToken
)
public
constant
returns (bool)
{
return (_menu[keccak256(baseToken, quoteToken)] || _menu[keccak256(quoteToken, baseToken)]);
}
//set the minimum sell amount for a token
// Function is used to avoid "dust offers" that have
// very small amount of tokens to sell, and it would
// cost more gas to accept the offer, than the value
// of tokens received.
function setMinSell(
ERC20 pay_gem, //token to assign minimum sell amount to
uint dust //maker (ask) minimum sell amount
)
public
auth
note
returns (bool)
{
_dust[pay_gem] = dust;
LogMinSell(pay_gem, dust);
return true;
}
//returns the minimum sell amount for an offer
function getMinSell(
ERC20 pay_gem //token for which minimum sell amount is queried
)
public
constant
returns (uint)
{
return _dust[pay_gem];
}
//set buy functionality enabled/disabled
function setBuyEnabled(bool buyEnabled_) public auth returns (bool) {
buyEnabled = buyEnabled_;
LogBuyEnabled(buyEnabled);
return true;
}
//set matching enabled/disabled
// If matchingEnabled true(default), then inserted offers are matched.
// Except the ones inserted by contracts, because those end up
// in the unsorted list of offers, that must be later sorted by
// keepers using insert().
// If matchingEnabled is false then MatchingMarket is reverted to ExpiringMarket,
// and matching is not done, and sorted lists are disabled.
function setMatchingEnabled(bool matchingEnabled_) public auth returns (bool) {
matchingEnabled = matchingEnabled_;
LogMatchingEnabled(matchingEnabled);
return true;
}
//return the best offer for a token pair
// the best offer is the lowest one if it's an ask,
// and highest one if it's a bid offer
function getBestOffer(ERC20 sell_gem, ERC20 buy_gem) public constant returns(uint) {
return _best[sell_gem][buy_gem];
}
//return the next worse offer in the sorted list
// the worse offer is the higher one if its an ask,
// a lower one if its a bid offer,
// and in both cases the newer one if they're equal.
function getWorseOffer(uint id) public constant returns(uint) {
return _rank[id].prev;
}
//return the next better offer in the sorted list
// the better offer is in the lower priced one if its an ask,
// the next higher priced one if its a bid offer
// and in both cases the older one if they're equal.
function getBetterOffer(uint id) public constant returns(uint) {
return _rank[id].next;
}
//return the amount of better offers for a token pair
function getOfferCount(ERC20 sell_gem, ERC20 buy_gem) public constant returns(uint) {
return _span[sell_gem][buy_gem];
}
//get the first unsorted offer that was inserted by a contract
// Contracts can't calculate the insertion position of their offer because it is not an O(1) operation.
// Their offers get put in the unsorted list of offers.
// Keepers can calculate the insertion position offchain and pass it to the insert() function to insert
// the unsorted offer into the sorted list. Unsorted offers will not be matched, but can be bought with buy().
function getFirstUnsortedOffer() public constant returns(uint) {
return _head;
}
//get the next unsorted offer
// Can be used to cycle through all the unsorted offers.
function getNextUnsortedOffer(uint id) public constant returns(uint) {
return _near[id];
}
function isOfferSorted(uint id) public constant returns(bool) {
return _rank[id].next != 0
|| _rank[id].prev != 0
|| _best[offers[id].pay_gem][offers[id].buy_gem] == id;
}
function sellAllAmount(ERC20 pay_gem, uint pay_amt, ERC20 buy_gem, uint min_fill_amount)
public
returns (uint fill_amt)
{
uint offerId;
while (pay_amt > 0) { //while there is amount to sell
offerId = getBestOffer(buy_gem, pay_gem); //Get the best offer for the token pair
require(offerId != 0); //Fails if there are not more offers
// There is a chance that pay_amt is smaller than 1 wei of the other token
if (pay_amt * 1 ether < wdiv(offers[offerId].buy_amt, offers[offerId].pay_amt)) {
break; //We consider that all amount is sold
}
if (pay_amt >= offers[offerId].buy_amt) { //If amount to sell is higher or equal than current offer amount to buy
fill_amt = add(fill_amt, offers[offerId].pay_amt); //Add amount bought to acumulator
pay_amt = sub(pay_amt, offers[offerId].buy_amt); //Decrease amount to sell
take(bytes32(offerId), uint128(offers[offerId].pay_amt)); //We take the whole offer
} else { // if lower
var baux = rmul(pay_amt * 10 ** 9, rdiv(offers[offerId].pay_amt, offers[offerId].buy_amt)) / 10 ** 9;
fill_amt = add(fill_amt, baux); //Add amount bought to acumulator
take(bytes32(offerId), uint128(baux)); //We take the portion of the offer that we need
pay_amt = 0; //All amount is sold
}
}
require(fill_amt >= min_fill_amount);
}
function buyAllAmount(ERC20 buy_gem, uint buy_amt, ERC20 pay_gem, uint max_fill_amount)
public
returns (uint fill_amt)
{
uint offerId;
while (buy_amt > 0) { //Meanwhile there is amount to buy
offerId = getBestOffer(buy_gem, pay_gem); //Get the best offer for the token pair
require(offerId != 0);
// There is a chance that buy_amt is smaller than 1 wei of the other token
if (buy_amt * 1 ether < wdiv(offers[offerId].pay_amt, offers[offerId].buy_amt)) {
break; //We consider that all amount is sold
}
if (buy_amt >= offers[offerId].pay_amt) { //If amount to buy is higher or equal than current offer amount to sell
fill_amt = add(fill_amt, offers[offerId].buy_amt); //Add amount sold to acumulator
buy_amt = sub(buy_amt, offers[offerId].pay_amt); //Decrease amount to buy
take(bytes32(offerId), uint128(offers[offerId].pay_amt)); //We take the whole offer
} else { //if lower
fill_amt = add(fill_amt, rmul(buy_amt * 10 ** 9, rdiv(offers[offerId].buy_amt, offers[offerId].pay_amt)) / 10 ** 9); //Add amount sold to acumulator
take(bytes32(offerId), uint128(buy_amt)); //We take the portion of the offer that we need
buy_amt = 0; //All amount is bought
}
}
require(fill_amt <= max_fill_amount);
}
function getBuyAmount(ERC20 buy_gem, ERC20 pay_gem, uint pay_amt) public constant returns (uint fill_amt) {
var offerId = getBestOffer(buy_gem, pay_gem); //Get best offer for the token pair
while (pay_amt > offers[offerId].buy_amt) {
fill_amt = add(fill_amt, offers[offerId].pay_amt); //Add amount to buy accumulator
pay_amt = sub(pay_amt, offers[offerId].buy_amt); //Decrease amount to pay
if (pay_amt > 0) { //If we still need more offers
offerId = getWorseOffer(offerId); //We look for the next best offer
require(offerId != 0); //Fails if there are not enough offers to complete
}
}
fill_amt = add(fill_amt, rmul(pay_amt * 10 ** 9, rdiv(offers[offerId].pay_amt, offers[offerId].buy_amt)) / 10 ** 9); //Add proportional amount of last offer to buy accumulator
}
function getPayAmount(ERC20 pay_gem, ERC20 buy_gem, uint buy_amt) public constant returns (uint fill_amt) {
var offerId = getBestOffer(buy_gem, pay_gem); //Get best offer for the token pair
while (buy_amt > offers[offerId].pay_amt) {
fill_amt = add(fill_amt, offers[offerId].buy_amt); //Add amount to pay accumulator
buy_amt = sub(buy_amt, offers[offerId].pay_amt); //Decrease amount to buy
if (buy_amt > 0) { //If we still need more offers
offerId = getWorseOffer(offerId); //We look for the next best offer
require(offerId != 0); //Fails if there are not enough offers to complete
}
}
fill_amt = add(fill_amt, rmul(buy_amt * 10 ** 9, rdiv(offers[offerId].buy_amt, offers[offerId].pay_amt)) / 10 ** 9); //Add proportional amount of last offer to pay accumulator
}
// ---- Internal Functions ---- //
function _buys(uint id, uint amount)
internal
returns (bool)
{
require(buyEnabled);
if (amount == offers[id].pay_amt && isOfferSorted(id)) {
//offers[id] must be removed from sorted list because all of it is bought
_unsort(id);
}
require(super.buy(id, amount));
return true;
}
//find the id of the next higher offer after offers[id]
function _find(uint id)
internal
view
returns (uint)
{
require( id > 0 );
address buy_gem = address(offers[id].buy_gem);
address pay_gem = address(offers[id].pay_gem);
uint top = _best[pay_gem][buy_gem];
uint old_top = 0;
// Find the larger-than-id order whose successor is less-than-id.
while (top != 0 && _isPricedLtOrEq(id, top)) {
old_top = top;
top = _rank[top].prev;
}
return old_top;
}
//find the id of the next higher offer after offers[id]
function _findpos(uint id, uint pos)
internal
view
returns (uint)
{
require(id > 0);
// Look for an active order.
while (pos != 0 && !isActive(pos)) {
pos = _rank[pos].prev;
}
if (pos == 0) {
//if we got to the end of list without a single active offer
return _find(id);
} else {
// if we did find a nearby active offer
// Walk the order book down from there...
if(_isPricedLtOrEq(id, pos)) {
uint old_pos;
// Guaranteed to run at least once because of
// the prior if statements.
while (pos != 0 && _isPricedLtOrEq(id, pos)) {
old_pos = pos;
pos = _rank[pos].prev;
}
return old_pos;
// ...or walk it up.
} else {
while (pos != 0 && !_isPricedLtOrEq(id, pos)) {
pos = _rank[pos].next;
}
return pos;
}
}
}
//return true if offers[low] priced less than or equal to offers[high]
function _isPricedLtOrEq(
uint low, //lower priced offer's id
uint high //higher priced offer's id
)
internal
view
returns (bool)
{
return mul(offers[low].buy_amt, offers[high].pay_amt)
>= mul(offers[high].buy_amt, offers[low].pay_amt);
}
//these variables are global only because of solidity local variable limit
//match offers with taker offer, and execute token transactions
function _matcho(
uint t_pay_amt, //taker sell how much
ERC20 t_pay_gem, //taker sell which token
uint t_buy_amt, //taker buy how much
ERC20 t_buy_gem, //taker buy which token
uint pos, //position id
bool rounding //match "close enough" orders?
)
internal
returns (uint id)
{
uint best_maker_id; //highest maker id
uint t_buy_amt_old; //taker buy how much saved
uint m_buy_amt; //maker offer wants to buy this much token
uint m_pay_amt; //maker offer wants to sell this much token
// there is at least one offer stored for token pair
while (_best[t_buy_gem][t_pay_gem] > 0) {
best_maker_id = _best[t_buy_gem][t_pay_gem];
m_buy_amt = offers[best_maker_id].buy_amt;
m_pay_amt = offers[best_maker_id].pay_amt;
// Ugly hack to work around rounding errors. Based on the idea that
// the furthest the amounts can stray from their "true" values is 1.
// Ergo the worst case has t_pay_amt and m_pay_amt at +1 away from
// their "correct" values and m_buy_amt and t_buy_amt at -1.
// Since (c - 1) * (d - 1) > (a + 1) * (b + 1) is equivalent to
// c * d > a * b + a + b + c + d, we write...
if (mul(m_buy_amt, t_buy_amt) > mul(t_pay_amt, m_pay_amt) +
(rounding ? m_buy_amt + t_buy_amt + t_pay_amt + m_pay_amt : 0))
{
break;
}
// ^ The `rounding` parameter is a compromise borne of a couple days
// of discussion.
buy(best_maker_id, min(m_pay_amt, t_buy_amt));
t_buy_amt_old = t_buy_amt;
t_buy_amt = sub(t_buy_amt, min(m_pay_amt, t_buy_amt));
t_pay_amt = mul(t_buy_amt, t_pay_amt) / t_buy_amt_old;
if (t_pay_amt == 0 || t_buy_amt == 0) {
break;
}
}
if (t_buy_amt > 0 && t_pay_amt > 0) {
//new offer should be created
id = super.offer(t_pay_amt, t_pay_gem, t_buy_amt, t_buy_gem);
//insert offer into the sorted list
_sort(id, pos);
}
}
// Make a new offer without putting it in the sorted list.
// Takes funds from the caller into market escrow.
// ****Available to authorized contracts only!**********
// Keepers should call insert(id,pos) to put offer in the sorted list.
function _offeru(
uint pay_amt, //maker (ask) sell how much
ERC20 pay_gem, //maker (ask) sell which token
uint buy_amt, //maker (ask) buy how much
ERC20 buy_gem //maker (ask) buy which token
)
internal
/*NOT synchronized!!! */
returns (uint id)
{
require(_dust[pay_gem] <= pay_amt);
id = super.offer(pay_amt, pay_gem, buy_amt, buy_gem);
_near[id] = _head;
_head = id;
LogUnsortedOffer(id);
}
//put offer into the sorted list
function _sort(
uint id, //maker (ask) id
uint pos //position to insert into
)
internal
{
require(isActive(id));
address buy_gem = address(offers[id].buy_gem);
address pay_gem = address(offers[id].pay_gem);
uint prev_id; //maker (ask) id
if (pos == 0 || !isOfferSorted(pos)) {
pos = _find(id);
} else {
pos = _findpos(id, pos);
//if user has entered a `pos` that belongs to another currency pair
//we start from scratch
if(pos != 0 && (offers[pos].pay_gem != offers[id].pay_gem
|| offers[pos].buy_gem != offers[id].buy_gem))
{
pos = 0;
pos=_find(id);
}
}
//requirement below is satisfied by statements above
//require(pos == 0 || isOfferSorted(pos));
if (pos != 0) { //offers[id] is not the highest offer
//requirement below is satisfied by statements above
//require(_isPricedLtOrEq(id, pos));
prev_id = _rank[pos].prev;
_rank[pos].prev = id;
_rank[id].next = pos;
} else { //offers[id] is the highest offer
prev_id = _best[pay_gem][buy_gem];
_best[pay_gem][buy_gem] = id;
}
if (prev_id != 0) { //if lower offer does exist
//requirement below is satisfied by statements above
//require(!_isPricedLtOrEq(id, prev_id));
_rank[prev_id].next = id;
_rank[id].prev = prev_id;
}
_span[pay_gem][buy_gem]++;
LogSortedOffer(id);
}
// Remove offer from the sorted list (does not cancel offer)
function _unsort(
uint id //id of maker (ask) offer to remove from sorted list
)
internal
returns (bool)
{
address buy_gem = address(offers[id].buy_gem);
address pay_gem = address(offers[id].pay_gem);
require(_span[pay_gem][buy_gem] > 0);
require(_rank[id].delb == 0 && //assert id is in the sorted list
isOfferSorted(id));
if (id != _best[pay_gem][buy_gem]) { // offers[id] is not the highest offer
require(_rank[_rank[id].next].prev == id);
_rank[_rank[id].next].prev = _rank[id].prev;
} else { //offers[id] is the highest offer
_best[pay_gem][buy_gem] = _rank[id].prev;
}
if (_rank[id].prev != 0) { //offers[id] is not the lowest offer
require(_rank[_rank[id].prev].next == id);
_rank[_rank[id].prev].next = _rank[id].next;
}
_span[pay_gem][buy_gem]--;
_rank[id].delb = block.number; //mark _rank[id] for deletion
return true;
}
//Hide offer from the unsorted order book (does not cancel offer)
function _hide(
uint id //id of maker offer to remove from unsorted list
)
internal
returns (bool)
{
uint uid = _head; //id of an offer in unsorted offers list
uint pre = uid; //id of previous offer in unsorted offers list
require(!isOfferSorted(id)); //make sure offer id is not in sorted offers list
if (_head == id) { //check if offer is first offer in unsorted offers list
_head = _near[id]; //set head to new first unsorted offer
_near[id] = 0; //delete order from unsorted order list
return true;
}
while (uid > 0 && uid != id) { //find offer in unsorted order list
pre = uid;
uid = _near[uid];
}
if (uid != id) { //did not find offer id in unsorted offers list
return false;
}
_near[pre] = _near[id]; //set previous unsorted offer to point to offer after offer id
_near[id] = 0; //delete order from unsorted order list
return true;
}
}
| return the next worse offer in the sorted list the worse offer is the higher one if its an ask, a lower one if its a bid offer, and in both cases the newer one if they're equal. | function getWorseOffer(uint id) public constant returns(uint) {
return _rank[id].prev;
}
| 2,494,720 | [
1,
2463,
326,
1024,
14591,
307,
10067,
316,
326,
3115,
666,
1377,
326,
14591,
307,
10067,
353,
326,
10478,
1245,
309,
2097,
392,
6827,
16,
1377,
279,
2612,
1245,
309,
2097,
279,
9949,
10067,
16,
1377,
471,
316,
3937,
6088,
326,
16069,
1245,
309,
2898,
4565,
3959,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
13876,
23035,
10513,
12,
11890,
612,
13,
1071,
5381,
1135,
12,
11890,
13,
288,
203,
3639,
327,
389,
11500,
63,
350,
8009,
10001,
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
] |
/**
*Submitted for verification at Etherscan.io on 2022-01-14
*/
/**
*Submitted for verification at Etherscan.io on 2022-01-13
*/
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
pragma solidity >=0.7.0 <0.9.0;
contract Downdle is ERC721Enumerable, Ownable {
event PaymentReleased(address to, uint256 amount);
mapping(address => bool) whitelistedAddresses;
address[3] private _shareholders;
uint[3] private _shares;
using Strings for uint256;
string baseURI;
string public baseExtension = ".json";
uint256 public cost = 0.01 ether;
uint256 public mintCount = 0;
uint256 public maxSupply = 3333;
uint256 public maxMintAmount = 20;
bool public paused = true;
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI
) ERC721(_name, _symbol) {
setBaseURI(_initBaseURI);
}
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function mint(uint256 _mintAmount) public payable {
// uint256 supply = totalSupply();
require(!paused, "Mint is currently paused");
require(_mintAmount > 0, "Mint amount must be greater than or equal to one");
require(_mintAmount <= maxMintAmount, "Mint amount greater than max allowed per mint tx");
require(mintCount + _mintAmount <= maxSupply, "Mint amount will exceed available number of tokens");
if (msg.sender != owner()) {
require(msg.value >= cost * _mintAmount, "Value does not match mint cost");
}
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, mintCount + i);
}
mintCount+=_mintAmount;
}
function walletOfOwner(address _owner) public view returns (uint256[] memory){
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory){
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension))
: "";
}
function getMintCount() external view returns (uint256){
return mintCount;
}
function burn(uint256 tokenId) public virtual {
_burn(tokenId);
}
function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner {
maxMintAmount = _newmaxMintAmount;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
modifier isWhitelisted(address _address) {
require(whitelistedAddresses[_address], "You need to be whitelisted");
_;
}
function checkIsWalletWhitelisted() public view isWhitelisted(msg.sender) returns(bool){
return (true);
}
function whitelistMint(uint256 _mintAmount) public payable {
require(!paused, "Mint is currently paused");
require(_mintAmount > 0, "Mint amount must be greater than or equal to one");
require(_mintAmount <= maxMintAmount, "Mint amount greater than max allowed per wallet");
require(mintCount + _mintAmount <= maxSupply, "Mint amount will exceed available number of tokens");
require(whitelistedAddresses[msg.sender], "Wallet is not whitelisted");
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, mintCount + i);
}
mintCount+=_mintAmount;
}
function addWalletToWhiteList(address _addressToWhitelist) public onlyOwner {
whitelistedAddresses[_addressToWhitelist] = true;
}
function withdraw() public payable onlyOwner {
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
require(os);
}
} | * @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);
}
| 101,880 | [
1,
12053,
537,
1375,
869,
68,
358,
20829,
603,
1375,
2316,
548,
68,
7377,
1282,
279,
288,
23461,
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,
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,
225,
445,
389,
12908,
537,
12,
2867,
358,
16,
2254,
5034,
1147,
548,
13,
2713,
5024,
288,
203,
565,
389,
2316,
12053,
4524,
63,
2316,
548,
65,
273,
358,
31,
203,
565,
3626,
1716,
685,
1125,
12,
654,
39,
27,
5340,
18,
8443,
951,
12,
2316,
548,
3631,
358,
16,
1147,
548,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/3/0x1213164Ae8EAc01051213bC6232f2E3e5f967080/sources/irc.sol | * @dev Initializes the contract setting the deployer as the initial owner./ | constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
| 14,131,644 | [
1,
9685,
326,
6835,
3637,
326,
7286,
264,
487,
326,
2172,
3410,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
565,
3885,
1832,
2713,
288,
203,
202,
3639,
1758,
1234,
12021,
273,
389,
3576,
12021,
5621,
203,
202,
3639,
389,
8443,
273,
1234,
12021,
31,
203,
202,
3639,
3626,
14223,
9646,
5310,
1429,
4193,
12,
2867,
12,
20,
3631,
1234,
12021,
1769,
203,
202,
565,
289,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xdca0641e507709FFE7e1e532533aC84e2c27c4bF/sources/localhost/staking/libs/LibFixedMath.sol | @dev Compute the natural exponent for a fixed-point number EXP_MIN_VAL <= `x` <= 1 Saturate to zero below EXP_MIN_VAL. e ^ -32 e ^ -16 e ^ -8 e ^ -4 e ^ -2 e ^ -1 e ^ -0.5 e ^ -0.25 e ^ -0.125 | function exp(int256 x) internal pure returns (int256 r) {
if (x < EXP_MIN_VAL) {
return 0;
}
if (x == 0) {
return FIXED_1;
}
if (x > EXP_MAX_VAL) {
LibRichErrors.rrevert(LibFixedMathRichErrors.SignedValueError(
LibFixedMathRichErrors.ValueErrorCodes.TOO_LARGE,
x
));
}
int256 z;
if ((x & int256(0x0000000000000000000000000000001000000000000000000000000000000000)) != 0) {
r = r * int256(0x00000000000000000000000000000000000000f1aaddd7742e56d32fb9f99744)
}
if ((x & int256(0x0000000000000000000000000000000800000000000000000000000000000000)) != 0) {
r = r * int256(0x00000000000000000000000000000000000afe10820813d65dfe6a33c07f738f)
}
if ((x & int256(0x0000000000000000000000000000000400000000000000000000000000000000)) != 0) {
r = r * int256(0x0000000000000000000000000000000002582ab704279e8efd15e0265855c47a)
}
if ((x & int256(0x0000000000000000000000000000000200000000000000000000000000000000)) != 0) {
r = r * int256(0x000000000000000000000000000000001152aaa3bf81cb9fdb76eae12d029571)
}
if ((x & int256(0x0000000000000000000000000000000100000000000000000000000000000000)) != 0) {
r = r * int256(0x000000000000000000000000000000002f16ac6c59de6f8d5d6f63c1482a7c86)
}
if ((x & int256(0x0000000000000000000000000000000080000000000000000000000000000000)) != 0) {
r = r * int256(0x000000000000000000000000000000004da2cbf1be5827f9eb3ad1aa9866ebb3)
}
if ((x & int256(0x0000000000000000000000000000000040000000000000000000000000000000)) != 0) {
r = r * int256(0x0000000000000000000000000000000063afbe7ab2082ba1a0ae5e4eb1b479dc)
}
if ((x & int256(0x0000000000000000000000000000000020000000000000000000000000000000)) != 0) {
r = r * int256(0x0000000000000000000000000000000070f5a893b608861e1f58934f97aea57d)
}
if ((x & int256(0x0000000000000000000000000000000010000000000000000000000000000000)) != 0) {
r = r * int256(0x00000000000000000000000000000000783eafef1c0a8f3978c7f81824d62ebf)
}
}
| 3,221,455 | [
1,
7018,
326,
15145,
9100,
364,
279,
5499,
17,
1153,
1300,
22615,
67,
6236,
67,
2669,
1648,
1375,
92,
68,
1648,
404,
25793,
295,
340,
358,
3634,
5712,
22615,
67,
6236,
67,
2669,
18,
425,
3602,
300,
1578,
425,
3602,
300,
2313,
425,
3602,
300,
28,
425,
3602,
300,
24,
425,
3602,
300,
22,
425,
3602,
300,
21,
425,
3602,
300,
20,
18,
25,
425,
3602,
300,
20,
18,
2947,
425,
3602,
300,
20,
18,
18473,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1329,
12,
474,
5034,
619,
13,
2713,
16618,
1135,
261,
474,
5034,
436,
13,
288,
203,
3639,
309,
261,
92,
411,
22615,
67,
6236,
67,
2669,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
3639,
309,
261,
92,
422,
374,
13,
288,
203,
5411,
327,
26585,
67,
21,
31,
203,
3639,
289,
203,
3639,
309,
261,
92,
405,
22615,
67,
6694,
67,
2669,
13,
288,
203,
5411,
10560,
22591,
4229,
18,
86,
266,
1097,
12,
5664,
7505,
10477,
22591,
4229,
18,
12294,
23610,
12,
203,
7734,
10560,
7505,
10477,
22591,
4229,
18,
23610,
6295,
18,
4296,
51,
67,
48,
28847,
16,
203,
7734,
619,
203,
5411,
262,
1769,
203,
3639,
289,
203,
203,
3639,
509,
5034,
998,
31,
203,
203,
3639,
309,
14015,
92,
473,
509,
5034,
12,
20,
92,
12648,
12648,
12648,
9449,
21,
12648,
12648,
12648,
2787,
11706,
3719,
480,
374,
13,
288,
203,
5411,
436,
273,
436,
380,
509,
5034,
12,
20,
92,
12648,
12648,
12648,
12648,
9449,
74,
21,
69,
361,
449,
4700,
9452,
73,
4313,
72,
1578,
19192,
29,
74,
2733,
5608,
24,
13,
203,
3639,
289,
203,
3639,
309,
14015,
92,
473,
509,
5034,
12,
20,
92,
12648,
12648,
12648,
17877,
28,
12648,
12648,
12648,
12648,
3719,
480,
374,
13,
288,
203,
5411,
436,
273,
436,
380,
509,
5034,
12,
20,
92,
12648,
12648,
12648,
12648,
3784,
2513,
21770,
26825,
3437,
72,
9222,
2180,
73,
26,
69,
3707,
71,
8642,
74,
27,
7414,
74,
13,
203,
3639,
289,
203,
3639,
309,
14015,
92,
2
] |
// SPDX-License-Identifier:MIT
pragma solidity >=0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./utils/GsnTypes.sol";
import "./interfaces/IPaymaster.sol";
import "./interfaces/IRelayHub.sol";
import "./utils/GsnEip712Library.sol";
import "./forwarder/IForwarder.sol";
/**
* Abstract base class to be inherited by a concrete Paymaster
* A subclass must implement:
* - preRelayedCall
* - postRelayedCall
*/
abstract contract BasePaymaster is IPaymaster, Ownable {
IRelayHub internal relayHub;
IForwarder public override trustedForwarder;
function getHubAddr() public override view returns (address) {
return address(relayHub);
}
//overhead of forwarder verify+signature, plus hub overhead.
uint256 constant public FORWARDER_HUB_OVERHEAD = 50000;
//These parameters are documented in IPaymaster.GasAndDataLimits
uint256 constant public PRE_RELAYED_CALL_GAS_LIMIT = 100000;
uint256 constant public POST_RELAYED_CALL_GAS_LIMIT = 110000;
uint256 constant public PAYMASTER_ACCEPTANCE_BUDGET = PRE_RELAYED_CALL_GAS_LIMIT + FORWARDER_HUB_OVERHEAD;
uint256 constant public CALLDATA_SIZE_LIMIT = 10500;
function getGasAndDataLimits()
public
override
virtual
view
returns (
IPaymaster.GasAndDataLimits memory limits
) {
return IPaymaster.GasAndDataLimits(
PAYMASTER_ACCEPTANCE_BUDGET,
PRE_RELAYED_CALL_GAS_LIMIT,
POST_RELAYED_CALL_GAS_LIMIT,
CALLDATA_SIZE_LIMIT
);
}
// this method must be called from preRelayedCall to validate that the forwarder
// is approved by the paymaster as well as by the recipient contract.
function _verifyForwarder(GsnTypes.RelayRequest calldata relayRequest)
public
view
{
require(address(trustedForwarder) == relayRequest.relayData.forwarder, "Forwarder is not trusted");
GsnEip712Library.verifyForwarderTrusted(relayRequest);
}
/*
* modifier to be used by recipients as access control protection for preRelayedCall & postRelayedCall
*/
modifier relayHubOnly() {
require(msg.sender == getHubAddr(), "can only be called by RelayHub");
_;
}
function setRelayHub(IRelayHub hub) public onlyOwner {
relayHub = hub;
}
function setTrustedForwarder(IForwarder forwarder) public onlyOwner {
trustedForwarder = forwarder;
}
/// check current deposit on relay hub.
function getRelayHubDeposit()
public
override
view
returns (uint) {
return relayHub.balanceOf(address(this));
}
// any money moved into the paymaster is transferred as a deposit.
// This way, we don't need to understand the RelayHub API in order to replenish
// the paymaster.
receive() external virtual payable {
require(address(relayHub) != address(0), "relay hub address not set");
relayHub.depositFor{value:msg.value}(address(this));
}
/// withdraw deposit from relayHub
function withdrawRelayHubDepositTo(uint amount, address payable target) public onlyOwner {
relayHub.withdraw(amount, target);
}
}
// SPDX-License-Identifier:MIT
// solhint-disable no-inline-assembly
pragma solidity >=0.7.6;
import "./interfaces/IRelayRecipient.sol";
/**
* A base contract to be inherited by any contract that want to receive relayed transactions
* A subclass must use "_msgSender()" instead of "msg.sender"
*/
abstract contract BaseRelayRecipient is IRelayRecipient {
/*
* Forwarder singleton we accept calls from
*/
address public trustedForwarder;
function isTrustedForwarder(address forwarder) public override view returns(bool) {
return forwarder == trustedForwarder;
}
/**
* return the sender of this call.
* if the call came through our trusted forwarder, return the original sender.
* otherwise, return `msg.sender`.
* should be used in the contract anywhere instead of msg.sender
*/
function _msgSender() internal override virtual view returns (address payable ret) {
if (msg.data.length >= 20 && isTrustedForwarder(msg.sender)) {
// At this point we know that the sender is a trusted forwarder,
// so we trust that the last bytes of msg.data are the verified sender address.
// extract sender address from the end of msg.data
assembly {
ret := shr(96,calldataload(sub(calldatasize(),20)))
}
} else {
return msg.sender;
}
}
/**
* return the msg.data of this call.
* if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes
* of the msg.data - so this method will strip those 20 bytes off.
* otherwise, return `msg.data`
* should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly
* signing or hashing the
*/
function _msgData() internal override virtual view returns (bytes memory ret) {
if (msg.data.length >= 20 && isTrustedForwarder(msg.sender)) {
return msg.data[0:msg.data.length-20];
} else {
return msg.data;
}
}
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "./forwarder/Forwarder.sol";
import "./BaseRelayRecipient.sol";
import "./utils/GsnUtils.sol";
/**
* batch forwarder support calling a method sendBatch in the forwarder itself.
* NOTE: the "target" of the request should be the BatchForwarder itself
*/
contract BatchForwarder is Forwarder, BaseRelayRecipient {
string public override versionRecipient = "2.2.0+opengsn.batched.irelayrecipient";
constructor() {
//needed for sendBatch
trustedForwarder = address(this);
}
function sendBatch(address[] calldata targets, bytes[] calldata encodedFunctions) external {
require(targets.length == encodedFunctions.length, "BatchForwarder: wrong length");
address sender = _msgSender();
for (uint i = 0; i < targets.length; i++) {
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory ret) = targets[i].call(abi.encodePacked(encodedFunctions[i], sender));
if (!success){
//re-throw the revert with the same revert reason.
GsnUtils.revertWithData(ret);
}
}
}
}
// SPDX-License-Identifier:MIT
pragma solidity >=0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
import "./utils/RLPReader.sol";
import "./utils/GsnUtils.sol";
import "./interfaces/IRelayHub.sol";
import "./interfaces/IPenalizer.sol";
contract Penalizer is IPenalizer {
string public override versionPenalizer = "2.2.0+opengsn.penalizer.ipenalizer";
using ECDSA for bytes32;
uint256 public immutable override penalizeBlockDelay;
uint256 public immutable override penalizeBlockExpiration;
constructor(
uint256 _penalizeBlockDelay,
uint256 _penalizeBlockExpiration
) {
penalizeBlockDelay = _penalizeBlockDelay;
penalizeBlockExpiration = _penalizeBlockExpiration;
}
function isTransactionType1(bytes calldata rawTransaction) public pure returns (bool) {
return (uint8(rawTransaction[0]) == 1);
}
function isTransactionTypeValid(bytes calldata rawTransaction) public pure returns(bool) {
uint8 transactionTypeByte = uint8(rawTransaction[0]);
return (transactionTypeByte >= 0xc0 && transactionTypeByte <= 0xfe);
}
function decodeTransaction(bytes calldata rawTransaction) public pure returns (Transaction memory transaction) {
if (isTransactionType1(rawTransaction)) {
(transaction.nonce,
transaction.gasPrice,
transaction.gasLimit,
transaction.to,
transaction.value,
transaction.data) = RLPReader.decodeTransactionType1(rawTransaction);
} else {
(transaction.nonce,
transaction.gasPrice,
transaction.gasLimit,
transaction.to,
transaction.value,
transaction.data) = RLPReader.decodeLegacyTransaction(rawTransaction);
}
return transaction;
}
mapping(bytes32 => uint) public commits;
/**
* any sender can call "commit(keccak(encodedPenalizeFunction))", to make sure
* no-one can front-run it to claim this penalization
*/
function commit(bytes32 commitHash) external override {
uint256 readyBlockNumber = block.number + penalizeBlockDelay;
commits[commitHash] = readyBlockNumber;
emit CommitAdded(msg.sender, commitHash, readyBlockNumber);
}
modifier commitRevealOnly() {
bytes32 commitHash = keccak256(abi.encodePacked(keccak256(msg.data), msg.sender));
uint256 readyBlockNumber = commits[commitHash];
delete commits[commitHash];
// msg.sender can only be fake during off-chain view call, allowing Penalizer process to check transactions
if(msg.sender != address(0)) {
require(readyBlockNumber != 0, "no commit");
require(readyBlockNumber < block.number, "reveal penalize too soon");
require(readyBlockNumber + penalizeBlockExpiration > block.number, "reveal penalize too late");
}
_;
}
function penalizeRepeatedNonce(
bytes calldata unsignedTx1,
bytes calldata signature1,
bytes calldata unsignedTx2,
bytes calldata signature2,
IRelayHub hub,
uint256 randomValue
)
public
override
commitRevealOnly {
(randomValue);
_penalizeRepeatedNonce(unsignedTx1, signature1, unsignedTx2, signature2, hub);
}
function _penalizeRepeatedNonce(
bytes calldata unsignedTx1,
bytes calldata signature1,
bytes calldata unsignedTx2,
bytes calldata signature2,
IRelayHub hub
)
private
{
// If a relay attacked the system by signing multiple transactions with the same nonce
// (so only one is accepted), anyone can grab both transactions from the blockchain and submit them here.
// Check whether unsignedTx1 != unsignedTx2, that both are signed by the same address,
// and that unsignedTx1.nonce == unsignedTx2.nonce.
// If all conditions are met, relay is considered an "offending relay".
// The offending relay will be unregistered immediately, its stake will be forfeited and given
// to the address who reported it (msg.sender), thus incentivizing anyone to report offending relays.
// If reported via a relay, the forfeited stake is split between
// msg.sender (the relay used for reporting) and the address that reported it.
address addr1 = keccak256(unsignedTx1).recover(signature1);
address addr2 = keccak256(unsignedTx2).recover(signature2);
require(addr1 == addr2, "Different signer");
require(addr1 != address(0), "ecrecover failed");
Transaction memory decodedTx1 = decodeTransaction(unsignedTx1);
Transaction memory decodedTx2 = decodeTransaction(unsignedTx2);
// checking that the same nonce is used in both transaction, with both signed by the same address
// and the actual data is different
// note: we compare the hash of the tx to save gas over iterating both byte arrays
require(decodedTx1.nonce == decodedTx2.nonce, "Different nonce");
bytes memory dataToCheck1 =
abi.encodePacked(decodedTx1.data, decodedTx1.gasLimit, decodedTx1.to, decodedTx1.value);
bytes memory dataToCheck2 =
abi.encodePacked(decodedTx2.data, decodedTx2.gasLimit, decodedTx2.to, decodedTx2.value);
require(keccak256(dataToCheck1) != keccak256(dataToCheck2), "tx is equal");
penalize(addr1, hub);
}
function penalizeIllegalTransaction(
bytes calldata unsignedTx,
bytes calldata signature,
IRelayHub hub,
uint256 randomValue
)
public
override
commitRevealOnly {
(randomValue);
_penalizeIllegalTransaction(unsignedTx, signature, hub);
}
function _penalizeIllegalTransaction(
bytes calldata unsignedTx,
bytes calldata signature,
IRelayHub hub
)
private
{
if (isTransactionTypeValid(unsignedTx)) {
Transaction memory decodedTx = decodeTransaction(unsignedTx);
if (decodedTx.to == address(hub)) {
bytes4 selector = GsnUtils.getMethodSig(decodedTx.data);
bool isWrongMethodCall = selector != IRelayHub.relayCall.selector;
bool isGasLimitWrong = GsnUtils.getParam(decodedTx.data, 4) != decodedTx.gasLimit;
require(
isWrongMethodCall || isGasLimitWrong,
"Legal relay transaction");
}
}
address relay = keccak256(unsignedTx).recover(signature);
require(relay != address(0), "ecrecover failed");
penalize(relay, hub);
}
function penalize(address relayWorker, IRelayHub hub) private {
hub.penalize(relayWorker, msg.sender);
}
}
/* solhint-disable avoid-low-level-calls */
/* solhint-disable no-inline-assembly */
/* solhint-disable not-rely-on-time */
/* solhint-disable avoid-tx-origin */
/* solhint-disable bracket-align */
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "./utils/MinLibBytes.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./utils/GsnUtils.sol";
import "./utils/GsnEip712Library.sol";
import "./utils/RelayHubValidator.sol";
import "./utils/GsnTypes.sol";
import "./interfaces/IRelayHub.sol";
import "./interfaces/IPaymaster.sol";
import "./forwarder/IForwarder.sol";
import "./interfaces/IStakeManager.sol";
contract RelayHub is IRelayHub, Ownable {
using SafeMath for uint256;
string public override versionHub = "2.2.0+opengsn.hub.irelayhub";
IStakeManager immutable override public stakeManager;
address immutable override public penalizer;
RelayHubConfig private config;
function getConfiguration() public override view returns (RelayHubConfig memory) {
return config;
}
function setConfiguration(RelayHubConfig memory _config) public override onlyOwner {
config = _config;
emit RelayHubConfigured(config);
}
uint256 public constant G_NONZERO = 16;
// maps relay worker's address to its manager's address
mapping(address => address) public override workerToManager;
// maps relay managers to the number of their workers
mapping(address => uint256) public override workerCount;
mapping(address => uint256) private balances;
uint256 public override deprecationBlock = type(uint).max;
constructor (
IStakeManager _stakeManager,
address _penalizer,
uint256 _maxWorkerCount,
uint256 _gasReserve,
uint256 _postOverhead,
uint256 _gasOverhead,
uint256 _maximumRecipientDeposit,
uint256 _minimumUnstakeDelay,
uint256 _minimumStake,
uint256 _dataGasCostPerByte,
uint256 _externalCallDataCostOverhead
) {
stakeManager = _stakeManager;
penalizer = _penalizer;
setConfiguration(RelayHubConfig(
_maxWorkerCount,
_gasReserve,
_postOverhead,
_gasOverhead,
_maximumRecipientDeposit,
_minimumUnstakeDelay,
_minimumStake,
_dataGasCostPerByte,
_externalCallDataCostOverhead
));
}
function registerRelayServer(uint256 baseRelayFee, uint256 pctRelayFee, string calldata url) external override {
address relayManager = msg.sender;
require(
isRelayManagerStaked(relayManager),
"relay manager not staked"
);
require(workerCount[relayManager] > 0, "no relay workers");
emit RelayServerRegistered(relayManager, baseRelayFee, pctRelayFee, url);
}
function addRelayWorkers(address[] calldata newRelayWorkers) external override {
address relayManager = msg.sender;
uint256 newWorkerCount = workerCount[relayManager] + newRelayWorkers.length;
workerCount[relayManager] = newWorkerCount;
require(newWorkerCount <= config.maxWorkerCount, "too many workers");
require(
isRelayManagerStaked(relayManager),
"relay manager not staked"
);
for (uint256 i = 0; i < newRelayWorkers.length; i++) {
require(workerToManager[newRelayWorkers[i]] == address(0), "this worker has a manager");
workerToManager[newRelayWorkers[i]] = relayManager;
}
emit RelayWorkersAdded(relayManager, newRelayWorkers, newWorkerCount);
}
function depositFor(address target) public override payable {
uint256 amount = msg.value;
require(amount <= config.maximumRecipientDeposit, "deposit too big");
balances[target] = balances[target].add(amount);
emit Deposited(target, msg.sender, amount);
}
function balanceOf(address target) external override view returns (uint256) {
return balances[target];
}
function withdraw(uint256 amount, address payable dest) public override {
address payable account = msg.sender;
require(balances[account] >= amount, "insufficient funds");
balances[account] = balances[account].sub(amount);
dest.transfer(amount);
emit Withdrawn(account, dest, amount);
}
function calldataGasCost(uint256 length) public override view returns (uint256) {
return config.dataGasCostPerByte.mul(length);
}
function verifyGasAndDataLimits(
uint256 maxAcceptanceBudget,
GsnTypes.RelayRequest calldata relayRequest,
uint256 initialGasLeft,
uint256 externalGasLimit
)
private
view
returns (IPaymaster.GasAndDataLimits memory gasAndDataLimits, uint256 maxPossibleGas) {
gasAndDataLimits =
IPaymaster(relayRequest.relayData.paymaster).getGasAndDataLimits{gas:50000}();
require(msg.data.length <= gasAndDataLimits.calldataSizeLimit, "msg.data exceeded limit" );
uint256 dataGasCost = calldataGasCost(msg.data.length);
uint256 externalCallDataCost = externalGasLimit - initialGasLeft - config.externalCallDataCostOverhead;
uint256 txDataCostPerByte = externalCallDataCost/msg.data.length;
require(txDataCostPerByte <= G_NONZERO, "invalid externalGasLimit");
require(maxAcceptanceBudget >= gasAndDataLimits.acceptanceBudget, "acceptance budget too high");
require(gasAndDataLimits.acceptanceBudget >= gasAndDataLimits.preRelayedCallGasLimit, "acceptance budget too low");
maxPossibleGas =
config.gasOverhead.add(
gasAndDataLimits.preRelayedCallGasLimit).add(
gasAndDataLimits.postRelayedCallGasLimit).add(
relayRequest.request.gas).add(
dataGasCost).add(
externalCallDataCost);
// This transaction must have enough gas to forward the call to the recipient with the requested amount, and not
// run out of gas later in this function.
require(
externalGasLimit >= maxPossibleGas,
"no gas for innerRelayCall");
uint256 maxPossibleCharge = calculateCharge(
maxPossibleGas,
relayRequest.relayData
);
// We don't yet know how much gas will be used by the recipient, so we make sure there are enough funds to pay
// for the maximum possible charge.
require(maxPossibleCharge <= balances[relayRequest.relayData.paymaster],
"Paymaster balance too low");
}
struct RelayCallData {
bool success;
bytes4 functionSelector;
uint256 initialGasLeft;
bytes recipientContext;
bytes relayedCallReturnValue;
IPaymaster.GasAndDataLimits gasAndDataLimits;
RelayCallStatus status;
uint256 innerGasUsed;
uint256 maxPossibleGas;
uint256 gasBeforeInner;
bytes retData;
address relayManager;
uint256 dataGasCost;
}
function relayCall(
uint maxAcceptanceBudget,
GsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData,
uint externalGasLimit
)
external
override
returns (bool paymasterAccepted, bytes memory returnValue)
{
RelayCallData memory vars;
vars.initialGasLeft = gasleft();
require(!isDeprecated(), "hub deprecated");
vars.functionSelector = relayRequest.request.data.length>=4 ? MinLibBytes.readBytes4(relayRequest.request.data, 0) : bytes4(0);
require(msg.sender == tx.origin, "relay worker must be EOA");
vars.relayManager = workerToManager[msg.sender];
require(vars.relayManager != address(0), "Unknown relay worker");
require(relayRequest.relayData.relayWorker == msg.sender, "Not a right worker");
require(
isRelayManagerStaked(vars.relayManager),
"relay manager not staked"
);
require(relayRequest.relayData.gasPrice <= tx.gasprice, "Invalid gas price");
require(externalGasLimit <= block.gaslimit, "Impossible gas limit");
(vars.gasAndDataLimits, vars.maxPossibleGas) =
verifyGasAndDataLimits(maxAcceptanceBudget, relayRequest, vars.initialGasLeft, externalGasLimit);
RelayHubValidator.verifyTransactionPacking(relayRequest,signature,approvalData);
{
//How much gas to pass down to innerRelayCall. must be lower than the default 63/64
// actually, min(gasleft*63/64, gasleft-GAS_RESERVE) might be enough.
uint256 innerGasLimit = gasleft()*63/64- config.gasReserve;
vars.gasBeforeInner = gasleft();
uint256 _tmpInitialGas = innerGasLimit + externalGasLimit + config.gasOverhead + config.postOverhead;
// Calls to the recipient are performed atomically inside an inner transaction which may revert in case of
// errors in the recipient. In either case (revert or regular execution) the return data encodes the
// RelayCallStatus value.
(bool success, bytes memory relayCallStatus) = address(this).call{gas:innerGasLimit}(
abi.encodeWithSelector(RelayHub.innerRelayCall.selector, relayRequest, signature, approvalData, vars.gasAndDataLimits,
_tmpInitialGas - gasleft(),
vars.maxPossibleGas
)
);
vars.success = success;
vars.innerGasUsed = vars.gasBeforeInner-gasleft();
(vars.status, vars.relayedCallReturnValue) = abi.decode(relayCallStatus, (RelayCallStatus, bytes));
if ( vars.relayedCallReturnValue.length>0 ) {
emit TransactionResult(vars.status, vars.relayedCallReturnValue);
}
}
{
vars.dataGasCost = calldataGasCost(msg.data.length);
if (!vars.success) {
//Failure cases where the PM doesn't pay
if (vars.status == RelayCallStatus.RejectedByPreRelayed ||
(vars.innerGasUsed <= vars.gasAndDataLimits.acceptanceBudget.add(vars.dataGasCost)) && (
vars.status == RelayCallStatus.RejectedByForwarder ||
vars.status == RelayCallStatus.RejectedByRecipientRevert //can only be thrown if rejectOnRecipientRevert==true
)) {
paymasterAccepted=false;
emit TransactionRejectedByPaymaster(
vars.relayManager,
relayRequest.relayData.paymaster,
relayRequest.request.from,
relayRequest.request.to,
msg.sender,
vars.functionSelector,
vars.innerGasUsed,
vars.relayedCallReturnValue);
return (false, vars.relayedCallReturnValue);
}
}
// We now perform the actual charge calculation, based on the measured gas used
uint256 gasUsed = (externalGasLimit - gasleft()) + config.gasOverhead;
uint256 charge = calculateCharge(gasUsed, relayRequest.relayData);
balances[relayRequest.relayData.paymaster] = balances[relayRequest.relayData.paymaster].sub(charge);
balances[vars.relayManager] = balances[vars.relayManager].add(charge);
emit TransactionRelayed(
vars.relayManager,
msg.sender,
relayRequest.request.from,
relayRequest.request.to,
relayRequest.relayData.paymaster,
vars.functionSelector,
vars.status,
charge);
return (true, "");
}
}
struct InnerRelayCallData {
uint256 balanceBefore;
bytes32 preReturnValue;
bool relayedCallSuccess;
bytes relayedCallReturnValue;
bytes recipientContext;
bytes data;
bool rejectOnRecipientRevert;
}
function innerRelayCall(
GsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData,
IPaymaster.GasAndDataLimits calldata gasAndDataLimits,
uint256 totalInitialGas,
uint256 maxPossibleGas
)
external
returns (RelayCallStatus, bytes memory)
{
InnerRelayCallData memory vars;
// A new gas measurement is performed inside innerRelayCall, since
// due to EIP150 available gas amounts cannot be directly compared across external calls
// This external function can only be called by RelayHub itself, creating an internal transaction. Calls to the
// recipient (preRelayedCall, the relayedCall, and postRelayedCall) are called from inside this transaction.
require(msg.sender == address(this), "Must be called by RelayHub");
// If either pre or post reverts, the whole internal transaction will be reverted, reverting all side effects on
// the recipient. The recipient will still be charged for the used gas by the relay.
// The paymaster is no allowed to withdraw balance from RelayHub during a relayed transaction. We check pre and
// post state to ensure this doesn't happen.
vars.balanceBefore = balances[relayRequest.relayData.paymaster];
// First preRelayedCall is executed.
// Note: we open a new block to avoid growing the stack too much.
vars.data = abi.encodeWithSelector(
IPaymaster.preRelayedCall.selector,
relayRequest, signature, approvalData, maxPossibleGas
);
{
bool success;
bytes memory retData;
(success, retData) = relayRequest.relayData.paymaster.call{gas:gasAndDataLimits.preRelayedCallGasLimit}(vars.data);
if (!success) {
GsnEip712Library.truncateInPlace(retData);
revertWithStatus(RelayCallStatus.RejectedByPreRelayed, retData);
}
(vars.recipientContext, vars.rejectOnRecipientRevert) = abi.decode(retData, (bytes,bool));
}
// The actual relayed call is now executed. The sender's address is appended at the end of the transaction data
{
bool forwarderSuccess;
(forwarderSuccess, vars.relayedCallSuccess, vars.relayedCallReturnValue) = GsnEip712Library.execute(relayRequest, signature);
if ( !forwarderSuccess ) {
revertWithStatus(RelayCallStatus.RejectedByForwarder, vars.relayedCallReturnValue);
}
if (vars.rejectOnRecipientRevert && !vars.relayedCallSuccess) {
// we trusted the recipient, but it reverted...
revertWithStatus(RelayCallStatus.RejectedByRecipientRevert, vars.relayedCallReturnValue);
}
}
// Finally, postRelayedCall is executed, with the relayedCall execution's status and a charge estimate
// We now determine how much the recipient will be charged, to pass this value to postRelayedCall for accurate
// accounting.
vars.data = abi.encodeWithSelector(
IPaymaster.postRelayedCall.selector,
vars.recipientContext,
vars.relayedCallSuccess,
totalInitialGas - gasleft(), /*gasUseWithoutPost*/
relayRequest.relayData
);
{
(bool successPost,bytes memory ret) = relayRequest.relayData.paymaster.call{gas:gasAndDataLimits.postRelayedCallGasLimit}(vars.data);
if (!successPost) {
revertWithStatus(RelayCallStatus.PostRelayedFailed, ret);
}
}
if (balances[relayRequest.relayData.paymaster] < vars.balanceBefore) {
revertWithStatus(RelayCallStatus.PaymasterBalanceChanged, "");
}
return (vars.relayedCallSuccess ? RelayCallStatus.OK : RelayCallStatus.RelayedCallFailed, vars.relayedCallReturnValue);
}
/**
* @dev Reverts the transaction with return data set to the ABI encoding of the status argument (and revert reason data)
*/
function revertWithStatus(RelayCallStatus status, bytes memory ret) private pure {
bytes memory data = abi.encode(status, ret);
GsnEip712Library.truncateInPlace(data);
assembly {
let dataSize := mload(data)
let dataPtr := add(data, 32)
revert(dataPtr, dataSize)
}
}
function calculateCharge(uint256 gasUsed, GsnTypes.RelayData calldata relayData) public override virtual view returns (uint256) {
return relayData.baseRelayFee.add((gasUsed.mul(relayData.gasPrice).mul(relayData.pctRelayFee.add(100))).div(100));
}
function isRelayManagerStaked(address relayManager) public override view returns (bool) {
return stakeManager.isRelayManagerStaked(relayManager, address(this), config.minimumStake, config.minimumUnstakeDelay);
}
function deprecateHub(uint256 fromBlock) public override onlyOwner {
require(deprecationBlock > block.number, "Already deprecated");
deprecationBlock = fromBlock;
emit HubDeprecated(fromBlock);
}
function isDeprecated() public override view returns (bool) {
return block.number >= deprecationBlock;
}
modifier penalizerOnly () {
require(msg.sender == penalizer, "Not penalizer");
_;
}
function penalize(address relayWorker, address payable beneficiary) external override penalizerOnly {
address relayManager = workerToManager[relayWorker];
// The worker must be controlled by a manager with a locked stake
require(relayManager != address(0), "Unknown relay worker");
require(
isRelayManagerStaked(relayManager),
"relay manager not staked"
);
IStakeManager.StakeInfo memory stakeInfo = stakeManager.getStakeInfo(relayManager);
stakeManager.penalizeRelayManager(relayManager, beneficiary, stakeInfo.stake);
}
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./interfaces/IStakeManager.sol";
contract StakeManager is IStakeManager {
using SafeMath for uint256;
string public override versionSM = "2.2.0+opengsn.stakemanager.istakemanager";
uint256 public immutable override maxUnstakeDelay;
/// maps relay managers to their stakes
mapping(address => StakeInfo) public stakes;
function getStakeInfo(address relayManager) external override view returns (StakeInfo memory stakeInfo) {
return stakes[relayManager];
}
/// maps relay managers to a map of addressed of their authorized hubs to the information on that hub
mapping(address => mapping(address => RelayHubInfo)) public authorizedHubs;
constructor(uint256 _maxUnstakeDelay) {
maxUnstakeDelay = _maxUnstakeDelay;
}
function setRelayManagerOwner(address payable owner) external override {
require(owner != address(0), "invalid owner");
require(stakes[msg.sender].owner == address(0), "already owned");
stakes[msg.sender].owner = owner;
emit OwnerSet(msg.sender, owner);
}
/// Put a stake for a relayManager and set its unstake delay. Only the owner can call this function.
/// @param relayManager - address that represents a stake entry and controls relay registrations on relay hubs
/// @param unstakeDelay - number of blocks to elapse before the owner can retrieve the stake after calling 'unlock'
function stakeForRelayManager(address relayManager, uint256 unstakeDelay) external override payable ownerOnly(relayManager) {
require(unstakeDelay >= stakes[relayManager].unstakeDelay, "unstakeDelay cannot be decreased");
require(unstakeDelay <= maxUnstakeDelay, "unstakeDelay too big");
stakes[relayManager].stake += msg.value;
stakes[relayManager].unstakeDelay = unstakeDelay;
emit StakeAdded(relayManager, stakes[relayManager].owner, stakes[relayManager].stake, stakes[relayManager].unstakeDelay);
}
function unlockStake(address relayManager) external override ownerOnly(relayManager) {
StakeInfo storage info = stakes[relayManager];
require(info.withdrawBlock == 0, "already pending");
uint withdrawBlock = block.number.add(info.unstakeDelay);
info.withdrawBlock = withdrawBlock;
emit StakeUnlocked(relayManager, msg.sender, withdrawBlock);
}
function withdrawStake(address relayManager) external override ownerOnly(relayManager) {
StakeInfo storage info = stakes[relayManager];
require(info.withdrawBlock > 0, "Withdrawal is not scheduled");
require(info.withdrawBlock <= block.number, "Withdrawal is not due");
uint256 amount = info.stake;
info.stake = 0;
info.withdrawBlock = 0;
msg.sender.transfer(amount);
emit StakeWithdrawn(relayManager, msg.sender, amount);
}
modifier ownerOnly (address relayManager) {
StakeInfo storage info = stakes[relayManager];
require(info.owner == msg.sender, "not owner");
_;
}
modifier managerOnly () {
StakeInfo storage info = stakes[msg.sender];
require(info.owner != address(0), "not manager");
_;
}
function authorizeHubByOwner(address relayManager, address relayHub) external ownerOnly(relayManager) override {
_authorizeHub(relayManager, relayHub);
}
function authorizeHubByManager(address relayHub) external managerOnly override {
_authorizeHub(msg.sender, relayHub);
}
function _authorizeHub(address relayManager, address relayHub) internal {
authorizedHubs[relayManager][relayHub].removalBlock = uint(-1);
emit HubAuthorized(relayManager, relayHub);
}
function unauthorizeHubByOwner(address relayManager, address relayHub) external override ownerOnly(relayManager) {
_unauthorizeHub(relayManager, relayHub);
}
function unauthorizeHubByManager(address relayHub) external override managerOnly {
_unauthorizeHub(msg.sender, relayHub);
}
function _unauthorizeHub(address relayManager, address relayHub) internal {
RelayHubInfo storage hubInfo = authorizedHubs[relayManager][relayHub];
require(hubInfo.removalBlock == uint(-1), "hub not authorized");
uint256 removalBlock = block.number.add(stakes[relayManager].unstakeDelay);
hubInfo.removalBlock = removalBlock;
emit HubUnauthorized(relayManager, relayHub, removalBlock);
}
function isRelayManagerStaked(address relayManager, address relayHub, uint256 minAmount, uint256 minUnstakeDelay)
external
override
view
returns (bool) {
StakeInfo storage info = stakes[relayManager];
bool isAmountSufficient = info.stake >= minAmount;
bool isDelaySufficient = info.unstakeDelay >= minUnstakeDelay;
bool isStakeLocked = info.withdrawBlock == 0;
bool isHubAuthorized = authorizedHubs[relayManager][relayHub].removalBlock == uint(-1);
return
isAmountSufficient &&
isDelaySufficient &&
isStakeLocked &&
isHubAuthorized;
}
/// Slash the stake of the relay relayManager. In order to prevent stake kidnapping, burns half of stake on the way.
/// @param relayManager - entry to penalize
/// @param beneficiary - address that receives half of the penalty amount
/// @param amount - amount to withdraw from stake
function penalizeRelayManager(address relayManager, address payable beneficiary, uint256 amount) external override {
uint256 removalBlock = authorizedHubs[relayManager][msg.sender].removalBlock;
require(removalBlock != 0, "hub not authorized");
require(removalBlock > block.number, "hub authorization expired");
// Half of the stake will be burned (sent to address 0)
require(stakes[relayManager].stake >= amount, "penalty exceeds stake");
stakes[relayManager].stake = SafeMath.sub(stakes[relayManager].stake, amount);
uint256 toBurn = SafeMath.div(amount, 2);
uint256 reward = SafeMath.sub(amount, toBurn);
// Ether is burned and transferred
address(0).transfer(toBurn);
beneficiary.transfer(reward);
emit StakePenalized(relayManager, beneficiary, reward);
}
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
import "./IForwarder.sol";
contract Forwarder is IForwarder {
using ECDSA for bytes32;
string public constant GENERIC_PARAMS = "address from,address to,uint256 value,uint256 gas,uint256 nonce,bytes data,uint256 validUntil";
string public constant EIP712_DOMAIN_TYPE = "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)";
mapping(bytes32 => bool) public typeHashes;
mapping(bytes32 => bool) public domains;
// Nonces of senders, used to prevent replay attacks
mapping(address => uint256) private nonces;
// solhint-disable-next-line no-empty-blocks
receive() external payable {}
function getNonce(address from)
public view override
returns (uint256) {
return nonces[from];
}
constructor() {
string memory requestType = string(abi.encodePacked("ForwardRequest(", GENERIC_PARAMS, ")"));
registerRequestTypeInternal(requestType);
}
function verify(
ForwardRequest calldata req,
bytes32 domainSeparator,
bytes32 requestTypeHash,
bytes calldata suffixData,
bytes calldata sig)
external override view {
_verifyNonce(req);
_verifySig(req, domainSeparator, requestTypeHash, suffixData, sig);
}
function execute(
ForwardRequest calldata req,
bytes32 domainSeparator,
bytes32 requestTypeHash,
bytes calldata suffixData,
bytes calldata sig
)
external payable
override
returns (bool success, bytes memory ret) {
_verifySig(req, domainSeparator, requestTypeHash, suffixData, sig);
_verifyAndUpdateNonce(req);
require(req.validUntil == 0 || req.validUntil > block.number, "FWD: request expired");
uint gasForTransfer = 0;
if ( req.value != 0 ) {
gasForTransfer = 40000; //buffer in case we need to move eth after the transaction.
}
bytes memory callData = abi.encodePacked(req.data, req.from);
require(gasleft()*63/64 >= req.gas + gasForTransfer, "FWD: insufficient gas");
// solhint-disable-next-line avoid-low-level-calls
(success,ret) = req.to.call{gas : req.gas, value : req.value}(callData);
if ( req.value != 0 && address(this).balance>0 ) {
// can't fail: req.from signed (off-chain) the request, so it must be an EOA...
payable(req.from).transfer(address(this).balance);
}
return (success,ret);
}
function _verifyNonce(ForwardRequest calldata req) internal view {
require(nonces[req.from] == req.nonce, "FWD: nonce mismatch");
}
function _verifyAndUpdateNonce(ForwardRequest calldata req) internal {
require(nonces[req.from]++ == req.nonce, "FWD: nonce mismatch");
}
function registerRequestType(string calldata typeName, string calldata typeSuffix) external override {
for (uint i = 0; i < bytes(typeName).length; i++) {
bytes1 c = bytes(typeName)[i];
require(c != "(" && c != ")", "FWD: invalid typename");
}
string memory requestType = string(abi.encodePacked(typeName, "(", GENERIC_PARAMS, ",", typeSuffix));
registerRequestTypeInternal(requestType);
}
function registerDomainSeparator(string calldata name, string calldata version) external override {
uint256 chainId;
/* solhint-disable-next-line no-inline-assembly */
assembly { chainId := chainid() }
bytes memory domainValue = abi.encode(
keccak256(bytes(EIP712_DOMAIN_TYPE)),
keccak256(bytes(name)),
keccak256(bytes(version)),
chainId,
address(this));
bytes32 domainHash = keccak256(domainValue);
domains[domainHash] = true;
emit DomainRegistered(domainHash, domainValue);
}
function registerRequestTypeInternal(string memory requestType) internal {
bytes32 requestTypehash = keccak256(bytes(requestType));
typeHashes[requestTypehash] = true;
emit RequestTypeRegistered(requestTypehash, requestType);
}
function _verifySig(
ForwardRequest calldata req,
bytes32 domainSeparator,
bytes32 requestTypeHash,
bytes calldata suffixData,
bytes calldata sig)
internal
view
{
require(domains[domainSeparator], "FWD: unregistered domain sep.");
require(typeHashes[requestTypeHash], "FWD: unregistered typehash");
bytes32 digest = keccak256(abi.encodePacked(
"\x19\x01", domainSeparator,
keccak256(_getEncoded(req, requestTypeHash, suffixData))
));
require(digest.recover(sig) == req.from, "FWD: signature mismatch");
}
function _getEncoded(
ForwardRequest calldata req,
bytes32 requestTypeHash,
bytes calldata suffixData
)
public
pure
returns (
bytes memory
) {
// we use encodePacked since we append suffixData as-is, not as dynamic param.
// still, we must make sure all first params are encoded as abi.encode()
// would encode them - as 256-bit-wide params.
return abi.encodePacked(
requestTypeHash,
uint256(uint160(req.from)),
uint256(uint160(req.to)),
req.value,
req.gas,
req.nonce,
keccak256(req.data),
req.validUntil,
suffixData
);
}
}
// SPDX-License-Identifier:MIT
pragma solidity >=0.7.6;
pragma abicoder v2;
interface IForwarder {
struct ForwardRequest {
address from;
address to;
uint256 value;
uint256 gas;
uint256 nonce;
bytes data;
uint256 validUntil;
}
event DomainRegistered(bytes32 indexed domainSeparator, bytes domainValue);
event RequestTypeRegistered(bytes32 indexed typeHash, string typeStr);
function getNonce(address from)
external view
returns(uint256);
/**
* verify the transaction would execute.
* validate the signature and the nonce of the request.
* revert if either signature or nonce are incorrect.
* also revert if domainSeparator or requestTypeHash are not registered.
*/
function verify(
ForwardRequest calldata forwardRequest,
bytes32 domainSeparator,
bytes32 requestTypeHash,
bytes calldata suffixData,
bytes calldata signature
) external view;
/**
* execute a transaction
* @param forwardRequest - all transaction parameters
* @param domainSeparator - domain used when signing this request
* @param requestTypeHash - request type used when signing this request.
* @param suffixData - the extension data used when signing this request.
* @param signature - signature to validate.
*
* the transaction is verified, and then executed.
* the success and ret of "call" are returned.
* This method would revert only verification errors. target errors
* are reported using the returned "success" and ret string
*/
function execute(
ForwardRequest calldata forwardRequest,
bytes32 domainSeparator,
bytes32 requestTypeHash,
bytes calldata suffixData,
bytes calldata signature
)
external payable
returns (bool success, bytes memory ret);
/**
* Register a new Request typehash.
* @param typeName - the name of the request type.
* @param typeSuffix - any extra data after the generic params.
* (must add at least one param. The generic ForwardRequest type is always registered by the constructor)
*/
function registerRequestType(string calldata typeName, string calldata typeSuffix) external;
/**
* Register a new domain separator.
* The domain separator must have the following fields: name,version,chainId, verifyingContract.
* the chainId is the current network's chainId, and the verifyingContract is this forwarder.
* This method is given the domain name and version to create and register the domain separator value.
* @param name the domain's display name
* @param version the domain/protocol version
*/
function registerDomainSeparator(string calldata name, string calldata version) external;
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "../Forwarder.sol";
// helper class for testing the forwarder.
contract TestForwarder {
function callExecute(Forwarder forwarder, Forwarder.ForwardRequest memory req,
bytes32 domainSeparator, bytes32 requestTypeHash, bytes memory suffixData, bytes memory sig) public payable {
(bool success, bytes memory error) = forwarder.execute{value:msg.value}(req, domainSeparator, requestTypeHash, suffixData, sig);
emit Result(success, success ? "" : this.decodeErrorMessage(error));
}
event Result(bool success, string error);
function decodeErrorMessage(bytes calldata ret) external pure returns (string memory message) {
//decode evert string: assume it has a standard Error(string) signature: simply skip the (selector,offset,length) fields
if ( ret.length>4+32+32 ) {
return abi.decode(ret[4:], (string));
}
//unknown buffer. return as-is
return string(ret);
}
function getChainId() public pure returns (uint256 id){
/* solhint-disable-next-line no-inline-assembly */
assembly { id := chainid() }
}
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
import "../../BaseRelayRecipient.sol";
contract TestForwarderTarget is BaseRelayRecipient {
string public override versionRecipient = "2.2.0+opengsn.test.recipient";
constructor(address forwarder) {
trustedForwarder = forwarder;
}
// solhint-disable-next-line no-empty-blocks
receive() external payable {}
event TestForwarderMessage(string message, bytes realMsgData, address realSender, address msgSender, address origin);
function emitMessage(string memory message) public {
// solhint-disable-next-line avoid-tx-origin
emit TestForwarderMessage(message, _msgData(), _msgSender(), msg.sender, tx.origin);
}
function publicMsgSender() public view returns (address) {
return _msgSender();
}
function publicMsgData() public view returns (bytes memory) {
return _msgData();
}
function mustReceiveEth(uint value) public payable {
require( msg.value == value, "didn't receive value");
}
event Reverting(string message);
function testRevert() public {
require(address(this) == address(0), "always fail");
emit Reverting("if you see this revert failed...");
}
}
// SPDX-License-Identifier:MIT
pragma solidity >=0.7.6;
pragma abicoder v2;
import "../utils/GsnTypes.sol";
interface IPaymaster {
/**
* @param acceptanceBudget -
* Paymaster expected gas budget to accept (or reject) a request
* This a gas required by any calculations that might need to reject the
* transaction, by preRelayedCall, forwarder and recipient.
* See value in BasePaymaster.PAYMASTER_ACCEPTANCE_BUDGET
* Transaction that gets rejected above that gas usage is on the paymaster's expense.
* As long this value is above preRelayedCallGasLimit (see defaults in BasePaymaster), the
* Paymaster is guaranteed it will never pay for rejected transactions.
* If this value is below preRelayedCallGasLimt, it might might make Paymaster open to a "griefing" attack.
*
* Specifying value too high might make the call rejected by some relayers.
*
* From a Relay's point of view, this is the highest gas value a paymaster might "grief" the relay,
* since the paymaster will pay anything above that (regardless if the tx reverts)
*
* @param preRelayedCallGasLimit - the max gas usage of preRelayedCall. any revert (including OOG)
* of preRelayedCall is a reject by the paymaster.
* as long as acceptanceBudget is above preRelayedCallGasLimit, any such revert (including OOG)
* is not payed by the paymaster.
* @param postRelayedCallGasLimit - the max gas usage of postRelayedCall.
* note that an OOG will revert the transaction, but the paymaster already committed to pay,
* so the relay will get compensated, at the expense of the paymaster
*/
struct GasAndDataLimits {
uint256 acceptanceBudget;
uint256 preRelayedCallGasLimit;
uint256 postRelayedCallGasLimit;
uint256 calldataSizeLimit;
}
/**
* Return the Gas Limits and msg.data max size constants used by the Paymaster.
*/
function getGasAndDataLimits()
external
view
returns (
GasAndDataLimits memory limits
);
function trustedForwarder() external view returns (IForwarder);
/**
* return the relayHub of this contract.
*/
function getHubAddr() external view returns (address);
/**
* Can be used to determine if the contract can pay for incoming calls before making any.
* @return the paymaster's deposit in the RelayHub.
*/
function getRelayHubDeposit() external view returns (uint256);
/**
* Called by Relay (and RelayHub), to validate if the paymaster agrees to pay for this call.
*
* MUST be protected with relayHubOnly() in case it modifies state.
*
* The Paymaster rejects by the following "revert" operations
* - preRelayedCall() method reverts
* - the forwarder reverts because of nonce or signature error
* - the paymaster returned "rejectOnRecipientRevert", and the recipient contract reverted.
* In any of the above cases, all paymaster calls (and recipient call) are reverted.
* In any other case, the paymaster agrees to pay for the gas cost of the transaction (note
* that this includes also postRelayedCall revert)
*
* The rejectOnRecipientRevert flag means the Paymaster "delegate" the rejection to the recipient
* code. It also means the Paymaster trust the recipient to reject fast: both preRelayedCall,
* forwarder check and receipient checks must fit into the GasLimits.acceptanceBudget,
* otherwise the TX is paid by the Paymaster.
*
* @param relayRequest - the full relay request structure
* @param signature - user's EIP712-compatible signature of the {@link relayRequest}.
* Note that in most cases the paymaster shouldn't try use it at all. It is always checked
* by the forwarder immediately after preRelayedCall returns.
* @param approvalData - extra dapp-specific data (e.g. signature from trusted party)
* @param maxPossibleGas - based on values returned from {@link getGasAndDataLimits},
* the RelayHub will calculate the maximum possible amount of gas the user may be charged for.
* In order to convert this value to wei, the Paymaster has to call "relayHub.calculateCharge()"
* return:
* a context to be passed to postRelayedCall
* rejectOnRecipientRevert - TRUE if paymaster want to reject the TX if the recipient reverts.
* FALSE means that rejects by the recipient will be completed on chain, and paid by the paymaster.
* (note that in the latter case, the preRelayedCall and postRelayedCall are not reverted).
*/
function preRelayedCall(
GsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData,
uint256 maxPossibleGas
)
external
returns (bytes memory context, bool rejectOnRecipientRevert);
/**
* This method is called after the actual relayed function call.
* It may be used to record the transaction (e.g. charge the caller by some contract logic) for this call.
*
* MUST be protected with relayHubOnly() in case it modifies state.
*
* @param context - the call context, as returned by the preRelayedCall
* @param success - true if the relayed call succeeded, false if it reverted
* @param gasUseWithoutPost - the actual amount of gas used by the entire transaction, EXCEPT
* the gas used by the postRelayedCall itself.
* @param relayData - the relay params of the request. can be used by relayHub.calculateCharge()
*
* Revert in this functions causes a revert of the client's relayed call (and preRelayedCall(), but the Paymaster
* is still committed to pay the relay for the entire transaction.
*/
function postRelayedCall(
bytes calldata context,
bool success,
uint256 gasUseWithoutPost,
GsnTypes.RelayData calldata relayData
) external;
function versionPaymaster() external view returns (string memory);
}
// SPDX-License-Identifier:MIT
pragma solidity >=0.7.6;
import "./IRelayHub.sol";
interface IPenalizer {
event CommitAdded(address indexed sender, bytes32 indexed commitHash, uint256 readyBlockNumber);
struct Transaction {
uint256 nonce;
uint256 gasPrice;
uint256 gasLimit;
address to;
uint256 value;
bytes data;
}
function commit(bytes32 commitHash) external;
function penalizeRepeatedNonce(
bytes calldata unsignedTx1,
bytes calldata signature1,
bytes calldata unsignedTx2,
bytes calldata signature2,
IRelayHub hub,
uint256 randomValue
) external;
function penalizeIllegalTransaction(
bytes calldata unsignedTx,
bytes calldata signature,
IRelayHub hub,
uint256 randomValue
) external;
function versionPenalizer() external view returns (string memory);
function penalizeBlockDelay() external view returns (uint256);
function penalizeBlockExpiration() external view returns (uint256);
}
// SPDX-License-Identifier:MIT
pragma solidity >=0.7.6;
pragma abicoder v2;
import "../utils/GsnTypes.sol";
import "./IStakeManager.sol";
interface IRelayHub {
struct RelayHubConfig {
// maximum number of worker accounts allowed per manager
uint256 maxWorkerCount;
// Gas set aside for all relayCall() instructions to prevent unexpected out-of-gas exceptions
uint256 gasReserve;
// Gas overhead to calculate gasUseWithoutPost
uint256 postOverhead;
// Gas cost of all relayCall() instructions after actual 'calculateCharge()'
// Assume that relay has non-zero balance (costs 15'000 more otherwise).
uint256 gasOverhead;
// Maximum funds that can be deposited at once. Prevents user error by disallowing large deposits.
uint256 maximumRecipientDeposit;
// Minimum unstake delay blocks of a relay manager's stake on the StakeManager
uint256 minimumUnstakeDelay;
// Minimum stake a relay can have. An attack on the network will never cost less than half this value.
uint256 minimumStake;
// relayCall()'s msg.data upper bound gas cost per byte
uint256 dataGasCostPerByte;
// relayCalls() minimal gas overhead when calculating cost of putting tx on chain.
uint256 externalCallDataCostOverhead;
}
event RelayHubConfigured(RelayHubConfig config);
/// Emitted when a relay server registers or updates its details
/// Looking at these events lets a client discover relay servers
event RelayServerRegistered(
address indexed relayManager,
uint256 baseRelayFee,
uint256 pctRelayFee,
string relayUrl
);
/// Emitted when relays are added by a relayManager
event RelayWorkersAdded(
address indexed relayManager,
address[] newRelayWorkers,
uint256 workersCount
);
/// Emitted when an account withdraws funds from RelayHub.
event Withdrawn(
address indexed account,
address indexed dest,
uint256 amount
);
/// Emitted when depositFor is called, including the amount and account that was funded.
event Deposited(
address indexed paymaster,
address indexed from,
uint256 amount
);
/// Emitted when an attempt to relay a call fails and Paymaster does not accept the transaction.
/// The actual relayed call was not executed, and the recipient not charged.
/// @param reason contains a revert reason returned from preRelayedCall or forwarder.
event TransactionRejectedByPaymaster(
address indexed relayManager,
address indexed paymaster,
address indexed from,
address to,
address relayWorker,
bytes4 selector,
uint256 innerGasUsed,
bytes reason
);
/// Emitted when a transaction is relayed. Note that the actual encoded function might be reverted: this will be
/// indicated in the status field.
/// Useful when monitoring a relay's operation and relayed calls to a contract.
/// Charge is the ether value deducted from the recipient's balance, paid to the relay's manager.
event TransactionRelayed(
address indexed relayManager,
address indexed relayWorker,
address indexed from,
address to,
address paymaster,
bytes4 selector,
RelayCallStatus status,
uint256 charge
);
event TransactionResult(
RelayCallStatus status,
bytes returnValue
);
event HubDeprecated(uint256 fromBlock);
/// Reason error codes for the TransactionRelayed event
/// @param OK - the transaction was successfully relayed and execution successful - never included in the event
/// @param RelayedCallFailed - the transaction was relayed, but the relayed call failed
/// @param RejectedByPreRelayed - the transaction was not relayed due to preRelatedCall reverting
/// @param RejectedByForwarder - the transaction was not relayed due to forwarder check (signature,nonce)
/// @param PostRelayedFailed - the transaction was relayed and reverted due to postRelatedCall reverting
/// @param PaymasterBalanceChanged - the transaction was relayed and reverted due to the paymaster balance change
enum RelayCallStatus {
OK,
RelayedCallFailed,
RejectedByPreRelayed,
RejectedByForwarder,
RejectedByRecipientRevert,
PostRelayedFailed,
PaymasterBalanceChanged
}
/// Add new worker addresses controlled by sender who must be a staked Relay Manager address.
/// Emits a RelayWorkersAdded event.
/// This function can be called multiple times, emitting new events
function addRelayWorkers(address[] calldata newRelayWorkers) external;
function registerRelayServer(uint256 baseRelayFee, uint256 pctRelayFee, string calldata url) external;
// Balance management
/// Deposits ether for a contract, so that it can receive (and pay for) relayed transactions. Unused balance can only
/// be withdrawn by the contract itself, by calling withdraw.
/// Emits a Deposited event.
function depositFor(address target) external payable;
/// Withdraws from an account's balance, sending it back to it. Relay managers call this to retrieve their revenue, and
/// contracts can also use it to reduce their funding.
/// Emits a Withdrawn event.
function withdraw(uint256 amount, address payable dest) external;
// Relaying
/// Relays a transaction. For this to succeed, multiple conditions must be met:
/// - Paymaster's "preRelayCall" method must succeed and not revert
/// - the sender must be a registered Relay Worker that the user signed
/// - the transaction's gas price must be equal or larger than the one that was signed by the sender
/// - the transaction must have enough gas to run all internal transactions if they use all gas available to them
/// - the Paymaster must have enough balance to pay the Relay Worker for the scenario when all gas is spent
///
/// If all conditions are met, the call will be relayed and the recipient charged.
///
/// Arguments:
/// @param maxAcceptanceBudget - max valid value for paymaster.getGasLimits().acceptanceBudget
/// @param relayRequest - all details of the requested relayed call
/// @param signature - client's EIP-712 signature over the relayRequest struct
/// @param approvalData: dapp-specific data forwarded to preRelayedCall.
/// This value is *not* verified by the Hub. For example, it can be used to pass a signature to the Paymaster
/// @param externalGasLimit - the value passed as gasLimit to the transaction.
///
/// Emits a TransactionRelayed event.
function relayCall(
uint maxAcceptanceBudget,
GsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData,
uint externalGasLimit
)
external
returns (bool paymasterAccepted, bytes memory returnValue);
function penalize(address relayWorker, address payable beneficiary) external;
function setConfiguration(RelayHubConfig memory _config) external;
// Deprecate hub (reverting relayCall()) from block number 'fromBlock'
// Can only be called by owner
function deprecateHub(uint256 fromBlock) external;
/// The fee is expressed as a base fee in wei plus percentage on actual charge.
/// E.g. a value of 40 stands for a 40% fee, so the recipient will be
/// charged for 1.4 times the spent amount.
function calculateCharge(uint256 gasUsed, GsnTypes.RelayData calldata relayData) external view returns (uint256);
/* getters */
/// Returns the whole hub configuration
function getConfiguration() external view returns (RelayHubConfig memory config);
function calldataGasCost(uint256 length) external view returns (uint256);
function workerToManager(address worker) external view returns(address);
function workerCount(address manager) external view returns(uint256);
/// Returns an account's deposits. It can be either a deposit of a paymaster, or a revenue of a relay manager.
function balanceOf(address target) external view returns (uint256);
function stakeManager() external view returns (IStakeManager);
function penalizer() external view returns (address);
/// Uses StakeManager info to decide if the Relay Manager can be considered staked
/// @return true if stake size and delay satisfy all requirements
function isRelayManagerStaked(address relayManager) external view returns(bool);
// Checks hubs' deprecation status
function isDeprecated() external view returns (bool);
// Returns the block number from which the hub no longer allows relaying calls.
function deprecationBlock() external view returns (uint256);
/// @return a SemVer-compliant version of the hub contract
function versionHub() external view returns (string memory);
}
// SPDX-License-Identifier:MIT
pragma solidity >=0.7.6;
/**
* a contract must implement this interface in order to support relayed transaction.
* It is better to inherit the BaseRelayRecipient as its implementation.
*/
abstract contract IRelayRecipient {
/**
* return if the forwarder is trusted to forward relayed transactions to us.
* the forwarder is required to verify the sender's signature, and verify
* the call is not a replay.
*/
function isTrustedForwarder(address forwarder) public virtual view returns(bool);
/**
* return the sender of this call.
* if the call came through our trusted forwarder, then the real sender is appended as the last 20 bytes
* of the msg.data.
* otherwise, return `msg.sender`
* should be used in the contract anywhere instead of msg.sender
*/
function _msgSender() internal virtual view returns (address payable);
/**
* return the msg.data of this call.
* if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes
* of the msg.data - so this method will strip those 20 bytes off.
* otherwise (if the call was made directly and not through the forwarder), return `msg.data`
* should be used in the contract instead of msg.data, where this difference matters.
*/
function _msgData() internal virtual view returns (bytes memory);
function versionRecipient() external virtual view returns (string memory);
}
// SPDX-License-Identifier:MIT
pragma solidity >=0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts/math/SafeMath.sol";
interface IStakeManager {
/// Emitted when a stake or unstakeDelay are initialized or increased
event StakeAdded(
address indexed relayManager,
address indexed owner,
uint256 stake,
uint256 unstakeDelay
);
/// Emitted once a stake is scheduled for withdrawal
event StakeUnlocked(
address indexed relayManager,
address indexed owner,
uint256 withdrawBlock
);
/// Emitted when owner withdraws relayManager funds
event StakeWithdrawn(
address indexed relayManager,
address indexed owner,
uint256 amount
);
/// Emitted when an authorized Relay Hub penalizes a relayManager
event StakePenalized(
address indexed relayManager,
address indexed beneficiary,
uint256 reward
);
event HubAuthorized(
address indexed relayManager,
address indexed relayHub
);
event HubUnauthorized(
address indexed relayManager,
address indexed relayHub,
uint256 removalBlock
);
event OwnerSet(
address indexed relayManager,
address indexed owner
);
/// @param stake - amount of ether staked for this relay
/// @param unstakeDelay - number of blocks to elapse before the owner can retrieve the stake after calling 'unlock'
/// @param withdrawBlock - first block number 'withdraw' will be callable, or zero if the unlock has not been called
/// @param owner - address that receives revenue and manages relayManager's stake
struct StakeInfo {
uint256 stake;
uint256 unstakeDelay;
uint256 withdrawBlock;
address payable owner;
}
struct RelayHubInfo {
uint256 removalBlock;
}
/// Set the owner of a Relay Manager. Called only by the RelayManager itself.
/// Note that owners cannot transfer ownership - if the entry already exists, reverts.
/// @param owner - owner of the relay (as configured off-chain)
function setRelayManagerOwner(address payable owner) external;
/// Only the owner can call this function. If the entry does not exist, reverts.
/// @param relayManager - address that represents a stake entry and controls relay registrations on relay hubs
/// @param unstakeDelay - number of blocks to elapse before the owner can retrieve the stake after calling 'unlock'
function stakeForRelayManager(address relayManager, uint256 unstakeDelay) external payable;
function unlockStake(address relayManager) external;
function withdrawStake(address relayManager) external;
function authorizeHubByOwner(address relayManager, address relayHub) external;
function authorizeHubByManager(address relayHub) external;
function unauthorizeHubByOwner(address relayManager, address relayHub) external;
function unauthorizeHubByManager(address relayHub) external;
function isRelayManagerStaked(address relayManager, address relayHub, uint256 minAmount, uint256 minUnstakeDelay)
external
view
returns (bool);
/// Slash the stake of the relay relayManager. In order to prevent stake kidnapping, burns half of stake on the way.
/// @param relayManager - entry to penalize
/// @param beneficiary - address that receives half of the penalty amount
/// @param amount - amount to withdraw from stake
function penalizeRelayManager(address relayManager, address payable beneficiary, uint256 amount) external;
function getStakeInfo(address relayManager) external view returns (StakeInfo memory stakeInfo);
function maxUnstakeDelay() external view returns (uint256);
function versionSM() external view returns (string memory);
}
// SPDX-License-Identifier:MIT
pragma solidity >=0.7.6;
interface IVersionRegistry {
//event emitted whenever a version is added
event VersionAdded(bytes32 indexed id, bytes32 version, string value, uint time);
//event emitted whenever a version is canceled
event VersionCanceled(bytes32 indexed id, bytes32 version, string reason);
/**
* add a version
* @param id the object-id to add a version (32-byte string)
* @param version the new version to add (32-byte string)
* @param value value to attach to this version
*/
function addVersion(bytes32 id, bytes32 version, string calldata value) external;
/**
* cancel a version.
*/
function cancelVersion(bytes32 id, bytes32 version, string calldata reason) external;
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
import "@opengsn/contracts/src/BaseRelayRecipient.sol";
//make sure that "payable" function that uses _msgSender() still works
// (its not required to use _msgSender(), since the default function
// will never be called through GSN, but still, if someone uses it,
// it should work)
contract PayableWithEmit is BaseRelayRecipient {
string public override versionRecipient = "2.2.0+opengsn.payablewithemit.irelayrecipient";
event Received(address sender, uint value, uint gasleft);
receive () external payable {
emit Received(_msgSender(), msg.value, gasleft());
}
//helper: send value to another contract
function doSend(address payable target) public payable {
uint before = gasleft();
// solhint-disable-next-line check-send-result
bool success = target.send(msg.value);
uint gasAfter = gasleft();
emit GasUsed(before-gasAfter, success);
}
event GasUsed(uint gasUsed, bool success);
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "./TestPaymasterEverythingAccepted.sol";
contract TestPaymasterConfigurableMisbehavior is TestPaymasterEverythingAccepted {
bool public withdrawDuringPostRelayedCall;
bool public withdrawDuringPreRelayedCall;
bool public returnInvalidErrorCode;
bool public revertPostRelayCall;
bool public outOfGasPre;
bool public revertPreRelayCall;
bool public revertPreRelayCallOnEvenBlocks;
bool public greedyAcceptanceBudget;
bool public expensiveGasLimits;
function setWithdrawDuringPostRelayedCall(bool val) public {
withdrawDuringPostRelayedCall = val;
}
function setWithdrawDuringPreRelayedCall(bool val) public {
withdrawDuringPreRelayedCall = val;
}
function setReturnInvalidErrorCode(bool val) public {
returnInvalidErrorCode = val;
}
function setRevertPostRelayCall(bool val) public {
revertPostRelayCall = val;
}
function setRevertPreRelayCall(bool val) public {
revertPreRelayCall = val;
}
function setRevertPreRelayCallOnEvenBlocks(bool val) public {
revertPreRelayCallOnEvenBlocks = val;
}
function setOutOfGasPre(bool val) public {
outOfGasPre = val;
}
function setGreedyAcceptanceBudget(bool val) public {
greedyAcceptanceBudget = val;
}
function setExpensiveGasLimits(bool val) public {
expensiveGasLimits = val;
}
// solhint-disable reason-string
// contains comments that are checked in tests
function preRelayedCall(
GsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData,
uint256 maxPossibleGas
)
external
override
relayHubOnly
returns (bytes memory, bool) {
(signature, approvalData, maxPossibleGas);
if (outOfGasPre) {
uint i = 0;
while (true) {
i++;
}
}
require(!returnInvalidErrorCode, "invalid code");
if (withdrawDuringPreRelayedCall) {
withdrawAllBalance();
}
if (revertPreRelayCall) {
revert("You asked me to revert, remember?");
}
if (revertPreRelayCallOnEvenBlocks && block.number % 2 == 0) {
revert("You asked me to revert on even blocks, remember?");
}
_verifyForwarder(relayRequest);
return ("", trustRecipientRevert);
}
function postRelayedCall(
bytes calldata context,
bool success,
uint256 gasUseWithoutPost,
GsnTypes.RelayData calldata relayData
)
external
override
relayHubOnly
{
(context, success, gasUseWithoutPost, relayData);
if (withdrawDuringPostRelayedCall) {
withdrawAllBalance();
}
if (revertPostRelayCall) {
revert("You asked me to revert, remember?");
}
}
/// leaving withdrawal public and unprotected
function withdrawAllBalance() public returns (uint256) {
require(address(relayHub) != address(0), "relay hub address not set");
uint256 balance = relayHub.balanceOf(address(this));
relayHub.withdraw(balance, address(this));
return balance;
}
IPaymaster.GasAndDataLimits private limits = super.getGasAndDataLimits();
function getGasAndDataLimits()
public override view
returns (IPaymaster.GasAndDataLimits memory) {
if (expensiveGasLimits) {
uint sum;
//memory access is 700gas, so we waste ~50000
for ( int i=0; i<60000; i+=700 ) {
sum = sum + limits.acceptanceBudget;
}
}
if (greedyAcceptanceBudget) {
return IPaymaster.GasAndDataLimits(limits.acceptanceBudget * 9, limits.preRelayedCallGasLimit, limits.postRelayedCallGasLimit,
limits.calldataSizeLimit);
}
return limits;
}
bool private trustRecipientRevert;
function setGasLimits(uint acceptanceBudget, uint preRelayedCallGasLimit, uint postRelayedCallGasLimit) public {
limits = IPaymaster.GasAndDataLimits(
acceptanceBudget,
preRelayedCallGasLimit,
postRelayedCallGasLimit,
limits.calldataSizeLimit
);
}
function setTrustRecipientRevert(bool on) public {
trustRecipientRevert = on;
}
// solhint-disable-next-line no-empty-blocks
receive() external override payable {}
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "../forwarder/IForwarder.sol";
import "../BasePaymaster.sol";
contract TestPaymasterEverythingAccepted is BasePaymaster {
function versionPaymaster() external view override virtual returns (string memory){
return "2.2.0+opengsn.test-pea.ipaymaster";
}
event SampleRecipientPreCall();
event SampleRecipientPostCall(bool success, uint actualCharge);
function preRelayedCall(
GsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData,
uint256 maxPossibleGas
)
external
override
virtual
returns (bytes memory, bool) {
(signature);
_verifyForwarder(relayRequest);
(approvalData, maxPossibleGas);
emit SampleRecipientPreCall();
return ("no revert here",false);
}
function postRelayedCall(
bytes calldata context,
bool success,
uint256 gasUseWithoutPost,
GsnTypes.RelayData calldata relayData
)
external
override
virtual
{
(context, gasUseWithoutPost, relayData);
emit SampleRecipientPostCall(success, gasUseWithoutPost);
}
function deposit() public payable {
require(address(relayHub) != address(0), "relay hub address not set");
relayHub.depositFor{value:msg.value}(address(this));
}
function withdrawAll(address payable destination) public {
uint256 amount = relayHub.balanceOf(address(this));
withdrawRelayHubDepositTo(amount, destination);
}
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
import "./TestPaymasterEverythingAccepted.sol";
contract TestPaymasterOwnerSignature is TestPaymasterEverythingAccepted {
using ECDSA for bytes32;
/**
* This demonstrates how dapps can provide an off-chain signatures to relayed transactions.
*/
function preRelayedCall(
GsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData,
uint256 maxPossibleGas
)
external
view
override
returns (bytes memory, bool) {
(signature, maxPossibleGas);
_verifyForwarder(relayRequest);
address signer =
keccak256(abi.encodePacked("I approve", relayRequest.request.from))
.toEthSignedMessageHash()
.recover(approvalData);
require(signer == owner(), "test: not approved");
return ("",false);
}
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "./TestPaymasterEverythingAccepted.sol";
contract TestPaymasterPreconfiguredApproval is TestPaymasterEverythingAccepted {
bytes public expectedApprovalData;
function setExpectedApprovalData(bytes memory val) public {
expectedApprovalData = val;
}
function preRelayedCall(
GsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData,
uint256 maxPossibleGas
)
external
view
override
returns (bytes memory, bool) {
(relayRequest, signature, approvalData, maxPossibleGas);
_verifyForwarder(relayRequest);
require(keccak256(expectedApprovalData) == keccak256(approvalData),
string(abi.encodePacked(
"test: unexpected approvalData: '", approvalData, "' instead of '", expectedApprovalData, "'")));
return ("",false);
}
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "./TestPaymasterEverythingAccepted.sol";
contract TestPaymasterStoreContext is TestPaymasterEverythingAccepted {
event SampleRecipientPreCallWithValues(
address relay,
address from,
bytes encodedFunction,
uint256 baseRelayFee,
uint256 pctRelayFee,
uint256 gasPrice,
uint256 gasLimit,
bytes approvalData,
uint256 maxPossibleGas
);
event SampleRecipientPostCallWithValues(
string context
);
/**
* This demonstrates how preRelayedCall can return 'context' data for reuse in postRelayedCall.
*/
function preRelayedCall(
GsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData,
uint256 maxPossibleGas
)
external
override
returns (bytes memory, bool) {
(signature, approvalData, maxPossibleGas);
_verifyForwarder(relayRequest);
emit SampleRecipientPreCallWithValues(
relayRequest.relayData.relayWorker,
relayRequest.request.from,
relayRequest.request.data,
relayRequest.relayData.baseRelayFee,
relayRequest.relayData.pctRelayFee,
relayRequest.relayData.gasPrice,
relayRequest.request.gas,
approvalData,
maxPossibleGas);
return ("context passed from preRelayedCall to postRelayedCall",false);
}
function postRelayedCall(
bytes calldata context,
bool success,
uint256 gasUseWithoutPost,
GsnTypes.RelayData calldata relayData
)
external
override
relayHubOnly
{
(context, success, gasUseWithoutPost, relayData);
emit SampleRecipientPostCallWithValues(string(context));
}
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "./TestPaymasterEverythingAccepted.sol";
contract TestPaymasterVariableGasLimits is TestPaymasterEverythingAccepted {
string public override versionPaymaster = "2.2.0+opengsn.test-vgl.ipaymaster";
event SampleRecipientPreCallWithValues(
uint256 gasleft,
uint256 maxPossibleGas
);
event SampleRecipientPostCallWithValues(
uint256 gasleft,
uint256 gasUseWithoutPost
);
function preRelayedCall(
GsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData,
uint256 maxPossibleGas
)
external
override
returns (bytes memory, bool) {
(signature, approvalData);
_verifyForwarder(relayRequest);
emit SampleRecipientPreCallWithValues(
gasleft(), maxPossibleGas);
return ("", false);
}
function postRelayedCall(
bytes calldata context,
bool success,
uint256 gasUseWithoutPost,
GsnTypes.RelayData calldata relayData
)
external
override
relayHubOnly
{
(context, success, gasUseWithoutPost, relayData);
emit SampleRecipientPostCallWithValues(gasleft(), gasUseWithoutPost);
}
}
/* solhint-disable avoid-tx-origin */
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
import "../utils/GsnUtils.sol";
import "../BaseRelayRecipient.sol";
import "./TestPaymasterConfigurableMisbehavior.sol";
contract TestRecipient is BaseRelayRecipient {
string public override versionRecipient = "2.2.0+opengsn.test.irelayrecipient";
constructor(address forwarder) {
setTrustedForwarder(forwarder);
}
function getTrustedForwarder() public view returns(address) {
return trustedForwarder;
}
function setTrustedForwarder(address forwarder) internal {
trustedForwarder = forwarder;
}
event Reverting(string message);
function testRevert() public {
require(address(this) == address(0), "always fail");
emit Reverting("if you see this revert failed...");
}
address payable public paymaster;
function setWithdrawDuringRelayedCall(address payable _paymaster) public {
paymaster = _paymaster;
}
// solhint-disable-next-line no-empty-blocks
receive() external payable {}
event SampleRecipientEmitted(string message, address realSender, address msgSender, address origin, uint256 msgValue, uint256 gasLeft, uint256 balance);
function emitMessage(string memory message) public payable returns (string memory) {
uint256 gasLeft = gasleft();
if (paymaster != address(0)) {
withdrawAllBalance();
}
emit SampleRecipientEmitted(message, _msgSender(), msg.sender, tx.origin, msg.value, gasLeft, address(this).balance);
return "emitMessage return value";
}
function withdrawAllBalance() public {
TestPaymasterConfigurableMisbehavior(paymaster).withdrawAllBalance();
}
// solhint-disable-next-line no-empty-blocks
function dontEmitMessage(string calldata message) public {}
function emitMessageNoParams() public {
emit SampleRecipientEmitted("Method with no parameters", _msgSender(), msg.sender, tx.origin, 0, gasleft(), address(this).balance);
}
//return (or revert) with a string in the given length
function checkReturnValues(uint len, bool doRevert) public view returns (string memory) {
(this);
string memory mesg = "this is a long message that we are going to return a small part from. we don't use a loop since we want a fixed gas usage of the method itself.";
require( bytes(mesg).length>=len, "invalid len: too large");
/* solhint-disable no-inline-assembly */
//cut the msg at that length
assembly { mstore(mesg, len) }
require(!doRevert, mesg);
return mesg;
}
//function with no return value (also test revert with no msg.
function checkNoReturnValues(bool doRevert) public view {
(this);
/* solhint-disable reason-string*/
require(!doRevert);
}
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "../utils/RelayHubValidator.sol";
contract TestRelayHubValidator {
//for testing purposes, we must be called from a method with same param signature as RelayCall
function dummyRelayCall(
uint, //paymasterMaxAcceptanceBudget,
GsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData,
uint //externalGasLimit
) external pure {
RelayHubValidator.verifyTransactionPacking(relayRequest, signature, approvalData);
}
// helper method for verifyTransactionPacking
function dynamicParamSize(bytes calldata buf) external pure returns (uint) {
return RelayHubValidator.dynamicParamSize(buf);
}
}
/* solhint-disable avoid-tx-origin */
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "../interfaces/IRelayHub.sol";
contract TestRelayWorkerContract {
function relayCall(
IRelayHub hub,
uint maxAcceptanceBudget,
GsnTypes.RelayRequest memory relayRequest,
bytes memory signature,
uint externalGasLimit)
public
{
hub.relayCall{gas:externalGasLimit}(maxAcceptanceBudget, relayRequest, signature, "", externalGasLimit);
}
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "../utils/GsnTypes.sol";
import "../utils/GsnEip712Library.sol";
import "../utils/GsnUtils.sol";
contract TestUtil {
function libRelayRequestName() public pure returns (string memory) {
return GsnEip712Library.RELAY_REQUEST_NAME;
}
function libRelayRequestType() public pure returns (string memory) {
return string(GsnEip712Library.RELAY_REQUEST_TYPE);
}
function libRelayRequestTypeHash() public pure returns (bytes32) {
return GsnEip712Library.RELAY_REQUEST_TYPEHASH;
}
function libRelayRequestSuffix() public pure returns (string memory) {
return GsnEip712Library.RELAY_REQUEST_SUFFIX;
}
//helpers for test to call the library funcs:
function callForwarderVerify(
GsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature
)
external
view {
GsnEip712Library.verify(relayRequest, signature);
}
function callForwarderVerifyAndCall(
GsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature
)
external
returns (
bool success,
bytes memory ret
) {
bool forwarderSuccess;
(forwarderSuccess, success, ret) = GsnEip712Library.execute(relayRequest, signature);
if ( !forwarderSuccess) {
GsnUtils.revertWithData(ret);
}
emit Called(success, success == false ? ret : bytes(""));
}
event Called(bool success, bytes error);
function splitRequest(
GsnTypes.RelayRequest calldata relayRequest
)
external
pure
returns (
bytes32 typeHash,
bytes memory suffixData
) {
(suffixData) = GsnEip712Library.splitRequest(relayRequest);
typeHash = GsnEip712Library.RELAY_REQUEST_TYPEHASH;
}
function libDomainSeparator(address forwarder) public pure returns (bytes32) {
return GsnEip712Library.domainSeparator(forwarder);
}
function libGetChainID() public pure returns (uint256) {
return GsnEip712Library.getChainID();
}
}
// SPDX-License-Identifier:MIT
pragma solidity >=0.7.6;
pragma abicoder v2;
import "../utils/GsnTypes.sol";
import "../interfaces/IRelayRecipient.sol";
import "../forwarder/IForwarder.sol";
import "./GsnUtils.sol";
/**
* Bridge Library to map GSN RelayRequest into a call of a Forwarder
*/
library GsnEip712Library {
// maximum length of return value/revert reason for 'execute' method. Will truncate result if exceeded.
uint256 private constant MAX_RETURN_SIZE = 1024;
//copied from Forwarder (can't reference string constants even from another library)
string public constant GENERIC_PARAMS = "address from,address to,uint256 value,uint256 gas,uint256 nonce,bytes data,uint256 validUntil";
bytes public constant RELAYDATA_TYPE = "RelayData(uint256 gasPrice,uint256 pctRelayFee,uint256 baseRelayFee,address relayWorker,address paymaster,address forwarder,bytes paymasterData,uint256 clientId)";
string public constant RELAY_REQUEST_NAME = "RelayRequest";
string public constant RELAY_REQUEST_SUFFIX = string(abi.encodePacked("RelayData relayData)", RELAYDATA_TYPE));
bytes public constant RELAY_REQUEST_TYPE = abi.encodePacked(
RELAY_REQUEST_NAME,"(",GENERIC_PARAMS,",", RELAY_REQUEST_SUFFIX);
bytes32 public constant RELAYDATA_TYPEHASH = keccak256(RELAYDATA_TYPE);
bytes32 public constant RELAY_REQUEST_TYPEHASH = keccak256(RELAY_REQUEST_TYPE);
struct EIP712Domain {
string name;
string version;
uint256 chainId;
address verifyingContract;
}
bytes32 public constant EIP712DOMAIN_TYPEHASH = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
function splitRequest(
GsnTypes.RelayRequest calldata req
)
internal
pure
returns (
bytes memory suffixData
) {
suffixData = abi.encode(
hashRelayData(req.relayData));
}
//verify that the recipient trusts the given forwarder
// MUST be called by paymaster
function verifyForwarderTrusted(GsnTypes.RelayRequest calldata relayRequest) internal view {
(bool success, bytes memory ret) = relayRequest.request.to.staticcall(
abi.encodeWithSelector(
IRelayRecipient.isTrustedForwarder.selector, relayRequest.relayData.forwarder
)
);
require(success, "isTrustedForwarder: reverted");
require(ret.length == 32, "isTrustedForwarder: bad response");
require(abi.decode(ret, (bool)), "invalid forwarder for recipient");
}
function verifySignature(GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature) internal view {
(bytes memory suffixData) = splitRequest(relayRequest);
bytes32 _domainSeparator = domainSeparator(relayRequest.relayData.forwarder);
IForwarder forwarder = IForwarder(payable(relayRequest.relayData.forwarder));
forwarder.verify(relayRequest.request, _domainSeparator, RELAY_REQUEST_TYPEHASH, suffixData, signature);
}
function verify(GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature) internal view {
verifyForwarderTrusted(relayRequest);
verifySignature(relayRequest, signature);
}
function execute(GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature) internal returns (bool forwarderSuccess, bool callSuccess, bytes memory ret) {
(bytes memory suffixData) = splitRequest(relayRequest);
bytes32 _domainSeparator = domainSeparator(relayRequest.relayData.forwarder);
/* solhint-disable-next-line avoid-low-level-calls */
(forwarderSuccess, ret) = relayRequest.relayData.forwarder.call(
abi.encodeWithSelector(IForwarder.execute.selector,
relayRequest.request, _domainSeparator, RELAY_REQUEST_TYPEHASH, suffixData, signature
));
if ( forwarderSuccess ) {
//decode return value of execute:
(callSuccess, ret) = abi.decode(ret, (bool, bytes));
}
truncateInPlace(ret);
}
//truncate the given parameter (in-place) if its length is above the given maximum length
// do nothing otherwise.
//NOTE: solidity warns unless the method is marked "pure", but it DOES modify its parameter.
function truncateInPlace(bytes memory data) internal pure {
MinLibBytes.truncateInPlace(data, MAX_RETURN_SIZE);
}
function domainSeparator(address forwarder) internal pure returns (bytes32) {
return hashDomain(EIP712Domain({
name : "GSN Relayed Transaction",
version : "2",
chainId : getChainID(),
verifyingContract : forwarder
}));
}
function getChainID() internal pure returns (uint256 id) {
/* solhint-disable no-inline-assembly */
assembly {
id := chainid()
}
}
function hashDomain(EIP712Domain memory req) internal pure returns (bytes32) {
return keccak256(abi.encode(
EIP712DOMAIN_TYPEHASH,
keccak256(bytes(req.name)),
keccak256(bytes(req.version)),
req.chainId,
req.verifyingContract));
}
function hashRelayData(GsnTypes.RelayData calldata req) internal pure returns (bytes32) {
return keccak256(abi.encode(
RELAYDATA_TYPEHASH,
req.gasPrice,
req.pctRelayFee,
req.baseRelayFee,
req.relayWorker,
req.paymaster,
req.forwarder,
keccak256(req.paymasterData),
req.clientId
));
}
}
// SPDX-License-Identifier:MIT
pragma solidity >=0.7.6;
import "../forwarder/IForwarder.sol";
interface GsnTypes {
/// @notice gasPrice, pctRelayFee and baseRelayFee must be validated inside of the paymaster's preRelayedCall in order not to overpay
struct RelayData {
uint256 gasPrice;
uint256 pctRelayFee;
uint256 baseRelayFee;
address relayWorker;
address paymaster;
address forwarder;
bytes paymasterData;
uint256 clientId;
}
//note: must start with the ForwardRequest to be an extension of the generic forwarder
struct RelayRequest {
IForwarder.ForwardRequest request;
RelayData relayData;
}
}
/* solhint-disable no-inline-assembly */
// SPDX-License-Identifier:MIT
pragma solidity >=0.7.6;
import "../utils/MinLibBytes.sol";
library GsnUtils {
/**
* extract method sig from encoded function call
*/
function getMethodSig(bytes memory msgData) internal pure returns (bytes4) {
return MinLibBytes.readBytes4(msgData, 0);
}
/**
* extract parameter from encoded-function block.
* see: https://solidity.readthedocs.io/en/develop/abi-spec.html#formal-specification-of-the-encoding
* the return value should be casted to the right type (uintXXX/bytesXXX/address/bool/enum)
*/
function getParam(bytes memory msgData, uint index) internal pure returns (uint) {
return MinLibBytes.readUint256(msgData, 4 + index * 32);
}
//re-throw revert with the same revert data.
function revertWithData(bytes memory data) internal pure {
assembly {
revert(add(data,32), mload(data))
}
}
}
// SPDX-License-Identifier: MIT
// minimal bytes manipulation required by GSN
// a minimal subset from 0x/LibBytes
/* solhint-disable no-inline-assembly */
pragma solidity >=0.7.6;
library MinLibBytes {
//truncate the given parameter (in-place) if its length is above the given maximum length
// do nothing otherwise.
//NOTE: solidity warns unless the method is marked "pure", but it DOES modify its parameter.
function truncateInPlace(bytes memory data, uint256 maxlen) internal pure {
if (data.length > maxlen) {
assembly { mstore(data, maxlen) }
}
}
/// @dev Reads an address from a position in a byte array.
/// @param b Byte array containing an address.
/// @param index Index in byte array of address.
/// @return result address from byte array.
function readAddress(
bytes memory b,
uint256 index
)
internal
pure
returns (address result)
{
require (b.length >= index + 20, "readAddress: data too short");
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Read address from array memory
assembly {
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 20-byte mask to obtain address
result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
return result;
}
function readBytes32(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes32 result)
{
require(b.length >= index + 32, "readBytes32: data too short" );
// Read the bytes32 from array memory
assembly {
result := mload(add(b, add(index,32)))
}
return result;
}
/// @dev Reads a uint256 value from a position in a byte array.
/// @param b Byte array containing a uint256 value.
/// @param index Index in byte array of uint256 value.
/// @return result uint256 value from byte array.
function readUint256(
bytes memory b,
uint256 index
)
internal
pure
returns (uint256 result)
{
result = uint256(readBytes32(b, index));
return result;
}
function readBytes4(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes4 result)
{
require(b.length >= index + 4, "readBytes4: data too short");
// Read the bytes4 from array memory
assembly {
result := mload(add(b, add(index,32)))
// Solidity does not require us to clean the trailing bytes.
// We do it anyway
result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000)
}
return result;
}
}
// SPDX-License-Identifier:APACHE-2.0
/*
* Taken from https://github.com/hamdiallam/Solidity-RLP
*/
/* solhint-disable */
pragma solidity ^0.7.6;
library RLPReader {
uint8 constant STRING_SHORT_START = 0x80;
uint8 constant STRING_LONG_START = 0xb8;
uint8 constant LIST_SHORT_START = 0xc0;
uint8 constant LIST_LONG_START = 0xf8;
uint8 constant WORD_SIZE = 32;
struct RLPItem {
uint len;
uint memPtr;
}
using RLPReader for bytes;
using RLPReader for uint;
using RLPReader for RLPReader.RLPItem;
// helper function to decode rlp encoded legacy ethereum transaction
/*
* @param rawTransaction RLP encoded legacy ethereum transaction rlp([nonce, gasPrice, gasLimit, to, value, data]))
* @return tuple (nonce,gasPrice,gasLimit,to,value,data)
*/
function decodeLegacyTransaction(bytes calldata rawTransaction) internal pure returns (uint, uint, uint, address, uint, bytes memory){
RLPReader.RLPItem[] memory values = rawTransaction.toRlpItem().toList(); // must convert to an rlpItem first!
return (values[0].toUint(), values[1].toUint(), values[2].toUint(), values[3].toAddress(), values[4].toUint(), values[5].toBytes());
}
/*
* @param rawTransaction format: 0x01 || rlp([chainId, nonce, gasPrice, gasLimit, to, value, data, access_list]))
* @return tuple (nonce,gasPrice,gasLimit,to,value,data)
*/
function decodeTransactionType1(bytes calldata rawTransaction) internal pure returns (uint, uint, uint, address, uint, bytes memory){
bytes memory payload = rawTransaction[1:rawTransaction.length];
RLPReader.RLPItem[] memory values = payload.toRlpItem().toList(); // must convert to an rlpItem first!
return (values[1].toUint(), values[2].toUint(), values[3].toUint(), values[4].toAddress(), values[5].toUint(), values[6].toBytes());
}
/*
* @param item RLP encoded bytes
*/
function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) {
if (item.length == 0)
return RLPItem(0, 0);
uint memPtr;
assembly {
memPtr := add(item, 0x20)
}
return RLPItem(item.length, memPtr);
}
/*
* @param item RLP encoded list in bytes
*/
function toList(RLPItem memory item) internal pure returns (RLPItem[] memory result) {
require(isList(item), "isList failed");
uint items = numItems(item);
result = new RLPItem[](items);
uint memPtr = item.memPtr + _payloadOffset(item.memPtr);
uint dataLen;
for (uint i = 0; i < items; i++) {
dataLen = _itemLength(memPtr);
result[i] = RLPItem(dataLen, memPtr);
memPtr = memPtr + dataLen;
}
}
/*
* Helpers
*/
// @return indicator whether encoded payload is a list. negate this function call for isData.
function isList(RLPItem memory item) internal pure returns (bool) {
uint8 byte0;
uint memPtr = item.memPtr;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < LIST_SHORT_START)
return false;
return true;
}
// @return number of payload items inside an encoded list.
function numItems(RLPItem memory item) internal pure returns (uint) {
uint count = 0;
uint currPtr = item.memPtr + _payloadOffset(item.memPtr);
uint endPtr = item.memPtr + item.len;
while (currPtr < endPtr) {
currPtr = currPtr + _itemLength(currPtr);
// skip over an item
count++;
}
return count;
}
// @return entire rlp item byte length
function _itemLength(uint memPtr) internal pure returns (uint len) {
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
return 1;
else if (byte0 < STRING_LONG_START)
return byte0 - STRING_SHORT_START + 1;
else if (byte0 < LIST_SHORT_START) {
assembly {
let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is
memPtr := add(memPtr, 1) // skip over the first byte
/* 32 byte word size */
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len
len := add(dataLen, add(byteLen, 1))
}
}
else if (byte0 < LIST_LONG_START) {
return byte0 - LIST_SHORT_START + 1;
}
else {
assembly {
let byteLen := sub(byte0, 0xf7)
memPtr := add(memPtr, 1)
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length
len := add(dataLen, add(byteLen, 1))
}
}
}
// @return number of bytes until the data
function _payloadOffset(uint memPtr) internal pure returns (uint) {
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
return 0;
else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START))
return 1;
else if (byte0 < LIST_SHORT_START) // being explicit
return byte0 - (STRING_LONG_START - 1) + 1;
else
return byte0 - (LIST_LONG_START - 1) + 1;
}
/** RLPItem conversions into data types **/
// @returns raw rlp encoding in bytes
function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) {
bytes memory result = new bytes(item.len);
uint ptr;
assembly {
ptr := add(0x20, result)
}
copy(item.memPtr, ptr, item.len);
return result;
}
function toBoolean(RLPItem memory item) internal pure returns (bool) {
require(item.len == 1, "Invalid RLPItem. Booleans are encoded in 1 byte");
uint result;
uint memPtr = item.memPtr;
assembly {
result := byte(0, mload(memPtr))
}
return result == 0 ? false : true;
}
function toAddress(RLPItem memory item) internal pure returns (address) {
// 1 byte for the length prefix according to RLP spec
require(item.len <= 21, "Invalid RLPItem. Addresses are encoded in 20 bytes or less");
return address(toUint(item));
}
function toUint(RLPItem memory item) internal pure returns (uint) {
uint offset = _payloadOffset(item.memPtr);
uint len = item.len - offset;
uint memPtr = item.memPtr + offset;
uint result;
assembly {
result := div(mload(memPtr), exp(256, sub(32, len))) // shift to the correct location
}
return result;
}
function toBytes(RLPItem memory item) internal pure returns (bytes memory) {
uint offset = _payloadOffset(item.memPtr);
uint len = item.len - offset;
// data length
bytes memory result = new bytes(len);
uint destPtr;
assembly {
destPtr := add(0x20, result)
}
copy(item.memPtr + offset, destPtr, len);
return result;
}
/*
* @param src Pointer to source
* @param dest Pointer to destination
* @param len Amount of memory to copy from the source
*/
function copy(uint src, uint dest, uint len) internal pure {
// copy as many word sizes as possible
for (; len >= WORD_SIZE; len -= WORD_SIZE) {
assembly {
mstore(dest, mload(src))
}
src += WORD_SIZE;
dest += WORD_SIZE;
}
// left over bytes. Mask is used to remove unwanted bytes from the word
uint mask = 256 ** (WORD_SIZE - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask)) // zero out src
let destpart := and(mload(dest), mask) // retrieve the bytes
mstore(dest, or(destpart, srcpart))
}
}
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.5;
pragma abicoder v2;
import "../utils/GsnTypes.sol";
library RelayHubValidator {
// validate that encoded relayCall is properly packed without any extra bytes
function verifyTransactionPacking(
GsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData
) internal pure {
// abicoder v2: https://docs.soliditylang.org/en/latest/abi-spec.html
// each static param/member is 1 word
// struct (with dynamic members) has offset to struct which is 1 word
// dynamic member is 1 word offset to actual value, which is 1-word length and ceil(length/32) words for data
// relayCall has 5 method params,
// relayRequest: 2 members
// relayData 8 members
// ForwardRequest: 7 members
// total 22 32-byte words if all dynamic params are zero-length.
uint expectedMsgDataLen = 4 + 22 * 32 +
dynamicParamSize(signature) +
dynamicParamSize(approvalData) +
dynamicParamSize(relayRequest.request.data) +
dynamicParamSize(relayRequest.relayData.paymasterData);
require(signature.length <= 65, "invalid signature length");
require(expectedMsgDataLen == msg.data.length, "extra msg.data bytes" );
}
// helper method for verifyTransactionPacking:
// size (in bytes) of the given "bytes" parameter. size include the length (32-byte word),
// and actual data size, rounded up to full 32-byte words
function dynamicParamSize(bytes calldata buf) internal pure returns (uint) {
return 32 + ((buf.length + 31) & uint(~31));
}
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
// solhint-disable not-rely-on-time
import "../interfaces/IVersionRegistry.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract VersionRegistry is IVersionRegistry, Ownable {
function addVersion(bytes32 id, bytes32 version, string calldata value) external override onlyOwner {
require(id != bytes32(0), "missing id");
require(version != bytes32(0), "missing version");
emit VersionAdded(id, version, value, block.timestamp);
}
function cancelVersion(bytes32 id, bytes32 version, string calldata reason) external override onlyOwner {
emit VersionCanceled(id, version, reason);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () /*internal*/ {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// SPDX-License-Identifier: 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
// solhint-disable no-inline-assembly
pragma solidity >=0.7.6;
import "./interfaces/IRelayRecipient.sol";
/**
* A base contract to be inherited by any contract that want to receive relayed transactions
* A subclass must use "_msgSender()" instead of "msg.sender"
*/
abstract contract BaseRelayRecipient is IRelayRecipient {
/*
* Forwarder singleton we accept calls from
*/
address public trustedForwarder;
function isTrustedForwarder(address forwarder) public override view returns(bool) {
return forwarder == trustedForwarder;
}
/**
* return the sender of this call.
* if the call came through our trusted forwarder, return the original sender.
* otherwise, return `msg.sender`.
* should be used in the contract anywhere instead of msg.sender
*/
function _msgSender() internal override virtual view returns (address payable ret) {
if (msg.data.length >= 20 && isTrustedForwarder(msg.sender)) {
// At this point we know that the sender is a trusted forwarder,
// so we trust that the last bytes of msg.data are the verified sender address.
// extract sender address from the end of msg.data
assembly {
ret := shr(96,calldataload(sub(calldatasize(),20)))
}
} else {
return msg.sender;
}
}
/**
* return the msg.data of this call.
* if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes
* of the msg.data - so this method will strip those 20 bytes off.
* otherwise, return `msg.data`
* should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly
* signing or hashing the
*/
function _msgData() internal override virtual view returns (bytes memory ret) {
if (msg.data.length >= 20 && isTrustedForwarder(msg.sender)) {
return msg.data[0:msg.data.length-20];
} else {
return msg.data;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier:MIT
pragma solidity >=0.7.6;
/**
* a contract must implement this interface in order to support relayed transaction.
* It is better to inherit the BaseRelayRecipient as its implementation.
*/
abstract contract IRelayRecipient {
/**
* return if the forwarder is trusted to forward relayed transactions to us.
* the forwarder is required to verify the sender's signature, and verify
* the call is not a replay.
*/
function isTrustedForwarder(address forwarder) public virtual view returns(bool);
/**
* return the sender of this call.
* if the call came through our trusted forwarder, then the real sender is appended as the last 20 bytes
* of the msg.data.
* otherwise, return `msg.sender`
* should be used in the contract anywhere instead of msg.sender
*/
function _msgSender() internal virtual view returns (address payable);
/**
* return the msg.data of this call.
* if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes
* of the msg.data - so this method will strip those 20 bytes off.
* otherwise (if the call was made directly and not through the forwarder), return `msg.data`
* should be used in the contract instead of msg.data, where this difference matters.
*/
function _msgData() internal virtual view returns (bytes memory);
function versionRecipient() external virtual view returns (string memory);
}
| Nonces of senders, used to prevent replay attacks solhint-disable-next-line no-empty-blocks | contract Forwarder is IForwarder {
using ECDSA for bytes32;
string public constant GENERIC_PARAMS = "address from,address to,uint256 value,uint256 gas,uint256 nonce,bytes data,uint256 validUntil";
string public constant EIP712_DOMAIN_TYPE = "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)";
mapping(bytes32 => bool) public typeHashes;
mapping(bytes32 => bool) public domains;
mapping(address => uint256) private nonces;
function getNonce(address from)
public view override
pragma solidity ^0.7.6;
receive() external payable {}
returns (uint256) {
return nonces[from];
}
constructor() {
string memory requestType = string(abi.encodePacked("ForwardRequest(", GENERIC_PARAMS, ")"));
registerRequestTypeInternal(requestType);
}
function verify(
ForwardRequest calldata req,
bytes32 domainSeparator,
bytes32 requestTypeHash,
bytes calldata suffixData,
bytes calldata sig)
external override view {
_verifyNonce(req);
_verifySig(req, domainSeparator, requestTypeHash, suffixData, sig);
}
function execute(
ForwardRequest calldata req,
bytes32 domainSeparator,
bytes32 requestTypeHash,
bytes calldata suffixData,
bytes calldata sig
)
external payable
override
returns (bool success, bytes memory ret) {
_verifySig(req, domainSeparator, requestTypeHash, suffixData, sig);
_verifyAndUpdateNonce(req);
require(req.validUntil == 0 || req.validUntil > block.number, "FWD: request expired");
uint gasForTransfer = 0;
if ( req.value != 0 ) {
}
bytes memory callData = abi.encodePacked(req.data, req.from);
require(gasleft()*63/64 >= req.gas + gasForTransfer, "FWD: insufficient gas");
if ( req.value != 0 && address(this).balance>0 ) {
payable(req.from).transfer(address(this).balance);
}
return (success,ret);
}
function execute(
ForwardRequest calldata req,
bytes32 domainSeparator,
bytes32 requestTypeHash,
bytes calldata suffixData,
bytes calldata sig
)
external payable
override
returns (bool success, bytes memory ret) {
_verifySig(req, domainSeparator, requestTypeHash, suffixData, sig);
_verifyAndUpdateNonce(req);
require(req.validUntil == 0 || req.validUntil > block.number, "FWD: request expired");
uint gasForTransfer = 0;
if ( req.value != 0 ) {
}
bytes memory callData = abi.encodePacked(req.data, req.from);
require(gasleft()*63/64 >= req.gas + gasForTransfer, "FWD: insufficient gas");
if ( req.value != 0 && address(this).balance>0 ) {
payable(req.from).transfer(address(this).balance);
}
return (success,ret);
}
(success,ret) = req.to.call{gas : req.gas, value : req.value}(callData);
function execute(
ForwardRequest calldata req,
bytes32 domainSeparator,
bytes32 requestTypeHash,
bytes calldata suffixData,
bytes calldata sig
)
external payable
override
returns (bool success, bytes memory ret) {
_verifySig(req, domainSeparator, requestTypeHash, suffixData, sig);
_verifyAndUpdateNonce(req);
require(req.validUntil == 0 || req.validUntil > block.number, "FWD: request expired");
uint gasForTransfer = 0;
if ( req.value != 0 ) {
}
bytes memory callData = abi.encodePacked(req.data, req.from);
require(gasleft()*63/64 >= req.gas + gasForTransfer, "FWD: insufficient gas");
if ( req.value != 0 && address(this).balance>0 ) {
payable(req.from).transfer(address(this).balance);
}
return (success,ret);
}
function _verifyNonce(ForwardRequest calldata req) internal view {
require(nonces[req.from] == req.nonce, "FWD: nonce mismatch");
}
function _verifyAndUpdateNonce(ForwardRequest calldata req) internal {
require(nonces[req.from]++ == req.nonce, "FWD: nonce mismatch");
}
function registerRequestType(string calldata typeName, string calldata typeSuffix) external override {
for (uint i = 0; i < bytes(typeName).length; i++) {
bytes1 c = bytes(typeName)[i];
require(c != "(" && c != ")", "FWD: invalid typename");
}
string memory requestType = string(abi.encodePacked(typeName, "(", GENERIC_PARAMS, ",", typeSuffix));
registerRequestTypeInternal(requestType);
}
function registerRequestType(string calldata typeName, string calldata typeSuffix) external override {
for (uint i = 0; i < bytes(typeName).length; i++) {
bytes1 c = bytes(typeName)[i];
require(c != "(" && c != ")", "FWD: invalid typename");
}
string memory requestType = string(abi.encodePacked(typeName, "(", GENERIC_PARAMS, ",", typeSuffix));
registerRequestTypeInternal(requestType);
}
function registerDomainSeparator(string calldata name, string calldata version) external override {
uint256 chainId;
bytes memory domainValue = abi.encode(
keccak256(bytes(EIP712_DOMAIN_TYPE)),
keccak256(bytes(name)),
keccak256(bytes(version)),
chainId,
address(this));
bytes32 domainHash = keccak256(domainValue);
domains[domainHash] = true;
emit DomainRegistered(domainHash, domainValue);
}
assembly { chainId := chainid() }
function registerRequestTypeInternal(string memory requestType) internal {
bytes32 requestTypehash = keccak256(bytes(requestType));
typeHashes[requestTypehash] = true;
emit RequestTypeRegistered(requestTypehash, requestType);
}
function _verifySig(
ForwardRequest calldata req,
bytes32 domainSeparator,
bytes32 requestTypeHash,
bytes calldata suffixData,
bytes calldata sig)
internal
view
{
require(domains[domainSeparator], "FWD: unregistered domain sep.");
require(typeHashes[requestTypeHash], "FWD: unregistered typehash");
bytes32 digest = keccak256(abi.encodePacked(
"\x19\x01", domainSeparator,
keccak256(_getEncoded(req, requestTypeHash, suffixData))
));
require(digest.recover(sig) == req.from, "FWD: signature mismatch");
}
function _getEncoded(
ForwardRequest calldata req,
bytes32 requestTypeHash,
bytes calldata suffixData
)
public
pure
returns (
bytes memory
) {
return abi.encodePacked(
requestTypeHash,
uint256(uint160(req.from)),
uint256(uint160(req.to)),
req.value,
req.gas,
req.nonce,
keccak256(req.data),
req.validUntil,
suffixData
);
}
}
| 45,701 | [
1,
3989,
764,
434,
1366,
414,
16,
1399,
358,
5309,
16033,
28444,
3704,
11317,
17,
8394,
17,
4285,
17,
1369,
1158,
17,
5531,
17,
7996,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
2457,
20099,
353,
467,
30839,
288,
203,
565,
1450,
7773,
19748,
364,
1731,
1578,
31,
203,
203,
565,
533,
1071,
5381,
18421,
67,
16785,
273,
315,
2867,
628,
16,
2867,
358,
16,
11890,
5034,
460,
16,
11890,
5034,
16189,
16,
11890,
5034,
7448,
16,
3890,
501,
16,
11890,
5034,
923,
9716,
14432,
203,
203,
565,
533,
1071,
5381,
512,
2579,
27,
2138,
67,
18192,
67,
2399,
273,
315,
41,
2579,
27,
2138,
3748,
12,
1080,
508,
16,
1080,
1177,
16,
11890,
5034,
2687,
548,
16,
2867,
3929,
310,
8924,
2225,
31,
203,
203,
565,
2874,
12,
3890,
1578,
516,
1426,
13,
1071,
618,
14455,
31,
203,
565,
2874,
12,
3890,
1578,
516,
1426,
13,
1071,
10128,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
1661,
764,
31,
203,
203,
203,
565,
445,
336,
13611,
12,
2867,
628,
13,
203,
565,
1071,
1476,
3849,
203,
683,
9454,
18035,
560,
3602,
20,
18,
27,
18,
26,
31,
203,
565,
6798,
1435,
3903,
8843,
429,
2618,
203,
565,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
1661,
764,
63,
2080,
15533,
203,
565,
289,
203,
203,
565,
3885,
1435,
288,
203,
203,
3639,
533,
3778,
27179,
273,
533,
12,
21457,
18,
3015,
4420,
329,
2932,
8514,
691,
2932,
16,
18421,
67,
16785,
16,
7310,
10019,
203,
3639,
1744,
691,
559,
3061,
12,
2293,
559,
1769,
203,
565,
289,
203,
203,
565,
445,
3929,
12,
203,
3639,
17206,
691,
745,
892,
1111,
16,
203,
3639,
1731,
1578,
2461,
6581,
16,
203,
3639,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
import "./ERC721ABurnable.sol";
import "./ERC721AOwnersExplicit.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
contract SelfImprovementSociety is ERC721ABurnable, ERC721AOwnersExplicit, Ownable, ReentrancyGuard {
using Address for address;
using Strings for uint256;
string private baseURI;
uint256 public immutable price = 0.06 ether;
uint256 public immutable maxTokensWallet = 21;
uint256 public immutable maxSupply = 5521;
uint256 public saleIsOpen;
constructor() ERC721A("SelfImprovementSociety", "SiS") {
reserveForTeam();
}
function reserveForTeam() internal {
_safeMint(msg.sender, 60);
}
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function mint(uint256 _amount) external payable {
require(totalSupply() + _amount < maxSupply, "Max supply reached");
if (msg.sender != owner()) {
require(_numberMinted(msg.sender) + _amount < maxTokensWallet, "Max token per wallet reached");
require(saleIsOpen == 1, "Sale is paused");
require(msg.value >= price *_amount, "Insufficient funds");
}
_safeMint(msg.sender, _amount);
}
function withdrawFunds() external onlyOwner nonReentrant {
(bool success, ) = msg.sender.call{value: address(this).balance}("");
require(success, "Transfer failed");
}
function setBaseURI(string calldata _newBaseURI) external onlyOwner {
baseURI = _newBaseURI;
}
function numberMinted(address owner) external view returns (uint256) {
return _numberMinted(owner);
}
function setSale(uint256 _saleIsOpen) external onlyOwner {
saleIsOpen = _saleIsOpen;
}
function setOwnersExplicit(uint256 quantity) external onlyOwner nonReentrant {
_setOwnersExplicit(quantity);
}
// Use with caution may run out of gas
function walletOfOwner(address _owner) public view returns (uint256[] memory) {
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount);
uint256 currentTokenId = 0;
uint256 ownedTokenIndex = 0;
while (ownedTokenIndex < ownerTokenCount && currentTokenId < maxSupply) {
address currentTokenOwner = ownerOf(currentTokenId);
if (currentTokenOwner == _owner) {
ownedTokenIds[ownedTokenIndex] = currentTokenId;
ownedTokenIndex++;
}
currentTokenId++;
}
return ownedTokenIds;
}
}
// SPDX-License-Identifier: MIT
// Creator: Chiru Labs
pragma solidity ^0.8.4;
import './ERC721A.sol';
/**
* @title ERC721A Burnable Token
* @dev ERC721A Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721ABurnable is ERC721A {
/**
* @dev Burns `tokenId`. See {ERC721A-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
_burn(tokenId, true);
}
}
// SPDX-License-Identifier: MIT
// Creator: Chiru Labs
pragma solidity ^0.8.4;
import './ERC721A.sol';
error AllOwnershipsHaveBeenSet();
error QuantityMustBeNonZero();
error NoTokensMintedYet();
abstract contract ERC721AOwnersExplicit is ERC721A {
uint256 public nextOwnerToExplicitlySet;
/**
* @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf().
*/
function _setOwnersExplicit(uint256 quantity) internal {
if (quantity == 0) revert QuantityMustBeNonZero();
if (_currentIndex == _startTokenId()) revert NoTokensMintedYet();
uint256 _nextOwnerToExplicitlySet = nextOwnerToExplicitlySet;
if (_nextOwnerToExplicitlySet == 0) {
_nextOwnerToExplicitlySet = _startTokenId();
}
if (_nextOwnerToExplicitlySet >= _currentIndex) revert AllOwnershipsHaveBeenSet();
// Index underflow is impossible.
// Counter or index overflow is incredibly unrealistic.
unchecked {
uint256 endIndex = _nextOwnerToExplicitlySet + quantity - 1;
// Set the end index to be the last token index
if (endIndex + 1 > _currentIndex) {
endIndex = _currentIndex - 1;
}
for (uint256 i = _nextOwnerToExplicitlySet; i <= endIndex; i++) {
if (_ownerships[i].addr == address(0) && !_ownerships[i].burned) {
TokenOwnership memory ownership = _ownershipOf(i);
_ownerships[i].addr = ownership.addr;
_ownerships[i].startTimestamp = ownership.startTimestamp;
}
}
nextOwnerToExplicitlySet = endIndex + 1;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// Creator: Chiru Labs
pragma solidity ^0.8.4;
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol';
import '@openzeppelin/contracts/utils/Address.sol';
import '@openzeppelin/contracts/utils/Context.sol';
import '@openzeppelin/contracts/utils/Strings.sol';
import '@openzeppelin/contracts/utils/introspection/ERC165.sol';
error ApprovalCallerNotOwnerNorApproved();
error ApprovalQueryForNonexistentToken();
error ApproveToCaller();
error ApprovalToCurrentOwner();
error BalanceQueryForZeroAddress();
error MintToZeroAddress();
error MintZeroQuantity();
error OwnerQueryForNonexistentToken();
error TransferCallerNotOwnerNorApproved();
error TransferFromIncorrectOwner();
error TransferToNonERC721ReceiverImplementer();
error TransferToZeroAddress();
error URIQueryForNonexistentToken();
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..).
*
* Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
*
* Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256).
*/
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Compiler will pack this into a single 256bit word.
struct TokenOwnership {
// The address of the owner.
address addr;
// Keeps track of the start time of ownership with minimal overhead for tokenomics.
uint64 startTimestamp;
// Whether the token has been burned.
bool burned;
}
// Compiler will pack this into a single 256bit word.
struct AddressData {
// Realistically, 2**64-1 is more than enough.
uint64 balance;
// Keeps track of mint count with minimal overhead for tokenomics.
uint64 numberMinted;
// Keeps track of burn count with minimal overhead for tokenomics.
uint64 numberBurned;
// For miscellaneous variable(s) pertaining to the address
// (e.g. number of whitelist mint slots used).
// If there are multiple variables, please pack them into a uint64.
uint64 aux;
}
// The tokenId of the next token to be minted.
uint256 internal _currentIndex;
// The number of tokens burned.
uint256 internal _burnCounter;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See _ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) internal _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_currentIndex = _startTokenId();
}
/**
* To change the starting tokenId, please override this function.
*/
function _startTokenId() internal view virtual returns (uint256) {
return 0;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
* @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens.
*/
function totalSupply() public view returns (uint256) {
// Counter underflow is impossible as _burnCounter cannot be incremented
// more than _currentIndex - _startTokenId() times
unchecked {
return _currentIndex - _burnCounter - _startTokenId();
}
}
/**
* Returns the total amount of tokens minted in the contract.
*/
function _totalMinted() internal view returns (uint256) {
// Counter underflow is impossible as _currentIndex does not decrement,
// and it is initialized to _startTokenId()
unchecked {
return _currentIndex - _startTokenId();
}
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
if (owner == address(0)) revert BalanceQueryForZeroAddress();
return uint256(_addressData[owner].balance);
}
/**
* Returns the number of tokens minted by `owner`.
*/
function _numberMinted(address owner) internal view returns (uint256) {
return uint256(_addressData[owner].numberMinted);
}
/**
* Returns the number of tokens burned by or on behalf of `owner`.
*/
function _numberBurned(address owner) internal view returns (uint256) {
return uint256(_addressData[owner].numberBurned);
}
/**
* Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
*/
function _getAux(address owner) internal view returns (uint64) {
return _addressData[owner].aux;
}
/**
* Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
* If there are multiple variables, please pack them into a uint64.
*/
function _setAux(address owner, uint64 aux) internal {
_addressData[owner].aux = aux;
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/
function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
// Invariant:
// There will always be an ownership that has an address and is not burned
// before an ownership that does not have an address and is not burned.
// Hence, curr will not underflow.
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
string memory baseURI = _baseURI();
return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : '';
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return '';
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
if (to == owner) revert ApprovalToCurrentOwner();
if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
if (operator == _msgSender()) revert ApproveToCaller();
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, '');
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
_transfer(from, to, tokenId);
if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _startTokenId() <= tokenId && tokenId < _currentIndex &&
!_ownerships[tokenId].burned;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, '');
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1
// updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
// Reentrancy protection
if (_currentIndex != startTokenId) revert();
} else {
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
bool isApprovedOrOwner = (_msgSender() == from ||
isApprovedForAll(from, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, from);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
TokenOwnership storage currSlot = _ownerships[tokenId];
currSlot.addr = to;
currSlot.startTimestamp = uint64(block.timestamp);
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
TokenOwnership storage nextSlot = _ownerships[nextTokenId];
if (nextSlot.addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId != _currentIndex) {
nextSlot.addr = from;
nextSlot.startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev This is equivalent to _burn(tokenId, false)
*/
function _burn(uint256 tokenId) internal virtual {
_burn(tokenId, false);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
address from = prevOwnership.addr;
if (approvalCheck) {
bool isApprovedOrOwner = (_msgSender() == from ||
isApprovedForAll(from, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, from);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
AddressData storage addressData = _addressData[from];
addressData.balance -= 1;
addressData.numberBurned += 1;
// Keep track of who burned the token, and the timestamp of burning.
TokenOwnership storage currSlot = _ownerships[tokenId];
currSlot.addr = from;
currSlot.startTimestamp = uint64(block.timestamp);
currSlot.burned = true;
// If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
TokenOwnership storage nextSlot = _ownerships[nextTokenId];
if (nextSlot.addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId != _currentIndex) {
nextSlot.addr = from;
nextSlot.startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
// Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
unchecked {
_burnCounter++;
}
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
* And also called before burning one token.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, `tokenId` will be burned by `from`.
* - `from` and `to` are never both zero.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
* And also called after one token has been burned.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` has been
* transferred to `to`.
* - When `from` is zero, `tokenId` has been minted for `to`.
* - When `to` is zero, `tokenId` has been burned by `from`.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
} | Use with caution may run out of gas | function walletOfOwner(address _owner) public view returns (uint256[] memory) {
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount);
uint256 currentTokenId = 0;
uint256 ownedTokenIndex = 0;
while (ownedTokenIndex < ownerTokenCount && currentTokenId < maxSupply) {
address currentTokenOwner = ownerOf(currentTokenId);
if (currentTokenOwner == _owner) {
ownedTokenIds[ownedTokenIndex] = currentTokenId;
ownedTokenIndex++;
}
currentTokenId++;
}
return ownedTokenIds;
}
| 14,829,085 | [
1,
3727,
598,
3474,
1421,
2026,
1086,
596,
434,
16189,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
9230,
951,
5541,
12,
2867,
389,
8443,
13,
1071,
1476,
1135,
261,
11890,
5034,
8526,
3778,
13,
288,
203,
3639,
2254,
5034,
3410,
1345,
1380,
273,
11013,
951,
24899,
8443,
1769,
203,
3639,
2254,
5034,
8526,
3778,
16199,
1345,
2673,
273,
394,
2254,
5034,
8526,
12,
8443,
1345,
1380,
1769,
203,
3639,
2254,
5034,
23719,
548,
273,
374,
31,
203,
3639,
2254,
5034,
16199,
1345,
1016,
273,
374,
31,
203,
203,
3639,
1323,
261,
995,
329,
1345,
1016,
411,
3410,
1345,
1380,
597,
23719,
548,
411,
943,
3088,
1283,
13,
288,
203,
5411,
1758,
23719,
5541,
273,
3410,
951,
12,
2972,
1345,
548,
1769,
203,
203,
5411,
309,
261,
2972,
1345,
5541,
422,
389,
8443,
13,
288,
203,
7734,
16199,
1345,
2673,
63,
995,
329,
1345,
1016,
65,
273,
23719,
548,
31,
203,
7734,
16199,
1345,
1016,
9904,
31,
203,
5411,
289,
203,
5411,
23719,
548,
9904,
31,
203,
3639,
289,
203,
3639,
327,
16199,
1345,
2673,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x2a8b06562A455A79f7027cEd093f1E9dC0fC53B2/sources/contracts/Converter.sol | * @dev Calculate the energy for specific staked token @param history The staking history for the staked token @param multiplier The multiplier for staked token @param periodEndTime Only calculate energy generated before periodEndTime @return total energy amount for the token/ | function _calculateEnergyForToken(
Stake[] memory history,
uint256 multiplier,
uint256 periodEndTime
) internal view returns (uint256) {
uint256 total = 0;
uint256 _time = currentTime() < periodEndTime ? currentTime() : periodEndTime;
for (uint256 i = history.length; i > 0; --i) {
Stake memory stake = history[i - 1];
if (_time < stake.time) continue;
bool lastIndex = i == history.length;
uint256 elapsedTime = lastIndex ? _time.sub(stake.time) : history[i].time.sub(stake.time);
total = total.add(elapsedTime.mul(stake.amount).mul(multiplier));
}
return total.div(SECONDS_PER_DAY);
}
| 2,906,643 | [
1,
8695,
326,
12929,
364,
2923,
384,
9477,
1147,
225,
4927,
1021,
384,
6159,
4927,
364,
326,
384,
9477,
1147,
225,
15027,
1021,
15027,
364,
384,
9477,
1147,
225,
3879,
25255,
5098,
4604,
12929,
4374,
1865,
3879,
25255,
327,
2078,
12929,
3844,
364,
326,
1147,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
11162,
664,
31920,
1290,
1345,
12,
203,
3639,
934,
911,
8526,
3778,
4927,
16,
203,
3639,
2254,
5034,
15027,
16,
203,
3639,
2254,
5034,
3879,
25255,
203,
565,
262,
2713,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
2078,
273,
374,
31,
203,
203,
3639,
2254,
5034,
389,
957,
273,
6680,
1435,
411,
3879,
25255,
692,
6680,
1435,
294,
3879,
25255,
31,
203,
3639,
364,
261,
11890,
5034,
277,
273,
4927,
18,
2469,
31,
277,
405,
374,
31,
1493,
77,
13,
288,
203,
5411,
934,
911,
3778,
384,
911,
273,
4927,
63,
77,
300,
404,
15533,
203,
5411,
309,
261,
67,
957,
411,
384,
911,
18,
957,
13,
1324,
31,
203,
203,
5411,
1426,
7536,
273,
277,
422,
4927,
18,
2469,
31,
203,
5411,
2254,
5034,
9613,
950,
273,
7536,
692,
389,
957,
18,
1717,
12,
334,
911,
18,
957,
13,
294,
4927,
63,
77,
8009,
957,
18,
1717,
12,
334,
911,
18,
957,
1769,
203,
203,
5411,
2078,
273,
2078,
18,
1289,
12,
26201,
950,
18,
16411,
12,
334,
911,
18,
8949,
2934,
16411,
12,
20538,
10019,
203,
3639,
289,
203,
3639,
327,
2078,
18,
2892,
12,
11609,
67,
3194,
67,
10339,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "hardhat/console.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
import "./interface/IDebtor.sol";
import "./interface/ICreditor.sol";
import "./interface/ISwap.sol";
import "./interface/ISelfCompoundingYield.sol";
import "./interface/ITimelockRegistryUpgradeable.sol";
import "./reward/interfaces/IStakingMultiRewards.sol";
import "./inheritance/StorageV1ConsumerUpgradeable.sol";
/**
Vault is a baseAsset lender.
Vehicles are borrowers that put money to work.
The design logic of the system:
Each vault and vehicle is treated as an independent entity.
Vault is willing to lend money, but with limited trust on the vehicles
Vehicles is willing to borrow money, but only when it is beneficial to how it is using.
Vehicle can potentially borrow from multiple vaults.
Its sole purpose being making money to repay debt and share profits to all stakeholders.
The vault focuses on:
1) Deciding where the money should be lended to.
2) Liquidating the returned baseAsset to longAsset.
*/
contract VaultUpgradeable is StorageV1ConsumerUpgradeable, ERC20Upgradeable, ICreditor {
using SafeERC20Upgradeable for IERC20Upgradeable;
using SafeMathUpgradeable for uint256;
using MathUpgradeable for uint256;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
event Deposit(address indexed _who, uint256 _amount);
event Withdraw(address indexed _who, uint256 _amount);
event Longed(uint256 totalDeposit, uint256 baseProfit, uint256 longedProfit);
event WithdrawFeeUpdated(uint256 _withdrawFeeRatio, uint256 _withdrawalFeeHalfDecayPeriod, uint256 _withdrawalFeeWaivedPeriod);
// Vault lends, vehicle borrows
// governance/admin to decide the maximum funds that could be invested
// in an IV.
// Operator push and pull the funds arbitrarily within these boundaries.
// That makes it easier to decentralize Operator.
struct VehicleInfo {
// Debt related
uint256 baseAssetDebt; // the amount of baseAsset that was borrowed by the vehicle
// how much the vault is willing to lend
bool disableBorrow; // if the vehicle can continue to borrow assets
uint256 lendMaxBps; // the vault is willing to lend `min(lendRatioNum * totalBaseAsset, borrowCap)`
uint256 lendCap; // the maximum amount that the vault is willing to lend to the vehicle
}
// users deposit baseAsset
// the accrued interest is returned with longAsset
address public baseAsset;
address public longAsset;
// if `selfCompoundingLongAsset` is address(0),
// then it is not self compounding, we distribute long asset to the pool as it is
address public selfCompoundingLongAsset;
// vehicle
mapping (address => VehicleInfo) public vInfo;
// We disable deposit and withdraw in the same block by default to prevent attacks
// However, we could allow it after the external protocol behaviour has been verified
mapping(address => bool) public flashDepositAndWithdrawAllowed;
mapping(address => uint256) public lastActivityBlock;
// By default, there is a withdrawal fee applied on users
// This flag allows us to exempt withdrawal fees on certain addresses
// This is useful for protocol collaboration
mapping(address => bool) public noWithdrawalFee;
mapping(address => uint256) public lastFeeTime;
// An artificial cap for experimental vaults
uint256 public depositCap;
// flag that determines if there's withdrawal fee
mapping(address => uint256) public withdrawalFeeOccured;
uint256 public withdrawFeeRatio; // Disable withdrawFee for newly deposted asset if it is set to 0.
uint256 public withdrawalFeeHalfDecayPeriod; // Disable withdrawFee while withdrawing if it is set to 0.
uint256 public withdrawalFeeWaivedPeriod;
// Unit of the withdrawl fee ratio and the lending cap.
uint256 constant BPS_UNIT = 10000;
// Our withdrawal fee will decay 1/2 for every decay period
// e.g. if decay period is 2 weeks, the maximum wtihdrawal fee after two weeks is 0.5%
// after 4 weeks: 0.25%.
// Maximum cap of allowed withdrawl fee. [Unit: BPS_UNIT]
uint256 constant WITHDRAWAL_FEE_RATIO_CAP = 100; // 1% max
// Investment vehicles that generates the interest
EnumerableSetUpgradeable.AddressSet investmentVehicles;
/// True if deposit is enabled.
bool public vaultDepositEnabled;
// Address of the reward pool (StakingMultiRewardsUpgradable)
address rewardPool;
modifier ifVaultDepositEnabled() {
require(vaultDepositEnabled, "Vault: Deposit not enabled");
require(totalSupply() <= depositCap, "Vault: Deposit cap reached");
_;
}
modifier onlyDebtor() {
require(isDebtor(msg.sender), "Vault: caller is not a debtor");
_;
}
modifier flashDepositAndWithdrawDefence() {
if(!flashDepositAndWithdrawAllowed[msg.sender]){
require(lastActivityBlock[msg.sender] != block.number, "Vault: flash forbidden");
}
lastActivityBlock[msg.sender] = block.number;
_;
}
modifier timelockPassed(address iv) {
// if timelock registry is not set, then timelock is not yet activated.
if(registry() != address(0)) {
// Check the timelock if it has been enabled.
// This is present to ease initial vault deployment and setup, once a vault has been setup and linked properly
// with the IVs, then we could proceed and enable the timelock.
if(ITimelockRegistryUpgradeable(registry()).vaultTimelockEnabled(address(this))) {
require(ITimelockRegistryUpgradeable(registry()).isIVActiveForVault(address(this), iv), "Vault: IV not available yet");
}
}
_;
}
/// Checks if the target address is debtor
/// @param _target target address
/// @return true if target address is debtor, false if not
function isDebtor(address _target) public view returns(bool) {
return investmentVehicles.contains(_target);
}
/// Initializes the contract
function initialize(
address _store,
address _baseAsset,
address _longAsset,
uint256 _depositCap
) public virtual initializer {
require(_baseAsset != _longAsset, "Base asset cannot be the same as long asset");
super.initialize(_store);
baseAsset = _baseAsset;
longAsset = _longAsset;
depositCap = _depositCap;
vaultDepositEnabled = true;
// All vaults have 0 withdraw fee in the beginning.
// to facilitate kickstarting the vault
_setWihdrawFeeParameter(0, 2 weeks, 6 weeks);
__ERC20_init(
string(abi.encodePacked("lVault: ", ERC20Upgradeable(_baseAsset).name(), "=>", ERC20Upgradeable(_longAsset).name())),
string(abi.encodePacked("long_", ERC20Upgradeable(_baseAsset).symbol(), "_", ERC20Upgradeable(_longAsset).symbol()))
);
}
/// Set the reward pool for distributing the longAsset.
///
/// See Also: StakingMultiRewardsUpgradable
/// @param _rewardPool Address of the reward pool.
function setRewardPool(address _rewardPool) public adminPriviledged {
rewardPool = _rewardPool;
}
// Deposit triggers investment when the investment ratio is under some threshold
/// Deposit baseAsset into the vault
/// @param amount The amount of baseAsset deposited from the user
function deposit(uint256 amount) public virtual {
_deposit(msg.sender, msg.sender, amount);
}
/// Deposit baseAsset into the vault for targetAccount.
/// @param targetAccount Target account to deposit for
/// @param amount The amount of baseAsset deposited from the user
function depositFor(address targetAccount, uint256 amount)
public virtual
{
_deposit(msg.sender, targetAccount, amount);
}
function _deposit(address assetFrom, address shareTo, uint256 amount)
internal virtual
ifVaultDepositEnabled
flashDepositAndWithdrawDefence
{
emit Deposit(shareTo, amount);
IERC20Upgradeable(baseAsset).safeTransferFrom(
assetFrom,
address(this),
amount
);
// Any deposits would reset the deposit time to the newest
_mint(shareTo, amount);
_accountWithdrawFeeAtDeposit(shareTo, amount);
}
function _accountWithdrawFeeAtDeposit(address _who, uint256 _amount) internal {
if(!noWithdrawalFee[_who] && withdrawFeeRatio > 0) {
uint256 withdrawFeeNewlyOccured = _amount.mul(withdrawFeeRatio).div(BPS_UNIT);
withdrawalFeeOccured[_who] = withdrawlFeePending(_who).add(withdrawFeeNewlyOccured);
lastFeeTime[msg.sender] = block.timestamp;
}
}
/// Withdraw the baseAsset from the vault.
/// Always withdraws 1:1, then distributes withdrawal fee
/// because the interest has already been paid in other forms.
/// The actual amount of the baseAsset user received is subjet to the pending withdraw fee.
/// @param amount Amount of the baseAsset to be withdrawed from the vault.
function withdraw(uint256 amount) public virtual flashDepositAndWithdrawDefence {
// The withdrawal starts from the first investmentVehicle
// This implies that we have the concept of investment depth:
// The more profitable ones are the ones with higher priority
// and would keep them deeper in the stack (`i` larger means deeper)
// There MUST be at least one investmentVehicle, thus it is ok not to use SafeMath here
uint256 balance = IERC20Upgradeable(address(this)).balanceOf(msg.sender);
require(balance >= amount, "msg.sender doesn't have that much balance.");
uint256 baseAssetBalanceInVault = IERC20Upgradeable(baseAsset).balanceOf(address(this));
if (investmentVehicles.length() > 0) {
for (
uint256 i = 0; // withdraw starts from the first vehicle
i < investmentVehicles.length() && baseAssetBalanceInVault < amount; // until it reaches the end, or if we got enough
i++
) {
_withdrawFromIV(investmentVehicles.at(i), amount - baseAssetBalanceInVault);
// Update `baseAssetBalanceInVault`
baseAssetBalanceInVault = IERC20Upgradeable(baseAsset).balanceOf(address(this));
}
}
uint256 sendAmount = MathUpgradeable.min(amount, baseAssetBalanceInVault);
_withdrawSendwithFee(msg.sender, sendAmount);
emit Withdraw(msg.sender, sendAmount);
_burn(msg.sender, sendAmount);
}
function _withdrawSendwithFee(address _who, uint256 _sendAmount) internal {
uint256 _balance = IERC20Upgradeable(address(this)).balanceOf(msg.sender);
uint256 _withdrawalFeePending = withdrawlFeePending(_who);
uint256 sendAmountActual = _sendAmount;
if(_withdrawalFeePending > 0)
{
uint256 withdrawFee = _withdrawalFeePending.mul(_sendAmount).div(_balance);
withdrawalFeeOccured[_who] = _withdrawalFeePending.sub(withdrawFee);
lastFeeTime[msg.sender] = block.timestamp;
sendAmountActual = _sendAmount.sub(withdrawFee);
IERC20Upgradeable(address(baseAsset)).safeTransfer(treasury(), withdrawFee);
}
IERC20Upgradeable(address(baseAsset)).safeTransfer(_who, sendAmountActual);
}
/// Withdral all the baseAsset from an IV.
/// @param _iv Address of the IV.
function withdrawAllFromIV(address _iv) public opsPriviledged {
_withdrawFromIV(_iv, baseAssetDebtOf(_iv));
}
/// Withdral ceterain amount of the baseAsset from an IV.
/// @param _iv Address of the IV.
/// @param _amount Amount of the baseAsset to be withdrawed.
function withdrawFromIV(address _iv, uint256 _amount) public opsPriviledged {
_withdrawFromIV(_iv, _amount);
}
/// Withdral ceterain amount of the baseAsset from multiple IVs.
/// See withdrawFromIV for details.
function withdrawFromIVs(address[] memory _ivs, uint256[] memory _amounts) public opsPriviledged {
for(uint256 i = 0; i < _ivs.length; i++) {
_withdrawFromIV(_ivs[i], _amounts[i]);
}
}
/// Withdral all the baseAsset from multiple IVs.
/// See withdrawAllFromIV for details.
function withdrawAllFromIVs(address[] memory _ivs) public opsPriviledged {
for(uint256 i = 0; i < _ivs.length; i++) {
_withdrawFromIV(_ivs[i], baseAssetDebtOf(_ivs[i]));
}
}
function _withdrawFromIV(address iv, uint256 amount) internal {
uint256 beforeWithdraw = IERC20Upgradeable(baseAsset).balanceOf(address(this));
// request amount
IDebtor(iv).withdrawAsCreditor(
amount
);
// refresh balance In Vault
uint256 afterWithdraw = IERC20Upgradeable(baseAsset).balanceOf(address(this));
uint256 actuallyWithdrawn = afterWithdraw.sub(beforeWithdraw);
_accountingDebtRepayment(iv, actuallyWithdrawn);
}
function _accountingDebtRepayment(address _debtor, uint256 repaymentAmountInBase) internal {
if(repaymentAmountInBase <= vInfo[_debtor].baseAssetDebt){
vInfo[_debtor].baseAssetDebt = (vInfo[_debtor].baseAssetDebt).sub(repaymentAmountInBase);
} else {
// this handles the anomaly case where we got more repayment than the debt.
vInfo[_debtor].baseAssetDebt = 0;
}
}
function _accountingFundsLendingOut(address _debtor, uint256 _fundsSentOutInBase) internal {
vInfo[_debtor].baseAssetDebt = (vInfo[_debtor].baseAssetDebt).add(_fundsSentOutInBase);
}
/// Invest all the available baseAsset in the vault.
function investAll() public opsPriviledged {
// V1 only invests into the default vehicle `investmentVehicles[0]`
// Vault only pushes funds into the vehicle
// but the money is not really at work, real investment has to
// happen under the hood
uint256 allAmount = IERC20Upgradeable(address(baseAsset)).balanceOf(address(this));
_investTo(investmentVehicles.at(0), allAmount);
}
/// Invest certain amount of the baseAsset in the vault to an IV.
/// @param _target Address of the IV.
/// @param _amount Amount of the baseAsset to be invested.
function investTo(address _target, uint256 _amount) public opsPriviledged {
_investTo(_target, _amount);
}
/// Invest certain amount of the baseAsset in the vault to multiple IVs.
function investToIVs(address[] memory _targets, uint256[] memory _amounts) public opsPriviledged {
for(uint256 i = 0 ; i < _targets.length; i++) {
_investTo(_targets[i], _amounts[i]);
}
}
/// Migrate certain amount of the baseAsset from one IV to another.
/// @param _fromIv Address of the source IV.
/// @param _toIv Address of the destination IV.
/// @param _pullAmount Amount of the baseAsset to be pulled out from old IV.
/// @param _pushAmount Amount of the baseAsset to be pushed into the new IV.
function migrateFunds(address _fromIv, address _toIv, uint256 _pullAmount, uint256 _pushAmount) public opsPriviledged {
_withdrawFromIV(_fromIv, _pullAmount);
_investTo(_toIv, _pushAmount);
}
/// Calculate the lending capacity of an IV.
/// This vault cannot lend baseAsset with amount more than the lending capacity.
/// @param _target Address of the IV.
/// @return Return the lending capacity. (Unit: BPS_UNIT)
function effectiveLendCapacity(address _target) public view returns (uint256) {
// totalSupply is the amount of baseAsset the vault holds
uint256 capByRatio = totalSupply().mul(vInfo[_target].lendMaxBps).div(BPS_UNIT);
return MathUpgradeable.min(
vInfo[_target].lendCap, // hard cap
capByRatio
);
}
function _investTo(address _target, uint256 _maxAmountBase) internal virtual returns(uint256){
require(isDebtor(_target), "Vault: investment vehicle not registered");
// The maximum amount that we will attempt to lend out will be the min of
// the provided argument and the effective lend cap
_maxAmountBase = MathUpgradeable.min(effectiveLendCapacity(_target), _maxAmountBase);
IERC20Upgradeable(address(baseAsset)).safeApprove(_target, 0);
IERC20Upgradeable(address(baseAsset)).safeApprove(_target, _maxAmountBase);
uint256 baseBefore = IERC20Upgradeable(address(baseAsset)).balanceOf(address(this));
uint256 reportInvested = IDebtor(address(_target)).askToInvestAsCreditor(
_maxAmountBase
);
uint256 baseAfter = IERC20Upgradeable(address(baseAsset)).balanceOf(address(this));
uint256 actualInvested = baseBefore.sub(baseAfter);
require(actualInvested == reportInvested, "Vault: report invested != actual invested");
IERC20Upgradeable(address(baseAsset)).safeApprove(_target, 0);
_accountingFundsLendingOut(_target, actualInvested);
return actualInvested;
}
/// Add an investment vehicle.
/// @param newVehicle Address of the new IV.
/// @param _lendMaxBps Lending capacity of the IV in ratio.
/// @param _lendCap Lending capacity of the IV.
function addInvestmentVehicle(
address newVehicle,
uint256 _lendMaxBps,
uint256 _lendCap
) public adminPriviledged timelockPassed(newVehicle) returns(uint256) {
require(!isDebtor(newVehicle),
"vehicle already registered");
vInfo[newVehicle] = VehicleInfo({
baseAssetDebt: 0,
disableBorrow: false, // borrow is enabled by default
lendMaxBps: _lendMaxBps,
lendCap: _lendCap
});
investmentVehicles.add(newVehicle);
}
/// This moves an IV to the lowest withdraw priority.
/// @param iv Address of the IV.
function moveInvestmentVehicleToLowestPriority(
address iv
) external adminPriviledged {
require(isDebtor(iv));
// This is done by removing iv from the list and re-adding it back.
// After that, the iv will be at the end of the list.
investmentVehicles.remove(iv);
investmentVehicles.add(iv);
}
/// Remove an IV from the vault.
/// @param _target Address of the IV.
function removeInvestmentVehicle(address _target) public adminPriviledged {
require(vInfo[_target].baseAssetDebt == 0, "cannot remove vehicle with nonZero debt");
investmentVehicles.remove(_target);
}
/// @return Return the number of the IVs added to this vault.
function investmentVehiclesLength() public view returns(uint256) {
return investmentVehicles.length();
}
/// @param idx Index of the IV.
/// @return Return the address of an IV.
function getInvestmentVehicle(uint256 idx) public view returns(address) {
return investmentVehicles.at(idx);
}
/// @param _iv Address of the IV.
/// @return Return the debt (in baseAsset) of an IV
function baseAssetDebtOf(address _iv) public view returns(uint256) {
return vInfo[_iv].baseAssetDebt;
}
/// Collect the interest from IVs and convert them into longAsset.
/// The converted longAsset would be distribute to user through the reward pool.
///
/// See also: StakingMultiRewardsUpgradeable
/// @param ivs List of IVs to collect interest from.
/// @param minimumLongProfit The minimum LongProfit collected.
function collectAndLong(address[] memory ivs, uint256 minimumLongProfit) public opsPriviledged virtual {
uint256 beforeBaseBalance = IERC20Upgradeable(baseAsset).balanceOf(address(this));
for(uint256 i = 0; i < ivs.length; i++){
address iv = ivs[i];
IDebtor(iv).withdrawAsCreditor( interestPendingInIV(iv) );
}
uint256 afterBaseBalance = IERC20Upgradeable(baseAsset).balanceOf(address(this));
uint256 baseProfit = afterBaseBalance.sub(beforeBaseBalance);
IERC20Upgradeable(baseAsset).safeApprove(swapCenter(), 0);
IERC20Upgradeable(baseAsset).safeApprove(swapCenter(), baseProfit);
uint256 longedProfit = ISwap(swapCenter()).swapExactTokenIn(baseAsset, longAsset, baseProfit, minimumLongProfit);
emit Longed(totalSupply(), baseProfit, longedProfit);
_distributeProfit(longedProfit);
}
function _distributeProfit(uint256 longedProfit) internal {
if(selfCompoundingLongAsset == address(0)){ // not wrapping, directly notify the reward pool
IERC20Upgradeable(longAsset).safeTransfer(rewardPool, longedProfit);
IStakingMultiRewards(rewardPool).notifyTargetRewardAmount(longAsset, longedProfit);
} else {
// we should wrap long asset to self compounding
IERC20Upgradeable(longAsset).safeApprove(selfCompoundingLongAsset, 0);
IERC20Upgradeable(longAsset).safeApprove(selfCompoundingLongAsset, longedProfit);
ISelfCompoundingYield(selfCompoundingLongAsset).deposit(longedProfit);
uint256 wrappedLongBalance = ERC20Upgradeable(selfCompoundingLongAsset).balanceOf(address(this));
// notify the wrapped long to the pool
IERC20Upgradeable(selfCompoundingLongAsset).safeTransfer(rewardPool, wrappedLongBalance);
IStakingMultiRewards(rewardPool).notifyTargetRewardAmount(selfCompoundingLongAsset, wrappedLongBalance);
}
}
/// Return the intest (profit) of the vault in an IV.
/// The interest is defined as the baseAsset balance of the vault
/// in IV minus the debt that the IV owed the vault.
/// @param iv The address of the IV.
/// @return The interest of the vault in the IV.
function interestPendingInIV(address iv) public view returns(uint256) {
uint256 balance = IDebtor(iv).baseAssetBalanceOf(address(this));
uint256 debt = vInfo[iv].baseAssetDebt;
if(balance > debt) {
return balance - debt; // No overflow problem.
} else {
return 0;
}
}
function _updateRewards(address targetAddr) internal {
require(rewardPool != address(0), "Reward pool needs to be set.");
IStakingMultiRewards(rewardPool).updateAllRewards(targetAddr);
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual override {
_updateRewards(sender);
_updateRewards(recipient);
super._transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal virtual override {
_updateRewards(account);
super._mint(account, amount);
}
function _burn(address account, uint256 amount) internal virtual override {
_updateRewards(account);
super._burn(account, amount);
}
/// Set the deposit cap.
/// @param _depositCap Deposit cap (in baseAsset) of the vault.
function setDepositCap(uint256 _depositCap) public adminPriviledged {
depositCap = _depositCap;
}
/// Set the deposit enabled flag.
/// @param _flag True if the deposit is enabled.
function setDepositEnabled(bool _flag) public adminPriviledged {
vaultDepositEnabled = _flag;
}
function setFlashDepositAndWithdrawAllowed(address[] memory _targets, bool _flag) public adminPriviledged {
for(uint256 i = 0 ; i < _targets.length; i++){
flashDepositAndWithdrawAllowed[_targets[i]] = _flag;
}
}
/// Add accounts to the no-withdrawl fee white list.
function setNoWithdrawalFee(address[] memory _targets, bool _flag) public adminPriviledged {
for(uint256 i = 0 ; i < _targets.length ; i++) {
noWithdrawalFee[_targets[i]] = _flag;
}
}
/// Set the withdraw fee parametrs.
/// See the withdraw fee documentation for more details
/// @param _withdrawFeeRatio The withdraw fee ratio. Unit: BPS_UNIT
/// @param _withdrawalFeeHalfDecayPeriod The half-decay period of the withdraw fee. [second]
/// @param _withdrawalFeeWaivedPeriod The withdraw fee waived period. [second]
function setWihdrawFeeParameter(
uint256 _withdrawFeeRatio,
uint256 _withdrawalFeeHalfDecayPeriod,
uint256 _withdrawalFeeWaivedPeriod
) external adminPriviledged {
_setWihdrawFeeParameter(_withdrawFeeRatio, _withdrawalFeeHalfDecayPeriod, _withdrawalFeeWaivedPeriod);
}
function _setWihdrawFeeParameter(
uint256 _withdrawFeeRatio,
uint256 _withdrawalFeeHalfDecayPeriod,
uint256 _withdrawalFeeWaivedPeriod
) internal {
require(_withdrawFeeRatio <= WITHDRAWAL_FEE_RATIO_CAP, "withdrawFeeRatio too large");
withdrawFeeRatio = _withdrawFeeRatio;
withdrawalFeeHalfDecayPeriod = _withdrawalFeeHalfDecayPeriod;
withdrawalFeeWaivedPeriod = _withdrawalFeeWaivedPeriod;
emit WithdrawFeeUpdated(_withdrawFeeRatio, _withdrawalFeeHalfDecayPeriod, _withdrawalFeeWaivedPeriod);
}
/// Calculate the current unsettled withdraw fee.
/// @param _who The address to calculate the fee.
/// @return fee Return the amount of the withdraw fee (as baseAsset).
function withdrawlFeePending(address _who) public view returns (uint256 fee) {
if(noWithdrawalFee[_who] || withdrawalFeeHalfDecayPeriod == 0){
return 0;
} else {
uint256 timePassed = block.timestamp.sub(lastFeeTime[_who]);
if(timePassed > withdrawalFeeWaivedPeriod) {
return 0;
} else {
// No need for safe math here.
return withdrawalFeeOccured[_who] >> (timePassed/withdrawalFeeHalfDecayPeriod);
}
}
}
/// Set the self-compounding vault for the long asset.
///
/// See also: SelfCompoundingYieldUpgradable
/// @param _selfCompoundingLong Address of the self-compounding vault.
function setLongSelfCompounding(address _selfCompoundingLong) public adminPriviledged {
selfCompoundingLongAsset = _selfCompoundingLong;
}
}
// 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: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using 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");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../GSN/ContextUpgradeable.sol";
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable {
using SafeMathUpgradeable for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../GSN/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @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);
}
}
// 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 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];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
interface IDebtor {
// Debtor should implement accounting at `withdrawAsCreditor()` and `askToInvestAsCreditor()`
function withdrawAsCreditor(uint256 _amount) external returns (uint256);
function askToInvestAsCreditor(uint256 _amount) external returns (uint256);
function baseAssetBalanceOf(
address _address
) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
interface ICreditor {
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
interface ISwap {
function swapExactTokenIn(address tokenIn, address tokenOut, uint256 amountIn, uint256 minAmountOut) external payable returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
interface ISelfCompoundingYield {
function baseAsset() external view returns (address);
function deposit(uint256 baseAmount) external;
function withdraw(uint256 shareAmount) external;
function shareToBaseAsset(uint256 share) external view returns (uint256);
function baseAssetToShare(uint256 baseAmount) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
interface ITimelockRegistryUpgradeable {
function effectiveTimelock() external view returns (uint256);
function isIVActiveGlobal(address iv) external view returns (bool);
function isIVActiveForVault(address vault, address iv) external view returns (bool);
function isIVInsuredByInsuranceVault(address vault, address iv) external view returns (bool);
function vaultTimelockEnabled(address vault) external view returns(bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.24;
// https://docs.synthetix.io/contracts/source/interfaces/istakingrewards
interface IStakingMultiRewards {
function totalSupply() external view returns(uint256);
function lastTimeRewardApplicable(address targetYield) external view returns (uint256) ;
function rewardPerToken(address targetYield) external view returns (uint256);
function earned(address targetYield, address account) external view returns(uint256);
function setRewardDistribution(address[] calldata _rewardDistributions, bool _flag) external;
function notifyTargetRewardAmount(address targetYield, uint256 reward) external;
function updateAllRewards(address targetAccount) external;
function updateReward(address targetYield, address targetAccount) external;
function getAllRewards() external;
function getAllRewardsFor(address user) external;
function getReward(address targetYield) external;
function getRewardFor(address user, address targetYield) external;
function addReward(address targetYield, uint256 duration, bool isSelfCompoundingYield) external;
function removeReward(address targetYield) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "../utilities/UnstructuredStorageWithTimelock.sol";
import "../StorageV1Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
contract StorageV1ConsumerUpgradeable is Initializable {
using UnstructuredStorageWithTimelock for bytes32;
// bytes32(uint256(keccak256("eip1967.proxy.storage")) - 1
bytes32 private constant _STORAGE_SLOT =
0x23bdfa8033717db08b14621917cfe422b93b161b8e3ef1c873d2197616ec0bb2;
modifier onlyGovernance() {
require(
msg.sender == governance(),
"StorageV1ConsumerUpgradeable: Only governance"
);
_;
}
modifier adminPriviledged() {
require(msg.sender == governance() ||
isAdmin(msg.sender),
"StorageV1ConsumerUpgradeable: not governance or admin");
_;
}
modifier opsPriviledged() {
require(msg.sender == governance() ||
isAdmin(msg.sender) ||
isOperator(msg.sender),
"StorageV1ConsumerUpgradeable: not governance or admin or operator");
_;
}
function initialize(address _store) public virtual initializer {
address curStorage = (_STORAGE_SLOT).fetchAddress();
require(
curStorage == address(0),
"StorageV1ConsumerUpgradeable: Initialized"
);
(_STORAGE_SLOT).setAddress(_store);
}
function store() public view returns (address) {
return (_STORAGE_SLOT).fetchAddress();
}
function governance() public view returns (address) {
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.governance();
}
function treasury() public view returns (address) {
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.treasury();
}
function swapCenter() public view returns (address) {
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.swapCenter();
}
function registry() public view returns (address) {
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.registry();
}
function storageFetchAddress(bytes32 key) public view returns (address) {
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.addressStorage(key);
}
function storageFetchAddressInArray(bytes32 key, uint256 index)
public
view
returns (address)
{
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.addressArrayStorage(key, index);
}
function storageFetchUint256(bytes32 key) public view returns (uint256) {
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.uint256Storage(key);
}
function storageFetchUint256InArray(bytes32 key, uint256 index)
public
view
returns (uint256)
{
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.uint256ArrayStorage(key, index);
}
function storageFetchBool(bytes32 key) public view returns (bool) {
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.boolStorage(key);
}
function storageFetchBoolInArray(bytes32 key, uint256 index)
public
view
returns (bool)
{
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.boolArrayStorage(key, index);
}
function isAdmin(address _who) public view returns (bool) {
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.isAdmin(_who);
}
function isOperator(address _who) public view returns (bool) {
StorageV1Upgradeable storageContract = StorageV1Upgradeable(store());
return storageContract.isOperator(_who);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
/**
UnstructuredStorageWithTimelock is a set of functions that facilitates setting/fetching unstructured storage
along with information of future updates and its timelock information.
For every content storage, there are two other slots that could be calculated automatically:
* Slot (The current value)
* Scheduled Slot (The future value)
* Scheduled Time (The future time)
Note that the library does NOT enforce timelock and does NOT store the timelock information.
*/
library UnstructuredStorageWithTimelock {
// This is used to calculate the time slot and scheduled content for different variables
uint256 private constant SCHEDULED_SIGNATURE = 0x111;
uint256 private constant TIMESLOT_SIGNATURE = 0xAAA;
function updateAddressWithTimelock(bytes32 _slot) internal {
require(
scheduledTime(_slot) > block.timestamp,
"Timelock has not passed"
);
setAddress(_slot, scheduledAddress(_slot));
}
function updateUint256WithTimelock(bytes32 _slot) internal {
require(
scheduledTime(_slot) > block.timestamp,
"Timelock has not passed"
);
setUint256(_slot, scheduledUint256(_slot));
}
function setAddress(bytes32 _slot, address _target) internal {
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(_slot, _target)
}
}
function fetchAddress(bytes32 _slot)
internal
view
returns (address result)
{
assembly {
result := sload(_slot)
}
}
function scheduledAddress(bytes32 _slot)
internal
view
returns (address result)
{
result = fetchAddress(scheduledContentSlot(_slot));
}
function scheduledUint256(bytes32 _slot)
internal
view
returns (uint256 result)
{
result = fetchUint256(scheduledContentSlot(_slot));
}
function setUint256(bytes32 _slot, uint256 _target) internal {
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(_slot, _target)
}
}
function fetchUint256(bytes32 _slot)
internal
view
returns (uint256 result)
{
assembly {
result := sload(_slot)
}
}
function scheduledContentSlot(bytes32 _slot)
internal
pure
returns (bytes32)
{
return
bytes32(
uint256(keccak256(abi.encodePacked(_slot, SCHEDULED_SIGNATURE)))
);
}
function scheduledTime(bytes32 _slot) internal view returns (uint256) {
return fetchUint256(scheduledTimeSlot(_slot));
}
function scheduledTimeSlot(bytes32 _slot) internal pure returns (bytes32) {
return
bytes32(
uint256(keccak256(abi.encodePacked(_slot, TIMESLOT_SIGNATURE)))
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "hardhat/console.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
contract StorageV1Upgradeable is Initializable {
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
address public proxyAdmin;
address public governance;
address public _treasury;
EnumerableSetUpgradeable.AddressSet admin;
EnumerableSetUpgradeable.AddressSet operator;
address public swapCenter;
address public registry;
bool public registryLocked;
mapping(bytes32 => address) public addressStorage;
mapping(bytes32 => address[]) public addressArrayStorage;
mapping(bytes32 => uint256) public uint256Storage;
mapping(bytes32 => uint256[]) public uint256ArrayStorage;
mapping(bytes32 => bool) public boolStorage;
mapping(bytes32 => bool[]) public boolArrayStorage;
event GovernanceChanged(address oldGov, address newGov);
event TreasuryChanged(address oldTreasury, address newTreasury);
event AdminAdded(address newAdmin);
event AdminRetired(address retiredAdmin);
event OperatorAdded(address newOperator);
event OperatorRetired(address oldOperator);
event RegistryChanged(address oldRegistry, address newRegistry);
event SwapCenterChanged(address oldSwapCenter, address newSwapCenter);
event RegistryLocked();
modifier onlyGovernance() {
require(msg.sender == governance, "StorageV1: not governance");
_;
}
modifier adminPriviledged() {
require(msg.sender == governance ||
isAdmin(msg.sender),
"StorageV1: not governance or admin");
_;
}
modifier registryNotLocked() {
require(!registryLocked, "StorageV1: registry locked");
_;
}
constructor() {
governance = msg.sender;
}
function initialize(address _governance, address _proxyAdmin) external initializer {
require(_governance != address(0), "!empty");
require(_proxyAdmin != address(0), "!empty");
governance = _governance;
proxyAdmin = _proxyAdmin;
}
function setGovernance(address _governance) external onlyGovernance {
require(_governance != address(0), "!empty");
emit GovernanceChanged(governance, _governance);
governance = _governance;
}
function treasury() external view returns (address) {
if(_treasury == address(0)) {
return governance;
} else {
return _treasury;
}
}
function setTreasury(address _newTreasury) external onlyGovernance {
require(_newTreasury != address(0));
emit TreasuryChanged(_treasury, _newTreasury);
_treasury = _newTreasury;
}
function setRegistry(address _registry) external onlyGovernance registryNotLocked {
require(_registry != address(0), "!empty");
emit RegistryChanged(registry, _registry);
registry = _registry;
}
function lockRegistry() external onlyGovernance {
emit RegistryLocked();
registryLocked = true;
// While the contract doesn't provide an unlock method
// It is still possible to unlock this via Timelock, by upgrading the
// implementation of the Timelock proxy.
}
function setSwapCenter(address _swapCenter) external onlyGovernance {
emit SwapCenterChanged(swapCenter, _swapCenter);
swapCenter = _swapCenter;
}
function setAddress(bytes32 index, address _newAddr)
external
onlyGovernance
{
addressStorage[index] = _newAddr;
}
function setAddressArray(bytes32 index, address[] memory _newAddrs)
external
onlyGovernance
{
addressArrayStorage[index] = _newAddrs;
}
function setUint256(bytes32 index, uint256 _newUint256)
external
onlyGovernance
{
uint256Storage[index] = _newUint256;
}
function setUint256Array(bytes32 index, uint256[] memory _newAddrs)
external
onlyGovernance
{
uint256ArrayStorage[index] = _newAddrs;
}
function setUint256(bytes32 index, bool _newBool) external onlyGovernance {
boolStorage[index] = _newBool;
}
function setBoolArray(bytes32 index, bool[] memory _newBools)
external
onlyGovernance
{
boolArrayStorage[index] = _newBools;
}
function numOfAdmin() public view returns (uint256) {
return admin.length();
}
function numOfOperator() public view returns (uint256) {
return operator.length();
}
function getAdmin(uint256 idx) public view returns (address){
return admin.at(idx);
}
function getOperator(uint256 idx) public view returns (address){
return operator.at(idx);
}
function addAdmin(address _who) public onlyGovernance returns (bool) {
emit AdminAdded(_who);
return admin.add(_who);
}
function addOperator(address _who) public adminPriviledged returns (bool) {
emit OperatorAdded(_who);
return operator.add(_who);
}
function removeAdmin(address _who) public onlyGovernance returns (bool) {
emit AdminRetired(_who);
return admin.remove(_who);
}
function removeOperator(address _who) public adminPriviledged returns (bool) {
emit OperatorRetired(_who);
return operator.remove(_who);
}
function isAdmin(address _who) public view returns (bool) {
return admin.contains(_who);
}
function isOperator(address _who) public view returns (bool) {
return operator.contains(_who);
}
}
| By default, there is a withdrawal fee applied on users This flag allows us to exempt withdrawal fees on certain addresses This is useful for protocol collaboration | mapping(address => bool) public noWithdrawalFee;
| 276,837 | [
1,
858,
805,
16,
1915,
353,
279,
598,
9446,
287,
14036,
6754,
603,
3677,
1220,
2982,
5360,
584,
358,
431,
5744,
598,
9446,
287,
1656,
281,
603,
8626,
6138,
1220,
353,
5301,
364,
1771,
21326,
22226,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
12,
2867,
516,
1426,
13,
1071,
1158,
1190,
9446,
287,
14667,
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
] |
pragma solidity ^0.4.23;
/*** @title SafeMath
* @dev https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */
library SafeMath {
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;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
interface ERC20 {
function transfer (address _beneficiary, uint256 _tokenAmount) external returns (bool);
function mintFromICO(address _to, uint256 _amount) external returns(bool);
function isWhitelisted(address wlCandidate) external returns(bool);
}
/**
* @title Ownable
* @dev https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/ownership/Ownable.sol
*/
contract Ownable {
address public owner;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
}
/**
* @title CrowdSale
* @dev https://github.com/
*/
contract OneStageMainSale is Ownable {
ERC20 public token;
ERC20 public authorize;
using SafeMath for uint;
address public backEndOperator = msg.sender;
address team = 0x7eDE8260e573d3A3dDfc058f19309DF5a1f7397E; // 33% - team и ранние инвесторы проекта
address bounty = 0x0cdb839B52404d49417C8Ded6c3E2157A06CdD37; // 2% - для баунти программы
address reserve = 0xC032D3fCA001b73e8cC3be0B75772329395caA49; // 5% - для резерва
mapping(address=>bool) public whitelist;
mapping(address => uint256) public investedEther;
uint256 public start1StageSale = 1539561601; // Monday, 15-Oct-18 00:00:01 UTC
uint256 public end1StageSale = 1542326399; // Thursday, 15-Nov-18 23:59:59 UTC
uint256 public investors; // общее количество инвесторов
uint256 public weisRaised; // общее колиество собранных Ether
uint256 public softCap1Stage = 1000000*1e18; // $2,600,000 = 1,000,000 INM
uint256 public hardCap1Stage = 1700000*1e18; // 1,700,000 INM = $4,420,000 USD
uint256 public buyPrice; // 2.6 USD
uint256 public dollarPrice; // Ether by USD
uint256 public soldTokens; // solded tokens - > 1,700,000 INM
event Authorized(address wlCandidate, uint timestamp);
event Revoked(address wlCandidate, uint timestamp);
event UpdateDollar(uint256 time, uint256 _rate);
modifier backEnd() {
require(msg.sender == backEndOperator || msg.sender == owner);
_;
}
// конструктор контракта
constructor(ERC20 _token, ERC20 _authorize, uint256 usdETH) public {
token = _token;
authorize = _authorize;
dollarPrice = usdETH;
buyPrice = (1e17/dollarPrice)*26; // 2.60 usd
}
// изменение даты начала предварительной распродажи
function setStartOneSale(uint256 newStart1Sale) public onlyOwner {
start1StageSale = newStart1Sale;
}
// изменение даты окончания предварительной распродажи
function setEndOneSale(uint256 newEnd1Sale) public onlyOwner {
end1StageSale = newEnd1Sale;
}
// Изменение адреса оператора бекэнда
function setBackEndAddress(address newBackEndOperator) public onlyOwner {
backEndOperator = newBackEndOperator;
}
// Изменение курса доллра к эфиру
function setBuyPrice(uint256 _dollar) public backEnd {
dollarPrice = _dollar;
buyPrice = (1e17/dollarPrice)*26; // 2.60 usd
emit UpdateDollar(now, dollarPrice);
}
/*******************************************************************************
* Payable's section
*/
function isOneStageSale() public constant returns(bool) {
return now >= start1StageSale && now <= end1StageSale;
}
// callback функция контракта
function () public payable {
require(authorize.isWhitelisted(msg.sender));
require(isOneStageSale());
require(msg.value >= 19*buyPrice); // ~ 50 USD
SaleOneStage(msg.sender, msg.value);
require(soldTokens<=hardCap1Stage);
investedEther[msg.sender] = investedEther[msg.sender].add(msg.value);
}
// выпуск токенов в период предварительной распродажи
function SaleOneStage(address _investor, uint256 _value) internal {
uint256 tokens = _value.mul(1e18).div(buyPrice);
uint256 tokensByDate = tokens.div(10);
uint256 bonusSumTokens = tokens.mul(bonusSum(tokens)).div(100);
tokens = tokens.add(tokensByDate).add(bonusSumTokens); // 60%
token.mintFromICO(_investor, tokens);
soldTokens = soldTokens.add(tokens);
uint256 tokensTeam = tokens.mul(11).div(20); // 33 %
token.mintFromICO(team, tokensTeam);
uint256 tokensBoynty = tokens.div(30); // 2 %
token.mintFromICO(bounty, tokensBoynty);
uint256 tokensReserve = tokens.div(12); // 5 %
token.mintFromICO(reserve, tokensReserve);
weisRaised = weisRaised.add(_value);
}
function bonusSum(uint256 _amount) pure private returns(uint256) {
if (_amount > 76923*1e18) { // 200k+ 10% INMCoin
return 10;
} else if (_amount > 19230*1e18) { // 50k - 200k 7% INMCoin
return 7;
} else if (_amount > 7692*1e18) { // 20k - 50k 5% INMCoin
return 5;
} else if (_amount > 1923*1e18) { // 5k - 20k 3% INMCoin
return 3;
} else {
return 0;
}
}
// Отправка эфира с контракта
function transferEthFromContract(address _to, uint256 amount) public onlyOwner {
_to.transfer(amount);
}
/*******************************************************************************
* Refundable
*/
function refund1ICO() public {
require(soldTokens < softCap1Stage && now > end1StageSale);
uint rate = investedEther[msg.sender];
require(investedEther[msg.sender] >= 0);
investedEther[msg.sender] = 0;
msg.sender.transfer(rate);
weisRaised = weisRaised.sub(rate);
}
} | изменение даты начала предварительной распродажи | function setStartOneSale(uint256 newStart1Sale) public onlyOwner {
start1StageSale = newStart1Sale;
}
| 5,496,748 | [
1,
145,
121,
145,
120,
145,
125,
145,
118,
145,
126,
145,
118,
145,
126,
145,
121,
145,
118,
225,
145,
117,
145,
113,
146,
229,
146,
238,
225,
145,
126,
145,
113,
146,
234,
145,
113,
145,
124,
145,
113,
225,
145,
128,
146,
227,
145,
118,
145,
117,
145,
115,
145,
113,
146,
227,
145,
121,
146,
229,
145,
118,
145,
124,
146,
239,
145,
126,
145,
127,
145,
122,
225,
146,
227,
145,
113,
146,
228,
145,
128,
146,
227,
145,
127,
145,
117,
145,
113,
145,
119,
145,
121,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
18171,
3335,
30746,
12,
11890,
5034,
394,
1685,
21,
30746,
13,
1071,
1338,
5541,
288,
203,
3639,
787,
21,
8755,
30746,
273,
394,
1685,
21,
30746,
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
] |
./full_match/73799/0xb5fF083230fa8f6241Bc17F5ca8cc1D3FB3fDBD7/sources/contracts/libraries/LibReward.sol | * @notice Error message thrown when trying to pay rewards while rewards are disabled/ | error RewardsDisabled();
| 16,362,037 | [
1,
668,
883,
6718,
1347,
8374,
358,
8843,
283,
6397,
1323,
283,
6397,
854,
5673,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
555,
534,
359,
14727,
8853,
5621,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/******************************************/
/* KeeperCompatibleInterface starts here */
/******************************************/
interface KeeperCompatibleInterface {
/**
* @notice checks if the contract requires work to be done.
* @param checkData data passed to the contract when checking for upkeep.
* @return upkeepNeeded boolean to indicate whether the keeper should call
* performUpkeep or not.
* @return performData bytes that the keeper should call performUpkeep with,
* if upkeep is needed.
*/
function checkUpkeep(
bytes calldata checkData
)
external
returns (
bool upkeepNeeded,
bytes memory performData
);
/**
* @notice Performs work on the contract. Executed by the keepers, via the registry.
* @param performData is the data which was passed back from the checkData
* simulation.
*/
function performUpkeep(
bytes calldata performData
) external;
}
/******************************************/
/* ChainlinkRequestInterface starts here */
/******************************************/
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;
}
/******************************************/
/* OracleInterface starts here */
/******************************************/
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
);
}
/******************************************/
/* OperatorInterface starts here */
/******************************************/
interface OperatorInterface is OracleInterface, ChainlinkRequestInterface {
function requestOracleData(
address sender,
uint256 payment,
bytes32 specId,
address callbackAddress,
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,
uint[] calldata amounts
)
external
payable;
function getAuthorizedSenders()
external
returns (
address[] memory
);
function setAuthorizedSenders(
address[] calldata senders
) external;
function getForwarder()
external
returns (
address
);
}
/******************************************/
/* PointerInterface starts here */
/******************************************/
interface PointerInterface {
function getAddress()
external
view
returns (
address
);
}
/******************************************/
/* LinkTokenInterface starts here */
/******************************************/
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
);
}
/******************************************/
/* ENSResolver starts here */
/******************************************/
abstract contract ENSResolver_Chainlink {
function addr(
bytes32 node
)
public
view
virtual
returns (
address
);
}
/******************************************/
/* ENSInterface starts here */
/******************************************/
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
);
}
/******************************************/
/* BufferChainlink starts here */
/******************************************/
/**
* @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;
uint 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,
uint 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,
uint capacity
)
private
pure
{
bytes memory oldbuf = buf.buf;
init(buf, capacity);
append(buf, oldbuf);
}
function max(
uint a,
uint b
)
private
pure
returns(
uint
)
{
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,
uint off,
bytes memory data,
uint len
)
internal
pure
returns(
buffer memory
)
{
require(len <= data.length);
if (off + len > buf.capacity) {
resize(buf, max(buf.capacity, len + off) * 2);
}
uint dest;
uint 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
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
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,
uint 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,
uint 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,
uint off,
bytes32 data,
uint len
)
private
pure
returns(
buffer memory
)
{
if (len + off > buf.capacity) {
resize(buf, (len + off) * 2);
}
uint 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,
uint 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,
uint off,
uint data,
uint len
)
private
pure
returns(
buffer memory
)
{
if (len + off > buf.capacity) {
resize(buf, (len + off) * 2);
}
uint 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,
uint data,
uint len
)
internal
pure
returns(
buffer memory
)
{
return writeInt(buf, buf.buf.length, data, len);
}
}
/******************************************/
/* CBORChainlink starts here */
/******************************************/
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 encodeType(
BufferChainlink.buffer memory buf,
uint8 major,
uint 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 if(value <= 0xFFFFFFFFFFFFFFFF) {
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
{
encodeType(buf, MAJOR_TYPE_INT, value);
}
function encodeInt(
BufferChainlink.buffer memory buf,
int value
)
internal
pure
{
if(value < -0x10000000000000000) {
encodeSignedBigNum(buf, value);
} else if(value > 0xFFFFFFFFFFFFFFFF) {
encodeBigNum(buf, value);
} else if(value >= 0) {
encodeType(buf, MAJOR_TYPE_INT, uint(value));
} else {
encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value));
}
}
function encodeBytes(
BufferChainlink.buffer memory buf,
bytes memory value
)
internal
pure
{
encodeType(buf, MAJOR_TYPE_BYTES, value.length);
buf.append(value);
}
function encodeBigNum(
BufferChainlink.buffer memory buf,
int value
)
internal
pure
{
buf.appendUint8(uint8((MAJOR_TYPE_TAG << 5) | TAG_TYPE_BIGNUM));
encodeBytes(buf, abi.encode(uint(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(uint(-1 - input)));
}
function encodeString(
BufferChainlink.buffer memory buf,
string memory value
)
internal
pure
{
encodeType(buf, MAJOR_TYPE_STRING, 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);
}
}
/******************************************/
/* Chainlink starts here */
/******************************************/
/**
* @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();
}
}
/******************************************/
/* ChainlinkClient starts here */
/******************************************/
/**
* @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 constant internal LINK_DIVISIBILITY = 10**18;
uint256 constant private AMOUNT_OVERRIDE = 0;
address constant private SENDER_OVERRIDE = address(0);
uint256 constant private ORACLE_ARGS_VERSION = 1;
uint256 constant private OPERATOR_ARGS_VERSION = 2;
bytes32 constant private ENS_TOKEN_SUBNAME = keccak256("link");
bytes32 constant private ENS_ORACLE_SUBNAME = keccak256("oracle");
address constant private LINK_TOKEN_POINTER = 0xC89bD4E1632D3A43CB03AAAd5262cbe4038Bc571;
ENSInterface private ens;
bytes32 private ensNode;
LinkTokenInterface private link;
OperatorInterface private oracle;
uint256 private requestCount = 1;
mapping(bytes32 => address) private 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 callbackAddress The callback address that the response will be sent to
* @param callbackFunctionSignature The callback function signature to use for the callback address
* @return A Chainlink Request struct in memory
*/
function buildChainlinkRequest(
bytes32 specId,
address callbackAddress,
bytes4 callbackFunctionSignature
)
internal
pure
returns (
Chainlink.Request memory
)
{
Chainlink.Request memory req;
return req.initialize(specId, callbackAddress, 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(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
)
{
return rawRequest(oracleAddress, req, payment, ORACLE_ARGS_VERSION, oracle.oracleRequest.selector);
}
/**
* @notice Creates a Chainlink request to the stored oracle address
* @dev This function supports multi-word response
* @dev Calls `requestOracleDataFrom` 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 requestOracleData(
Chainlink.Request memory req,
uint256 payment
)
internal
returns (
bytes32
)
{
return requestOracleDataFrom(address(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 requestOracleDataFrom(
address oracleAddress,
Chainlink.Request memory req,
uint256 payment
)
internal
returns (
bytes32 requestId
)
{
return rawRequest(oracleAddress, req, payment, OPERATOR_ARGS_VERSION, oracle.requestOracleData.selector);
}
/**
* @notice Make a request to an oracle
* @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
* @param argsVersion The version of data support (single word, multi word)
* @return requestId The request ID
*/
function rawRequest(
address oracleAddress,
Chainlink.Request memory req,
uint256 payment,
uint256 argsVersion,
bytes4 funcSelector
)
private
returns (
bytes32 requestId
)
{
requestId = keccak256(abi.encodePacked(this, requestCount));
req.nonce = requestCount;
pendingRequests[requestId] = oracleAddress;
emit ChainlinkRequested(requestId);
bytes memory encodedData = abi.encodeWithSelector(
funcSelector,
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.callbackAddress,
req.callbackFunctionId,
req.nonce,
argsVersion,
req.buf.buf);
require(link.transferAndCall(oracleAddress, payment, encodedData), "unable to transferAndCall to oracle");
requestCount += 1;
}
/**
* @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(pendingRequests[requestId]);
delete pendingRequests[requestId];
emit ChainlinkCancelled(requestId);
requested.cancelOracleRequest(requestId, payment, callbackFunc, expiration);
}
/**
* @notice Sets the stored oracle address
* @param oracleAddress The address of the oracle contract
*/
function setChainlinkOracle(
address oracleAddress
)
internal
{
oracle = OperatorInterface(oracleAddress);
}
/**
* @notice Sets the LINK token address
* @param linkAddress The address of the LINK token contract
*/
function setChainlinkToken(
address linkAddress
)
internal
{
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(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(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)
{
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
{
ens = ENSInterface(ensAddress);
ensNode = node;
bytes32 linkSubnode = keccak256(abi.encodePacked(ensNode, ENS_TOKEN_SUBNAME));
ENSResolver_Chainlink resolver = ENSResolver_Chainlink(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(ensNode, ENS_ORACLE_SUBNAME));
ENSResolver_Chainlink resolver = ENSResolver_Chainlink(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 == pendingRequests[requestId],
"Source must be the oracle of the request");
delete 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(pendingRequests[requestId] == address(0), "Request is already pending");
_;
}
}
/******************************************/
/* IERC20 starts here */
/******************************************/
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/******************************************/
/* Context starts here */
/******************************************/
// File: @openzeppelin/contracts/GSN/Context.sol
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with 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 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;
}
}
/******************************************/
/* Ownable starts here */
/******************************************/
// File: @openzeppelin/contracts/access/Ownable.sol
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view 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;
}
}
/******************************************/
/* Benchmark starts here */
/******************************************/
abstract contract Benchmark
{
function rebase(uint256 supplyDelta, bool increaseSupply) external virtual returns (uint256);
function totalSupply() external virtual view returns (uint256);
}
/******************************************/
/* BenchmarkSync starts here */
/******************************************/
abstract contract Sync
{
function syncPools() external virtual;
}
/******************************************/
/* KeeperRebase starts here */
/******************************************/
contract KeeperRebase is KeeperCompatibleInterface, ChainlinkClient, Ownable {
using Chainlink for Chainlink.Request;
uint256 public FEE = 1 * 10 ** 18;
bytes32 public JOBID = bytes32("2bde90044c644ac192cc015c9274d870");
address public constant LINK = 0x514910771AF9Ca656af840dff83E8264EcF986CA;
address public constant ORACLE = 0x049Bd8C3adC3fE7d3Fc2a44541d955A537c2A484;
Benchmark public constant BENCHMARK = Benchmark(0x67c597624B17b16fb77959217360B7cD18284253);
Sync public SYNC = Sync(0x4C3aA5160aE34210CC5B783Cd642e4bAACF34b40);
uint256 public keeperInterval;
uint256 public lastRebase;
int256 public latestPrice;
int256 public targetPrice;
bool public rebaseActive;
event UpkeepPerformed();
event RebasePerformed(uint256 supplyDelta, bool increaseSupply);
constructor() {
setChainlinkToken(LINK);
setChainlinkOracle(ORACLE);
lastRebase = block.timestamp;
}
/******************************************/
/* Administration starts here */
/******************************************/
function setJobId(bytes32 _jobId) external onlyOwner {
JOBID = _jobId;
}
function setFee(uint256 _fee) external onlyOwner {
FEE = _fee;
}
function setKeeperInterval(uint256 _interval) external onlyOwner {
keeperInterval = _interval;
}
function setTargetPrice(int256 _targetPrice) external onlyOwner {
targetPrice = _targetPrice;
}
function setSyncContract(address _sync) external onlyOwner {
SYNC = Sync(_sync);
}
function setRebaseActive(bool _active) external onlyOwner {
rebaseActive = _active;
}
/******************************************/
/* KeeperNetwork starts here */
/******************************************/
function checkUpkeep(bytes calldata checkData) external override returns (bool upkeepNeeded, bytes memory performData) {
upkeepNeeded = (block.timestamp - lastRebase) > keeperInterval;
}
function performUpkeep(bytes calldata performData) external override {
require((block.timestamp - lastRebase) > keeperInterval, "Too soon.");
lastRebase = block.timestamp;
initiateRebase();
emit UpkeepPerformed();
}
/******************************************/
/* MARK Oracle starts here */
/******************************************/
function abs(int x) private pure returns (int) {
return x >= 0 ? x : -x;
}
function initiatePublicRebase() external {
IERC20(LINK).transferFrom(msg.sender, address(this), FEE);
initiateRebase();
}
function initiateRebase() internal {
sendChainlinkRequest(buildChainlinkRequest(JOBID, address(this), this.rebaseCallback.selector), FEE);
}
function rebaseCallback(bytes32 _requestId, uint256 _price) external {
validateChainlinkCallback(_requestId);
latestPrice = int(_price);
int256 rebasePercentage = (latestPrice - targetPrice) * 1e18 / targetPrice;
uint256 absolutePercentage = uint256(abs(rebasePercentage));
uint256 supplyDelta = BENCHMARK.totalSupply() * absolutePercentage / 1e18;
bool increaseSupply = rebasePercentage >= 0 ? true : false;
if (rebaseActive == true) {
BENCHMARK.rebase(supplyDelta, increaseSupply);
SYNC.syncPools();
}
emit RebasePerformed(supplyDelta, increaseSupply);
}
} | * @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
)
{
return rawRequest(oracleAddress, req, payment, ORACLE_ARGS_VERSION, oracle.oracleRequest.selector);
}
| 487,322 | [
1,
2729,
279,
7824,
1232,
590,
358,
326,
1269,
20865,
1758,
225,
31902,
471,
9064,
279,
590,
1599,
16,
17071,
326,
1191,
7448,
16,
471,
4692,
1375,
13866,
1876,
1477,
68,
358,
1366,
22926,
1492,
3414,
279,
590,
603,
326,
1018,
20865,
6835,
18,
7377,
1282,
7824,
1232,
11244,
871,
18,
225,
20865,
1887,
1021,
1758,
434,
326,
20865,
364,
326,
590,
225,
1111,
1021,
6454,
7824,
1232,
1567,
225,
5184,
1021,
3844,
434,
22926,
358,
1366,
364,
326,
590,
327,
14459,
1021,
590,
1599,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
225,
445,
1366,
3893,
1232,
691,
774,
12,
203,
565,
1758,
20865,
1887,
16,
203,
565,
7824,
1232,
18,
691,
3778,
1111,
16,
203,
565,
2254,
5034,
5184,
203,
225,
262,
203,
565,
2713,
203,
565,
1135,
261,
203,
1377,
1731,
1578,
14459,
203,
565,
262,
203,
225,
288,
203,
565,
327,
1831,
691,
12,
280,
16066,
1887,
16,
1111,
16,
5184,
16,
4869,
2226,
900,
67,
22439,
67,
5757,
16,
20865,
18,
280,
16066,
691,
18,
9663,
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
] |
pragma solidity ^0.4.18;
/**
* Math operations with safety checks that throw on error
*/
contract SafeMath {
function safeMul(uint256 a, uint256 b) public pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint256 a, uint256 b) public pure returns (uint256) {
//assert(a > 0);// Solidity automatically throws when dividing by 0
//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;
}
function safeSub(uint256 a, uint256 b) public pure returns (uint256) {
assert(b <= a);
return a - b;
}
function safeAdd(uint256 a, uint256 b) public pure returns (uint256) {
uint256 c = a + b;
assert(c>=a && c>=b);
return c;
}
}
/*
* ERC20 interface
* see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
function totalSupply() public constant returns (uint256);
function balanceOf(address _owner) public constant returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint256);
/* ERC20 Events */
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract ContractReceiver {
function tokenFallback(address _from, uint256 _value, bytes _data) public;
}
contract ERC223 is ERC20 {
function transfer(address _to, uint256 _value, bytes _data) public returns (bool success);
function transfer(address _to, uint256 _value, bytes _data, string _custom_fallback) public returns (bool success);
/* ERC223 Events */
event Transfer(address indexed _from, address indexed _to, uint256 _value, bytes _data);
}
contract BankeraToken is ERC223, SafeMath {
string public constant name = "Banker Token"; // Set the name for display purposes
string public constant symbol = "BNK"; // Set the symbol for display purposes
uint8 public constant decimals = 8; // Amount of decimals for display purposes
uint256 private issued = 0; // tokens count issued to addresses
uint256 private totalTokens = 25000000000 * 100000000; //25,000,000,000.0000 0000 BNK
address private contractOwner;
address private rewardManager;
address private roundManager;
address private issueManager;
uint64 public currentRound = 0;
bool public paused = false;
mapping (uint64 => Reward) public reward; //key - round, value - reward in round
mapping (address => AddressBalanceInfoStructure) public accountBalances; //key - address, value - address balance info
mapping (uint64 => uint256) public issuedTokensInRound; //key - round, value - issued tokens
mapping (address => mapping (address => uint256)) internal allowed;
uint256 public blocksPerRound; // blocks per round
uint256 public lastBlockNumberInRound;
struct Reward {
uint64 roundNumber;
uint256 rewardInWei;
uint256 rewardRate; //reward rate in wei. 1 sBNK - xxx wei
bool isConfigured;
}
struct AddressBalanceInfoStructure {
uint256 addressBalance;
mapping (uint256 => uint256) roundBalanceMap; //key - round number, value - total token amount in round
mapping (uint64 => bool) wasModifiedInRoundMap; //key - round number, value - is modified in round
uint64[] mapKeys; //round balance map keys
uint64 claimedRewardTillRound;
uint256 totalClaimedReward;
}
/* Initializes contract with initial blocks per round number*/
function BankeraToken(uint256 _blocksPerRound, uint64 _round) public {
contractOwner = msg.sender;
lastBlockNumberInRound = block.number;
blocksPerRound = _blocksPerRound;
currentRound = _round;
}
function() public whenNotPaused payable {
}
// Public functions
/**
* @dev Reject all ERC223 compatible tokens
* @param _from address The address that is transferring the tokens
* @param _value uint256 the amount of the specified token
* @param _data Bytes The data passed from the caller.
*/
function tokenFallback(address _from, uint256 _value, bytes _data) public whenNotPaused view {
revert();
}
function setReward(uint64 _roundNumber, uint256 _roundRewardInWei) public whenNotPaused onlyRewardManager {
isNewRound();
Reward storage rewardInfo = reward[_roundNumber];
//validations
assert(rewardInfo.roundNumber == _roundNumber);
assert(!rewardInfo.isConfigured); //allow just not configured reward configuration
rewardInfo.rewardInWei = _roundRewardInWei;
if(_roundRewardInWei > 0){
rewardInfo.rewardRate = safeDiv(_roundRewardInWei, issuedTokensInRound[_roundNumber]);
}
rewardInfo.isConfigured = true;
}
/* Change contract owner */
function changeContractOwner(address _newContractOwner) public onlyContractOwner {
isNewRound();
if (_newContractOwner != contractOwner) {
contractOwner = _newContractOwner;
} else {
revert();
}
}
/* Change reward contract owner */
function changeRewardManager(address _newRewardManager) public onlyContractOwner {
isNewRound();
if (_newRewardManager != rewardManager) {
rewardManager = _newRewardManager;
} else {
revert();
}
}
/* Change round contract owner */
function changeRoundManager(address _newRoundManager) public onlyContractOwner {
isNewRound();
if (_newRoundManager != roundManager) {
roundManager = _newRoundManager;
} else {
revert();
}
}
/* Change issue contract owner */
function changeIssueManager(address _newIssueManager) public onlyContractOwner {
isNewRound();
if (_newIssueManager != issueManager) {
issueManager = _newIssueManager;
} else {
revert();
}
}
function setBlocksPerRound(uint64 _newBlocksPerRound) public whenNotPaused onlyRoundManager {
blocksPerRound = _newBlocksPerRound;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyContractOwner whenNotPaused public {
paused = true;
}
/**
* @dev called by the owner to resume, returns to normal state
*/
function resume() onlyContractOwner whenPaused public {
paused = false;
}
/**
*
* permission checker
*/
modifier onlyContractOwner() {
if(msg.sender != contractOwner){
revert();
}
_;
}
/**
* set reward for round (reward admin)
*/
modifier onlyRewardManager() {
if(msg.sender != rewardManager && msg.sender != contractOwner){
revert();
}
_;
}
/**
* adjust round length (round admin)
*/
modifier onlyRoundManager() {
if(msg.sender != roundManager && msg.sender != contractOwner){
revert();
}
_;
}
/**
* issue tokens to ETH addresses (issue admin)
*/
modifier onlyIssueManager() {
if(msg.sender != issueManager && msg.sender != contractOwner){
revert();
}
_;
}
modifier notSelf(address _to) {
if(msg.sender == _to){
revert();
}
_;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
function getRoundBalance(address _address, uint256 _round) public view returns (uint256) {
return accountBalances[_address].roundBalanceMap[_round];
}
function isModifiedInRound(address _address, uint64 _round) public view returns (bool) {
return accountBalances[_address].wasModifiedInRoundMap[_round];
}
function getBalanceModificationRounds(address _address) public view returns (uint64[]) {
return accountBalances[_address].mapKeys;
}
//action for issue tokens
function issueTokens(address _receiver, uint256 _tokenAmount) public whenNotPaused onlyIssueManager {
isNewRound();
issue(_receiver, _tokenAmount);
}
function withdrawEther() public onlyContractOwner {
isNewRound();
if(this.balance > 0) {
contractOwner.transfer(this.balance);
} else {
revert();
}
}
/* Send coins from owner to other address */
/*Override*/
function transfer(address _to, uint256 _value) public notSelf(_to) whenNotPaused returns (bool success){
require(_to != address(0));
//added due to backwards compatibility reasons
bytes memory empty;
if(isContract(_to)) {
return transferToContract(msg.sender, _to, _value, empty);
}
else {
return transferToAddress(msg.sender, _to, _value, empty);
}
}
/*Override*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return accountBalances[_owner].addressBalance;
}
/*Override*/
function totalSupply() public constant returns (uint256){
return totalTokens;
}
/**
* @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
*/
/*Override*/
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
require(_to != address(0));
require(_value <= allowed[_from][msg.sender]);
//added due to backwards compatibility reasons
bytes memory empty;
if(isContract(_to)) {
require(transferToContract(_from, _to, _value, empty));
}
else {
require(transferToAddress(_from, _to, _value, empty));
}
allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _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.
*/
/*Override*/
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
/*Override*/
function allowance(address _owner, address _spender) public view whenNotPaused returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = safeAdd(allowed[msg.sender][_spender], _addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool) {
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = safeSub(oldValue, _subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
// Function that is called when a user or another contract wants to transfer funds .
/*Override*/
function transfer(address _to, uint256 _value, bytes _data) public whenNotPaused notSelf(_to) returns (bool success){
require(_to != address(0));
if(isContract(_to)) {
return transferToContract(msg.sender, _to, _value, _data);
}
else {
return transferToAddress(msg.sender, _to, _value, _data);
}
}
// Function that is called when a user or another contract wants to transfer funds.
/*Override*/
function transfer(address _to, uint256 _value, bytes _data, string _custom_fallback) public whenNotPaused notSelf(_to) returns (bool success){
require(_to != address(0));
if(isContract(_to)) {
if(accountBalances[msg.sender].addressBalance < _value){ // Check if the sender has enough
revert();
}
if(safeAdd(accountBalances[_to].addressBalance, _value) < accountBalances[_to].addressBalance){ // Check for overflows
revert();
}
isNewRound();
subFromAddressBalancesInfo(msg.sender, _value); // Subtract from the sender
addToAddressBalancesInfo(_to, _value); // Add the same to the recipient
assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data));
/* Notify anyone listening that this transfer took place */
Transfer(msg.sender, _to, _value, _data);
Transfer(msg.sender, _to, _value);
return true;
}
else {
return transferToAddress(msg.sender, _to, _value, _data);
}
}
function claimReward() public whenNotPaused returns (uint256 rewardAmountInWei) {
isNewRound();
return claimRewardTillRound(currentRound);
}
function claimRewardTillRound(uint64 _claimTillRound) public whenNotPaused returns (uint256 rewardAmountInWei) {
isNewRound();
rewardAmountInWei = calculateClaimableRewardTillRound(msg.sender, _claimTillRound);
accountBalances[msg.sender].claimedRewardTillRound = _claimTillRound;
if (rewardAmountInWei > 0){
accountBalances[msg.sender].totalClaimedReward = safeAdd(accountBalances[msg.sender].totalClaimedReward, rewardAmountInWei);
msg.sender.transfer(rewardAmountInWei);
}
return rewardAmountInWei;
}
function calculateClaimableReward(address _address) public constant returns (uint256 rewardAmountInWei) {
return calculateClaimableRewardTillRound(_address, currentRound);
}
function calculateClaimableRewardTillRound(address _address, uint64 _claimTillRound) public constant returns (uint256) {
uint256 rewardAmountInWei = 0;
if (_claimTillRound > currentRound) { revert(); }
if (currentRound < 1) { revert(); }
AddressBalanceInfoStructure storage accountBalanceInfo = accountBalances[_address];
if(accountBalanceInfo.mapKeys.length == 0){ revert(); }
uint64 userLastClaimedRewardRound = accountBalanceInfo.claimedRewardTillRound;
if (_claimTillRound < userLastClaimedRewardRound) { revert(); }
for (uint64 workRound = userLastClaimedRewardRound; workRound < _claimTillRound; workRound++) {
Reward storage rewardInfo = reward[workRound];
assert(rewardInfo.isConfigured); //don't allow to withdraw reward if affected reward is not configured
if(accountBalanceInfo.wasModifiedInRoundMap[workRound]){
rewardAmountInWei = safeAdd(rewardAmountInWei, safeMul(accountBalanceInfo.roundBalanceMap[workRound], rewardInfo.rewardRate));
} else {
uint64 lastBalanceModifiedRound = 0;
for (uint256 i = accountBalanceInfo.mapKeys.length; i > 0; i--) {
uint64 modificationInRound = accountBalanceInfo.mapKeys[i-1];
if (modificationInRound <= workRound) {
lastBalanceModifiedRound = modificationInRound;
break;
}
}
rewardAmountInWei = safeAdd(rewardAmountInWei, safeMul(accountBalanceInfo.roundBalanceMap[lastBalanceModifiedRound], rewardInfo.rewardRate));
}
}
return rewardAmountInWei;
}
function createRounds(uint256 maxRounds) public {
uint256 blocksAfterLastRound = safeSub(block.number, lastBlockNumberInRound); //current block number - last round block number = blocks after last round
if(blocksAfterLastRound >= blocksPerRound){ // need to increase reward round if blocks after last round is greater or equal blocks per round
uint256 roundsNeedToCreate = safeDiv(blocksAfterLastRound, blocksPerRound); //calculate how many rounds need to create
if(roundsNeedToCreate > maxRounds){
roundsNeedToCreate = maxRounds;
}
lastBlockNumberInRound = safeAdd(lastBlockNumberInRound, safeMul(roundsNeedToCreate, blocksPerRound));
for (uint256 i = 0; i < roundsNeedToCreate; i++) {
updateRoundInformation();
}
}
}
// Private functions
//assemble the given address bytecode. If bytecode exists then the _address is a contract.
function isContract(address _address) private view returns (bool is_contract) {
uint256 length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_address)
}
return (length > 0);
}
function isNewRound() private {
uint256 blocksAfterLastRound = safeSub(block.number, lastBlockNumberInRound); //current block number - last round block number = blocks after last round
if(blocksAfterLastRound >= blocksPerRound){ // need to increase reward round if blocks after last round is greater or equal blocks per round
updateRoundsInformation(blocksAfterLastRound);
}
}
function updateRoundsInformation(uint256 _blocksAfterLastRound) private {
uint256 roundsNeedToCreate = safeDiv(_blocksAfterLastRound, blocksPerRound); //calculate how many rounds need to create
lastBlockNumberInRound = safeAdd(lastBlockNumberInRound, safeMul(roundsNeedToCreate, blocksPerRound)); //calculate last round creation block number
for (uint256 i = 0; i < roundsNeedToCreate; i++) {
updateRoundInformation();
}
}
function updateRoundInformation() private {
issuedTokensInRound[currentRound] = issued;
Reward storage rewardInfo = reward[currentRound];
rewardInfo.roundNumber = currentRound;
currentRound = currentRound + 1;
}
function issue(address _receiver, uint256 _tokenAmount) private {
if(_tokenAmount == 0){
revert();
}
uint256 newIssuedAmount = safeAdd(_tokenAmount, issued);
if(newIssuedAmount > totalTokens){
revert();
}
addToAddressBalancesInfo(_receiver, _tokenAmount);
issued = newIssuedAmount;
bytes memory empty;
if(isContract(_receiver)) {
ContractReceiver receiverContract = ContractReceiver(_receiver);
receiverContract.tokenFallback(msg.sender, _tokenAmount, empty);
}
/* Notify anyone listening that this transfer took place */
Transfer(msg.sender, _receiver, _tokenAmount, empty);
Transfer(msg.sender, _receiver, _tokenAmount);
}
function addToAddressBalancesInfo(address _receiver, uint256 _tokenAmount) private {
AddressBalanceInfoStructure storage accountBalance = accountBalances[_receiver];
if(!accountBalance.wasModifiedInRoundMap[currentRound]){ //allow just push one time per round
// If user first time get update balance set user claimed reward round to round before.
if(accountBalance.mapKeys.length == 0 && currentRound > 0){
accountBalance.claimedRewardTillRound = currentRound;
}
accountBalance.mapKeys.push(currentRound);
accountBalance.wasModifiedInRoundMap[currentRound] = true;
}
accountBalance.addressBalance = safeAdd(accountBalance.addressBalance, _tokenAmount);
accountBalance.roundBalanceMap[currentRound] = accountBalance.addressBalance;
}
function subFromAddressBalancesInfo(address _adr, uint256 _tokenAmount) private {
AddressBalanceInfoStructure storage accountBalance = accountBalances[_adr];
if(!accountBalance.wasModifiedInRoundMap[currentRound]){ //allow just push one time per round
accountBalance.mapKeys.push(currentRound);
accountBalance.wasModifiedInRoundMap[currentRound] = true;
}
accountBalance.addressBalance = safeSub(accountBalance.addressBalance, _tokenAmount);
accountBalance.roundBalanceMap[currentRound] = accountBalance.addressBalance;
}
//function that is called when transaction target is an address
function transferToAddress(address _from, address _to, uint256 _value, bytes _data) private returns (bool success) {
if(accountBalances[_from].addressBalance < _value){ // Check if the sender has enough
revert();
}
if(safeAdd(accountBalances[_to].addressBalance, _value) < accountBalances[_to].addressBalance){ // Check for overflows
revert();
}
isNewRound();
subFromAddressBalancesInfo(_from, _value); // Subtract from the sender
addToAddressBalancesInfo(_to, _value); // Add the same to the recipient
/* Notify anyone listening that this transfer took place */
Transfer(_from, _to, _value, _data);
Transfer(_from, _to, _value);
return true;
}
//function that is called when transaction target is a contract
function transferToContract(address _from, address _to, uint256 _value, bytes _data) private returns (bool success) {
if(accountBalances[_from].addressBalance < _value){ // Check if the sender has enough
revert();
}
if(safeAdd(accountBalances[_to].addressBalance, _value) < accountBalances[_to].addressBalance){ // Check for overflows
revert();
}
isNewRound();
subFromAddressBalancesInfo(_from, _value); // Subtract from the sender
addToAddressBalancesInfo(_to, _value); // Add the same to the recipient
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(_from, _value, _data);
/* Notify anyone listening that this transfer took place */
Transfer(_from, _to, _value, _data);
Transfer(_from, _to, _value);
return true;
}
} | * permission checker/ | modifier onlyContractOwner() {
if(msg.sender != contractOwner){
revert();
}
_;
}
| 6,212,630 | [
1,
9827,
12489,
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,
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,
202,
20597,
1338,
8924,
5541,
1435,
288,
203,
202,
202,
430,
12,
3576,
18,
15330,
480,
6835,
5541,
15329,
203,
1082,
202,
266,
1097,
5621,
203,
202,
202,
97,
203,
202,
202,
67,
31,
203,
202,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
import 'openzeppelin-solidity/contracts/math/SafeMath.sol';
import 'openzeppelin-solidity/contracts/math/Math.sol';
import 'openzeppelin-solidity/contracts/ownership/Ownable.sol';
import 'openzeppelin-solidity/contracts/lifecycle/Pausable.sol';
import 'openzeppelin-solidity/contracts/lifecycle/Destructible.sol';
import './libraries/strings.sol';
import './libraries/Array256Lib.sol';
import './BadgesLedger.sol';
/**
* @title Mecenas
* The main mecenas contract. Here is all the main logic to register
* content creators and be able to support then via prepaid monthly
* subscriptions. There is a percent fee + fixed fee per every subs
* that goes to the contract owner to support development. Content
* creators can withdraw their wage monthly.
*/
contract Mecenas is Ownable, Pausable, Destructible {
using SafeMath for uint256;
using Math for uint256;
using Array256Lib for uint256[];
using strings for *;
address public owner;
uint256 public ownerBalance;
BadgesLedger public badgesLedger;
uint public feePercent;
uint public fixedFee;
struct PriceTierSuggestion {
uint256 price;
string title;
string description;
}
struct MecenasMessage {
bytes32 mecenasNick;
address mecenasAddress;
address contentCreatorAddress;
string message;
uint subscriptions;
uint priceTier;
}
struct MecenasSupport {
bytes32 nickname;
address[] supportsContentCreators;
}
struct ContentCreator {
bytes32 nickname;
string description;
uint256 creationTimestamp;
uint256 subscriptionIndex;
uint256 payday;
uint256 balance;
string ipfsAvatar;
address[] mecenasAddresses;
mapping (uint => uint256[]) mecenasSubscriptions;
}
struct Badge {
uint256 tokenId;
address contentCreatorAddress;
}
mapping (address => PriceTierSuggestion[3]) public suggestPriceTiers;
mapping (address => MecenasMessage[]) public messageInbox;
mapping (address => ContentCreator) public contentCreators;
mapping (address => MecenasSupport) public mecenas;
mapping (address => Badge[]) public mecenasBadges;
mapping (bytes32 => address) public contentCreatorAddresses;
/**
* @dev Emits a new subscription message, from the mecenas to the content creator.
* It can be showed in the main website or integrated into a streaming platform,
* to show in live and see the content creator reaction.
*
* An integration with Twitch could be possible.
*/
event newSubscriptionMessage(address contentCreatorAddress, bytes32 mecenasNickname, string mecenasMessage);
/**
* Emits a new content creator. This can be consumed in the webapp to show latest content creators.
*/
event newContentCreator(address contentCreatorAddress, bytes32 nickname, string ipfsAvatar);
/**
* @dev Initialize the contract, sets an owner, a default feePercent and fixedFee.
*/
constructor() public {
owner = msg.sender;
feePercent = 1;
fixedFee = 0.0006 ether;
}
/** @dev Set the badges ledger contract address
* @param badgesLedgerAddress the Badges ledger deployed address
*/
function setBadgesLedgerContract(address badgesLedgerAddress) public onlyOwner {
badgesLedger = BadgesLedger(badgesLedgerAddress);
}
/**
* @dev Modifier to throw when msg.value is less than contract owner fee;
*/
modifier minimumAmount {
require(msg.value > getMinimumAmount());
_;
}
/**
* @dev Calculate and returns the minimum amount possible to surpass owner fees.
* @return uint The minimum possible amount to surpass fees.
*/
function getMinimumAmount() public view returns(uint) {
return fixedFee.add(fixedFee.mul(feePercent).div(100));
}
/**
* @dev Function that returns true if first argument is greater than minimum owner fee.
* @param amount Test if amount is greater than minimum amount.
* @return boolean
*/
function greaterThanMinimumAmount(uint amount) public view returns (bool) {
return amount > getMinimumAmount();
}
/** Owner functions **/
/**
* @dev Set percent fee per content creator subscription.
* @param newFee The new percent fee to be set
*/
function setPercentFee(uint256 newFee) public onlyOwner {
feePercent = newFee;
}
/**
* @dev Set fixed fee per content creator subscription.
* @param newFee The new fixed fee to be set.
*/
function setFixedFee(uint256 newFee) public onlyOwner {
fixedFee = newFee;
}
/**
* @dev Pay the fee to the contract owner. Returns the remain amount to support the content creator.
* @return uint256 Returns the remaining amount after fees.
*/
function payFee() private returns(uint256) {
require(msg.value > getMinimumAmount());
uint256 currentAmount = msg.value;
uint256 fee = fixedFee.add(currentAmount.mul(feePercent).div(100));
uint256 amountAfterFee = currentAmount - fee;
require(amountAfterFee > 0);
ownerBalance = ownerBalance + fee;
return amountAfterFee;
}
/** @dev Withdraw owner fees, only callable by owner.
*/
function withdrawFees() public onlyOwner {
// Remember to substract the pending withdraw before
// sending to prevent re-entrancy attacks
uint256 transferAmount = ownerBalance;
ownerBalance -= transferAmount;
msg.sender.transfer(transferAmount);
}
/**
* Content creator functions
*/
/** @dev Get content creator tiers length, to be able to iterate it later.
* @param contentCreatorAddress The content creator address.
* @return The length of the array.
*/
function getTiersLength(address contentCreatorAddress) public view returns (uint) {
return suggestPriceTiers[contentCreatorAddress].length;
}
/** @dev Get content creator tier content, by index.
* @param contentCreatorAddress The content creator address.
* @param index The index of the array.
* @return title The title of the tier.
* @return description The description of the tier.
* @return price The price of the tier.
*/
function getTier(address contentCreatorAddress, uint index) public view returns (
string title,
string description,
uint price
) {
PriceTierSuggestion memory tier = suggestPriceTiers[contentCreatorAddress][index];
title = tier.title;
description = tier.description;
price = tier.price;
}
/** @dev Content creator getter
* @param addressInput The content creator address.
* @return nickname The content creator name.
* @return description Content creator description.
* @return creationTimestamp Creation timestamp
* @return payday Next content creator payday date
* @return balance Current content creator balance
* @return ipfsAvatar Current content creator Avatar IPFS hash
* @return totalMecenas The number of subscriptions
* @return contentCreatorAddress Address
* @return wage The next wage value.
*/
function getContentCreator(address addressInput) public view returns (
bytes32 nickname,
string description,
uint256 creationTimestamp,
uint256 payday,
uint256 balance,
string ipfsAvatar,
uint256 totalMecenas,
address contentCreatorAddress,
uint256 wage
) {
ContentCreator memory contentCreator = contentCreators[addressInput];
nickname = contentCreator.nickname;
description = contentCreator.description;
creationTimestamp = contentCreator.creationTimestamp;
payday = contentCreator.payday;
balance = contentCreator.balance;
ipfsAvatar = contentCreator.ipfsAvatar;
totalMecenas = contentCreator.mecenasAddresses.length;
contentCreatorAddress = addressInput;
wage = calculateNextWage(addressInput);
}
/** @dev Content creator getter
* @param nickname The content creator nickname.
* @return contentCreatorAddress address of content creator.
*/
function getContentCreatorAddress(bytes32 nickname) public view returns (
address contentCreatorAddress
) {
contentCreatorAddress = contentCreatorAddresses[nickname];
}
/** @dev Content creator getter
* @param nick The content creator nickname.
* @return nickname The content creator name.
* @return description Content creator description.
* @return creationTimestamp Creation timestamp
* @return payday Next content creator payday date
* @return balance Current content creator balance
* @return ipfsAvatar Current content creator Avatar IPFS hash
* @return totalMecenas The number of subscriptions
* @return contentCreatorAddress Address
* @return wage The next wage value.
*/
function getContentCreatorByNickname(bytes32 nick) public view returns (
bytes32 nickname,
string description,
uint256 creationTimestamp,
uint256 payday,
uint256 balance,
string ipfsAvatar,
uint256 totalMecenas,
address contentCreatorAddress,
uint256 wage
) {
contentCreatorAddress = getContentCreatorAddress(nick);
require(contentCreatorAddress != address(0));
ContentCreator memory contentCreator = contentCreators[contentCreatorAddress];
nickname = contentCreator.nickname;
description = contentCreator.description;
creationTimestamp = contentCreator.creationTimestamp;
payday = contentCreator.payday;
balance = contentCreator.balance;
ipfsAvatar = contentCreator.ipfsAvatar;
totalMecenas = contentCreator.mecenasAddresses.length;
wage = calculateNextWage(contentCreatorAddress);
}
/**
* @dev Sets the default price tiers to the current msg.sender
*/
function setDefaultPriceTiers() private {
// Default tiers
PriceTierSuggestion memory tierSilver = PriceTierSuggestion({
title: "Silver",
description: "You will receive a Silver badge token in compensation, ocassional extra content like making-off videos or photos. And a lot of love.",
price: getMinimumAmount() + 0.01 ether
});
PriceTierSuggestion memory tierGold = PriceTierSuggestion({
title: "Gold",
description: "You will receive a Gold badge token in compensation, extra video content and audio commentary of new and old videos. And a lot of love.",
price: getMinimumAmount() + 0.02 ether
});
PriceTierSuggestion memory tierPlatinum = PriceTierSuggestion({
title: "Platinum",
description: "You will receive a Gold badge token in compensation, all of above and access to an exclusive forum, where i will reply to any question you want to ask to me. And a lot of love.",
price: getMinimumAmount() + 0.05 ether
});
suggestPriceTiers[msg.sender][0] = tierSilver;
suggestPriceTiers[msg.sender][1] = tierGold;
suggestPriceTiers[msg.sender][2] = tierPlatinum;
}
/**
* @dev Gets the Mecenas Badge name for adding it to the Token URI
* @param amount uint256 with the amount.
* @param priceTiers The tiers of the content creator.
*/
function getSubscriberLevel(uint256 amount, PriceTierSuggestion[3] priceTiers) private pure returns (string){
bool levelFound = false;
uint priceTierIndex = 0;
uint currentLevel = 0;
for(uint counter = 0; counter < 3; counter++){
if(amount > uint(priceTiers[counter].price)) {
if (uint(priceTiers[counter].price) > currentLevel) {
currentLevel = priceTiers[counter].price;
priceTierIndex = counter;
if (levelFound == false) {
levelFound = true;
}
}
}
}
if (levelFound == false) {
return "Subscriber";
}
return priceTiers[priceTierIndex].title;
}
/** @dev Content creator getter
* @param nickname The content creator name.
* @param description Content creator description.
* @param ipfsAvatar Current content creator Avatar IPFS hash
*/
function contentCreatorFactory(bytes32 nickname, string description, string ipfsAvatar) public whenNotPaused {
ContentCreator storage contentCreator = contentCreators[msg.sender];
// At least nickname must be greater than zero chars, be unique, and content creator must not exists
require(nickname.length > 0 && contentCreatorAddresses[nickname] == address(0) && contentCreator.payday == 0);
// Initialize a new content creator
contentCreatorAddresses[nickname] = msg.sender;
contentCreator.nickname = nickname;
contentCreator.description = description;
contentCreator.creationTimestamp = now;
contentCreator.payday = now + 30 days;
contentCreator.balance = 0;
contentCreator.ipfsAvatar = ipfsAvatar;
contentCreator.subscriptionIndex = 1;
setDefaultPriceTiers();
// Emit content creator event
emit newContentCreator(msg.sender, nickname, ipfsAvatar);
}
/**
* @dev Change the content creator address, only allowed by content creator itself.
* @param newAddress The new address to be set.
*/
function changeContentCreatorAddress(address newAddress) public whenNotPaused {
ContentCreator memory current = contentCreators[msg.sender];
require(current.payday > 0);
delete contentCreators[msg.sender];
delete contentCreatorAddresses[current.nickname];
contentCreators[newAddress] = current;
contentCreatorAddresses[current.nickname] = newAddress;
}
/**
* @dev Change the content creator avatar, only allowed by content creator itself.
* @param avatarHash The new avatar IPFS hash to be set.
*/
function changeAvatar(string avatarHash) public whenNotPaused {
ContentCreator storage current = contentCreators[msg.sender];
require(current.payday > 0);
current.ipfsAvatar = avatarHash;
}
/**
* @dev Change the content creator tier, by index, only allowed by content creator itself.
* @param tierIndex The tier index to change.
* @param title The new title name to be set.
* @param description The new description to be set.
* @param price The new price to be set.
*/
function changeContentCreatorTiers(uint tierIndex, string title, string description, uint256 price) public whenNotPaused {
ContentCreator storage current = contentCreators[msg.sender];
// Check if content creator is initialized, price is greater than minimum amount and string params are not empty.
require(current.payday > 0 && price > getMinimumAmount() && bytes(title).length > 0 && bytes(description).length > 0);
// Replace value in global map variable
suggestPriceTiers[msg.sender][tierIndex] = PriceTierSuggestion({
title: title,
description: description,
price: price
});
}
/**
* @dev Change the content creator description, only allowed by content creator itself.
* @param description The new description to be set.
*/
function changeDescription(string description) public whenNotPaused {
ContentCreator storage current = contentCreators[msg.sender];
require(current.payday > 0);
current.description = description;
}
/**
* @dev Calculate next content creator wage.
* @param contentCreatorAddress Content creator address
* @return uint with the next content creator wage.
*/
function calculateNextWage(address contentCreatorAddress) public view returns (uint256){
ContentCreator storage contentCreator = contentCreators[contentCreatorAddress];
return contentCreator.mecenasSubscriptions[contentCreator.subscriptionIndex].sumElements();
}
/**
* @dev Allow content creator to withdraw once the payload date is greater or equal than today. If contract
* is paused, this function is still reachable for content creators.
*/
function monthlyWithdraw() public {
ContentCreator storage current = contentCreators[msg.sender];
uint nextWage = current.mecenasSubscriptions[current.subscriptionIndex].sumElements();
// Allow withdraw only after payday
require(now >= current.payday && current.balance > 0);
// If the current balance is less than the theorical monthly withdraw, withdraw that lower amount.
uint transferAmount = current.balance.min256(nextWage);
// Remember to lock the withdraw function until next month
current.payday = current.payday + 30 days;
// Point to the next subscription index
current.subscriptionIndex = current.subscriptionIndex + 1;
// Remember to substract the pending withdraw before
// sending to prevent re-entrancy attacks
current.balance = current.balance - transferAmount;
msg.sender.transfer(transferAmount);
}
/** Mecenas functions **/
/**
* @dev Emit a Mecenas Message event to be consumed in a stream or website. Show the support from the mecenas to the content creator.
* @param mecenasNickname Mecenas nickname.
* @param contentCreatorAddress Content creator address subscription.
* @param message Mecenas message.
* @param subscriptions Number of months subbed.
* @param priceTier The subscription price per month.
*/
function broadcastNewSubscription(bytes32 mecenasNickname, address contentCreatorAddress, string message, uint256 subscriptions, uint256 priceTier) private {
MecenasMessage memory newSubMessage = MecenasMessage({
mecenasNick: mecenasNickname,
mecenasAddress: msg.sender,
contentCreatorAddress: contentCreatorAddress,
message: message,
subscriptions: subscriptions,
priceTier: priceTier
});
// Save message into storage
messageInbox[contentCreatorAddress].push(newSubMessage);
// Send a new subscription event
emit newSubscriptionMessage(newSubMessage.contentCreatorAddress, newSubMessage.mecenasNick, newSubMessage.message);
}
/**
* @dev Support a determined content creator, via a prepaid monthly subscription.
* You can set any price, regarding the suggested price tiers, and add a support message to the content creator.
* @param mecenasNickname Mecenas nickname.
* @param contentCreatorAddress Content creator address subscription.
* @param message Mecenas message.
* @param subscriptions Number of months subbed.
*/
function supportContentCreator(address contentCreatorAddress, uint256 subscriptions, string message, bytes32 mecenasNickname) public payable whenNotPaused{
require(contentCreatorAddress != address(0) && msg.value > 0);
// Calculate fee and sum to contract owner balance
uint256 amountAfterFees = payFee();
// Calculate price per month subscription (totalAmount / months = priceTier)
uint256 priceTier = amountAfterFees.div(subscriptions);
ContentCreator storage contentCreator = contentCreators[contentCreatorAddress];
require(contentCreator.subscriptionIndex >= 1);
// Add the subscriptions to the content creator
for (uint newSub = 0; newSub < subscriptions; newSub++) {
contentCreator.mecenasSubscriptions[contentCreator.subscriptionIndex + newSub].push(priceTier);
contentCreator.balance = contentCreator.balance + priceTier;
}
// Add the mecenas address to the content creator
contentCreator.mecenasAddresses.push(msg.sender);
// Save mecenas into global variable
mecenas[msg.sender].nickname = mecenasNickname;
mecenas[msg.sender].supportsContentCreators.push(contentCreatorAddress);
// Mint SubscriptionBadge to Mecenas
uint tokenId = badgesLedger.totalSupply() + 1;
string memory subscriptionLevel = getSubscriberLevel(priceTier, suggestPriceTiers[contentCreatorAddress]);
// Token uri contains "level" string
string memory tokenUri = subscriptionLevel;
badgesLedger.mintSubscriptionBadge(msg.sender, tokenId, tokenUri);
// Save token into separate map, that contains tokenId and contentCreator address, mapped by mecenas address.
Badge[] storage mecenasTokens = mecenasBadges[msg.sender];
mecenasTokens.push(Badge({tokenId: tokenId, contentCreatorAddress: contentCreatorAddress}));
// Send message to the content creator inbox and emit event
broadcastNewSubscription(mecenasNickname, contentCreatorAddress, message, subscriptions, priceTier);
}
} | * @dev Content creator getter @param addressInput The content creator address. @return nickname The content creator name. @return description Content creator description. @return creationTimestamp Creation timestamp @return payday Next content creator payday date @return balance Current content creator balance @return ipfsAvatar Current content creator Avatar IPFS hash @return totalMecenas The number of subscriptions @return contentCreatorAddress Address @return wage The next wage value./ | function getContentCreator(address addressInput) public view returns (
bytes32 nickname,
string description,
uint256 creationTimestamp,
uint256 payday,
uint256 balance,
string ipfsAvatar,
uint256 totalMecenas,
address contentCreatorAddress,
uint256 wage
) {
ContentCreator memory contentCreator = contentCreators[addressInput];
nickname = contentCreator.nickname;
description = contentCreator.description;
creationTimestamp = contentCreator.creationTimestamp;
payday = contentCreator.payday;
balance = contentCreator.balance;
ipfsAvatar = contentCreator.ipfsAvatar;
totalMecenas = contentCreator.mecenasAddresses.length;
contentCreatorAddress = addressInput;
wage = calculateNextWage(addressInput);
}
| 7,284,490 | [
1,
1350,
11784,
7060,
225,
1758,
1210,
1021,
913,
11784,
1758,
18,
327,
19570,
1021,
913,
11784,
508,
18,
327,
2477,
3697,
11784,
2477,
18,
327,
6710,
4921,
18199,
2858,
327,
8843,
2881,
4804,
913,
11784,
8843,
2881,
1509,
327,
11013,
6562,
913,
11784,
11013,
327,
2359,
2556,
23999,
6562,
913,
11784,
8789,
8761,
2971,
4931,
1651,
327,
2078,
49,
557,
275,
345,
1021,
1300,
434,
11912,
327,
913,
10636,
1887,
5267,
327,
341,
410,
1021,
1024,
341,
410,
460,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
5154,
10636,
12,
2867,
1758,
1210,
13,
1071,
1476,
1135,
261,
203,
1377,
1731,
1578,
19570,
16,
203,
1377,
533,
2477,
16,
203,
1377,
2254,
5034,
6710,
4921,
16,
203,
1377,
2254,
5034,
8843,
2881,
16,
203,
1377,
2254,
5034,
11013,
16,
203,
1377,
533,
2359,
2556,
23999,
16,
203,
1377,
2254,
5034,
2078,
49,
557,
275,
345,
16,
203,
1377,
1758,
913,
10636,
1887,
16,
203,
1377,
2254,
5034,
341,
410,
203,
565,
262,
288,
203,
565,
3697,
10636,
3778,
913,
10636,
273,
913,
1996,
3062,
63,
2867,
1210,
15533,
203,
565,
19570,
273,
913,
10636,
18,
17091,
529,
31,
203,
565,
2477,
273,
913,
10636,
18,
3384,
31,
203,
565,
6710,
4921,
273,
913,
10636,
18,
17169,
4921,
31,
203,
565,
8843,
2881,
273,
913,
10636,
18,
10239,
2881,
31,
203,
565,
11013,
273,
913,
10636,
18,
12296,
31,
203,
565,
2359,
2556,
23999,
273,
913,
10636,
18,
625,
2556,
23999,
31,
203,
565,
2078,
49,
557,
275,
345,
273,
913,
10636,
18,
81,
557,
275,
345,
7148,
18,
2469,
31,
203,
565,
913,
10636,
1887,
273,
1758,
1210,
31,
203,
565,
341,
410,
273,
4604,
2134,
59,
410,
12,
2867,
1210,
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
] |
pragma solidity >=0.8.0;
//SPDX-License-Identifier: MIT
import "hardhat/console.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
contract WagmiContract is ReentrancyGuard {
using SafeMath for uint256;
struct Listing {
// Identifier
uint256 id;
// a boolean to check that the listing exists.
bool exists;
// address of the NFT contract.
address tokenAddr;
// id of the token on the NFT contract.
uint256 tokenId;
// address of the owner.
address ownerAddr;
// price of the NFT to be sold at, in base 10^18.
uint256 listPrice;
// commission given to promoters for referring people, in base 10^2.
uint256 promoterReward;
// discount given to buyers if they are referred, in base 10^2.
uint256 buyerReward;
// Token Image URI
string resourceUri;
// Metadata name
string resourceName;
}
// the NFTs that are being sold on Wagmi.
uint256 listingId = 0;
// index (listingId) => Listing
Listing[] listings;
// the set of registered promoters. mapping used for O(1) access.
mapping(address => bool) promoters;
event NewListing(uint256 _listingId);
event BoughtListing(uint256 _listingId);
/**
* Gives WagmiContract the authority to manage the owner's NFT.
* @param _tokenAddr address of the NFT contract.
* @param _tokenId id of the token on the NFT contract.
*/
function approveWagmi(address _tokenAddr, uint256 _tokenId) internal {
require(
IERC721(_tokenAddr).ownerOf(_tokenId) == msg.sender,
"Token is not owned by caller"
);
IERC721(_tokenAddr).approve(address(this), _tokenId);
}
/**
* Gets all the listings on the platform
* TODO: Limit listings
*/
function getListings() external view returns (Listing[] memory) {
return listings;
}
/**
* Lists an NFT on the Wagmi marketplace.
* @param _tokenAddr address of the NFT contract.
* @param _tokenId id of the token on the NFT contract.
* @param _listPrice price of the NFT to be sold at.
* @param _promoterReward commission given to promoters for referring people.
* @param _buyerReward discount given to buyers if they are referred.
* todo: ensure that msg.sender is owner of NFT.
*/
function listNFT(
address _tokenAddr,
uint256 _tokenId,
uint256 _listPrice,
uint256 _promoterReward,
uint256 _buyerReward
) external payable returns (uint256) {
uint256 expectedDeposit = _listPrice
.mul(_promoterReward.add(_buyerReward))
.div(100);
require(msg.value == expectedDeposit, "Expected deposit is wrong");
listings.push(
Listing({
id: listingId,
exists: true,
tokenAddr: _tokenAddr,
tokenId: _tokenId,
ownerAddr: msg.sender,
listPrice: _listPrice,
promoterReward: _promoterReward,
buyerReward: _buyerReward,
resourceUri: ERC721(_tokenAddr).tokenURI(_tokenId),
resourceName: ERC721(_tokenAddr).name()
})
);
approveWagmi(_tokenAddr, _tokenId);
emit NewListing(listingId);
return listingId++;
}
/**
* Retrieves the information of a listing on the Wagmi marketplace.
* @param _listingId id of the listing.
* @return the information of the listing.
*/
function getListing(uint256 _listingId)
external
view
returns (Listing memory)
{
require(_listingId <= listingId, "Invalid listing id");
require(listings[_listingId].exists == true, "listing does not exist");
return listings[_listingId];
}
/**
* Delist an NFT from the Wagmi marketplace.
* @param _listingId id of the listing.
*/
function removeListing(uint256 _listingId) external {
require(_listingId <= listingId, "Invalid listing id");
require(listings[_listingId].exists == true, "listing does not exist");
delete listings[_listingId];
}
/**
* Allow people to sign up as promoters on the Wagmi marketplace.
*/
function promoterSignUp() external {
promoters[msg.sender] = true;
}
function isPromoter() external view returns (bool) {
return promoters[msg.sender];
}
/**
* Purchase an NFT.
* @param _listingId id of the listing.
* @param _promoterAddr address of the referrer. the null address (0x0)
* is used if the NFT is bought without a promoter address.
*/
function buyNFT(uint256 _listingId, address _promoterAddr)
external
payable
nonReentrant
{
require(_listingId <= listingId, "Invalid listing id");
Listing storage listing = listings[_listingId];
require(listing.exists, "Listing does not exist anymore");
require(
msg.value >= listing.listPrice,
"Buyer amount is below listed price"
);
address tokenOperator = IERC721(listing.tokenAddr).getApproved(
listing.tokenId
);
require(
tokenOperator == address(this),
"Contract is not approved to send NFT"
);
// Transfer commission
if (_promoterAddr != address(0)) {
uint256 promoterRewardFee = listing
.promoterReward
.mul(listing.listPrice)
.div(100);
uint256 buyerRewardFee = listing.buyerReward.mul(listing.buyerReward).div(
100
);
payable(_promoterAddr).transfer(promoterRewardFee);
(bool success, ) = msg.sender.call{value: buyerRewardFee}("");
require(success, "Sending reward to buyer failed");
}
// TODO: Replace with safeTransferFrom by checking ERC721Receiver implementer
IERC721(listing.tokenAddr).transferFrom(
listing.ownerAddr,
msg.sender,
listing.tokenId
);
payable(listing.ownerAddr).transfer(listing.listPrice);
emit BoughtListing(_listingId);
}
}
| * Allow people to sign up as promoters on the Wagmi marketplace./ | function promoterSignUp() external {
promoters[msg.sender] = true;
}
| 15,794,862 | [
1,
7009,
16951,
358,
1573,
731,
487,
3012,
352,
414,
603,
326,
678,
346,
9197,
29917,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
3012,
20005,
2766,
1211,
1435,
3903,
288,
203,
565,
3012,
352,
414,
63,
3576,
18,
15330,
65,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
/// @author jpegmint.xyz
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
/**
*/
contract ERC721Virtual is ERC721, IERC721Enumerable {
mapping(uint256 => bool) private _mintedTokens;
constructor(string memory name_, string memory symbol_) ERC721(name_, symbol_) {}
/**
* @dev Owners can have max 1 of virutal tokens.
*/
function balanceOf(address owner) public view virtual override(ERC721, IERC721) returns (uint256) {
require(owner != address(0), "ERC721Virtual: balance query for the zero address");
return 1;
}
/**
* @dev Owner is always tokenId -> address
*/
function ownerOf(uint256 tokenId) public view virtual override(ERC721, IERC721) returns (address) {
address owner = address(uint160(tokenId));
require(owner != address(0), "ERC721Virtual: owner query for nonexistent token");
return owner;
}
/**
* @dev Force use of this ownerOf function
*/
function approve(address to, uint256 tokenId) public virtual override(ERC721, IERC721) {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721Virtual: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721Virtual: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev Virtual tokens always exist either as virtual or minted
*/
function _exists(uint256 tokenId) internal view virtual override returns (bool) {
return ownerOf(tokenId) != address(0);
}
/**
* @dev Force use of this ownerOf function
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual override returns (bool) {
require(_exists(tokenId), "ERC721Virtual: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
*/
function _mint(address to, uint256 tokenId) internal virtual override {
require(to != address(0), "ERC721Virtual: mint to the zero address");
require(to == ownerOf(tokenId), "ERC721Virtual: only owner can mint virtual token");
require(!_mintedTokens[tokenId], "ERC721Virtual: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_mintedTokens[tokenId] = true;
emit Transfer(address(0), to, tokenId);
}
/**
*/
function _burn(uint256 tokenId) internal virtual override {
address owner = ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
_approve(address(0), tokenId);
_mintedTokens[tokenId] = false;
emit Transfer(owner, address(0), tokenId);
}
function transferFrom(address, address, uint256) public virtual override(ERC721, IERC721) {
revert("ERC721Virtual: Virtual tokens can not be transferred");
}
function safeTransferFrom(address, address, uint256) public virtual override(ERC721, IERC721) {
revert("ERC721Virtual: Virtual tokens can not be transferred");
}
function safeTransferFrom(address, address, uint256, bytes memory) public virtual override(ERC721, IERC721) {
revert("ERC721Virtual: Virtual tokens can not be transferred");
}
/**
* @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 == 0, "ERC721Virtual: owner index out of bounds");
return uint256(uint160(owner));
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return type(uint160).max;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < totalSupply(), "ERC721Virtual: global index out of bounds");
return index + 1;
}
}
| * @dev See {IERC721Enumerable-totalSupply}./ | function totalSupply() public view virtual override returns (uint256) {
return type(uint160).max;
}
| 997,995 | [
1,
9704,
288,
45,
654,
39,
27,
5340,
3572,
25121,
17,
4963,
3088,
1283,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2078,
3088,
1283,
1435,
1071,
1476,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
618,
12,
11890,
16874,
2934,
1896,
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
] |
/*
Copyright 2017-2018 RigoBlock, Rigo Investment Sagl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.4.21;
pragma experimental "v0.5.0";
import { AuthorityFace as Authority } from "../Authority/AuthorityFace.sol";
import { DragoEventfulFace as DragoEventful } from "../DragoEventful/DragoEventfulFace.sol";
import { DragoFace } from "./DragoFace.sol";
import { OwnedUninitialized as Owned } from "../utils/Owned/OwnedUninitialized.sol";
import { SafeMathLight as SafeMath } from "../utils/SafeMath/SafeMathLight.sol";
import { DragoExchangeExtension } from "./DragoExchangeExtension/DragoExchangeExtension.sol";
/// @title Drago - A set of rules for a drago.
/// @author Gabriele Rigo - <[email protected]>
contract Drago is Owned, SafeMath, DragoFace {
using DragoExchangeExtension for *;
DragoExchangeExtension.Admin libraryAdmin;
string constant VERSION = 'HF 0.4.1';
uint constant BASE = 1000000; // tokens are divisible by 1 million
mapping (address => Account) accounts;
DragoData data;
Admin admin;
struct Receipt {
uint units;
uint32 activation;
}
struct Account {
uint balance;
Receipt receipt;
mapping(address => address[]) approvedAccount;
}
struct DragoData {
string name;
string symbol;
uint dragoId;
uint totalSupply;
uint sellPrice;
uint buyPrice;
uint transactionFee; // in basis points 1 = 0.01%
uint32 minPeriod;
}
struct Admin {
address authority;
address dragoDao;
address feeCollector;
uint minOrder; // minimum stake to avoid dust clogging things up
uint ratio; // ratio is 80%
}
modifier onlyDragoDao {
require(msg.sender == admin.dragoDao);
_;
}
modifier onlyOwnerOrAuthority {
Authority auth = Authority(admin.authority);
require(auth.isAuthority(msg.sender) || msg.sender == owner);
_;
}
modifier whenApprovedExchange(address _exchange) {
Authority auth = Authority(admin.authority);
require(auth.isWhitelistedExchange(_exchange));
_;
}
modifier ownerOrApprovedExchange() {
Authority auth = Authority(admin.authority);
require(auth.isWhitelistedExchange(msg.sender) || msg.sender == owner);
_;
}
modifier minimumStake(uint amount) {
require (amount >= admin.minOrder);
_;
}
modifier hasEnough(uint _amount) {
require(accounts[msg.sender].balance >= _amount);
_;
}
modifier positiveAmount(uint _amount) {
require(accounts[msg.sender].balance + _amount > accounts[msg.sender].balance);
_;
}
modifier minimumPeriodPast {
require(block.timestamp >= accounts[msg.sender].receipt.activation);
_;
}
modifier buyPriceHigherOrEqual(uint _sellPrice, uint _buyPrice) {
require(_sellPrice <= _buyPrice);
_;
}
modifier notPriceError(uint _sellPrice, uint _buyPrice) {
if (_sellPrice <= data.sellPrice / 10 || _buyPrice >= data.buyPrice * 10) return;
_;
}
function Drago(
string _dragoName,
string _dragoSymbol,
uint _dragoId,
address _owner,
address _authority)
public
{
data.name = _dragoName;
data.symbol = _dragoSymbol;
data.dragoId = _dragoId;
data.sellPrice = 1 ether;
data.buyPrice = 1 ether;
owner = _owner;
admin.authority = _authority;
admin.dragoDao = msg.sender;
admin.minOrder = 1 finney;
admin.feeCollector = _owner;
admin.ratio = 80;
}
// CORE FUNCTIONS
/// @dev Allows an exchange contract to send Ether back
function()
external
payable
whenApprovedExchange(msg.sender)
{}
/// @dev Allows a user to buy into a drago
/// @return Bool the function executed correctly
function buyDrago()
external
payable
minimumStake(msg.value)
returns (bool success)
{
require(buyDragoInternal(msg.sender));
return true;
}
/// @dev Allows a user to buy into a drago on behalf of an address
/// @param _hodler Address of the target user
/// @return Bool the function executed correctly
function buyDragoOnBehalf(address _hodler)
external
payable
minimumStake(msg.value)
returns (bool success)
{
require(buyDragoInternal(_hodler));
return true;
}
/// @dev Allows a user to sell from a drago
/// @param _amount Number of shares to sell
/// @return Bool the function executed correctly
function sellDrago(uint256 _amount)
external
hasEnough(_amount)
positiveAmount(_amount)
minimumPeriodPast
returns (bool success)
{
uint feeDrago;
uint feeDragoDao;
uint netAmount;
uint netRevenue;
(feeDrago, feeDragoDao, netAmount, netRevenue) = getSaleAmounts(_amount);
addSaleLog(_amount, netRevenue);
allocateSaleTokens(msg.sender, _amount, feeDrago, feeDragoDao);
data.totalSupply = safeSub(data.totalSupply, netAmount);
msg.sender.transfer(netRevenue);
return true;
}
/// @dev Allows drago owner or authority to set the price for a drago
/// @param _newSellPrice Price in wei
/// @param _newBuyPrice Price in wei
function setPrices(uint _newSellPrice, uint _newBuyPrice)
external
onlyOwnerOrAuthority
buyPriceHigherOrEqual(_newSellPrice, _newBuyPrice)
notPriceError(_newSellPrice, _newBuyPrice)
{
DragoEventful events = DragoEventful(getDragoEventful());
require(events.setDragoPrice(msg.sender, this, _newSellPrice, _newBuyPrice));
data.sellPrice = _newSellPrice;
data.buyPrice = _newBuyPrice;
}
/// @dev Allows drago dao/factory to change fee split ratio
/// @param _ratio Number of ratio for wizard, from 0 to 100
function changeRatio(uint _ratio)
external
onlyDragoDao
{
DragoEventful events = DragoEventful(getDragoEventful());
require(events.changeRatio(msg.sender, this, _ratio));
admin.ratio = _ratio;
}
/// @dev Allows drago owner to set the transaction fee
/// @param _transactionFee Value of the transaction fee in basis points
function setTransactionFee(uint _transactionFee)
external
onlyOwner
{
require(_transactionFee <= 100); //fee cannot be higher than 1%
DragoEventful events = DragoEventful(getDragoEventful());
require(events.setTransactionFee(msg.sender, this, _transactionFee));
data.transactionFee = _transactionFee;
}
/// @dev Allows owner to decide where to receive the fee
/// @param _feeCollector Address of the fee receiver
function changeFeeCollector(address _feeCollector)
external
onlyOwner
{
DragoEventful events = DragoEventful(getDragoEventful());
events.changeFeeCollector(msg.sender, this, _feeCollector);
admin.feeCollector = _feeCollector;
}
/// @dev Allows drago dao/factory to upgrade its address
/// @param _dragoDao Address of the new drago dao
function changeDragoDao(address _dragoDao)
external
onlyDragoDao
{
DragoEventful events = DragoEventful(getDragoEventful());
require(events.changeDragoDao(msg.sender, this, _dragoDao));
admin.dragoDao = _dragoDao;
}
/// @dev Allows drago dao/factory to change the minimum holding period
/// @param _minPeriod Number of blocks
function changeMinPeriod(uint32 _minPeriod)
external
onlyDragoDao
{
data.minPeriod = _minPeriod;
}
function depositToExchange(address _exchange, uint _amount)
external
onlyOwner
whenApprovedExchange(_exchange)
{
_exchange.transfer(_amount);
}
/// @dev Allows owner or approved exchange to send a transaction to exchange
/// @dev With data of signed/unsigned transaction
/// @param _exchange Address of the exchange
function operateOnExchange(address _exchange)
external
ownerOrApprovedExchange()
{
DragoExchangeExtension.operateOnExchange(libraryAdmin, _exchange);
}
// PUBLIC CONSTANT FUNCTIONS
/// @dev Calculates how many shares a user holds
/// @param _who Address of the target account
/// @return Number of shares
function balanceOf(address _who)
external view
returns (uint256)
{
return accounts[_who].balance;
}
/// @dev Gets the address of the logger contract
/// @return Address of the logger contrac
function getEventful()
external view
returns (address)
{
Authority auth = Authority(admin.authority);
return auth.getDragoEventful();
}
/// @dev Finds details of a drago pool
/// @return String name of a drago
/// @return String symbol of a drago
/// @return Value of the share price in wei
/// @return Value of the share price in wei
function getData()
external view
returns (
string name,
string symbol,
uint sellPrice,
uint buyPrice
)
{
name = data.name;
symbol = data.symbol;
sellPrice = data.sellPrice;
buyPrice = data.buyPrice;
}
/// @dev Finds the administrative data of the pool
/// @return Address of the account where a user collects fees
/// @return Address of the drago dao/factory
/// @return Number of the fee split ratio
/// @return Value of the transaction fee in basis points
/// @return Number of the minimum holding period for shares
function getAdminData()
external view
returns (
address, //owner
address feeCollector,
address dragoDao,
uint ratio,
uint transactionFee,
uint32 minPeriod
)
{
return (
owner,
admin.feeCollector,
admin.dragoDao,
admin.ratio,
data.transactionFee,
data.minPeriod
);
}
/// @dev Returns the version of the type of vault
/// @return String of the version
function getVersion()
external view
returns (string)
{
return VERSION;
}
/// @dev Returns the total amount of issued tokens for this drago
/// @return Number of shares
function totalSupply() external view returns (uint256) {
return data.totalSupply;
}
// INTERNAL FUNCTIONS
/// @dev Executes the pool purchase
/// @param _hodler Address of the target user
/// @return Bool the function executed correctly
function buyDragoInternal(address _hodler)
internal
returns (bool success)
{
uint grossAmount;
uint feeDrago;
uint feeDragoDao;
uint amount;
(grossAmount, feeDrago, feeDragoDao, amount) = getPurchaseAmounts();
addPurchaseLog(amount);
allocatePurchaseTokens(_hodler, amount, feeDrago, feeDragoDao);
data.totalSupply = safeAdd(data.totalSupply, grossAmount);
return true;
}
/// @dev Allocates tokens to buyer, splits fee in tokens to wizard and dao
/// @param _hodler Address of the buyer
/// @param _amount Value of issued tokens
/// @param _feeDrago Number of shares as fee
/// @param _feeDragoDao Number of shares as fee to dao
function allocatePurchaseTokens(
address _hodler,
uint _amount,
uint _feeDrago,
uint _feeDragoDao)
internal
{
accounts[_hodler].balance = safeAdd(accounts[_hodler].balance, _amount);
accounts[admin.feeCollector].balance = safeAdd(accounts[admin.feeCollector].balance, _feeDrago);
accounts[admin.dragoDao].balance = safeAdd(accounts[admin.dragoDao].balance, _feeDragoDao);
accounts[_hodler].receipt.activation = uint32(now) + data.minPeriod;
}
/// @dev Destroys tokens of seller, splits fee in tokens to wizard and dao
/// @param _hodler Address of the seller
/// @param _amount Value of burnt tokens
/// @param _feeDrago Number of shares as fee
/// @param _feeDragoDao Number of shares as fee to dao
function allocateSaleTokens(
address _hodler,
uint _amount,
uint _feeDrago,
uint _feeDragoDao)
internal
{
accounts[_hodler].balance = safeSub(accounts[_hodler].balance, _amount);
accounts[admin.feeCollector].balance = safeAdd(accounts[admin.feeCollector].balance, _feeDrago);
accounts[admin.dragoDao].balance = safeAdd(accounts[admin.dragoDao].balance, _feeDragoDao);
}
/// @dev Sends a buy log to the eventful contract
/// @param _amount Number of purchased shares
function addPurchaseLog(uint _amount)
internal
{
bytes memory name = bytes(data.name);
bytes memory symbol = bytes(data.symbol);
Authority auth = Authority(admin.authority);
DragoEventful events = DragoEventful(auth.getDragoEventful());
require(events.buyDrago(msg.sender, this, msg.value, _amount, name, symbol));
}
/// @dev Sends a sell log to the eventful contract
/// @param _amount Number of sold shares
/// @param _netRevenue Value of sale for hodler
function addSaleLog(uint _amount, uint _netRevenue)
internal
{
bytes memory name = bytes(data.name);
bytes memory symbol = bytes(data.symbol);
Authority auth = Authority(admin.authority);
DragoEventful events = DragoEventful(auth.getDragoEventful());
require(events.sellDrago(msg.sender, this, _amount, _netRevenue, name, symbol));
}
/// @dev Calculates the correct purchase amounts
/// @return Number of new shares
/// @return Value of fee in shares
/// @return Value of fee in shares to dao
/// @return Value of net purchased shares
function getPurchaseAmounts()
internal
view
returns (
uint grossAmount,
uint feeDrago,
uint feeDragoDao,
uint amount
)
{
grossAmount = safeDiv(msg.value * BASE, data.buyPrice);
uint fee = safeMul(grossAmount, data.transactionFee) / 10000; //fee is in basis points
return (
grossAmount = safeDiv(msg.value * BASE, data.buyPrice),
feeDrago = safeMul(fee , admin.ratio) / 100,
feeDragoDao = safeSub(fee, feeDrago),
amount = safeSub(grossAmount, fee)
);
}
/// @dev Calculates the correct sale amounts
/// @return Value of fee in shares
/// @return Value of fee in shares to dao
/// @return Value of net sold shares
/// @return Value of sale amount for hodler
function getSaleAmounts(uint _amount)
internal
view
returns (
uint feeDrago,
uint feeDragoDao,
uint netAmount,
uint netRevenue
)
{
uint fee = safeMul(_amount, data.transactionFee) / 10000; //fee is in basis points
return (
feeDrago = safeMul(fee, admin.ratio) / 100,
feeDragoDao = safeSub(fee, feeDragoDao),
netAmount = safeSub(_amount, fee),
netRevenue = (safeMul(netAmount, data.sellPrice) / BASE)
);
}
/// @dev Returns the address of the exchange adapter
/// @param _exchange Address of the target exchange
/// @return Address of the exchange adapter
function getExchangeAdapter(address _exchange)
internal
view
returns (address)
{
Authority auth = Authority(admin.authority);
return auth.getExchangeAdapter(_exchange);
}
/// @dev Gets the address of the logger contract
/// @return Address of the logger contrac
function getDragoEventful()
internal view
returns (address)
{
Authority auth = Authority(admin.authority);
return auth.getDragoEventful();
}
}
| @dev Finds details of a drago pool @return String name of a drago @return String symbol of a drago @return Value of the share price in wei @return Value of the share price in wei | function getData()
external view
returns (
string name,
string symbol,
uint sellPrice,
uint buyPrice
)
{
name = data.name;
symbol = data.symbol;
sellPrice = data.sellPrice;
buyPrice = data.buyPrice;
}
| 5,492,672 | [
1,
8947,
3189,
434,
279,
8823,
83,
2845,
327,
514,
508,
434,
279,
8823,
83,
327,
514,
3273,
434,
279,
8823,
83,
327,
1445,
434,
326,
7433,
6205,
316,
732,
77,
327,
1445,
434,
326,
7433,
6205,
316,
732,
77,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
4303,
1435,
203,
3639,
3903,
1476,
203,
3639,
1135,
261,
203,
5411,
533,
508,
16,
203,
5411,
533,
3273,
16,
203,
5411,
2254,
357,
80,
5147,
16,
203,
5411,
2254,
30143,
5147,
203,
3639,
262,
203,
565,
288,
203,
3639,
508,
273,
501,
18,
529,
31,
203,
3639,
3273,
273,
501,
18,
7175,
31,
203,
3639,
357,
80,
5147,
273,
501,
18,
87,
1165,
5147,
31,
203,
3639,
30143,
5147,
273,
501,
18,
70,
9835,
5147,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "./libs/DecMath.sol";
import "./moneymarkets/IMoneyMarket.sol";
import "./models/fee/IFeeModel.sol";
import "./models/interest/IInterestModel.sol";
import "./NFT.sol";
import "./rewards/MPHMinter.sol";
import "./models/interest-oracle/IInterestOracle.sol";
// DeLorean Interest -- It's coming back from the future!
// EL PSY CONGROO
// Author: Zefram Lou
// Contact: [email protected]
contract DInterest is ReentrancyGuard, Ownable {
using SafeMath for uint256;
using DecMath for uint256;
using SafeERC20 for ERC20;
using Address for address;
// Constants
uint256 internal constant PRECISION = 10**18;
uint256 internal constant ONE = 10**18;
uint256 internal constant EXTRA_PRECISION = 10**27; // used for sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
// User deposit data
// Each deposit has an ID used in the depositNFT, which is equal to its index in `deposits` plus 1
struct Deposit {
uint256 amount; // Amount of stablecoin deposited
uint256 maturationTimestamp; // Unix timestamp after which the deposit may be withdrawn, in seconds
uint256 interestOwed; // Deficit incurred to the pool at time of deposit
uint256 initialMoneyMarketIncomeIndex; // Money market's income index at time of deposit
bool active; // True if not yet withdrawn, false if withdrawn
bool finalSurplusIsNegative;
uint256 finalSurplusAmount; // Surplus remaining after withdrawal
uint256 mintMPHAmount; // Amount of MPH minted to user
uint256 depositTimestamp; // Unix timestamp at time of deposit, in seconds
}
Deposit[] internal deposits;
uint256 public latestFundedDepositID; // the ID of the most recently created deposit that was funded
uint256 public unfundedUserDepositAmount; // the deposited stablecoin amount (plus interest owed) whose deficit hasn't been funded
// Funding data
// Each funding has an ID used in the fundingNFT, which is equal to its index in `fundingList` plus 1
struct Funding {
// deposits with fromDepositID < ID <= toDepositID are funded
uint256 fromDepositID;
uint256 toDepositID;
uint256 recordedFundedDepositAmount; // the current stablecoin amount earning interest for the funder
uint256 recordedMoneyMarketIncomeIndex; // the income index at the last update (creation or withdrawal)
uint256 creationTimestamp; // Unix timestamp at time of deposit, in seconds
}
Funding[] internal fundingList;
// the sum of (recordedFundedDepositAmount / recordedMoneyMarketIncomeIndex) of all fundings
uint256
public sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex;
// Params
uint256 public MinDepositPeriod; // Minimum deposit period, in seconds
uint256 public MaxDepositPeriod; // Maximum deposit period, in seconds
uint256 public MinDepositAmount; // Minimum deposit amount for each deposit, in stablecoins
uint256 public MaxDepositAmount; // Maximum deposit amount for each deposit, in stablecoins
// Instance variables
uint256 public totalDeposit;
uint256 public totalInterestOwed;
// External smart contracts
IMoneyMarket public moneyMarket;
ERC20 public stablecoin;
IFeeModel public feeModel;
IInterestModel public interestModel;
IInterestOracle public interestOracle;
NFT public depositNFT;
NFT public fundingNFT;
MPHMinter public mphMinter;
// Events
event EDeposit(
address indexed sender,
uint256 indexed depositID,
uint256 amount,
uint256 maturationTimestamp,
uint256 interestAmount,
uint256 mintMPHAmount
);
event EWithdraw(
address indexed sender,
uint256 indexed depositID,
uint256 indexed fundingID,
bool early,
uint256 takeBackMPHAmount
);
event EFund(
address indexed sender,
uint256 indexed fundingID,
uint256 deficitAmount
);
event ESetParamAddress(
address indexed sender,
string indexed paramName,
address newValue
);
event ESetParamUint(
address indexed sender,
string indexed paramName,
uint256 newValue
);
struct DepositLimit {
uint256 MinDepositPeriod;
uint256 MaxDepositPeriod;
uint256 MinDepositAmount;
uint256 MaxDepositAmount;
}
constructor(
DepositLimit memory _depositLimit,
address _moneyMarket, // Address of IMoneyMarket that's used for generating interest (owner must be set to this DInterest contract)
address _stablecoin, // Address of the stablecoin used to store funds
address _feeModel, // Address of the FeeModel contract that determines how fees are charged
address _interestModel, // Address of the InterestModel contract that determines how much interest to offer
address _interestOracle, // Address of the InterestOracle contract that provides the average interest rate
address _depositNFT, // Address of the NFT representing ownership of deposits (owner must be set to this DInterest contract)
address _fundingNFT, // Address of the NFT representing ownership of fundings (owner must be set to this DInterest contract)
address _mphMinter // Address of the contract for handling minting MPH to users
) public {
// Verify input addresses
require(
_moneyMarket.isContract() &&
_stablecoin.isContract() &&
_feeModel.isContract() &&
_interestModel.isContract() &&
_interestOracle.isContract() &&
_depositNFT.isContract() &&
_fundingNFT.isContract() &&
_mphMinter.isContract(),
"DInterest: An input address is not a contract"
);
moneyMarket = IMoneyMarket(_moneyMarket);
stablecoin = ERC20(_stablecoin);
feeModel = IFeeModel(_feeModel);
interestModel = IInterestModel(_interestModel);
interestOracle = IInterestOracle(_interestOracle);
depositNFT = NFT(_depositNFT);
fundingNFT = NFT(_fundingNFT);
mphMinter = MPHMinter(_mphMinter);
// Ensure moneyMarket uses the same stablecoin
require(
moneyMarket.stablecoin() == _stablecoin,
"DInterest: moneyMarket.stablecoin() != _stablecoin"
);
// Ensure interestOracle uses the same moneyMarket
require(
interestOracle.moneyMarket() == _moneyMarket,
"DInterest: interestOracle.moneyMarket() != _moneyMarket"
);
// Verify input uint256 parameters
require(
_depositLimit.MaxDepositPeriod > 0 &&
_depositLimit.MaxDepositAmount > 0,
"DInterest: An input uint256 is 0"
);
require(
_depositLimit.MinDepositPeriod <= _depositLimit.MaxDepositPeriod,
"DInterest: Invalid DepositPeriod range"
);
require(
_depositLimit.MinDepositAmount <= _depositLimit.MaxDepositAmount,
"DInterest: Invalid DepositAmount range"
);
MinDepositPeriod = _depositLimit.MinDepositPeriod;
MaxDepositPeriod = _depositLimit.MaxDepositPeriod;
MinDepositAmount = _depositLimit.MinDepositAmount;
MaxDepositAmount = _depositLimit.MaxDepositAmount;
totalDeposit = 0;
}
/**
Public actions
*/
function deposit(uint256 amount, uint256 maturationTimestamp)
external
nonReentrant
{
_deposit(amount, maturationTimestamp);
}
function withdraw(uint256 depositID, uint256 fundingID)
external
nonReentrant
{
_withdraw(depositID, fundingID, false);
}
function earlyWithdraw(uint256 depositID, uint256 fundingID)
external
nonReentrant
{
_withdraw(depositID, fundingID, true);
}
function multiDeposit(
uint256[] calldata amountList,
uint256[] calldata maturationTimestampList
) external nonReentrant {
require(
amountList.length == maturationTimestampList.length,
"DInterest: List lengths unequal"
);
for (uint256 i = 0; i < amountList.length; i = i.add(1)) {
_deposit(amountList[i], maturationTimestampList[i]);
}
}
function multiWithdraw(
uint256[] calldata depositIDList,
uint256[] calldata fundingIDList
) external nonReentrant {
require(
depositIDList.length == fundingIDList.length,
"DInterest: List lengths unequal"
);
for (uint256 i = 0; i < depositIDList.length; i = i.add(1)) {
_withdraw(depositIDList[i], fundingIDList[i], false);
}
}
function multiEarlyWithdraw(
uint256[] calldata depositIDList,
uint256[] calldata fundingIDList
) external nonReentrant {
require(
depositIDList.length == fundingIDList.length,
"DInterest: List lengths unequal"
);
for (uint256 i = 0; i < depositIDList.length; i = i.add(1)) {
_withdraw(depositIDList[i], fundingIDList[i], true);
}
}
/**
Deficit funding
*/
function fundAll() external nonReentrant {
// Calculate current deficit
(bool isNegative, uint256 deficit) = surplus();
require(isNegative, "DInterest: No deficit available");
require(
!depositIsFunded(deposits.length),
"DInterest: All deposits funded"
);
// Create funding struct
uint256 incomeIndex = moneyMarket.incomeIndex();
require(incomeIndex > 0, "DInterest: incomeIndex == 0");
fundingList.push(
Funding({
fromDepositID: latestFundedDepositID,
toDepositID: deposits.length,
recordedFundedDepositAmount: unfundedUserDepositAmount,
recordedMoneyMarketIncomeIndex: incomeIndex,
creationTimestamp: now
})
);
// Update relevant values
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
.add(
unfundedUserDepositAmount.mul(EXTRA_PRECISION).div(incomeIndex)
);
latestFundedDepositID = deposits.length;
unfundedUserDepositAmount = 0;
_fund(deficit);
}
function fundMultiple(uint256 toDepositID) external nonReentrant {
require(
toDepositID > latestFundedDepositID,
"DInterest: Deposits already funded"
);
require(
toDepositID <= deposits.length,
"DInterest: Invalid toDepositID"
);
(bool isNegative, uint256 surplus) = surplus();
require(isNegative, "DInterest: No deficit available");
uint256 totalDeficit = 0;
uint256 totalSurplus = 0;
uint256 totalDepositAndInterestToFund = 0;
// Deposits with ID [latestFundedDepositID+1, toDepositID] will be funded
for (
uint256 id = latestFundedDepositID.add(1);
id <= toDepositID;
id = id.add(1)
) {
Deposit storage depositEntry = _getDeposit(id);
if (depositEntry.active) {
// Deposit still active, use current surplus
(isNegative, surplus) = surplusOfDeposit(id);
} else {
// Deposit has been withdrawn, use recorded final surplus
(isNegative, surplus) = (
depositEntry.finalSurplusIsNegative,
depositEntry.finalSurplusAmount
);
}
if (isNegative) {
// Add on deficit to total
totalDeficit = totalDeficit.add(surplus);
} else {
// Has surplus
totalSurplus = totalSurplus.add(surplus);
}
if (depositEntry.active) {
totalDepositAndInterestToFund = totalDepositAndInterestToFund
.add(depositEntry.amount)
.add(depositEntry.interestOwed);
}
}
if (totalSurplus >= totalDeficit) {
// Deposits selected have a surplus as a whole, revert
revert("DInterest: Selected deposits in surplus");
} else {
// Deduct surplus from totalDeficit
totalDeficit = totalDeficit.sub(totalSurplus);
}
// Create funding struct
uint256 incomeIndex = moneyMarket.incomeIndex();
require(incomeIndex > 0, "DInterest: incomeIndex == 0");
fundingList.push(
Funding({
fromDepositID: latestFundedDepositID,
toDepositID: toDepositID,
recordedFundedDepositAmount: totalDepositAndInterestToFund,
recordedMoneyMarketIncomeIndex: incomeIndex,
creationTimestamp: now
})
);
// Update relevant values
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
.add(
totalDepositAndInterestToFund.mul(EXTRA_PRECISION).div(incomeIndex)
);
latestFundedDepositID = toDepositID;
unfundedUserDepositAmount = unfundedUserDepositAmount.sub(
totalDepositAndInterestToFund
);
_fund(totalDeficit);
}
function payInterestToFunder(uint256 fundingID)
external
returns (uint256 interestAmount)
{
address funder = fundingNFT.ownerOf(fundingID);
require(funder == msg.sender, "DInterest: not funder");
Funding storage f = _getFunding(fundingID);
uint256 currentMoneyMarketIncomeIndex = moneyMarket.incomeIndex();
interestAmount = f
.recordedFundedDepositAmount
.mul(currentMoneyMarketIncomeIndex)
.div(f.recordedMoneyMarketIncomeIndex)
.sub(f.recordedFundedDepositAmount);
// Update funding values
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
.sub(
f.recordedFundedDepositAmount.mul(EXTRA_PRECISION).div(
f.recordedMoneyMarketIncomeIndex
)
);
f.recordedMoneyMarketIncomeIndex = currentMoneyMarketIncomeIndex;
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
.add(
f.recordedFundedDepositAmount.mul(EXTRA_PRECISION).div(
f.recordedMoneyMarketIncomeIndex
)
);
// Send interest to funder
if (interestAmount > 0) {
interestAmount = moneyMarket.withdraw(interestAmount);
if (interestAmount > 0) {
stablecoin.safeTransfer(funder, interestAmount);
}
}
}
/**
Public getters
*/
function calculateInterestAmount(
uint256 depositAmount,
uint256 depositPeriodInSeconds
) public returns (uint256 interestAmount) {
(, uint256 moneyMarketInterestRatePerSecond) =
interestOracle.updateAndQuery();
(bool surplusIsNegative, uint256 surplusAmount) = surplus();
return
interestModel.calculateInterestAmount(
depositAmount,
depositPeriodInSeconds,
moneyMarketInterestRatePerSecond,
surplusIsNegative,
surplusAmount
);
}
/**
@notice Computes the floating interest amount owed to deficit funders, which will be paid out
when a funded deposit is withdrawn.
Formula: \sum_i recordedFundedDepositAmount_i * (incomeIndex / recordedMoneyMarketIncomeIndex_i - 1)
= incomeIndex * (\sum_i recordedFundedDepositAmount_i / recordedMoneyMarketIncomeIndex_i)
- (totalDeposit + totalInterestOwed - unfundedUserDepositAmount)
where i refers to a funding
*/
function totalInterestOwedToFunders()
public
returns (uint256 interestOwed)
{
uint256 currentValue =
moneyMarket
.incomeIndex()
.mul(
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
)
.div(EXTRA_PRECISION);
uint256 initialValue =
totalDeposit.add(totalInterestOwed).sub(unfundedUserDepositAmount);
if (currentValue < initialValue) {
return 0;
}
return currentValue.sub(initialValue);
}
function surplus() public returns (bool isNegative, uint256 surplusAmount) {
uint256 totalValue = moneyMarket.totalValue();
uint256 totalOwed =
totalDeposit.add(totalInterestOwed).add(
totalInterestOwedToFunders()
);
if (totalValue >= totalOwed) {
// Locked value more than owed deposits, positive surplus
isNegative = false;
surplusAmount = totalValue.sub(totalOwed);
} else {
// Locked value less than owed deposits, negative surplus
isNegative = true;
surplusAmount = totalOwed.sub(totalValue);
}
}
function surplusOfDeposit(uint256 depositID)
public
returns (bool isNegative, uint256 surplusAmount)
{
Deposit storage depositEntry = _getDeposit(depositID);
uint256 currentMoneyMarketIncomeIndex = moneyMarket.incomeIndex();
uint256 currentDepositValue =
depositEntry.amount.mul(currentMoneyMarketIncomeIndex).div(
depositEntry.initialMoneyMarketIncomeIndex
);
uint256 owed = depositEntry.amount.add(depositEntry.interestOwed);
if (currentDepositValue >= owed) {
// Locked value more than owed deposits, positive surplus
isNegative = false;
surplusAmount = currentDepositValue.sub(owed);
} else {
// Locked value less than owed deposits, negative surplus
isNegative = true;
surplusAmount = owed.sub(currentDepositValue);
}
}
function depositIsFunded(uint256 id) public view returns (bool) {
return (id <= latestFundedDepositID);
}
function depositsLength() external view returns (uint256) {
return deposits.length;
}
function fundingListLength() external view returns (uint256) {
return fundingList.length;
}
function getDeposit(uint256 depositID)
external
view
returns (Deposit memory)
{
return deposits[depositID.sub(1)];
}
function getFunding(uint256 fundingID)
external
view
returns (Funding memory)
{
return fundingList[fundingID.sub(1)];
}
function moneyMarketIncomeIndex() external returns (uint256) {
return moneyMarket.incomeIndex();
}
/**
Param setters
*/
function setFeeModel(address newValue) external onlyOwner {
require(newValue.isContract(), "DInterest: not contract");
feeModel = IFeeModel(newValue);
emit ESetParamAddress(msg.sender, "feeModel", newValue);
}
function setInterestModel(address newValue) external onlyOwner {
require(newValue.isContract(), "DInterest: not contract");
interestModel = IInterestModel(newValue);
emit ESetParamAddress(msg.sender, "interestModel", newValue);
}
function setInterestOracle(address newValue) external onlyOwner {
require(newValue.isContract(), "DInterest: not contract");
interestOracle = IInterestOracle(newValue);
require(
interestOracle.moneyMarket() == address(moneyMarket),
"DInterest: moneyMarket mismatch"
);
emit ESetParamAddress(msg.sender, "interestOracle", newValue);
}
function setRewards(address newValue) external onlyOwner {
require(newValue.isContract(), "DInterest: not contract");
moneyMarket.setRewards(newValue);
emit ESetParamAddress(msg.sender, "moneyMarket.rewards", newValue);
}
function setMPHMinter(address newValue) external onlyOwner {
require(newValue.isContract(), "DInterest: not contract");
mphMinter = MPHMinter(newValue);
emit ESetParamAddress(msg.sender, "mphMinter", newValue);
}
function setMinDepositPeriod(uint256 newValue) external onlyOwner {
require(newValue <= MaxDepositPeriod, "DInterest: invalid value");
MinDepositPeriod = newValue;
emit ESetParamUint(msg.sender, "MinDepositPeriod", newValue);
}
function setMaxDepositPeriod(uint256 newValue) external onlyOwner {
require(
newValue >= MinDepositPeriod && newValue > 0,
"DInterest: invalid value"
);
MaxDepositPeriod = newValue;
emit ESetParamUint(msg.sender, "MaxDepositPeriod", newValue);
}
function setMinDepositAmount(uint256 newValue) external onlyOwner {
require(
newValue <= MaxDepositAmount && newValue > 0,
"DInterest: invalid value"
);
MinDepositAmount = newValue;
emit ESetParamUint(msg.sender, "MinDepositAmount", newValue);
}
function setMaxDepositAmount(uint256 newValue) external onlyOwner {
require(
newValue >= MinDepositAmount && newValue > 0,
"DInterest: invalid value"
);
MaxDepositAmount = newValue;
emit ESetParamUint(msg.sender, "MaxDepositAmount", newValue);
}
function setDepositNFTTokenURI(uint256 tokenId, string calldata newURI)
external
onlyOwner
{
depositNFT.setTokenURI(tokenId, newURI);
}
function setDepositNFTBaseURI(string calldata newURI) external onlyOwner {
depositNFT.setBaseURI(newURI);
}
function setDepositNFTContractURI(string calldata newURI)
external
onlyOwner
{
depositNFT.setContractURI(newURI);
}
function setFundingNFTTokenURI(uint256 tokenId, string calldata newURI)
external
onlyOwner
{
fundingNFT.setTokenURI(tokenId, newURI);
}
function setFundingNFTBaseURI(string calldata newURI) external onlyOwner {
fundingNFT.setBaseURI(newURI);
}
function setFundingNFTContractURI(string calldata newURI)
external
onlyOwner
{
fundingNFT.setContractURI(newURI);
}
/**
Internal getters
*/
function _getDeposit(uint256 depositID)
internal
view
returns (Deposit storage)
{
return deposits[depositID.sub(1)];
}
function _getFunding(uint256 fundingID)
internal
view
returns (Funding storage)
{
return fundingList[fundingID.sub(1)];
}
/**
Internals
*/
function _deposit(uint256 amount, uint256 maturationTimestamp) internal {
// Ensure deposit amount is not more than maximum
require(
amount >= MinDepositAmount && amount <= MaxDepositAmount,
"DInterest: Deposit amount out of range"
);
// Ensure deposit period is at least MinDepositPeriod
uint256 depositPeriod = maturationTimestamp.sub(now);
require(
depositPeriod >= MinDepositPeriod &&
depositPeriod <= MaxDepositPeriod,
"DInterest: Deposit period out of range"
);
// Update totalDeposit
totalDeposit = totalDeposit.add(amount);
// Calculate interest
uint256 interestAmount = calculateInterestAmount(amount, depositPeriod);
require(interestAmount > 0, "DInterest: interestAmount == 0");
// Update funding related data
uint256 id = deposits.length.add(1);
unfundedUserDepositAmount = unfundedUserDepositAmount.add(amount).add(
interestAmount
);
// Update totalInterestOwed
totalInterestOwed = totalInterestOwed.add(interestAmount);
// Mint MPH for msg.sender
uint256 mintMPHAmount =
mphMinter.mintDepositorReward(
msg.sender,
amount,
depositPeriod,
interestAmount
);
// Record deposit data for `msg.sender`
deposits.push(
Deposit({
amount: amount,
maturationTimestamp: maturationTimestamp,
interestOwed: interestAmount,
initialMoneyMarketIncomeIndex: moneyMarket.incomeIndex(),
active: true,
finalSurplusIsNegative: false,
finalSurplusAmount: 0,
mintMPHAmount: mintMPHAmount,
depositTimestamp: now
})
);
// Transfer `amount` stablecoin to DInterest
stablecoin.safeTransferFrom(msg.sender, address(this), amount);
// Lend `amount` stablecoin to money market
stablecoin.safeIncreaseAllowance(address(moneyMarket), amount);
moneyMarket.deposit(amount);
// Mint depositNFT
depositNFT.mint(msg.sender, id);
// Emit event
emit EDeposit(
msg.sender,
id,
amount,
maturationTimestamp,
interestAmount,
mintMPHAmount
);
}
function _withdraw(
uint256 depositID,
uint256 fundingID,
bool early
) internal {
Deposit storage depositEntry = _getDeposit(depositID);
// Verify deposit is active and set to inactive
require(depositEntry.active, "DInterest: Deposit not active");
depositEntry.active = false;
if (early) {
// Verify `now < depositEntry.maturationTimestamp`
require(
now < depositEntry.maturationTimestamp,
"DInterest: Deposit mature, use withdraw() instead"
);
// Verify `now > depositEntry.depositTimestamp`
require(
now > depositEntry.depositTimestamp,
"DInterest: Deposited in same block"
);
} else {
// Verify `now >= depositEntry.maturationTimestamp`
require(
now >= depositEntry.maturationTimestamp,
"DInterest: Deposit not mature"
);
}
// Verify msg.sender owns the depositNFT
require(
depositNFT.ownerOf(depositID) == msg.sender,
"DInterest: Sender doesn't own depositNFT"
);
// Restrict scope to prevent stack too deep error
{
// Take back MPH
uint256 takeBackMPHAmount =
mphMinter.takeBackDepositorReward(
msg.sender,
depositEntry.mintMPHAmount,
early
);
// Emit event
emit EWithdraw(
msg.sender,
depositID,
fundingID,
early,
takeBackMPHAmount
);
}
// Update totalDeposit
totalDeposit = totalDeposit.sub(depositEntry.amount);
// Update totalInterestOwed
totalInterestOwed = totalInterestOwed.sub(depositEntry.interestOwed);
// Fetch the income index & surplus before withdrawal, to prevent our withdrawal from
// increasing the income index when the money market vault total supply is extremely small
// (vault as in yEarn & Harvest vaults)
uint256 currentMoneyMarketIncomeIndex = moneyMarket.incomeIndex();
require(
currentMoneyMarketIncomeIndex > 0,
"DInterest: currentMoneyMarketIncomeIndex == 0"
);
(bool depositSurplusIsNegative, uint256 depositSurplus) =
surplusOfDeposit(depositID);
// Restrict scope to prevent stack too deep error
{
uint256 feeAmount;
uint256 withdrawAmount;
if (early) {
// Withdraw the principal of the deposit from money market
withdrawAmount = depositEntry.amount;
} else {
// Withdraw the principal & the interest from money market
feeAmount = feeModel.getFee(depositEntry.interestOwed);
withdrawAmount = depositEntry.amount.add(
depositEntry.interestOwed
);
}
withdrawAmount = moneyMarket.withdraw(withdrawAmount);
// Send `withdrawAmount - feeAmount` stablecoin to `msg.sender`
stablecoin.safeTransfer(msg.sender, withdrawAmount.sub(feeAmount));
// Send `feeAmount` stablecoin to feeModel beneficiary
if (feeAmount > 0) {
stablecoin.safeTransfer(feeModel.beneficiary(), feeAmount);
}
}
// If deposit was funded, payout interest to funder
if (depositIsFunded(depositID)) {
_payInterestToFunder(
fundingID,
depositID,
depositEntry.amount,
depositEntry.maturationTimestamp,
depositEntry.interestOwed,
depositSurplusIsNegative,
depositSurplus,
currentMoneyMarketIncomeIndex,
early
);
} else {
// Remove deposit from future deficit fundings
unfundedUserDepositAmount = unfundedUserDepositAmount.sub(
depositEntry.amount.add(depositEntry.interestOwed)
);
// Record remaining surplus
depositEntry.finalSurplusIsNegative = depositSurplusIsNegative;
depositEntry.finalSurplusAmount = depositSurplus;
}
}
function _payInterestToFunder(
uint256 fundingID,
uint256 depositID,
uint256 depositAmount,
uint256 depositMaturationTimestamp,
uint256 depositInterestOwed,
bool depositSurplusIsNegative,
uint256 depositSurplus,
uint256 currentMoneyMarketIncomeIndex,
bool early
) internal {
Funding storage f = _getFunding(fundingID);
require(
depositID > f.fromDepositID && depositID <= f.toDepositID,
"DInterest: Deposit not funded by fundingID"
);
uint256 interestAmount =
f
.recordedFundedDepositAmount
.mul(currentMoneyMarketIncomeIndex)
.div(f.recordedMoneyMarketIncomeIndex)
.sub(f.recordedFundedDepositAmount);
// Update funding values
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
.sub(
f.recordedFundedDepositAmount.mul(EXTRA_PRECISION).div(
f.recordedMoneyMarketIncomeIndex
)
);
f.recordedFundedDepositAmount = f.recordedFundedDepositAmount.sub(
depositAmount.add(depositInterestOwed)
);
f.recordedMoneyMarketIncomeIndex = currentMoneyMarketIncomeIndex;
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
.add(
f.recordedFundedDepositAmount.mul(EXTRA_PRECISION).div(
f.recordedMoneyMarketIncomeIndex
)
);
// Send interest to funder
address funder = fundingNFT.ownerOf(fundingID);
uint256 transferToFunderAmount =
(early && depositSurplusIsNegative)
? interestAmount.add(depositSurplus)
: interestAmount;
if (transferToFunderAmount > 0) {
transferToFunderAmount = moneyMarket.withdraw(
transferToFunderAmount
);
if (transferToFunderAmount > 0) {
stablecoin.safeTransfer(funder, transferToFunderAmount);
}
}
// Mint funder rewards
mphMinter.mintFunderReward(
funder,
depositAmount,
f.creationTimestamp,
depositMaturationTimestamp,
interestAmount,
early
);
}
function _fund(uint256 totalDeficit) internal {
// Transfer `totalDeficit` stablecoins from msg.sender
stablecoin.safeTransferFrom(msg.sender, address(this), totalDeficit);
// Deposit `totalDeficit` stablecoins into moneyMarket
stablecoin.safeIncreaseAllowance(address(moneyMarket), totalDeficit);
moneyMarket.deposit(totalDeficit);
// Mint fundingNFT
fundingNFT.mint(msg.sender, fundingList.length);
// Emit event
uint256 fundingID = fundingList.length;
emit EFund(msg.sender, fundingID, totalDeficit);
}
}
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.5.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {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;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
pragma solidity ^0.5.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract ReentrancyGuard {
bool private _notEntered;
constructor () internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
pragma solidity ^0.5.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.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/math/SafeMath.sol";
// Decimal math library
library DecMath {
using SafeMath for uint256;
uint256 internal constant PRECISION = 10**18;
function decmul(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(b).div(PRECISION);
}
function decdiv(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(PRECISION).div(b);
}
}
pragma solidity 0.5.17;
// Interface for money market protocols (Compound, Aave, bZx, etc.)
interface IMoneyMarket {
function deposit(uint256 amount) external;
function withdraw(uint256 amountInUnderlying)
external
returns (uint256 actualAmountWithdrawn);
function claimRewards() external; // Claims farmed tokens (e.g. COMP, CRV) and sends it to the rewards pool
function totalValue() external returns (uint256); // The total value locked in the money market, in terms of the underlying stablecoin
function incomeIndex() external returns (uint256); // Used for calculating the interest generated (e.g. cDai's price for the Compound market)
function stablecoin() external view returns (address);
function setRewards(address newValue) external;
event ESetParamAddress(
address indexed sender,
string indexed paramName,
address newValue
);
}
pragma solidity 0.5.17;
interface IFeeModel {
function beneficiary() external view returns (address payable);
function getFee(uint256 _txAmount)
external
pure
returns (uint256 _feeAmount);
}
pragma solidity 0.5.17;
interface IInterestModel {
function calculateInterestAmount(
uint256 depositAmount,
uint256 depositPeriodInSeconds,
uint256 moneyMarketInterestRatePerSecond,
bool surplusIsNegative,
uint256 surplusAmount
) external view returns (uint256 interestAmount);
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/token/ERC721/ERC721Metadata.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
contract NFT is ERC721Metadata, Ownable {
string internal _contractURI;
constructor(string memory name, string memory symbol)
public
ERC721Metadata(name, symbol)
{}
function contractURI() external view returns (string memory) {
return _contractURI;
}
function mint(address to, uint256 tokenId) external onlyOwner {
_safeMint(to, tokenId);
}
function burn(uint256 tokenId) external onlyOwner {
_burn(tokenId);
}
function setContractURI(string calldata newURI) external onlyOwner {
_contractURI = newURI;
}
function setTokenURI(uint256 tokenId, string calldata newURI)
external
onlyOwner
{
_setTokenURI(tokenId, newURI);
}
function setBaseURI(string calldata newURI) external onlyOwner {
_setBaseURI(newURI);
}
}
pragma solidity ^0.5.0;
import "../../GSN/Context.sol";
import "./ERC721.sol";
import "./IERC721Metadata.sol";
import "../../introspection/ERC165.sol";
contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Base URI
string private _baseURI;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/**
* @dev Constructor function
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
}
/**
* @dev Gets the token name.
* @return string representing the token name
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the URI for a given token ID. May return an empty string.
*
* If the token's URI is non-empty and a base URI was set (via
* {_setBaseURI}), it will be added to the token ID's URI as a prefix.
*
* Reverts if the token ID does not exist.
*/
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
// Even if there is a base URI, it is only appended to non-empty token-specific URIs
if (bytes(_tokenURI).length == 0) {
return "";
} else {
// abi.encodePacked is being used to concatenate strings
return string(abi.encodePacked(_baseURI, _tokenURI));
}
}
/**
* @dev Internal function to set the token URI for a given token.
*
* Reverts if the token ID does not exist.
*
* TIP: if all token IDs share a prefix (e.g. if your URIs look like
* `http://api.myproject.com/token/<id>`), use {_setBaseURI} to store
* it and save gas.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI}.
*
* _Available since v2.5.0._
*/
function _setBaseURI(string memory baseURI) internal {
_baseURI = baseURI;
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a preffix in {tokenURI} to each token's URI, when
* they are non-empty.
*
* _Available since v2.5.0._
*/
function baseURI() external view returns (string memory) {
return _baseURI;
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use _burn(uint256) instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
pragma solidity ^0.5.0;
import "../../GSN/Context.sol";
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
import "../../drafts/Counters.sol";
import "../../introspection/ERC165.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping (uint256 => address) private _tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => Counters.Counter) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
constructor () public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
}
/**
* @dev Gets the balance of the specified address.
* @param owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address owner) public view returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _ownedTokensCount[owner].current();
}
/**
* @dev Gets the owner of the specified token ID.
* @param tokenId uint256 ID of the token to query the owner of
* @return address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 tokenId) public view returns (address) {
address owner = _tokenOwner[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) public view returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf.
* @param to operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address to, bool approved) public {
require(to != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][to] = approved;
emit ApprovalForAll(_msgSender(), to, approved);
}
/**
* @dev Tells whether an operator is approved by a given owner.
* @param owner owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address owner, address operator) public view returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address.
* Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
* Requires the msg.sender to be the owner, approved, or operator.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address from, address to, uint256 tokenId) public {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transferFrom(from, to, tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the _msgSender() to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransferFrom(from, to, tokenId, _data);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal {
_transferFrom(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether the specified token exists.
* @param tokenId uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
/**
* @dev Returns whether the given spender can transfer a given token ID.
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _safeMint(address to, uint256 tokenId) internal {
_safeMint(to, tokenId, "");
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
* @param _data bytes data to send along with a safe transfer check
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, uint256 tokenId) internal {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].increment();
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {_burn} instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own");
_clearApproval(tokenId);
_ownedTokensCount[owner].decrement();
_tokenOwner[tokenId] = address(0);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* @param tokenId uint256 ID of the token being burned
*/
function _burn(uint256 tokenId) internal {
_burn(ownerOf(tokenId), tokenId);
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transferFrom(address from, address to, uint256 tokenId) internal {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_clearApproval(tokenId);
_ownedTokensCount[from].decrement();
_ownedTokensCount[to].increment();
_tokenOwner[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* This is an internal detail of the `ERC721` contract and its use is deprecated.
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
internal returns (bool)
{
if (!to.isContract()) {
return true;
}
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = to.call(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
));
if (!success) {
if (returndata.length > 0) {
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert("ERC721: transfer to non ERC721Receiver implementer");
}
} else {
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
}
/**
* @dev Private function to clear current approval of a given token ID.
* @param tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(uint256 tokenId) private {
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
pragma solidity ^0.5.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
contract IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of NFTs in `owner`'s account.
*/
function balanceOf(address owner) public view returns (uint256 balance);
/**
* @dev Returns the owner of the NFT specified by `tokenId`.
*/
function ownerOf(uint256 tokenId) public view returns (address owner);
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
*
*
* Requirements:
* - `from`, `to` cannot be zero.
* - `tokenId` must be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this
* NFT by either {approve} or {setApprovalForAll}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public;
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
* Requirements:
* - If the caller is not `from`, it must be approved to move this NFT by
* either {approve} or {setApprovalForAll}.
*/
function transferFrom(address from, address to, uint256 tokenId) public;
function approve(address to, uint256 tokenId) public;
function getApproved(uint256 tokenId) public view returns (address operator);
function setApprovalForAll(address operator, bool _approved) public;
function isApprovedForAll(address owner, address operator) public view returns (bool);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public;
}
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
pragma solidity ^0.5.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a {IERC721-safeTransferFrom}. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data)
public returns (bytes4);
}
pragma solidity ^0.5.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
pragma solidity ^0.5.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
pragma solidity ^0.5.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "./MPHToken.sol";
import "../models/issuance/IMPHIssuanceModel.sol";
import "./Vesting.sol";
contract MPHMinter is Ownable {
using Address for address;
using SafeMath for uint256;
mapping(address => bool) public poolWhitelist;
modifier onlyWhitelistedPool {
require(poolWhitelist[msg.sender], "MPHMinter: sender not whitelisted");
_;
}
event ESetParamAddress(
address indexed sender,
string indexed paramName,
address newValue
);
event WhitelistPool(
address indexed sender,
address pool,
bool isWhitelisted
);
event MintDepositorReward(
address indexed sender,
address indexed to,
uint256 depositorReward
);
event TakeBackDepositorReward(
address indexed sender,
address indexed from,
uint256 takeBackAmount
);
event MintFunderReward(
address indexed sender,
address indexed to,
uint256 funderReward
);
/**
External contracts
*/
MPHToken public mph;
address public govTreasury;
address public devWallet;
IMPHIssuanceModel public issuanceModel;
Vesting public vesting;
constructor(
address _mph,
address _govTreasury,
address _devWallet,
address _issuanceModel,
address _vesting
) public {
mph = MPHToken(_mph);
govTreasury = _govTreasury;
devWallet = _devWallet;
issuanceModel = IMPHIssuanceModel(_issuanceModel);
vesting = Vesting(_vesting);
}
/**
@notice Mints the MPH reward to a depositor upon deposit.
@param to The depositor
@param depositAmount The deposit amount in the pool's stablecoins
@param depositPeriodInSeconds The deposit's lock period in seconds
@param interestAmount The deposit's fixed-rate interest amount in the pool's stablecoins
@return depositorReward The MPH amount to mint to the depositor
*/
function mintDepositorReward(
address to,
uint256 depositAmount,
uint256 depositPeriodInSeconds,
uint256 interestAmount
) external onlyWhitelistedPool returns (uint256) {
if (mph.owner() != address(this)) {
// not the owner of the MPH token, cannot mint
emit MintDepositorReward(msg.sender, to, 0);
return 0;
}
(
uint256 depositorReward,
uint256 devReward,
uint256 govReward
) = issuanceModel.computeDepositorReward(
msg.sender,
depositAmount,
depositPeriodInSeconds,
interestAmount
);
if (depositorReward == 0 && devReward == 0 && govReward == 0) {
return 0;
}
// mint and vest depositor reward
mph.ownerMint(address(this), depositorReward);
uint256 vestPeriodInSeconds = issuanceModel
.poolDepositorRewardVestPeriod(msg.sender);
if (vestPeriodInSeconds == 0) {
// no vesting, transfer to `to`
mph.transfer(to, depositorReward);
} else {
// vest the MPH to `to`
mph.increaseAllowance(address(vesting), depositorReward);
vesting.vest(to, depositorReward, vestPeriodInSeconds);
}
mph.ownerMint(devWallet, devReward);
mph.ownerMint(govTreasury, govReward);
emit MintDepositorReward(msg.sender, to, depositorReward);
return depositorReward;
}
/**
@notice Takes back MPH from depositor upon withdrawal.
If takeBackAmount > devReward + govReward, the extra MPH should be burnt.
@param from The depositor
@param mintMPHAmount The MPH amount originally minted to the depositor as reward
@param early True if the deposit is withdrawn early, false if the deposit is mature
@return takeBackAmount The MPH amount to take back from the depositor
*/
function takeBackDepositorReward(
address from,
uint256 mintMPHAmount,
bool early
) external onlyWhitelistedPool returns (uint256) {
(
uint256 takeBackAmount,
uint256 devReward,
uint256 govReward
) = issuanceModel.computeTakeBackDepositorRewardAmount(
msg.sender,
mintMPHAmount,
early
);
if (takeBackAmount == 0 && devReward == 0 && govReward == 0) {
return 0;
}
require(
takeBackAmount >= devReward.add(govReward),
"MPHMinter: takeBackAmount < devReward + govReward"
);
mph.transferFrom(from, address(this), takeBackAmount);
mph.transfer(devWallet, devReward);
mph.transfer(govTreasury, govReward);
mph.burn(takeBackAmount.sub(devReward).sub(govReward));
emit TakeBackDepositorReward(msg.sender, from, takeBackAmount);
return takeBackAmount;
}
/**
@notice Mints the MPH reward to a deficit funder upon withdrawal of an underlying deposit.
@param to The funder
@param depositAmount The deposit amount in the pool's stablecoins
@param fundingCreationTimestamp The timestamp of the funding's creation, in seconds
@param maturationTimestamp The maturation timestamp of the deposit, in seconds
@param interestPayoutAmount The interest payout amount to the funder, in the pool's stablecoins.
Includes the interest from other funded deposits.
@param early True if the deposit is withdrawn early, false if the deposit is mature
@return funderReward The MPH amount to mint to the funder
*/
function mintFunderReward(
address to,
uint256 depositAmount,
uint256 fundingCreationTimestamp,
uint256 maturationTimestamp,
uint256 interestPayoutAmount,
bool early
) external onlyWhitelistedPool returns (uint256) {
if (mph.owner() != address(this)) {
// not the owner of the MPH token, cannot mint
emit MintDepositorReward(msg.sender, to, 0);
return 0;
}
(
uint256 funderReward,
uint256 devReward,
uint256 govReward
) = issuanceModel.computeFunderReward(
msg.sender,
depositAmount,
fundingCreationTimestamp,
maturationTimestamp,
interestPayoutAmount,
early
);
if (funderReward == 0 && devReward == 0 && govReward == 0) {
return 0;
}
// mint and vest funder reward
mph.ownerMint(address(this), funderReward);
uint256 vestPeriodInSeconds = issuanceModel.poolFunderRewardVestPeriod(
msg.sender
);
if (vestPeriodInSeconds == 0) {
// no vesting, transfer to `to`
mph.transfer(to, funderReward);
} else {
// vest the MPH to `to`
mph.increaseAllowance(address(vesting), funderReward);
vesting.vest(to, funderReward, vestPeriodInSeconds);
}
mph.ownerMint(devWallet, devReward);
mph.ownerMint(govTreasury, govReward);
emit MintFunderReward(msg.sender, to, funderReward);
return funderReward;
}
/**
Param setters
*/
function setGovTreasury(address newValue) external onlyOwner {
require(newValue != address(0), "MPHMinter: 0 address");
govTreasury = newValue;
emit ESetParamAddress(msg.sender, "govTreasury", newValue);
}
function setDevWallet(address newValue) external onlyOwner {
require(newValue != address(0), "MPHMinter: 0 address");
devWallet = newValue;
emit ESetParamAddress(msg.sender, "devWallet", newValue);
}
function setMPHTokenOwner(address newValue) external onlyOwner {
require(newValue != address(0), "MPHMinter: 0 address");
mph.transferOwnership(newValue);
emit ESetParamAddress(msg.sender, "mphTokenOwner", newValue);
}
function setMPHTokenOwnerToZero() external onlyOwner {
mph.renounceOwnership();
emit ESetParamAddress(msg.sender, "mphTokenOwner", address(0));
}
function setIssuanceModel(address newValue) external onlyOwner {
require(newValue.isContract(), "MPHMinter: not contract");
issuanceModel = IMPHIssuanceModel(newValue);
emit ESetParamAddress(msg.sender, "issuanceModel", newValue);
}
function setVesting(address newValue) external onlyOwner {
require(newValue.isContract(), "MPHMinter: not contract");
vesting = Vesting(newValue);
emit ESetParamAddress(msg.sender, "vesting", newValue);
}
function setPoolWhitelist(address pool, bool isWhitelisted)
external
onlyOwner
{
require(pool.isContract(), "MPHMinter: pool not contract");
poolWhitelist[pool] = isWhitelisted;
emit WhitelistPool(msg.sender, pool, isWhitelisted);
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
contract MPHToken is ERC20, ERC20Burnable, Ownable {
string public constant name = "88mph.app";
string public constant symbol = "MPH";
uint8 public constant decimals = 18;
bool public initialized;
function init() public {
require(!initialized, "MPHToken: initialized");
initialized = true;
_transferOwnership(msg.sender);
}
function ownerMint(address account, uint256 amount)
public
onlyOwner
returns (bool)
{
_mint(account, amount);
return true;
}
}
pragma solidity ^0.5.0;
import "../../GSN/Context.sol";
import "./ERC20.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public {
_burn(_msgSender(), amount);
}
/**
* @dev See {ERC20-_burnFrom}.
*/
function burnFrom(address account, uint256 amount) public {
_burnFrom(account, amount);
}
}
pragma solidity 0.5.17;
interface IMPHIssuanceModel {
/**
@notice Computes the MPH amount to reward to a depositor upon deposit.
@param pool The DInterest pool trying to mint reward
@param depositAmount The deposit amount in the pool's stablecoins
@param depositPeriodInSeconds The deposit's lock period in seconds
@param interestAmount The deposit's fixed-rate interest amount in the pool's stablecoins
@return depositorReward The MPH amount to mint to the depositor
devReward The MPH amount to mint to the dev wallet
govReward The MPH amount to mint to the gov treasury
*/
function computeDepositorReward(
address pool,
uint256 depositAmount,
uint256 depositPeriodInSeconds,
uint256 interestAmount
)
external
view
returns (
uint256 depositorReward,
uint256 devReward,
uint256 govReward
);
/**
@notice Computes the MPH amount to take back from a depositor upon withdrawal.
If takeBackAmount > devReward + govReward, the extra MPH should be burnt.
@param pool The DInterest pool trying to mint reward
@param mintMPHAmount The MPH amount originally minted to the depositor as reward
@param early True if the deposit is withdrawn early, false if the deposit is mature
@return takeBackAmount The MPH amount to take back from the depositor
devReward The MPH amount from takeBackAmount to send to the dev wallet
govReward The MPH amount from takeBackAmount to send to the gov treasury
*/
function computeTakeBackDepositorRewardAmount(
address pool,
uint256 mintMPHAmount,
bool early
)
external
view
returns (
uint256 takeBackAmount,
uint256 devReward,
uint256 govReward
);
/**
@notice Computes the MPH amount to reward to a deficit funder upon withdrawal of an underlying deposit.
@param pool The DInterest pool trying to mint reward
@param depositAmount The deposit amount in the pool's stablecoins
@param fundingCreationTimestamp The timestamp of the funding's creation, in seconds
@param maturationTimestamp The maturation timestamp of the deposit, in seconds
@param interestPayoutAmount The interest payout amount to the funder, in the pool's stablecoins.
Includes the interest from other funded deposits.
@param early True if the deposit is withdrawn early, false if the deposit is mature
@return funderReward The MPH amount to mint to the funder
devReward The MPH amount to mint to the dev wallet
govReward The MPH amount to mint to the gov treasury
*/
function computeFunderReward(
address pool,
uint256 depositAmount,
uint256 fundingCreationTimestamp,
uint256 maturationTimestamp,
uint256 interestPayoutAmount,
bool early
)
external
view
returns (
uint256 funderReward,
uint256 devReward,
uint256 govReward
);
/**
@notice The period over which the depositor reward will be vested, in seconds.
*/
function poolDepositorRewardVestPeriod(address pool)
external
view
returns (uint256 vestPeriodInSeconds);
/**
@notice The period over which the funder reward will be vested, in seconds.
*/
function poolFunderRewardVestPeriod(address pool)
external
view
returns (uint256 vestPeriodInSeconds);
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
contract Vesting {
using SafeERC20 for IERC20;
using SafeMath for uint256;
struct Vest {
uint256 amount;
uint256 vestPeriodInSeconds;
uint256 creationTimestamp;
uint256 withdrawnAmount;
}
mapping(address => Vest[]) public accountVestList;
IERC20 public token;
constructor(address _token) public {
token = IERC20(_token);
}
function vest(
address to,
uint256 amount,
uint256 vestPeriodInSeconds
) external returns (uint256 vestIdx) {
require(vestPeriodInSeconds > 0, "Vesting: vestPeriodInSeconds == 0");
// transfer `amount` tokens from `msg.sender`
token.safeTransferFrom(msg.sender, address(this), amount);
// create vest object
vestIdx = accountVestList[to].length;
accountVestList[to].push(
Vest({
amount: amount,
vestPeriodInSeconds: vestPeriodInSeconds,
creationTimestamp: now,
withdrawnAmount: 0
})
);
}
function withdrawVested(address account, uint256 vestIdx)
external
returns (uint256 withdrawnAmount)
{
// compute withdrawable amount
withdrawnAmount = _getVestWithdrawableAmount(account, vestIdx);
if (withdrawnAmount == 0) {
return 0;
}
// update vest object
uint256 recordedWithdrawnAmount = accountVestList[account][vestIdx]
.withdrawnAmount;
accountVestList[account][vestIdx]
.withdrawnAmount = recordedWithdrawnAmount.add(withdrawnAmount);
// transfer tokens to vest recipient
token.safeTransfer(account, withdrawnAmount);
}
function getVestWithdrawableAmount(address account, uint256 vestIdx)
external
view
returns (uint256)
{
return _getVestWithdrawableAmount(account, vestIdx);
}
function _getVestWithdrawableAmount(address account, uint256 vestIdx)
internal
view
returns (uint256)
{
// read vest data
Vest storage vest = accountVestList[account][vestIdx];
uint256 vestFullAmount = vest.amount;
uint256 vestCreationTimestamp = vest.creationTimestamp;
uint256 vestPeriodInSeconds = vest.vestPeriodInSeconds;
// compute vested amount
uint256 vestedAmount;
if (now >= vestCreationTimestamp.add(vestPeriodInSeconds)) {
// vest period has passed, fully withdrawable
vestedAmount = vestFullAmount;
} else {
// vest period has not passed, linearly unlock
vestedAmount = vestFullAmount
.mul(now.sub(vestCreationTimestamp))
.div(vestPeriodInSeconds);
}
// deduct already withdrawn amount and return
return vestedAmount.sub(vest.withdrawnAmount);
}
}
pragma solidity 0.5.17;
interface IInterestOracle {
function updateAndQuery() external returns (bool updated, uint256 value);
function query() external view returns (uint256 value);
function moneyMarket() external view returns (address);
}
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "./libs/DecMath.sol";
import "./moneymarkets/IMoneyMarket.sol";
import "./models/fee/IFeeModel.sol";
import "./models/interest/IInterestModel.sol";
import "./NFT.sol";
import "./rewards/MPHMinter.sol";
import "./models/interest-oracle/IInterestOracle.sol";
// DeLorean Interest -- It's coming back from the future!
// EL PSY CONGROO
// Author: Zefram Lou
// Contact: [email protected]
contract DInterestWithDepositFee is ReentrancyGuard, Ownable {
using SafeMath for uint256;
using DecMath for uint256;
using SafeERC20 for ERC20;
using Address for address;
// Constants
uint256 internal constant PRECISION = 10**18;
uint256 internal constant ONE = 10**18;
uint256 internal constant EXTRA_PRECISION = 10**27; // used for sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
// User deposit data
// Each deposit has an ID used in the depositNFT, which is equal to its index in `deposits` plus 1
struct Deposit {
uint256 amount; // Amount of stablecoin deposited
uint256 maturationTimestamp; // Unix timestamp after which the deposit may be withdrawn, in seconds
uint256 interestOwed; // Deficit incurred to the pool at time of deposit
uint256 initialMoneyMarketIncomeIndex; // Money market's income index at time of deposit
bool active; // True if not yet withdrawn, false if withdrawn
bool finalSurplusIsNegative;
uint256 finalSurplusAmount; // Surplus remaining after withdrawal
uint256 mintMPHAmount; // Amount of MPH minted to user
uint256 depositTimestamp; // Unix timestamp at time of deposit, in seconds
}
Deposit[] internal deposits;
uint256 public latestFundedDepositID; // the ID of the most recently created deposit that was funded
uint256 public unfundedUserDepositAmount; // the deposited stablecoin amount (plus interest owed) whose deficit hasn't been funded
// Funding data
// Each funding has an ID used in the fundingNFT, which is equal to its index in `fundingList` plus 1
struct Funding {
// deposits with fromDepositID < ID <= toDepositID are funded
uint256 fromDepositID;
uint256 toDepositID;
uint256 recordedFundedDepositAmount; // the current stablecoin amount earning interest for the funder
uint256 recordedMoneyMarketIncomeIndex; // the income index at the last update (creation or withdrawal)
uint256 creationTimestamp; // Unix timestamp at time of deposit, in seconds
}
Funding[] internal fundingList;
// the sum of (recordedFundedDepositAmount / recordedMoneyMarketIncomeIndex) of all fundings
uint256
public sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex;
// Params
uint256 public MinDepositPeriod; // Minimum deposit period, in seconds
uint256 public MaxDepositPeriod; // Maximum deposit period, in seconds
uint256 public MinDepositAmount; // Minimum deposit amount for each deposit, in stablecoins
uint256 public MaxDepositAmount; // Maximum deposit amount for each deposit, in stablecoins
uint256 public DepositFee; // The deposit fee charged by the money market
// Instance variables
uint256 public totalDeposit;
uint256 public totalInterestOwed;
// External smart contracts
IMoneyMarket public moneyMarket;
ERC20 public stablecoin;
IFeeModel public feeModel;
IInterestModel public interestModel;
IInterestOracle public interestOracle;
NFT public depositNFT;
NFT public fundingNFT;
MPHMinter public mphMinter;
// Events
event EDeposit(
address indexed sender,
uint256 indexed depositID,
uint256 amount,
uint256 maturationTimestamp,
uint256 interestAmount,
uint256 mintMPHAmount
);
event EWithdraw(
address indexed sender,
uint256 indexed depositID,
uint256 indexed fundingID,
bool early,
uint256 takeBackMPHAmount
);
event EFund(
address indexed sender,
uint256 indexed fundingID,
uint256 deficitAmount
);
event ESetParamAddress(
address indexed sender,
string indexed paramName,
address newValue
);
event ESetParamUint(
address indexed sender,
string indexed paramName,
uint256 newValue
);
struct DepositLimit {
uint256 MinDepositPeriod;
uint256 MaxDepositPeriod;
uint256 MinDepositAmount;
uint256 MaxDepositAmount;
uint256 DepositFee;
}
constructor(
DepositLimit memory _depositLimit,
address _moneyMarket, // Address of IMoneyMarket that's used for generating interest (owner must be set to this DInterest contract)
address _stablecoin, // Address of the stablecoin used to store funds
address _feeModel, // Address of the FeeModel contract that determines how fees are charged
address _interestModel, // Address of the InterestModel contract that determines how much interest to offer
address _interestOracle, // Address of the InterestOracle contract that provides the average interest rate
address _depositNFT, // Address of the NFT representing ownership of deposits (owner must be set to this DInterest contract)
address _fundingNFT, // Address of the NFT representing ownership of fundings (owner must be set to this DInterest contract)
address _mphMinter // Address of the contract for handling minting MPH to users
) public {
// Verify input addresses
require(
_moneyMarket.isContract() &&
_stablecoin.isContract() &&
_feeModel.isContract() &&
_interestModel.isContract() &&
_interestOracle.isContract() &&
_depositNFT.isContract() &&
_fundingNFT.isContract() &&
_mphMinter.isContract(),
"DInterest: An input address is not a contract"
);
moneyMarket = IMoneyMarket(_moneyMarket);
stablecoin = ERC20(_stablecoin);
feeModel = IFeeModel(_feeModel);
interestModel = IInterestModel(_interestModel);
interestOracle = IInterestOracle(_interestOracle);
depositNFT = NFT(_depositNFT);
fundingNFT = NFT(_fundingNFT);
mphMinter = MPHMinter(_mphMinter);
// Ensure moneyMarket uses the same stablecoin
require(
moneyMarket.stablecoin() == _stablecoin,
"DInterest: moneyMarket.stablecoin() != _stablecoin"
);
// Ensure interestOracle uses the same moneyMarket
require(
interestOracle.moneyMarket() == _moneyMarket,
"DInterest: interestOracle.moneyMarket() != _moneyMarket"
);
// Verify input uint256 parameters
require(
_depositLimit.MaxDepositPeriod > 0 &&
_depositLimit.MaxDepositAmount > 0,
"DInterest: An input uint256 is 0"
);
require(
_depositLimit.MinDepositPeriod <= _depositLimit.MaxDepositPeriod,
"DInterest: Invalid DepositPeriod range"
);
require(
_depositLimit.MinDepositAmount <= _depositLimit.MaxDepositAmount,
"DInterest: Invalid DepositAmount range"
);
MinDepositPeriod = _depositLimit.MinDepositPeriod;
MaxDepositPeriod = _depositLimit.MaxDepositPeriod;
MinDepositAmount = _depositLimit.MinDepositAmount;
MaxDepositAmount = _depositLimit.MaxDepositAmount;
DepositFee = _depositLimit.DepositFee;
totalDeposit = 0;
}
/**
Public actions
*/
function deposit(uint256 amount, uint256 maturationTimestamp)
external
nonReentrant
{
_deposit(amount, maturationTimestamp);
}
function withdraw(uint256 depositID, uint256 fundingID)
external
nonReentrant
{
_withdraw(depositID, fundingID, false);
}
function earlyWithdraw(uint256 depositID, uint256 fundingID)
external
nonReentrant
{
_withdraw(depositID, fundingID, true);
}
function multiDeposit(
uint256[] calldata amountList,
uint256[] calldata maturationTimestampList
) external nonReentrant {
require(
amountList.length == maturationTimestampList.length,
"DInterest: List lengths unequal"
);
for (uint256 i = 0; i < amountList.length; i = i.add(1)) {
_deposit(amountList[i], maturationTimestampList[i]);
}
}
function multiWithdraw(
uint256[] calldata depositIDList,
uint256[] calldata fundingIDList
) external nonReentrant {
require(
depositIDList.length == fundingIDList.length,
"DInterest: List lengths unequal"
);
for (uint256 i = 0; i < depositIDList.length; i = i.add(1)) {
_withdraw(depositIDList[i], fundingIDList[i], false);
}
}
function multiEarlyWithdraw(
uint256[] calldata depositIDList,
uint256[] calldata fundingIDList
) external nonReentrant {
require(
depositIDList.length == fundingIDList.length,
"DInterest: List lengths unequal"
);
for (uint256 i = 0; i < depositIDList.length; i = i.add(1)) {
_withdraw(depositIDList[i], fundingIDList[i], true);
}
}
/**
Deficit funding
*/
function fundAll() external nonReentrant {
// Calculate current deficit
(bool isNegative, uint256 deficit) = surplus();
require(isNegative, "DInterest: No deficit available");
require(
!depositIsFunded(deposits.length),
"DInterest: All deposits funded"
);
// Create funding struct
uint256 incomeIndex = moneyMarket.incomeIndex();
require(incomeIndex > 0, "DInterest: incomeIndex == 0");
fundingList.push(
Funding({
fromDepositID: latestFundedDepositID,
toDepositID: deposits.length,
recordedFundedDepositAmount: unfundedUserDepositAmount,
recordedMoneyMarketIncomeIndex: incomeIndex,
creationTimestamp: now
})
);
// Update relevant values
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
.add(
unfundedUserDepositAmount.mul(EXTRA_PRECISION).div(incomeIndex)
);
latestFundedDepositID = deposits.length;
unfundedUserDepositAmount = 0;
_fund(deficit);
}
function fundMultiple(uint256 toDepositID) external nonReentrant {
require(
toDepositID > latestFundedDepositID,
"DInterest: Deposits already funded"
);
require(
toDepositID <= deposits.length,
"DInterest: Invalid toDepositID"
);
(bool isNegative, uint256 surplus) = surplus();
require(isNegative, "DInterest: No deficit available");
uint256 totalDeficit = 0;
uint256 totalSurplus = 0;
uint256 totalDepositAndInterestToFund = 0;
// Deposits with ID [latestFundedDepositID+1, toDepositID] will be funded
for (
uint256 id = latestFundedDepositID.add(1);
id <= toDepositID;
id = id.add(1)
) {
Deposit storage depositEntry = _getDeposit(id);
if (depositEntry.active) {
// Deposit still active, use current surplus
(isNegative, surplus) = surplusOfDeposit(id);
} else {
// Deposit has been withdrawn, use recorded final surplus
(isNegative, surplus) = (
depositEntry.finalSurplusIsNegative,
depositEntry.finalSurplusAmount
);
}
if (isNegative) {
// Add on deficit to total
totalDeficit = totalDeficit.add(surplus);
} else {
// Has surplus
totalSurplus = totalSurplus.add(surplus);
}
if (depositEntry.active) {
totalDepositAndInterestToFund = totalDepositAndInterestToFund
.add(depositEntry.amount)
.add(depositEntry.interestOwed);
}
}
if (totalSurplus >= totalDeficit) {
// Deposits selected have a surplus as a whole, revert
revert("DInterest: Selected deposits in surplus");
} else {
// Deduct surplus from totalDeficit
totalDeficit = totalDeficit.sub(totalSurplus);
}
// Create funding struct
uint256 incomeIndex = moneyMarket.incomeIndex();
require(incomeIndex > 0, "DInterest: incomeIndex == 0");
fundingList.push(
Funding({
fromDepositID: latestFundedDepositID,
toDepositID: toDepositID,
recordedFundedDepositAmount: totalDepositAndInterestToFund,
recordedMoneyMarketIncomeIndex: incomeIndex,
creationTimestamp: now
})
);
// Update relevant values
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
.add(
totalDepositAndInterestToFund.mul(EXTRA_PRECISION).div(incomeIndex)
);
latestFundedDepositID = toDepositID;
unfundedUserDepositAmount = unfundedUserDepositAmount.sub(
totalDepositAndInterestToFund
);
_fund(totalDeficit);
}
function payInterestToFunder(uint256 fundingID)
external
returns (uint256 interestAmount)
{
address funder = fundingNFT.ownerOf(fundingID);
require(funder == msg.sender, "DInterest: not funder");
Funding storage f = _getFunding(fundingID);
uint256 currentMoneyMarketIncomeIndex = moneyMarket.incomeIndex();
interestAmount = f
.recordedFundedDepositAmount
.mul(currentMoneyMarketIncomeIndex)
.div(f.recordedMoneyMarketIncomeIndex)
.sub(f.recordedFundedDepositAmount);
// Update funding values
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
.sub(
f.recordedFundedDepositAmount.mul(EXTRA_PRECISION).div(
f.recordedMoneyMarketIncomeIndex
)
);
f.recordedMoneyMarketIncomeIndex = currentMoneyMarketIncomeIndex;
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
.add(
f.recordedFundedDepositAmount.mul(EXTRA_PRECISION).div(
f.recordedMoneyMarketIncomeIndex
)
);
// Send interest to funder
if (interestAmount > 0) {
interestAmount = moneyMarket.withdraw(interestAmount);
if (interestAmount > 0) {
stablecoin.safeTransfer(funder, interestAmount);
}
}
}
/**
Public getters
*/
function calculateInterestAmount(
uint256 depositAmount,
uint256 depositPeriodInSeconds
) public returns (uint256 interestAmount) {
(, uint256 moneyMarketInterestRatePerSecond) =
interestOracle.updateAndQuery();
(bool surplusIsNegative, uint256 surplusAmount) = surplus();
return
interestModel.calculateInterestAmount(
depositAmount,
depositPeriodInSeconds,
moneyMarketInterestRatePerSecond,
surplusIsNegative,
surplusAmount
);
}
/**
@notice Computes the floating interest amount owed to deficit funders, which will be paid out
when a funded deposit is withdrawn.
Formula: \sum_i recordedFundedDepositAmount_i * (incomeIndex / recordedMoneyMarketIncomeIndex_i - 1)
= incomeIndex * (\sum_i recordedFundedDepositAmount_i / recordedMoneyMarketIncomeIndex_i)
- (totalDeposit + totalInterestOwed - unfundedUserDepositAmount)
where i refers to a funding
*/
function totalInterestOwedToFunders()
public
returns (uint256 interestOwed)
{
uint256 currentValue =
moneyMarket
.incomeIndex()
.mul(
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
)
.div(EXTRA_PRECISION);
uint256 initialValue =
totalDeposit.add(totalInterestOwed).sub(unfundedUserDepositAmount);
if (currentValue < initialValue) {
return 0;
}
return currentValue.sub(initialValue);
}
function surplus() public returns (bool isNegative, uint256 surplusAmount) {
uint256 totalValue = moneyMarket.totalValue();
uint256 totalOwed =
totalDeposit.add(totalInterestOwed).add(
totalInterestOwedToFunders()
);
if (totalValue >= totalOwed) {
// Locked value more than owed deposits, positive surplus
isNegative = false;
surplusAmount = totalValue.sub(totalOwed);
} else {
// Locked value less than owed deposits, negative surplus
isNegative = true;
surplusAmount = totalOwed.sub(totalValue);
}
}
function surplusOfDeposit(uint256 depositID)
public
returns (bool isNegative, uint256 surplusAmount)
{
Deposit storage depositEntry = _getDeposit(depositID);
uint256 currentMoneyMarketIncomeIndex = moneyMarket.incomeIndex();
uint256 currentDepositValue =
depositEntry.amount.mul(currentMoneyMarketIncomeIndex).div(
depositEntry.initialMoneyMarketIncomeIndex
);
uint256 owed = depositEntry.amount.add(depositEntry.interestOwed);
if (currentDepositValue >= owed) {
// Locked value more than owed deposits, positive surplus
isNegative = false;
surplusAmount = currentDepositValue.sub(owed);
} else {
// Locked value less than owed deposits, negative surplus
isNegative = true;
surplusAmount = owed.sub(currentDepositValue);
}
}
function depositIsFunded(uint256 id) public view returns (bool) {
return (id <= latestFundedDepositID);
}
function depositsLength() external view returns (uint256) {
return deposits.length;
}
function fundingListLength() external view returns (uint256) {
return fundingList.length;
}
function getDeposit(uint256 depositID)
external
view
returns (Deposit memory)
{
return deposits[depositID.sub(1)];
}
function getFunding(uint256 fundingID)
external
view
returns (Funding memory)
{
return fundingList[fundingID.sub(1)];
}
function moneyMarketIncomeIndex() external returns (uint256) {
return moneyMarket.incomeIndex();
}
/**
Param setters
*/
function setFeeModel(address newValue) external onlyOwner {
require(newValue.isContract(), "DInterest: not contract");
feeModel = IFeeModel(newValue);
emit ESetParamAddress(msg.sender, "feeModel", newValue);
}
function setInterestModel(address newValue) external onlyOwner {
require(newValue.isContract(), "DInterest: not contract");
interestModel = IInterestModel(newValue);
emit ESetParamAddress(msg.sender, "interestModel", newValue);
}
function setInterestOracle(address newValue) external onlyOwner {
require(newValue.isContract(), "DInterest: not contract");
interestOracle = IInterestOracle(newValue);
require(
interestOracle.moneyMarket() == address(moneyMarket),
"DInterest: moneyMarket mismatch"
);
emit ESetParamAddress(msg.sender, "interestOracle", newValue);
}
function setRewards(address newValue) external onlyOwner {
require(newValue.isContract(), "DInterest: not contract");
moneyMarket.setRewards(newValue);
emit ESetParamAddress(msg.sender, "moneyMarket.rewards", newValue);
}
function setMPHMinter(address newValue) external onlyOwner {
require(newValue.isContract(), "DInterest: not contract");
mphMinter = MPHMinter(newValue);
emit ESetParamAddress(msg.sender, "mphMinter", newValue);
}
function setMinDepositPeriod(uint256 newValue) external onlyOwner {
require(newValue <= MaxDepositPeriod, "DInterest: invalid value");
MinDepositPeriod = newValue;
emit ESetParamUint(msg.sender, "MinDepositPeriod", newValue);
}
function setMaxDepositPeriod(uint256 newValue) external onlyOwner {
require(
newValue >= MinDepositPeriod && newValue > 0,
"DInterest: invalid value"
);
MaxDepositPeriod = newValue;
emit ESetParamUint(msg.sender, "MaxDepositPeriod", newValue);
}
function setMinDepositAmount(uint256 newValue) external onlyOwner {
require(
newValue <= MaxDepositAmount && newValue > 0,
"DInterest: invalid value"
);
MinDepositAmount = newValue;
emit ESetParamUint(msg.sender, "MinDepositAmount", newValue);
}
function setMaxDepositAmount(uint256 newValue) external onlyOwner {
require(
newValue >= MinDepositAmount && newValue > 0,
"DInterest: invalid value"
);
MaxDepositAmount = newValue;
emit ESetParamUint(msg.sender, "MaxDepositAmount", newValue);
}
function setDepositFee(uint256 newValue) external onlyOwner {
require(
newValue < PRECISION,
"DInterest: invalid value"
);
DepositFee = newValue;
emit ESetParamUint(msg.sender, "DepositFee", newValue);
}
function setDepositNFTTokenURI(uint256 tokenId, string calldata newURI)
external
onlyOwner
{
depositNFT.setTokenURI(tokenId, newURI);
}
function setDepositNFTBaseURI(string calldata newURI) external onlyOwner {
depositNFT.setBaseURI(newURI);
}
function setDepositNFTContractURI(string calldata newURI)
external
onlyOwner
{
depositNFT.setContractURI(newURI);
}
function setFundingNFTTokenURI(uint256 tokenId, string calldata newURI)
external
onlyOwner
{
fundingNFT.setTokenURI(tokenId, newURI);
}
function setFundingNFTBaseURI(string calldata newURI) external onlyOwner {
fundingNFT.setBaseURI(newURI);
}
function setFundingNFTContractURI(string calldata newURI)
external
onlyOwner
{
fundingNFT.setContractURI(newURI);
}
/**
Internal getters
*/
function _getDeposit(uint256 depositID)
internal
view
returns (Deposit storage)
{
return deposits[depositID.sub(1)];
}
function _getFunding(uint256 fundingID)
internal
view
returns (Funding storage)
{
return fundingList[fundingID.sub(1)];
}
function _applyDepositFee(uint256 depositAmount)
internal
view
returns (uint256)
{
return depositAmount.mul(PRECISION.sub(DepositFee)).div(PRECISION);
}
/**
Internals
*/
function _deposit(uint256 amount, uint256 maturationTimestamp) internal {
// Ensure deposit amount is not more than maximum
require(
amount >= MinDepositAmount && amount <= MaxDepositAmount,
"DInterest: Deposit amount out of range"
);
// Ensure deposit period is at least MinDepositPeriod
uint256 depositPeriod = maturationTimestamp.sub(now);
require(
depositPeriod >= MinDepositPeriod &&
depositPeriod <= MaxDepositPeriod,
"DInterest: Deposit period out of range"
);
// Apply fee to deposit amount
amount = _applyDepositFee(amount);
// Update totalDeposit
totalDeposit = totalDeposit.add(amount);
// Calculate interest
uint256 interestAmount = calculateInterestAmount(amount, depositPeriod);
require(interestAmount > 0, "DInterest: interestAmount == 0");
// Update funding related data
uint256 id = deposits.length.add(1);
unfundedUserDepositAmount = unfundedUserDepositAmount.add(amount).add(
interestAmount
);
// Update totalInterestOwed
totalInterestOwed = totalInterestOwed.add(interestAmount);
// Mint MPH for msg.sender
uint256 mintMPHAmount =
mphMinter.mintDepositorReward(
msg.sender,
amount,
depositPeriod,
interestAmount
);
// Record deposit data for `msg.sender`
deposits.push(
Deposit({
amount: amount,
maturationTimestamp: maturationTimestamp,
interestOwed: interestAmount,
initialMoneyMarketIncomeIndex: moneyMarket.incomeIndex(),
active: true,
finalSurplusIsNegative: false,
finalSurplusAmount: 0,
mintMPHAmount: mintMPHAmount,
depositTimestamp: now
})
);
// Transfer `amount` stablecoin to DInterest
stablecoin.safeTransferFrom(msg.sender, address(this), amount);
// Lend `amount` stablecoin to money market
stablecoin.safeIncreaseAllowance(address(moneyMarket), amount);
moneyMarket.deposit(amount);
// Mint depositNFT
depositNFT.mint(msg.sender, id);
// Emit event
emit EDeposit(
msg.sender,
id,
amount,
maturationTimestamp,
interestAmount,
mintMPHAmount
);
}
function _withdraw(
uint256 depositID,
uint256 fundingID,
bool early
) internal {
Deposit storage depositEntry = _getDeposit(depositID);
// Verify deposit is active and set to inactive
require(depositEntry.active, "DInterest: Deposit not active");
depositEntry.active = false;
if (early) {
// Verify `now < depositEntry.maturationTimestamp`
require(
now < depositEntry.maturationTimestamp,
"DInterest: Deposit mature, use withdraw() instead"
);
// Verify `now > depositEntry.depositTimestamp`
require(
now > depositEntry.depositTimestamp,
"DInterest: Deposited in same block"
);
} else {
// Verify `now >= depositEntry.maturationTimestamp`
require(
now >= depositEntry.maturationTimestamp,
"DInterest: Deposit not mature"
);
}
// Verify msg.sender owns the depositNFT
require(
depositNFT.ownerOf(depositID) == msg.sender,
"DInterest: Sender doesn't own depositNFT"
);
// Restrict scope to prevent stack too deep error
{
// Take back MPH
uint256 takeBackMPHAmount =
mphMinter.takeBackDepositorReward(
msg.sender,
depositEntry.mintMPHAmount,
early
);
// Emit event
emit EWithdraw(
msg.sender,
depositID,
fundingID,
early,
takeBackMPHAmount
);
}
// Update totalDeposit
totalDeposit = totalDeposit.sub(depositEntry.amount);
// Update totalInterestOwed
totalInterestOwed = totalInterestOwed.sub(depositEntry.interestOwed);
// Fetch the income index & surplus before withdrawal, to prevent our withdrawal from
// increasing the income index when the money market vault total supply is extremely small
// (vault as in yEarn & Harvest vaults)
uint256 currentMoneyMarketIncomeIndex = moneyMarket.incomeIndex();
require(
currentMoneyMarketIncomeIndex > 0,
"DInterest: currentMoneyMarketIncomeIndex == 0"
);
(bool depositSurplusIsNegative, uint256 depositSurplus) =
surplusOfDeposit(depositID);
// Restrict scope to prevent stack too deep error
{
uint256 feeAmount;
uint256 withdrawAmount;
if (early) {
// Withdraw the principal of the deposit from money market
withdrawAmount = depositEntry.amount;
} else {
// Withdraw the principal & the interest from money market
feeAmount = feeModel.getFee(depositEntry.interestOwed);
withdrawAmount = depositEntry.amount.add(
depositEntry.interestOwed
);
}
withdrawAmount = moneyMarket.withdraw(withdrawAmount);
// Send `withdrawAmount - feeAmount` stablecoin to `msg.sender`
stablecoin.safeTransfer(msg.sender, withdrawAmount.sub(feeAmount));
// Send `feeAmount` stablecoin to feeModel beneficiary
if (feeAmount > 0) {
stablecoin.safeTransfer(feeModel.beneficiary(), feeAmount);
}
}
// If deposit was funded, payout interest to funder
if (depositIsFunded(depositID)) {
_payInterestToFunder(
fundingID,
depositID,
depositEntry.amount,
depositEntry.maturationTimestamp,
depositEntry.interestOwed,
depositSurplusIsNegative,
depositSurplus,
currentMoneyMarketIncomeIndex,
early
);
} else {
// Remove deposit from future deficit fundings
unfundedUserDepositAmount = unfundedUserDepositAmount.sub(
depositEntry.amount.add(depositEntry.interestOwed)
);
// Record remaining surplus
depositEntry.finalSurplusIsNegative = depositSurplusIsNegative;
depositEntry.finalSurplusAmount = depositSurplus;
}
}
function _payInterestToFunder(
uint256 fundingID,
uint256 depositID,
uint256 depositAmount,
uint256 depositMaturationTimestamp,
uint256 depositInterestOwed,
bool depositSurplusIsNegative,
uint256 depositSurplus,
uint256 currentMoneyMarketIncomeIndex,
bool early
) internal {
Funding storage f = _getFunding(fundingID);
require(
depositID > f.fromDepositID && depositID <= f.toDepositID,
"DInterest: Deposit not funded by fundingID"
);
uint256 interestAmount =
f
.recordedFundedDepositAmount
.mul(currentMoneyMarketIncomeIndex)
.div(f.recordedMoneyMarketIncomeIndex)
.sub(f.recordedFundedDepositAmount);
// Update funding values
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
.sub(
f.recordedFundedDepositAmount.mul(EXTRA_PRECISION).div(
f.recordedMoneyMarketIncomeIndex
)
);
f.recordedFundedDepositAmount = f.recordedFundedDepositAmount.sub(
depositAmount.add(depositInterestOwed)
);
f.recordedMoneyMarketIncomeIndex = currentMoneyMarketIncomeIndex;
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
.add(
f.recordedFundedDepositAmount.mul(EXTRA_PRECISION).div(
f.recordedMoneyMarketIncomeIndex
)
);
// Send interest to funder
address funder = fundingNFT.ownerOf(fundingID);
uint256 transferToFunderAmount =
(early && depositSurplusIsNegative)
? interestAmount.add(depositSurplus)
: interestAmount;
if (transferToFunderAmount > 0) {
transferToFunderAmount = moneyMarket.withdraw(
transferToFunderAmount
);
if (transferToFunderAmount > 0) {
stablecoin.safeTransfer(funder, transferToFunderAmount);
}
}
// Mint funder rewards
mphMinter.mintFunderReward(
funder,
depositAmount,
f.creationTimestamp,
depositMaturationTimestamp,
interestAmount,
early
);
}
function _fund(uint256 totalDeficit) internal {
// Transfer `totalDeficit` stablecoins from msg.sender
stablecoin.safeTransferFrom(msg.sender, address(this), totalDeficit);
// Deposit `totalDeficit` stablecoins into moneyMarket
stablecoin.safeIncreaseAllowance(address(moneyMarket), totalDeficit);
moneyMarket.deposit(totalDeficit);
// Mint fundingNFT
fundingNFT.mint(msg.sender, fundingList.length);
// Emit event
uint256 fundingID = fundingList.length;
emit EFund(msg.sender, fundingID, totalDeficit);
}
}
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "../DInterest.sol";
import "../NFT.sol";
import "../rewards/MPHToken.sol";
import "../models/fee/IFeeModel.sol";
contract FractionalDeposit is ERC20, IERC721Receiver, Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20;
bool public initialized;
DInterest public pool;
NFT public nft;
MPHToken public mph;
uint256 public nftID;
uint256 public mintMPHAmount;
bool public active;
string public name;
string public symbol;
uint8 public decimals;
event WithdrawDeposit();
event RedeemShares(
address indexed user,
uint256 amountInShares,
uint256 redeemStablecoinAmount
);
function init(
address _owner,
address _pool,
address _mph,
uint256 _nftID,
string calldata _tokenName,
string calldata _tokenSymbol
) external {
require(!initialized, "FractionalDeposit: initialized");
initialized = true;
_transferOwnership(_owner);
pool = DInterest(_pool);
mph = MPHToken(_mph);
nft = NFT(pool.depositNFT());
nftID = _nftID;
active = true;
name = _tokenName;
symbol = _tokenSymbol;
// ensure contract is owner of NFT
require(
nft.ownerOf(_nftID) == address(this),
"FractionalDeposit: not deposit owner"
);
// mint tokens to owner
DInterest.Deposit memory deposit = pool.getDeposit(_nftID);
require(deposit.active, "FractionalDeposit: deposit inactive");
uint256 rawInterestOwed = deposit.interestOwed;
uint256 interestAfterFee = rawInterestOwed.sub(pool.feeModel().getFee(rawInterestOwed));
uint256 initialSupply = deposit.amount.add(interestAfterFee);
_mint(_owner, initialSupply);
// transfer MPH from msg.sender
mintMPHAmount = deposit.mintMPHAmount;
mph.transferFrom(msg.sender, address(this), mintMPHAmount);
// set decimals to be the same as the underlying stablecoin
decimals = ERC20Detailed(address(pool.stablecoin())).decimals();
}
function withdrawDeposit(uint256 fundingID) external {
_withdrawDeposit(fundingID);
}
function transferNFTToOwner() external {
require(!active, "FractionalDeposit: deposit active");
// transfer NFT to owner
nft.safeTransferFrom(address(this), owner(), nftID);
}
function redeemShares(uint256 amountInShares, uint256 fundingID)
external
returns (uint256 redeemStablecoinAmount)
{
if (active) {
// if deposit is still active, call withdrawDeposit()
_withdrawDeposit(fundingID);
}
ERC20 stablecoin = pool.stablecoin();
uint256 stablecoinBalance = stablecoin.balanceOf(address(this));
redeemStablecoinAmount = amountInShares.mul(stablecoinBalance).div(
totalSupply()
);
if (redeemStablecoinAmount > stablecoinBalance) {
// prevent transferring too much
redeemStablecoinAmount = stablecoinBalance;
}
// burn shares from sender
_burn(msg.sender, amountInShares);
// transfer pro rata withdrawn deposit
stablecoin.safeTransfer(msg.sender, redeemStablecoinAmount);
emit RedeemShares(msg.sender, amountInShares, redeemStablecoinAmount);
}
function _withdrawDeposit(uint256 fundingID) internal {
require(active, "FractionalDeposit: deposit inactive");
active = false;
uint256 _nftID = nftID;
// withdraw deposit from DInterest pool
mph.increaseAllowance(address(pool.mphMinter()), mintMPHAmount);
pool.withdraw(_nftID, fundingID);
// return leftover MPH
uint256 mphBalance = mph.balanceOf(address(this));
if (mphBalance > 0) {
mph.transfer(owner(), mphBalance);
}
emit WithdrawDeposit();
}
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a {IERC721-safeTransferFrom}. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes memory data
) public returns (bytes4) {
// only allow incoming transfer if not initialized
require(!initialized, "FractionalDeposit: initialized");
return this.onERC721Received.selector;
}
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "../libs/CloneFactory.sol";
import "./FractionalDeposit.sol";
import "../DInterest.sol";
import "../NFT.sol";
import "../rewards/MPHToken.sol";
contract FractionalDepositFactory is CloneFactory, IERC721Receiver {
address public template;
MPHToken public mph;
event CreateClone(address _clone);
constructor(address _template, address _mph) public {
template = _template;
mph = MPHToken(_mph);
}
function createFractionalDeposit(
address _pool,
uint256 _nftID,
string calldata _tokenName,
string calldata _tokenSymbol
) external returns (FractionalDeposit) {
FractionalDeposit clone = FractionalDeposit(createClone(template));
// transfer NFT from msg.sender to clone
DInterest pool = DInterest(_pool);
NFT nft = NFT(pool.depositNFT());
nft.safeTransferFrom(msg.sender, address(this), _nftID);
nft.safeTransferFrom(address(this), address(clone), _nftID);
// transfer MPH reward from msg.sender
DInterest.Deposit memory deposit = pool.getDeposit(_nftID);
uint256 mintMPHAmount = deposit.mintMPHAmount;
mph.transferFrom(msg.sender, address(this), mintMPHAmount);
mph.increaseAllowance(address(clone), mintMPHAmount);
// initialize
clone.init(
msg.sender,
_pool,
address(mph),
_nftID,
_tokenName,
_tokenSymbol
);
emit CreateClone(address(clone));
return clone;
}
function isFractionalDeposit(address query) external view returns (bool) {
return isClone(template, query);
}
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a {IERC721-safeTransferFrom}. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes memory data
) public returns (bytes4) {
return this.onERC721Received.selector;
}
}
pragma solidity 0.5.17;
/*
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.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target) internal returns (address 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)
}
}
function isClone(address target, address query) internal view returns (bool result) {
bytes20 targetBytes = bytes20(target);
assembly {
let clone := mload(0x40)
mstore(clone, 0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000)
mstore(add(clone, 0xa), targetBytes)
mstore(add(clone, 0x1e), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "../DInterest.sol";
import "./FractionalDeposit.sol";
import "./FractionalDepositFactory.sol";
// OpenZeppelin contract modified to support cloned contracts
contract ClonedReentrancyGuard {
bool internal _notEntered;
/**
* @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(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
contract ZeroCouponBond is ERC20, ClonedReentrancyGuard, IERC721Receiver {
using SafeERC20 for ERC20;
bool public initialized;
DInterest public pool;
FractionalDepositFactory public fractionalDepositFactory;
ERC20 public stablecoin;
uint256 public maturationTimestamp;
string public name;
string public symbol;
uint8 public decimals;
event Mint(
address indexed sender,
address indexed fractionalDepositAddress,
uint256 amount
);
event RedeemFractionalDepositShares(
address indexed sender,
address indexed fractionalDepositAddress,
uint256 fundingID
);
event RedeemStablecoin(address indexed sender, uint256 amount);
function init(
address _pool,
address _fractionalDepositFactory,
uint256 _maturationTimestamp,
string calldata _tokenName,
string calldata _tokenSymbol
) external {
require(!initialized, "ZeroCouponBond: initialized");
initialized = true;
_notEntered = true;
pool = DInterest(_pool);
fractionalDepositFactory = FractionalDepositFactory(
_fractionalDepositFactory
);
stablecoin = pool.stablecoin();
maturationTimestamp = _maturationTimestamp;
name = _tokenName;
symbol = _tokenSymbol;
// set decimals to be the same as the underlying stablecoin
decimals = ERC20Detailed(address(pool.stablecoin())).decimals();
// infinite approval to fractional deposit factory to save gas during minting with NFT
pool.depositNFT().setApprovalForAll(_fractionalDepositFactory, true);
fractionalDepositFactory.mph().approve(
_fractionalDepositFactory,
uint256(-1)
);
}
function mintWithDepositNFT(
uint256 nftID,
string calldata fractionalDepositName,
string calldata fractionalDepositSymbol
)
external
nonReentrant
returns (
uint256 zeroCouponBondsAmount,
FractionalDeposit fractionalDeposit
)
{
// ensure the deposit's maturation time is on or before that of the ZCB
DInterest.Deposit memory depositStruct = pool.getDeposit(nftID);
uint256 depositMaturationTimestamp = depositStruct.maturationTimestamp;
require(
depositMaturationTimestamp <= maturationTimestamp,
"ZeroCouponBonds: maturation too late"
);
// transfer MPH from `msg.sender`
MPHToken mph = fractionalDepositFactory.mph();
mph.transferFrom(
msg.sender,
address(this),
depositStruct.mintMPHAmount
);
// transfer deposit NFT from `msg.sender`
NFT depositNFT = pool.depositNFT();
depositNFT.safeTransferFrom(msg.sender, address(this), nftID);
// call fractionalDepositFactory to create fractional deposit using NFT
fractionalDeposit = fractionalDepositFactory.createFractionalDeposit(
address(pool),
nftID,
fractionalDepositName,
fractionalDepositSymbol
);
fractionalDeposit.transferOwnership(msg.sender);
// mint zero coupon bonds to `msg.sender`
zeroCouponBondsAmount = fractionalDeposit.totalSupply();
_mint(msg.sender, zeroCouponBondsAmount);
emit Mint(
msg.sender,
address(fractionalDeposit),
zeroCouponBondsAmount
);
}
function redeemFractionalDepositShares(
address fractionalDepositAddress,
uint256 fundingID
) external nonReentrant {
FractionalDeposit fractionalDeposit =
FractionalDeposit(fractionalDepositAddress);
uint256 balance = fractionalDeposit.balanceOf(address(this));
fractionalDeposit.redeemShares(balance, fundingID);
emit RedeemFractionalDepositShares(
msg.sender,
fractionalDepositAddress,
fundingID
);
}
function redeemStablecoin(uint256 amount)
external
nonReentrant
returns (uint256 actualRedeemedAmount)
{
require(now >= maturationTimestamp, "ZeroCouponBond: not mature");
uint256 stablecoinBalance = stablecoin.balanceOf(address(this));
actualRedeemedAmount = amount > stablecoinBalance
? stablecoinBalance
: amount;
// burn `actualRedeemedAmount` zero coupon bonds from `msg.sender`
_burn(msg.sender, actualRedeemedAmount);
// transfer `actualRedeemedAmount` stablecoins to `msg.sender`
stablecoin.safeTransfer(msg.sender, actualRedeemedAmount);
emit RedeemStablecoin(msg.sender, actualRedeemedAmount);
}
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a {IERC721-safeTransferFrom}. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes memory data
) public returns (bytes4) {
return this.onERC721Received.selector;
}
}
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../libs/CloneFactory.sol";
import "./ZeroCouponBond.sol";
contract ZeroCouponBondFactory is CloneFactory {
address public template;
address public fractionalDepositFactory;
event CreateClone(address _clone);
constructor(address _template, address _fractionalDepositFactory) public {
template = _template;
fractionalDepositFactory = _fractionalDepositFactory;
}
function createZeroCouponBond(
address _pool,
uint256 _maturationTimetstamp,
string calldata _tokenName,
string calldata _tokenSymbol
) external returns (ZeroCouponBond) {
ZeroCouponBond clone = ZeroCouponBond(createClone(template));
// initialize
clone.init(
_pool,
fractionalDepositFactory,
_maturationTimetstamp,
_tokenName,
_tokenSymbol
);
emit CreateClone(address(clone));
return clone;
}
function isZeroCouponBond(address query) external view returns (bool) {
return isClone(template, query);
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../libs/DecMath.sol";
contract ATokenMock is ERC20, ERC20Detailed {
using SafeMath for uint256;
using DecMath for uint256;
uint256 internal constant YEAR = 31556952; // Number of seconds in one Gregorian calendar year (365.2425 days)
ERC20 public dai;
uint256 public liquidityRate;
uint256 public normalizedIncome;
address[] public users;
mapping(address => bool) public isUser;
constructor(address _dai)
public
ERC20Detailed("aDAI", "aDAI", 18)
{
dai = ERC20(_dai);
liquidityRate = 10 ** 26; // 10% APY
normalizedIncome = 10 ** 27;
}
function mint(address _user, uint256 _amount) external {
_mint(_user, _amount);
if (!isUser[_user]) {
users.push(_user);
isUser[_user] = true;
}
}
function burn(address _user, uint256 _amount) external {
_burn(_user, _amount);
}
function mintInterest(uint256 _seconds) external {
uint256 interest;
address user;
for (uint256 i = 0; i < users.length; i++) {
user = users[i];
interest = balanceOf(user).mul(_seconds).mul(liquidityRate).div(YEAR.mul(10**27));
_mint(user, interest);
}
normalizedIncome = normalizedIncome.mul(_seconds).mul(liquidityRate).div(YEAR.mul(10**27)).add(normalizedIncome);
}
function setLiquidityRate(uint256 _liquidityRate) external {
liquidityRate = _liquidityRate;
}
}
/**
Modified from https://github.com/bugduino/idle-contracts/blob/master/contracts/mocks/cDAIMock.sol
at commit b85dafa8e55e053cb2d403fc4b28cfe86f2116d4
Original license:
Copyright 2020 Idle Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.17;
// interfaces
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
contract CERC20Mock is ERC20, ERC20Detailed {
address public dai;
uint256 internal _supplyRate;
uint256 internal _exchangeRate;
constructor(address _dai) public ERC20Detailed("cDAI", "cDAI", 8) {
dai = _dai;
uint256 daiDecimals = ERC20Detailed(_dai).decimals();
_exchangeRate = 2 * (10**(daiDecimals + 8)); // 1 cDAI = 0.02 DAI
_supplyRate = 45290900000; // 10% supply rate per year
}
function mint(uint256 amount) external returns (uint256) {
require(
ERC20(dai).transferFrom(msg.sender, address(this), amount),
"Error during transferFrom"
); // 1 DAI
_mint(msg.sender, (amount * 10**18) / _exchangeRate);
return 0;
}
function redeemUnderlying(uint256 amount) external returns (uint256) {
_burn(msg.sender, (amount * 10**18) / _exchangeRate);
require(
ERC20(dai).transfer(msg.sender, amount),
"Error during transfer"
); // 1 DAI
return 0;
}
function exchangeRateStored() external view returns (uint256) {
return _exchangeRate;
}
function exchangeRateCurrent() external view returns (uint256) {
return _exchangeRate;
}
function _setExchangeRateStored(uint256 _rate) external returns (uint256) {
_exchangeRate = _rate;
}
function supplyRatePerBlock() external view returns (uint256) {
return _supplyRate;
}
function _setSupplyRatePerBlock(uint256 _rate) external {
_supplyRate = _rate;
}
}
pragma solidity 0.5.17;
// interfaces
import "./ERC20Mock.sol";
contract ComptrollerMock {
uint256 public constant CLAIM_AMOUNT = 10**18;
ERC20Mock public comp;
constructor (address _comp) public {
comp = ERC20Mock(_comp);
}
function claimComp(address holder) external {
comp.mint(holder, CLAIM_AMOUNT);
}
function getCompAddress() external view returns (address) {
return address(comp);
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
contract ERC20Mock is ERC20, ERC20Detailed("", "", 6) {
function mint(address to, uint256 amount) public {
_mint(to, amount);
}
function transfer(address recipient, uint256 amount) public returns (bool) {
require(amount > 0, "ERC20Mock: amount 0");
_transfer(_msgSender(), recipient, amount);
return true;
}
}
/*
____ __ __ __ _
/ __/__ __ ___ / /_ / / ___ / /_ (_)__ __
_\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ /
/___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\
/___/
* Synthetix: Rewards.sol
*
* Docs: https://docs.synthetix.io/
*
*
* MIT License
* ===========
*
* Copyright (c) 2020 Synthetix
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
pragma solidity 0.5.17;
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
contract IRewardDistributionRecipient is Ownable {
mapping(address => bool) public isRewardDistribution;
function notifyRewardAmount(uint256 reward) external;
modifier onlyRewardDistribution() {
require(
isRewardDistribution[_msgSender()],
"Caller is not reward distribution"
);
_;
}
function setRewardDistribution(
address _rewardDistribution,
bool _isRewardDistribution
) external onlyOwner {
isRewardDistribution[_rewardDistribution] = _isRewardDistribution;
}
}
contract LPTokenWrapper {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public stakeToken;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
constructor(address _stakeToken) public {
stakeToken = IERC20(_stakeToken);
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function stake(uint256 amount) public {
_totalSupply = _totalSupply.add(amount);
_balances[msg.sender] = _balances[msg.sender].add(amount);
stakeToken.safeTransferFrom(msg.sender, address(this), amount);
}
function withdraw(uint256 amount) public {
_totalSupply = _totalSupply.sub(amount);
_balances[msg.sender] = _balances[msg.sender].sub(amount);
stakeToken.safeTransfer(msg.sender, amount);
}
}
contract HarvestStakingMock is LPTokenWrapper, IRewardDistributionRecipient {
IERC20 public rewardToken;
uint256 public constant DURATION = 7 days;
uint256 public starttime;
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
modifier checkStart {
require(block.timestamp >= starttime, "Rewards: not start");
_;
}
constructor(
address _stakeToken,
address _rewardToken,
uint256 _starttime
) public LPTokenWrapper(_stakeToken) {
rewardToken = IERC20(_rewardToken);
starttime = _starttime;
}
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
function rewardPerToken() public view returns (uint256) {
if (totalSupply() == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(1e18)
.div(totalSupply())
);
}
function earned(address account) public view returns (uint256) {
return
balanceOf(account)
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(1e18)
.add(rewards[account]);
}
// stake visibility is public as overriding LPTokenWrapper's stake() function
function stake(uint256 amount) public updateReward(msg.sender) checkStart {
require(amount > 0, "Rewards: cannot stake 0");
super.stake(amount);
emit Staked(msg.sender, amount);
}
function withdraw(uint256 amount)
public
updateReward(msg.sender)
checkStart
{
require(amount > 0, "Rewards: cannot withdraw 0");
super.withdraw(amount);
emit Withdrawn(msg.sender, amount);
}
function exit() external {
withdraw(balanceOf(msg.sender));
getReward();
}
function getReward() public updateReward(msg.sender) checkStart {
uint256 reward = earned(msg.sender);
if (reward > 0) {
rewards[msg.sender] = 0;
rewardToken.safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
}
function notifyRewardAmount(uint256 reward)
external
onlyRewardDistribution
updateReward(address(0))
{
// https://sips.synthetix.io/sips/sip-77
require(reward > 0, "Rewards: reward == 0");
require(
reward < uint256(-1) / 10**18,
"Rewards: rewards too large, would lock"
);
if (block.timestamp > starttime) {
if (block.timestamp >= periodFinish) {
rewardRate = reward.div(DURATION);
} else {
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = reward.add(leftover).div(DURATION);
}
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(DURATION);
emit RewardAdded(reward);
} else {
rewardRate = reward.div(DURATION);
lastUpdateTime = starttime;
periodFinish = starttime.add(DURATION);
emit RewardAdded(reward);
}
}
}
pragma solidity ^0.5.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
pragma solidity 0.5.17;
contract LendingPoolAddressesProviderMock {
address internal pool;
address internal core;
function getLendingPool() external view returns (address) {
return pool;
}
function setLendingPoolImpl(address _pool) external {
pool = _pool;
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./ATokenMock.sol";
contract LendingPoolMock {
mapping(address => address) internal reserveAToken;
function setReserveAToken(address _reserve, address _aTokenAddress)
external
{
reserveAToken[_reserve] = _aTokenAddress;
}
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16
) external {
// Transfer asset
ERC20 token = ERC20(asset);
token.transferFrom(msg.sender, address(this), amount);
// Mint aTokens
address aTokenAddress = reserveAToken[asset];
ATokenMock aToken = ATokenMock(aTokenAddress);
aToken.mint(onBehalfOf, amount);
}
function withdraw(
address asset,
uint256 amount,
address to
) external returns (uint256) {
// Burn aTokens
address aTokenAddress = reserveAToken[asset];
ATokenMock aToken = ATokenMock(aTokenAddress);
aToken.burn(msg.sender, amount);
// Transfer asset
ERC20 token = ERC20(asset);
token.transfer(to, amount);
}
// The equivalent of exchangeRateStored() for Compound cTokens
function getReserveNormalizedIncome(address asset)
external
view
returns (uint256)
{
address aTokenAddress = reserveAToken[asset];
ATokenMock aToken = ATokenMock(aTokenAddress);
return aToken.normalizedIncome();
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../libs/DecMath.sol";
contract VaultMock is ERC20, ERC20Detailed {
using SafeMath for uint256;
using DecMath for uint256;
ERC20 public underlying;
constructor(address _underlying) public ERC20Detailed("yUSD", "yUSD", 18) {
underlying = ERC20(_underlying);
}
function deposit(uint256 tokenAmount) public {
uint256 sharePrice = getPricePerFullShare();
_mint(msg.sender, tokenAmount.decdiv(sharePrice));
underlying.transferFrom(msg.sender, address(this), tokenAmount);
}
function withdraw(uint256 sharesAmount) public {
uint256 sharePrice = getPricePerFullShare();
uint256 underlyingAmount = sharesAmount.decmul(sharePrice);
_burn(msg.sender, sharesAmount);
underlying.transfer(msg.sender, underlyingAmount);
}
function getPricePerFullShare() public view returns (uint256) {
uint256 _totalSupply = totalSupply();
if (_totalSupply == 0) {
return 10**18;
}
return underlying.balanceOf(address(this)).decdiv(_totalSupply);
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "./IFeeModel.sol";
contract PercentageFeeModel is IFeeModel, Ownable {
using SafeMath for uint256;
address payable public beneficiary;
event SetBeneficiary(address newBeneficiary);
constructor(address payable _beneficiary) public {
beneficiary = _beneficiary;
}
function getFee(uint256 _txAmount)
external
pure
returns (uint256 _feeAmount)
{
_feeAmount = _txAmount.div(5); // Precision is decreased by 1 decimal place
}
function setBeneficiary(address payable newValue) external onlyOwner {
require(newValue != address(0), "PercentageFeeModel: 0 address");
beneficiary = newValue;
emit SetBeneficiary(newValue);
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../moneymarkets/IMoneyMarket.sol";
import "../../libs/DecMath.sol";
import "./IInterestOracle.sol";
contract EMAOracle is IInterestOracle {
using SafeMath for uint256;
using DecMath for uint256;
uint256 internal constant PRECISION = 10**18;
/**
Immutable parameters
*/
uint256 public UPDATE_INTERVAL;
uint256 public UPDATE_MULTIPLIER;
uint256 public ONE_MINUS_UPDATE_MULTIPLIER;
/**
Public variables
*/
uint256 public emaStored;
uint256 public lastIncomeIndex;
uint256 public lastUpdateTimestamp;
/**
External contracts
*/
IMoneyMarket public moneyMarket;
constructor(
uint256 _emaInitial,
uint256 _updateInterval,
uint256 _smoothingFactor,
uint256 _averageWindowInIntervals,
address _moneyMarket
) public {
emaStored = _emaInitial;
UPDATE_INTERVAL = _updateInterval;
lastUpdateTimestamp = now;
uint256 updateMultiplier = _smoothingFactor.div(_averageWindowInIntervals.add(1));
UPDATE_MULTIPLIER = updateMultiplier;
ONE_MINUS_UPDATE_MULTIPLIER = PRECISION.sub(updateMultiplier);
moneyMarket = IMoneyMarket(_moneyMarket);
lastIncomeIndex = moneyMarket.incomeIndex();
}
function updateAndQuery() public returns (bool updated, uint256 value) {
uint256 timeElapsed = now - lastUpdateTimestamp;
if (timeElapsed < UPDATE_INTERVAL) {
return (false, emaStored);
}
// save gas by loading storage variables to memory
uint256 _lastIncomeIndex = lastIncomeIndex;
uint256 _emaStored = emaStored;
uint256 newIncomeIndex = moneyMarket.incomeIndex();
uint256 incomingValue = newIncomeIndex.sub(_lastIncomeIndex).decdiv(_lastIncomeIndex).div(timeElapsed);
updated = true;
value = incomingValue.mul(UPDATE_MULTIPLIER).add(_emaStored.mul(ONE_MINUS_UPDATE_MULTIPLIER)).div(PRECISION);
emaStored = value;
lastIncomeIndex = newIncomeIndex;
lastUpdateTimestamp = now;
}
function query() public view returns (uint256 value) {
return emaStored;
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../libs/DecMath.sol";
contract LinearInterestModel {
using SafeMath for uint256;
using DecMath for uint256;
uint256 public constant PRECISION = 10**18;
uint256 public IRMultiplier;
constructor(uint256 _IRMultiplier) public {
IRMultiplier = _IRMultiplier;
}
function calculateInterestAmount(
uint256 depositAmount,
uint256 depositPeriodInSeconds,
uint256 moneyMarketInterestRatePerSecond,
bool, /*surplusIsNegative*/
uint256 /*surplusAmount*/
) external view returns (uint256 interestAmount) {
// interestAmount = depositAmount * moneyMarketInterestRatePerSecond * IRMultiplier * depositPeriodInSeconds
interestAmount = depositAmount
.mul(PRECISION)
.decmul(moneyMarketInterestRatePerSecond)
.decmul(IRMultiplier)
.mul(depositPeriodInSeconds)
.div(PRECISION);
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../../libs/DecMath.sol";
import "./IMPHIssuanceModel.sol";
contract MPHIssuanceModel01 is Ownable, IMPHIssuanceModel {
using Address for address;
using DecMath for uint256;
using SafeMath for uint256;
uint256 internal constant PRECISION = 10**18;
/**
@notice The multiplier applied when minting MPH for a pool's depositor reward.
Unit is MPH-wei per depositToken-wei per second. (wei here is the smallest decimal place)
Scaled by 10^18.
NOTE: The depositToken's decimals matter!
*/
mapping(address => uint256) public poolDepositorRewardMintMultiplier;
/**
@notice The multiplier applied when taking back MPH from depositors upon withdrawal.
No unit, is a proportion between 0 and 1.
Scaled by 10^18.
*/
mapping(address => uint256) public poolDepositorRewardTakeBackMultiplier;
/**
@notice The multiplier applied when minting MPH for a pool's funder reward.
Unit is MPH-wei per depositToken-wei per second. (wei here is the smallest decimal place)
Scaled by 10^18.
NOTE: The depositToken's decimals matter!
*/
mapping(address => uint256) public poolFunderRewardMultiplier;
/**
@notice The period over which the depositor reward will be vested, in seconds.
*/
mapping(address => uint256) public poolDepositorRewardVestPeriod;
/**
@notice The period over which the funder reward will be vested, in seconds.
*/
mapping(address => uint256) public poolFunderRewardVestPeriod;
/**
@notice Multiplier used for calculating dev reward
*/
uint256 public devRewardMultiplier;
event ESetParamAddress(
address indexed sender,
string indexed paramName,
address newValue
);
event ESetParamUint(
address indexed sender,
string indexed paramName,
address indexed pool,
uint256 newValue
);
constructor(uint256 _devRewardMultiplier) public {
devRewardMultiplier = _devRewardMultiplier;
}
/**
@notice Computes the MPH amount to reward to a depositor upon deposit.
@param pool The DInterest pool trying to mint reward
@param depositAmount The deposit amount in the pool's stablecoins
@param depositPeriodInSeconds The deposit's lock period in seconds
@param interestAmount The deposit's fixed-rate interest amount in the pool's stablecoins
@return depositorReward The MPH amount to mint to the depositor
devReward The MPH amount to mint to the dev wallet
govReward The MPH amount to mint to the gov treasury
*/
function computeDepositorReward(
address pool,
uint256 depositAmount,
uint256 depositPeriodInSeconds,
uint256 interestAmount
)
external
view
returns (
uint256 depositorReward,
uint256 devReward,
uint256 govReward
)
{
uint256 mintAmount = depositAmount.mul(depositPeriodInSeconds).decmul(
poolDepositorRewardMintMultiplier[pool]
);
depositorReward = mintAmount;
devReward = mintAmount.decmul(devRewardMultiplier);
govReward = 0;
}
/**
@notice Computes the MPH amount to take back from a depositor upon withdrawal.
If takeBackAmount > devReward + govReward, the extra MPH should be burnt.
@param pool The DInterest pool trying to mint reward
@param mintMPHAmount The MPH amount originally minted to the depositor as reward
@param early True if the deposit is withdrawn early, false if the deposit is mature
@return takeBackAmount The MPH amount to take back from the depositor
devReward The MPH amount from takeBackAmount to send to the dev wallet
govReward The MPH amount from takeBackAmount to send to the gov treasury
*/
function computeTakeBackDepositorRewardAmount(
address pool,
uint256 mintMPHAmount,
bool early
)
external
view
returns (
uint256 takeBackAmount,
uint256 devReward,
uint256 govReward
)
{
takeBackAmount = early
? mintMPHAmount
: mintMPHAmount.decmul(poolDepositorRewardTakeBackMultiplier[pool]);
devReward = 0;
govReward = early ? 0 : takeBackAmount;
}
/**
@notice Computes the MPH amount to reward to a deficit funder upon withdrawal of an underlying deposit.
@param pool The DInterest pool trying to mint reward
@param depositAmount The deposit amount in the pool's stablecoins
@param fundingCreationTimestamp The timestamp of the funding's creation, in seconds
@param maturationTimestamp The maturation timestamp of the deposit, in seconds
@param interestPayoutAmount The interest payout amount to the funder, in the pool's stablecoins.
Includes the interest from other funded deposits.
@param early True if the deposit is withdrawn early, false if the deposit is mature
@return funderReward The MPH amount to mint to the funder
devReward The MPH amount to mint to the dev wallet
govReward The MPH amount to mint to the gov treasury
*/
function computeFunderReward(
address pool,
uint256 depositAmount,
uint256 fundingCreationTimestamp,
uint256 maturationTimestamp,
uint256 interestPayoutAmount,
bool early
)
external
view
returns (
uint256 funderReward,
uint256 devReward,
uint256 govReward
)
{
if (early) {
return (0, 0, 0);
}
funderReward = maturationTimestamp > fundingCreationTimestamp
? depositAmount
.mul(maturationTimestamp.sub(fundingCreationTimestamp))
.decmul(poolFunderRewardMultiplier[pool])
: 0;
devReward = funderReward.decmul(devRewardMultiplier);
govReward = 0;
}
/**
Param setters
*/
function setPoolDepositorRewardMintMultiplier(
address pool,
uint256 newMultiplier
) external onlyOwner {
require(pool.isContract(), "MPHIssuanceModel: pool not contract");
poolDepositorRewardMintMultiplier[pool] = newMultiplier;
emit ESetParamUint(
msg.sender,
"poolDepositorRewardMintMultiplier",
pool,
newMultiplier
);
}
function setPoolDepositorRewardTakeBackMultiplier(
address pool,
uint256 newMultiplier
) external onlyOwner {
require(pool.isContract(), "MPHIssuanceModel: pool not contract");
require(
newMultiplier <= PRECISION,
"MPHIssuanceModel: invalid multiplier"
);
poolDepositorRewardTakeBackMultiplier[pool] = newMultiplier;
emit ESetParamUint(
msg.sender,
"poolDepositorRewardTakeBackMultiplier",
pool,
newMultiplier
);
}
function setPoolFunderRewardMultiplier(address pool, uint256 newMultiplier)
external
onlyOwner
{
require(pool.isContract(), "MPHIssuanceModel: pool not contract");
poolFunderRewardMultiplier[pool] = newMultiplier;
emit ESetParamUint(
msg.sender,
"poolFunderRewardMultiplier",
pool,
newMultiplier
);
}
function setPoolDepositorRewardVestPeriod(
address pool,
uint256 newVestPeriodInSeconds
) external onlyOwner {
require(pool.isContract(), "MPHIssuanceModel: pool not contract");
poolDepositorRewardVestPeriod[pool] = newVestPeriodInSeconds;
emit ESetParamUint(
msg.sender,
"poolDepositorRewardVestPeriod",
pool,
newVestPeriodInSeconds
);
}
function setPoolFunderRewardVestPeriod(
address pool,
uint256 newVestPeriodInSeconds
) external onlyOwner {
require(pool.isContract(), "MPHIssuanceModel: pool not contract");
poolFunderRewardVestPeriod[pool] = newVestPeriodInSeconds;
emit ESetParamUint(
msg.sender,
"poolFunderRewardVestPeriod",
pool,
newVestPeriodInSeconds
);
}
function setDevRewardMultiplier(uint256 newMultiplier) external onlyOwner {
require(
newMultiplier <= PRECISION,
"MPHIssuanceModel: invalid multiplier"
);
devRewardMultiplier = newMultiplier;
emit ESetParamUint(
msg.sender,
"devRewardMultiplier",
address(0),
newMultiplier
);
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../IMoneyMarket.sol";
import "./imports/ILendingPool.sol";
import "./imports/ILendingPoolAddressesProvider.sol";
contract AaveMarket is IMoneyMarket, Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20;
using Address for address;
uint16 internal constant REFERRALCODE = 20; // Aave referral program code
ILendingPoolAddressesProvider public provider; // Used for fetching the current address of LendingPool
ERC20 public stablecoin;
ERC20 public aToken;
constructor(
address _provider,
address _aToken,
address _stablecoin
) public {
// Verify input addresses
require(
_provider.isContract() &&
_aToken.isContract() &&
_stablecoin.isContract(),
"AaveMarket: An input address is not a contract"
);
provider = ILendingPoolAddressesProvider(_provider);
stablecoin = ERC20(_stablecoin);
aToken = ERC20(_aToken);
}
function deposit(uint256 amount) external onlyOwner {
require(amount > 0, "AaveMarket: amount is 0");
ILendingPool lendingPool = ILendingPool(provider.getLendingPool());
// Transfer `amount` stablecoin from `msg.sender`
stablecoin.safeTransferFrom(msg.sender, address(this), amount);
// Approve `amount` stablecoin to lendingPool
stablecoin.safeIncreaseAllowance(address(lendingPool), amount);
// Deposit `amount` stablecoin to lendingPool
lendingPool.deposit(
address(stablecoin),
amount,
address(this),
REFERRALCODE
);
}
function withdraw(uint256 amountInUnderlying)
external
onlyOwner
returns (uint256 actualAmountWithdrawn)
{
require(amountInUnderlying > 0, "AaveMarket: amountInUnderlying is 0");
ILendingPool lendingPool = ILendingPool(provider.getLendingPool());
// Redeem `amountInUnderlying` aToken, since 1 aToken = 1 stablecoin
// Transfer `amountInUnderlying` stablecoin to `msg.sender`
lendingPool.withdraw(
address(stablecoin),
amountInUnderlying,
msg.sender
);
return amountInUnderlying;
}
function claimRewards() external {}
function totalValue() external returns (uint256) {
return aToken.balanceOf(address(this));
}
function incomeIndex() external returns (uint256) {
ILendingPool lendingPool = ILendingPool(provider.getLendingPool());
return lendingPool.getReserveNormalizedIncome(address(stablecoin));
}
function setRewards(address newValue) external {}
}
pragma solidity 0.5.17;
// Aave lending pool interface
// Documentation: https://docs.aave.com/developers/the-core-protocol/lendingpool/ilendingpool
// refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties.
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);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.5.17;
/**
* @title LendingPoolAddressesProvider contract
* @dev Main registry of addresses part of or connected to the protocol, including permissioned roles
* - Acting also as factory of proxies and admin of those, so with right to change its implementations
* - Owned by the Aave Governance
* @author Aave
**/
interface ILendingPoolAddressesProvider {
function getLendingPool() external view returns (address);
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../IMoneyMarket.sol";
import "../../libs/DecMath.sol";
import "./imports/ICERC20.sol";
import "./imports/IComptroller.sol";
contract CompoundERC20Market is IMoneyMarket, Ownable {
using DecMath for uint256;
using SafeERC20 for ERC20;
using Address for address;
uint256 internal constant ERRCODE_OK = 0;
ICERC20 public cToken;
IComptroller public comptroller;
address public rewards;
ERC20 public stablecoin;
constructor(
address _cToken,
address _comptroller,
address _rewards,
address _stablecoin
) public {
// Verify input addresses
require(
_cToken.isContract() &&
_comptroller.isContract() &&
_rewards.isContract() &&
_stablecoin.isContract(),
"CompoundERC20Market: An input address is not a contract"
);
cToken = ICERC20(_cToken);
comptroller = IComptroller(_comptroller);
rewards = _rewards;
stablecoin = ERC20(_stablecoin);
}
function deposit(uint256 amount) external onlyOwner {
require(amount > 0, "CompoundERC20Market: amount is 0");
// Transfer `amount` stablecoin from `msg.sender`
stablecoin.safeTransferFrom(msg.sender, address(this), amount);
// Deposit `amount` stablecoin into cToken
stablecoin.safeIncreaseAllowance(address(cToken), amount);
require(
cToken.mint(amount) == ERRCODE_OK,
"CompoundERC20Market: Failed to mint cTokens"
);
}
function withdraw(uint256 amountInUnderlying)
external
onlyOwner
returns (uint256 actualAmountWithdrawn)
{
require(
amountInUnderlying > 0,
"CompoundERC20Market: amountInUnderlying is 0"
);
// Withdraw `amountInUnderlying` stablecoin from cToken
require(
cToken.redeemUnderlying(amountInUnderlying) == ERRCODE_OK,
"CompoundERC20Market: Failed to redeem"
);
// Transfer `amountInUnderlying` stablecoin to `msg.sender`
stablecoin.safeTransfer(msg.sender, amountInUnderlying);
return amountInUnderlying;
}
function claimRewards() external {
comptroller.claimComp(address(this));
ERC20 comp = ERC20(comptroller.getCompAddress());
comp.safeTransfer(rewards, comp.balanceOf(address(this)));
}
function totalValue() external returns (uint256) {
uint256 cTokenBalance = cToken.balanceOf(address(this));
// Amount of stablecoin units that 1 unit of cToken can be exchanged for, scaled by 10^18
uint256 cTokenPrice = cToken.exchangeRateCurrent();
return cTokenBalance.decmul(cTokenPrice);
}
function incomeIndex() external returns (uint256) {
return cToken.exchangeRateCurrent();
}
/**
Param setters
*/
function setRewards(address newValue) external onlyOwner {
require(newValue.isContract(), "CompoundERC20Market: not contract");
rewards = newValue;
emit ESetParamAddress(msg.sender, "rewards", newValue);
}
}
pragma solidity 0.5.17;
// Compound finance ERC20 market interface
// Documentation: https://compound.finance/docs/ctokens
interface ICERC20 {
function transfer(address dst, uint256 amount) external returns (bool);
function transferFrom(address src, address dst, uint256 amount)
external
returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function allowance(address owner, address spender)
external
view
returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint256);
function getAccountSnapshot(address account)
external
view
returns (uint256, uint256, uint256, uint256);
function borrowRatePerBlock() external view returns (uint256);
function supplyRatePerBlock() external view returns (uint256);
function totalBorrowsCurrent() external returns (uint256);
function borrowBalanceCurrent(address account) external returns (uint256);
function borrowBalanceStored(address account)
external
view
returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function getCash() external view returns (uint256);
function accrueInterest() external returns (uint256);
function seize(address liquidator, address borrower, uint256 seizeTokens)
external
returns (uint256);
function mint(uint256 mintAmount) external returns (uint256);
function redeem(uint256 redeemTokens) external returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
function borrow(uint256 borrowAmount) external returns (uint256);
function repayBorrow(uint256 repayAmount) external returns (uint256);
function repayBorrowBehalf(address borrower, uint256 repayAmount)
external
returns (uint256);
function liquidateBorrow(
address borrower,
uint256 repayAmount,
address cTokenCollateral
) external returns (uint256);
}
pragma solidity 0.5.17;
// Compound finance Comptroller interface
// Documentation: https://compound.finance/docs/comptroller
interface IComptroller {
function claimComp(address holder) external;
function getCompAddress() external view returns (address);
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../IMoneyMarket.sol";
import "../../libs/DecMath.sol";
import "./imports/ICERC20.sol";
contract CreamERC20Market is IMoneyMarket, Ownable {
using DecMath for uint256;
using SafeERC20 for ERC20;
using Address for address;
uint256 internal constant ERRCODE_OK = 0;
ICERC20 public cToken;
ERC20 public stablecoin;
constructor(address _cToken, address _stablecoin) public {
// Verify input addresses
require(
_cToken.isContract() && _stablecoin.isContract(),
"CreamERC20Market: An input address is not a contract"
);
cToken = ICERC20(_cToken);
stablecoin = ERC20(_stablecoin);
}
function deposit(uint256 amount) external onlyOwner {
require(amount > 0, "CreamERC20Market: amount is 0");
// Transfer `amount` stablecoin from `msg.sender`
stablecoin.safeTransferFrom(msg.sender, address(this), amount);
// Deposit `amount` stablecoin into cToken
stablecoin.safeIncreaseAllowance(address(cToken), amount);
require(
cToken.mint(amount) == ERRCODE_OK,
"CreamERC20Market: Failed to mint cTokens"
);
}
function withdraw(uint256 amountInUnderlying)
external
onlyOwner
returns (uint256 actualAmountWithdrawn)
{
require(
amountInUnderlying > 0,
"CreamERC20Market: amountInUnderlying is 0"
);
// Withdraw `amountInUnderlying` stablecoin from cToken
require(
cToken.redeemUnderlying(amountInUnderlying) == ERRCODE_OK,
"CreamERC20Market: Failed to redeem"
);
// Transfer `amountInUnderlying` stablecoin to `msg.sender`
stablecoin.safeTransfer(msg.sender, amountInUnderlying);
return amountInUnderlying;
}
function claimRewards() external {}
function totalValue() external returns (uint256) {
uint256 cTokenBalance = cToken.balanceOf(address(this));
// Amount of stablecoin units that 1 unit of cToken can be exchanged for, scaled by 10^18
uint256 cTokenPrice = cToken.exchangeRateCurrent();
return cTokenBalance.decmul(cTokenPrice);
}
function incomeIndex() external returns (uint256) {
return cToken.exchangeRateCurrent();
}
/**
Param setters
*/
function setRewards(address newValue) external onlyOwner {}
}
pragma solidity 0.5.17;
// Compound finance ERC20 market interface
// Documentation: https://compound.finance/docs/ctokens
interface ICERC20 {
function transfer(address dst, uint256 amount) external returns (bool);
function transferFrom(address src, address dst, uint256 amount)
external
returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function allowance(address owner, address spender)
external
view
returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint256);
function getAccountSnapshot(address account)
external
view
returns (uint256, uint256, uint256, uint256);
function borrowRatePerBlock() external view returns (uint256);
function supplyRatePerBlock() external view returns (uint256);
function totalBorrowsCurrent() external returns (uint256);
function borrowBalanceCurrent(address account) external returns (uint256);
function borrowBalanceStored(address account)
external
view
returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function getCash() external view returns (uint256);
function accrueInterest() external returns (uint256);
function seize(address liquidator, address borrower, uint256 seizeTokens)
external
returns (uint256);
function mint(uint256 mintAmount) external returns (uint256);
function redeem(uint256 redeemTokens) external returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
function borrow(uint256 borrowAmount) external returns (uint256);
function repayBorrow(uint256 repayAmount) external returns (uint256);
function repayBorrowBehalf(address borrower, uint256 repayAmount)
external
returns (uint256);
function liquidateBorrow(
address borrower,
uint256 repayAmount,
address cTokenCollateral
) external returns (uint256);
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../IMoneyMarket.sol";
import "../../libs/DecMath.sol";
import "./imports/HarvestVault.sol";
import "./imports/HarvestStaking.sol";
contract HarvestMarket is IMoneyMarket, Ownable {
using SafeMath for uint256;
using DecMath for uint256;
using SafeERC20 for ERC20;
using Address for address;
HarvestVault public vault;
address public rewards;
HarvestStaking public stakingPool;
ERC20 public stablecoin;
constructor(
address _vault,
address _rewards,
address _stakingPool,
address _stablecoin
) public {
// Verify input addresses
require(
_vault.isContract() &&
_rewards.isContract() &&
_stakingPool.isContract() &&
_stablecoin.isContract(),
"HarvestMarket: An input address is not a contract"
);
vault = HarvestVault(_vault);
rewards = _rewards;
stakingPool = HarvestStaking(_stakingPool);
stablecoin = ERC20(_stablecoin);
}
function deposit(uint256 amount) external onlyOwner {
require(amount > 0, "HarvestMarket: amount is 0");
// Transfer `amount` stablecoin from `msg.sender`
stablecoin.safeTransferFrom(msg.sender, address(this), amount);
// Approve `amount` stablecoin to vault
stablecoin.safeIncreaseAllowance(address(vault), amount);
// Deposit `amount` stablecoin to vault
vault.deposit(amount);
// Stake vault token balance into staking pool
uint256 vaultShareBalance = vault.balanceOf(address(this));
vault.approve(address(stakingPool), vaultShareBalance);
stakingPool.stake(vaultShareBalance);
}
function withdraw(uint256 amountInUnderlying)
external
onlyOwner
returns (uint256 actualAmountWithdrawn)
{
require(
amountInUnderlying > 0,
"HarvestMarket: amountInUnderlying is 0"
);
// Withdraw `amountInShares` shares from vault
uint256 sharePrice = vault.getPricePerFullShare();
uint256 amountInShares = amountInUnderlying.decdiv(sharePrice);
if (amountInShares > 0) {
stakingPool.withdraw(amountInShares);
vault.withdraw(amountInShares);
}
// Transfer stablecoin to `msg.sender`
actualAmountWithdrawn = stablecoin.balanceOf(address(this));
if (actualAmountWithdrawn > 0) {
stablecoin.safeTransfer(msg.sender, actualAmountWithdrawn);
}
}
function claimRewards() external {
stakingPool.getReward();
ERC20 rewardToken = ERC20(stakingPool.rewardToken());
rewardToken.safeTransfer(rewards, rewardToken.balanceOf(address(this)));
}
function totalValue() external returns (uint256) {
uint256 sharePrice = vault.getPricePerFullShare();
uint256 shareBalance = vault.balanceOf(address(this)).add(stakingPool.balanceOf(address(this)));
return shareBalance.decmul(sharePrice);
}
function incomeIndex() external returns (uint256) {
return vault.getPricePerFullShare();
}
/**
Param setters
*/
function setRewards(address newValue) external onlyOwner {
require(newValue.isContract(), "HarvestMarket: not contract");
rewards = newValue;
emit ESetParamAddress(msg.sender, "rewards", newValue);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.5.17;
interface HarvestVault {
function deposit(uint256) external;
function withdraw(uint256) external;
function getPricePerFullShare() external view returns (uint256);
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
);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.5.17;
interface HarvestStaking {
function stake(uint256 amount) external;
function withdraw(uint256 amount) external;
function getReward() external;
function rewardToken() external returns (address);
function balanceOf(address account) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.5.17;
interface Vault {
function deposit(uint256) external;
function withdraw(uint256) external;
function getPricePerFullShare() external view returns (uint256);
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.5.17;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../IMoneyMarket.sol";
import "../../libs/DecMath.sol";
import "./imports/Vault.sol";
contract YVaultMarket is IMoneyMarket, Ownable {
using SafeMath for uint256;
using DecMath for uint256;
using SafeERC20 for ERC20;
using Address for address;
Vault public vault;
ERC20 public stablecoin;
constructor(address _vault, address _stablecoin) public {
// Verify input addresses
require(
_vault.isContract() && _stablecoin.isContract(),
"YVaultMarket: An input address is not a contract"
);
vault = Vault(_vault);
stablecoin = ERC20(_stablecoin);
}
function deposit(uint256 amount) external onlyOwner {
require(amount > 0, "YVaultMarket: amount is 0");
// Transfer `amount` stablecoin from `msg.sender`
stablecoin.safeTransferFrom(msg.sender, address(this), amount);
// Approve `amount` stablecoin to vault
stablecoin.safeIncreaseAllowance(address(vault), amount);
// Deposit `amount` stablecoin to vault
vault.deposit(amount);
}
function withdraw(uint256 amountInUnderlying)
external
onlyOwner
returns (uint256 actualAmountWithdrawn)
{
require(
amountInUnderlying > 0,
"YVaultMarket: amountInUnderlying is 0"
);
// Withdraw `amountInShares` shares from vault
uint256 sharePrice = vault.getPricePerFullShare();
uint256 amountInShares = amountInUnderlying.decdiv(sharePrice);
if (amountInShares > 0) {
vault.withdraw(amountInShares);
}
// Transfer stablecoin to `msg.sender`
actualAmountWithdrawn = stablecoin.balanceOf(address(this));
if (actualAmountWithdrawn > 0) {
stablecoin.safeTransfer(msg.sender, actualAmountWithdrawn);
}
}
function claimRewards() external {}
function totalValue() external returns (uint256) {
uint256 sharePrice = vault.getPricePerFullShare();
uint256 shareBalance = vault.balanceOf(address(this));
return shareBalance.decmul(sharePrice);
}
function incomeIndex() external returns (uint256) {
return vault.getPricePerFullShare();
}
function setRewards(address newValue) external {}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.5.17;
import "./OneSplitDumper.sol";
import "./withdrawers/CurveLPWithdrawer.sol";
import "./withdrawers/YearnWithdrawer.sol";
contract Dumper is OneSplitDumper, CurveLPWithdrawer, YearnWithdrawer {
constructor(
address _oneSplit,
address _rewards,
address _rewardToken
) public OneSplitDumper(_oneSplit, _rewards, _rewardToken) {}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.5.17;
import "@openzeppelin/contracts/access/roles/SignerRole.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./imports/OneSplitAudit.sol";
import "../IRewards.sol";
contract OneSplitDumper is SignerRole {
using SafeERC20 for IERC20;
OneSplitAudit public oneSplit;
IRewards public rewards;
IERC20 public rewardToken;
constructor(
address _oneSplit,
address _rewards,
address _rewardToken
) public {
oneSplit = OneSplitAudit(_oneSplit);
rewards = IRewards(_rewards);
rewardToken = IERC20(_rewardToken);
}
function getDumpParams(address tokenAddress, uint256 parts)
external
view
returns (uint256 returnAmount, uint256[] memory distribution)
{
IERC20 token = IERC20(tokenAddress);
uint256 tokenBalance = token.balanceOf(address(this));
(returnAmount, distribution) = oneSplit.getExpectedReturn(
tokenAddress,
address(rewardToken),
tokenBalance,
parts,
0
);
}
function dump(
address tokenAddress,
uint256 returnAmount,
uint256[] calldata distribution
) external onlySigner {
// dump token for rewardToken
IERC20 token = IERC20(tokenAddress);
uint256 tokenBalance = token.balanceOf(address(this));
token.safeIncreaseAllowance(address(oneSplit), tokenBalance);
uint256 rewardTokenBalanceBefore = rewardToken.balanceOf(address(this));
oneSplit.swap(
tokenAddress,
address(rewardToken),
tokenBalance,
returnAmount,
distribution,
0
);
uint256 rewardTokenBalanceAfter = rewardToken.balanceOf(address(this));
require(
rewardTokenBalanceAfter > rewardTokenBalanceBefore,
"OneSplitDumper: receivedRewardTokenAmount == 0"
);
}
function notify() external onlySigner {
uint256 balance = rewardToken.balanceOf(address(this));
rewardToken.safeTransfer(address(rewards), balance);
rewards.notifyRewardAmount(balance);
}
}
pragma solidity ^0.5.0;
import "../../GSN/Context.sol";
import "../Roles.sol";
contract SignerRole is Context {
using Roles for Roles.Role;
event SignerAdded(address indexed account);
event SignerRemoved(address indexed account);
Roles.Role private _signers;
constructor () internal {
_addSigner(_msgSender());
}
modifier onlySigner() {
require(isSigner(_msgSender()), "SignerRole: caller does not have the Signer role");
_;
}
function isSigner(address account) public view returns (bool) {
return _signers.has(account);
}
function addSigner(address account) public onlySigner {
_addSigner(account);
}
function renounceSigner() public {
_removeSigner(_msgSender());
}
function _addSigner(address account) internal {
_signers.add(account);
emit SignerAdded(account);
}
function _removeSigner(address account) internal {
_signers.remove(account);
emit SignerRemoved(account);
}
}
pragma solidity ^0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.5.17;
interface OneSplitAudit {
function swap(
address fromToken,
address destToken,
uint256 amount,
uint256 minReturn,
uint256[] calldata distribution,
uint256 flags
) external payable;
function getExpectedReturn(
address fromToken,
address destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
)
external
view
returns (uint256 returnAmount, uint256[] memory distribution);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.5.17;
interface IRewards {
function notifyRewardAmount(uint256 reward) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.5.17;
import "@openzeppelin/contracts/access/roles/SignerRole.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../imports/Curve.sol";
import "../../IRewards.sol";
contract CurveLPWithdrawer is SignerRole {
function curveWithdraw2(
address lpTokenAddress,
address curvePoolAddress,
uint256[2] calldata minAmounts
) external onlySigner {
IERC20 lpToken = IERC20(lpTokenAddress);
uint256 lpTokenBalance = lpToken.balanceOf(address(this));
ICurveFi curvePool = ICurveFi(curvePoolAddress);
curvePool.remove_liquidity(lpTokenBalance, minAmounts);
}
function curveWithdraw3(
address lpTokenAddress,
address curvePoolAddress,
uint256[3] calldata minAmounts
) external onlySigner {
IERC20 lpToken = IERC20(lpTokenAddress);
uint256 lpTokenBalance = lpToken.balanceOf(address(this));
ICurveFi curvePool = ICurveFi(curvePoolAddress);
curvePool.remove_liquidity(lpTokenBalance, minAmounts);
}
function curveWithdraw4(
address lpTokenAddress,
address curvePoolAddress,
uint256[4] calldata minAmounts
) external onlySigner {
IERC20 lpToken = IERC20(lpTokenAddress);
uint256 lpTokenBalance = lpToken.balanceOf(address(this));
ICurveFi curvePool = ICurveFi(curvePoolAddress);
curvePool.remove_liquidity(lpTokenBalance, minAmounts);
}
function curveWithdraw5(
address lpTokenAddress,
address curvePoolAddress,
uint256[5] calldata minAmounts
) external onlySigner {
IERC20 lpToken = IERC20(lpTokenAddress);
uint256 lpTokenBalance = lpToken.balanceOf(address(this));
ICurveFi curvePool = ICurveFi(curvePoolAddress);
curvePool.remove_liquidity(lpTokenBalance, minAmounts);
}
function curveWithdrawOneCoin(
address lpTokenAddress,
address curvePoolAddress,
int128 coinIndex,
uint256 minAmount
) external onlySigner {
IERC20 lpToken = IERC20(lpTokenAddress);
uint256 lpTokenBalance = lpToken.balanceOf(address(this));
Zap curvePool = Zap(curvePoolAddress);
curvePool.remove_liquidity_one_coin(
lpTokenBalance,
coinIndex,
minAmount
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.5.17;
interface ICurveFi {
function remove_liquidity_imbalance(
uint256[2] calldata amounts,
uint256 max_burn_amount
) external;
function remove_liquidity_imbalance(
uint256[3] calldata amounts,
uint256 max_burn_amount
) external;
function remove_liquidity_imbalance(
uint256[4] calldata amounts,
uint256 max_burn_amount
) external;
function remove_liquidity_imbalance(
uint256[5] calldata amounts,
uint256 max_burn_amount
) external;
function remove_liquidity(uint256 _amount, uint256[2] calldata amounts)
external;
function remove_liquidity(uint256 _amount, uint256[3] calldata amounts)
external;
function remove_liquidity(uint256 _amount, uint256[4] calldata amounts)
external;
function remove_liquidity(uint256 _amount, uint256[5] calldata amounts)
external;
}
interface Zap {
function remove_liquidity_one_coin(
uint256,
int128,
uint256
) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.5.17;
import "@openzeppelin/contracts/access/roles/SignerRole.sol";
import "../imports/yERC20.sol";
contract YearnWithdrawer is SignerRole {
function yearnWithdraw(address yTokenAddress) external onlySigner {
yERC20 yToken = yERC20(yTokenAddress);
uint256 balance = yToken.balanceOf(address(this));
yToken.withdraw(balance);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.5.17;
// NOTE: Basically an alias for Vaults
interface yERC20 {
function balanceOf(address owner) external view returns (uint256);
function deposit(uint256 _amount) external;
function withdraw(uint256 _amount) external;
function getPricePerFullShare() external view returns (uint256);
}
/*
____ __ __ __ _
/ __/__ __ ___ / /_ / / ___ / /_ (_)__ __
_\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ /
/___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\
/___/
* Synthetix: Rewards.sol
*
* Docs: https://docs.synthetix.io/
*
*
* MIT License
* ===========
*
* Copyright (c) 2020 Synthetix
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
pragma solidity 0.5.17;
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
contract IRewardDistributionRecipient is Ownable {
mapping(address => bool) public isRewardDistribution;
function notifyRewardAmount(uint256 reward) external;
modifier onlyRewardDistribution() {
require(
isRewardDistribution[_msgSender()],
"Caller is not reward distribution"
);
_;
}
function setRewardDistribution(
address _rewardDistribution,
bool _isRewardDistribution
) external onlyOwner {
isRewardDistribution[_rewardDistribution] = _isRewardDistribution;
}
}
contract LPTokenWrapper {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public stakeToken;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
constructor(address _stakeToken) public {
stakeToken = IERC20(_stakeToken);
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function stake(uint256 amount) public {
_totalSupply = _totalSupply.add(amount);
_balances[msg.sender] = _balances[msg.sender].add(amount);
stakeToken.safeTransferFrom(msg.sender, address(this), amount);
}
function withdraw(uint256 amount) public {
_totalSupply = _totalSupply.sub(amount);
_balances[msg.sender] = _balances[msg.sender].sub(amount);
stakeToken.safeTransfer(msg.sender, amount);
}
}
contract Rewards is LPTokenWrapper, IRewardDistributionRecipient {
IERC20 public rewardToken;
uint256 public constant DURATION = 7 days;
uint256 public starttime;
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
modifier checkStart {
require(block.timestamp >= starttime, "Rewards: not start");
_;
}
constructor(
address _stakeToken,
address _rewardToken,
uint256 _starttime
) public LPTokenWrapper(_stakeToken) {
rewardToken = IERC20(_rewardToken);
starttime = _starttime;
}
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
function rewardPerToken() public view returns (uint256) {
if (totalSupply() == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(1e18)
.div(totalSupply())
);
}
function earned(address account) public view returns (uint256) {
return
balanceOf(account)
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(1e18)
.add(rewards[account]);
}
// stake visibility is public as overriding LPTokenWrapper's stake() function
function stake(uint256 amount) public updateReward(msg.sender) checkStart {
require(amount > 0, "Rewards: cannot stake 0");
super.stake(amount);
emit Staked(msg.sender, amount);
}
function withdraw(uint256 amount)
public
updateReward(msg.sender)
checkStart
{
require(amount > 0, "Rewards: cannot withdraw 0");
super.withdraw(amount);
emit Withdrawn(msg.sender, amount);
}
function exit() external {
withdraw(balanceOf(msg.sender));
getReward();
}
function getReward() public updateReward(msg.sender) checkStart {
uint256 reward = earned(msg.sender);
if (reward > 0) {
rewards[msg.sender] = 0;
rewardToken.safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
}
function notifyRewardAmount(uint256 reward)
external
onlyRewardDistribution
updateReward(address(0))
{
// https://sips.synthetix.io/sips/sip-77
require(reward > 0, "Rewards: reward == 0");
require(
reward < uint256(-1) / 10**18,
"Rewards: rewards too large, would lock"
);
if (block.timestamp > starttime) {
if (block.timestamp >= periodFinish) {
rewardRate = reward.div(DURATION);
} else {
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = reward.add(leftover).div(DURATION);
}
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(DURATION);
emit RewardAdded(reward);
} else {
rewardRate = reward.div(DURATION);
lastUpdateTime = starttime;
periodFinish = starttime.add(DURATION);
emit RewardAdded(reward);
}
}
}
pragma solidity 0.5.17;
interface CurveZapIn {
/**
@notice This function adds liquidity to a Curve pool with ETH or ERC20 tokens
@param toWhomToIssue The address to return the Curve LP tokens to
@param fromToken The ERC20 token used for investment (address(0x00) if ether)
@param swapAddress Curve swap address for the pool
@param incomingTokenQty The amount of fromToken to invest
@param minPoolTokens The minimum acceptable quantity of tokens to receive. Reverts otherwise
@return Amount of Curve LP tokens received
*/
function ZapIn(
address toWhomToIssue,
address fromToken,
address swapAddress,
uint256 incomingTokenQty,
uint256 minPoolTokens
) external payable returns (uint256 crvTokensBought);
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "./imports/CurveZapIn.sol";
import "../DInterest.sol";
import "../NFT.sol";
contract ZapCurve is IERC721Receiver {
using SafeERC20 for ERC20;
modifier active {
isActive = true;
_;
isActive = false;
}
CurveZapIn public constant zapper =
CurveZapIn(0xf9A724c2607E5766a7Bbe530D6a7e173532F9f3a);
bool public isActive;
function zapCurveDeposit(
address pool,
address swapAddress,
address inputToken,
uint256 inputTokenAmount,
uint256 minOutputTokenAmount,
uint256 maturationTimestamp
) external active {
DInterest poolContract = DInterest(pool);
ERC20 stablecoin = poolContract.stablecoin();
NFT depositNFT = poolContract.depositNFT();
// zap into curve
uint256 outputTokenAmount =
_zapTokenInCurve(
swapAddress,
inputToken,
inputTokenAmount,
minOutputTokenAmount
);
// create deposit
stablecoin.safeIncreaseAllowance(pool, outputTokenAmount);
poolContract.deposit(outputTokenAmount, maturationTimestamp);
// transfer deposit NFT to msg.sender
uint256 nftID = poolContract.depositsLength();
depositNFT.safeTransferFrom(address(this), msg.sender, nftID);
}
function zapCurveFundAll(
address pool,
address swapAddress,
address inputToken,
uint256 inputTokenAmount,
uint256 minOutputTokenAmount
) external active {
DInterest poolContract = DInterest(pool);
ERC20 stablecoin = poolContract.stablecoin();
NFT fundingNFT = poolContract.fundingNFT();
// zap into curve
uint256 outputTokenAmount =
_zapTokenInCurve(
swapAddress,
inputToken,
inputTokenAmount,
minOutputTokenAmount
);
// create funding
stablecoin.safeIncreaseAllowance(pool, outputTokenAmount);
poolContract.fundAll();
// transfer funding NFT to msg.sender
uint256 nftID = poolContract.fundingListLength();
fundingNFT.safeTransferFrom(address(this), msg.sender, nftID);
}
function zapCurveFundMultiple(
address pool,
address swapAddress,
address inputToken,
uint256 inputTokenAmount,
uint256 minOutputTokenAmount,
uint256 toDepositID
) external active {
DInterest poolContract = DInterest(pool);
ERC20 stablecoin = poolContract.stablecoin();
NFT fundingNFT = poolContract.fundingNFT();
// zap into curve
uint256 outputTokenAmount =
_zapTokenInCurve(
swapAddress,
inputToken,
inputTokenAmount,
minOutputTokenAmount
);
// create funding
stablecoin.safeIncreaseAllowance(pool, outputTokenAmount);
poolContract.fundMultiple(toDepositID);
// transfer funding NFT to msg.sender
uint256 nftID = poolContract.fundingListLength();
fundingNFT.safeTransferFrom(address(this), msg.sender, nftID);
}
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a {IERC721-safeTransferFrom}. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes memory data
) public returns (bytes4) {
require(isActive, "ZapCurve: inactive");
return this.onERC721Received.selector;
}
function _zapTokenInCurve(
address swapAddress,
address inputToken,
uint256 inputTokenAmount,
uint256 minOutputTokenAmount
) internal returns (uint256 outputTokenAmount) {
ERC20 inputTokenContract = ERC20(inputToken);
// transfer inputToken from msg.sender
inputTokenContract.safeTransferFrom(
msg.sender,
address(this),
inputTokenAmount
);
// zap inputToken into curve
inputTokenContract.safeIncreaseAllowance(
address(zapper),
inputTokenAmount
);
outputTokenAmount = zapper.ZapIn(
address(this),
inputToken,
swapAddress,
inputTokenAmount,
minOutputTokenAmount
);
}
} | DeLorean Interest -- It's coming back from the future! EL PSY CONGROO Author: Zefram Lou Contact: [email protected] Constants User deposit data Each deposit has an ID used in the depositNFT, which is equal to its index in `deposits` plus 1 | contract DInterestWithDepositFee is ReentrancyGuard, Ownable {
using SafeMath for uint256;
using DecMath for uint256;
using SafeERC20 for ERC20;
using Address for address;
uint256 internal constant PRECISION = 10**18;
uint256 internal constant ONE = 10**18;
struct Deposit {
bool finalSurplusIsNegative;
}
Deposit[] internal deposits;
struct Funding {
uint256 fromDepositID;
uint256 toDepositID;
}
Funding[] internal fundingList;
public sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex;
uint256 public totalInterestOwed;
ERC20 public stablecoin;
IFeeModel public feeModel;
IInterestModel public interestModel;
IInterestOracle public interestOracle;
NFT public depositNFT;
NFT public fundingNFT;
MPHMinter public mphMinter;
address indexed sender,
uint256 indexed depositID,
uint256 amount,
uint256 maturationTimestamp,
uint256 interestAmount,
uint256 mintMPHAmount
);
event EWithdraw(
address indexed sender,
uint256 indexed depositID,
uint256 indexed fundingID,
bool early,
uint256 takeBackMPHAmount
);
event EFund(
address indexed sender,
uint256 indexed fundingID,
uint256 deficitAmount
);
event ESetParamAddress(
address indexed sender,
string indexed paramName,
address newValue
);
event ESetParamUint(
address indexed sender,
string indexed paramName,
uint256 newValue
);
uint256
uint256 public totalDeposit;
IMoneyMarket public moneyMarket;
event EDeposit(
struct DepositLimit {
uint256 MinDepositPeriod;
uint256 MaxDepositPeriod;
uint256 MinDepositAmount;
uint256 MaxDepositAmount;
uint256 DepositFee;
}
constructor(
DepositLimit memory _depositLimit,
) public {
require(
_moneyMarket.isContract() &&
_stablecoin.isContract() &&
_feeModel.isContract() &&
_interestModel.isContract() &&
_interestOracle.isContract() &&
_depositNFT.isContract() &&
_fundingNFT.isContract() &&
_mphMinter.isContract(),
"DInterest: An input address is not a contract"
);
moneyMarket = IMoneyMarket(_moneyMarket);
stablecoin = ERC20(_stablecoin);
feeModel = IFeeModel(_feeModel);
interestModel = IInterestModel(_interestModel);
interestOracle = IInterestOracle(_interestOracle);
depositNFT = NFT(_depositNFT);
fundingNFT = NFT(_fundingNFT);
mphMinter = MPHMinter(_mphMinter);
require(
moneyMarket.stablecoin() == _stablecoin,
"DInterest: moneyMarket.stablecoin() != _stablecoin"
);
require(
interestOracle.moneyMarket() == _moneyMarket,
"DInterest: interestOracle.moneyMarket() != _moneyMarket"
);
require(
_depositLimit.MaxDepositPeriod > 0 &&
_depositLimit.MaxDepositAmount > 0,
"DInterest: An input uint256 is 0"
);
require(
_depositLimit.MinDepositPeriod <= _depositLimit.MaxDepositPeriod,
"DInterest: Invalid DepositPeriod range"
);
require(
_depositLimit.MinDepositAmount <= _depositLimit.MaxDepositAmount,
"DInterest: Invalid DepositAmount range"
);
MinDepositPeriod = _depositLimit.MinDepositPeriod;
MaxDepositPeriod = _depositLimit.MaxDepositPeriod;
MinDepositAmount = _depositLimit.MinDepositAmount;
MaxDepositAmount = _depositLimit.MaxDepositAmount;
DepositFee = _depositLimit.DepositFee;
totalDeposit = 0;
}
Public actions
function deposit(uint256 amount, uint256 maturationTimestamp)
external
nonReentrant
{
_deposit(amount, maturationTimestamp);
}
function withdraw(uint256 depositID, uint256 fundingID)
external
nonReentrant
{
_withdraw(depositID, fundingID, false);
}
function earlyWithdraw(uint256 depositID, uint256 fundingID)
external
nonReentrant
{
_withdraw(depositID, fundingID, true);
}
function multiDeposit(
uint256[] calldata amountList,
uint256[] calldata maturationTimestampList
) external nonReentrant {
require(
amountList.length == maturationTimestampList.length,
"DInterest: List lengths unequal"
);
for (uint256 i = 0; i < amountList.length; i = i.add(1)) {
_deposit(amountList[i], maturationTimestampList[i]);
}
}
function multiDeposit(
uint256[] calldata amountList,
uint256[] calldata maturationTimestampList
) external nonReentrant {
require(
amountList.length == maturationTimestampList.length,
"DInterest: List lengths unequal"
);
for (uint256 i = 0; i < amountList.length; i = i.add(1)) {
_deposit(amountList[i], maturationTimestampList[i]);
}
}
function multiWithdraw(
uint256[] calldata depositIDList,
uint256[] calldata fundingIDList
) external nonReentrant {
require(
depositIDList.length == fundingIDList.length,
"DInterest: List lengths unequal"
);
for (uint256 i = 0; i < depositIDList.length; i = i.add(1)) {
_withdraw(depositIDList[i], fundingIDList[i], false);
}
}
function multiWithdraw(
uint256[] calldata depositIDList,
uint256[] calldata fundingIDList
) external nonReentrant {
require(
depositIDList.length == fundingIDList.length,
"DInterest: List lengths unequal"
);
for (uint256 i = 0; i < depositIDList.length; i = i.add(1)) {
_withdraw(depositIDList[i], fundingIDList[i], false);
}
}
function multiEarlyWithdraw(
uint256[] calldata depositIDList,
uint256[] calldata fundingIDList
) external nonReentrant {
require(
depositIDList.length == fundingIDList.length,
"DInterest: List lengths unequal"
);
for (uint256 i = 0; i < depositIDList.length; i = i.add(1)) {
_withdraw(depositIDList[i], fundingIDList[i], true);
}
}
function multiEarlyWithdraw(
uint256[] calldata depositIDList,
uint256[] calldata fundingIDList
) external nonReentrant {
require(
depositIDList.length == fundingIDList.length,
"DInterest: List lengths unequal"
);
for (uint256 i = 0; i < depositIDList.length; i = i.add(1)) {
_withdraw(depositIDList[i], fundingIDList[i], true);
}
}
Deficit funding
function fundAll() external nonReentrant {
(bool isNegative, uint256 deficit) = surplus();
require(isNegative, "DInterest: No deficit available");
require(
!depositIsFunded(deposits.length),
"DInterest: All deposits funded"
);
uint256 incomeIndex = moneyMarket.incomeIndex();
require(incomeIndex > 0, "DInterest: incomeIndex == 0");
fundingList.push(
Funding({
fromDepositID: latestFundedDepositID,
toDepositID: deposits.length,
recordedFundedDepositAmount: unfundedUserDepositAmount,
recordedMoneyMarketIncomeIndex: incomeIndex,
creationTimestamp: now
})
);
.add(
unfundedUserDepositAmount.mul(EXTRA_PRECISION).div(incomeIndex)
);
latestFundedDepositID = deposits.length;
unfundedUserDepositAmount = 0;
_fund(deficit);
}
function fundAll() external nonReentrant {
(bool isNegative, uint256 deficit) = surplus();
require(isNegative, "DInterest: No deficit available");
require(
!depositIsFunded(deposits.length),
"DInterest: All deposits funded"
);
uint256 incomeIndex = moneyMarket.incomeIndex();
require(incomeIndex > 0, "DInterest: incomeIndex == 0");
fundingList.push(
Funding({
fromDepositID: latestFundedDepositID,
toDepositID: deposits.length,
recordedFundedDepositAmount: unfundedUserDepositAmount,
recordedMoneyMarketIncomeIndex: incomeIndex,
creationTimestamp: now
})
);
.add(
unfundedUserDepositAmount.mul(EXTRA_PRECISION).div(incomeIndex)
);
latestFundedDepositID = deposits.length;
unfundedUserDepositAmount = 0;
_fund(deficit);
}
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
function fundMultiple(uint256 toDepositID) external nonReentrant {
require(
toDepositID > latestFundedDepositID,
"DInterest: Deposits already funded"
);
require(
toDepositID <= deposits.length,
"DInterest: Invalid toDepositID"
);
(bool isNegative, uint256 surplus) = surplus();
require(isNegative, "DInterest: No deficit available");
uint256 totalDeficit = 0;
uint256 totalSurplus = 0;
uint256 totalDepositAndInterestToFund = 0;
for (
uint256 id = latestFundedDepositID.add(1);
id <= toDepositID;
id = id.add(1)
) {
Deposit storage depositEntry = _getDeposit(id);
if (depositEntry.active) {
(isNegative, surplus) = surplusOfDeposit(id);
(isNegative, surplus) = (
depositEntry.finalSurplusIsNegative,
depositEntry.finalSurplusAmount
);
}
if (isNegative) {
totalDeficit = totalDeficit.add(surplus);
totalSurplus = totalSurplus.add(surplus);
}
if (depositEntry.active) {
totalDepositAndInterestToFund = totalDepositAndInterestToFund
.add(depositEntry.amount)
.add(depositEntry.interestOwed);
}
}
if (totalSurplus >= totalDeficit) {
revert("DInterest: Selected deposits in surplus");
totalDeficit = totalDeficit.sub(totalSurplus);
}
require(incomeIndex > 0, "DInterest: incomeIndex == 0");
fundingList.push(
Funding({
fromDepositID: latestFundedDepositID,
toDepositID: toDepositID,
recordedFundedDepositAmount: totalDepositAndInterestToFund,
recordedMoneyMarketIncomeIndex: incomeIndex,
creationTimestamp: now
})
);
.add(
totalDepositAndInterestToFund.mul(EXTRA_PRECISION).div(incomeIndex)
);
latestFundedDepositID = toDepositID;
unfundedUserDepositAmount = unfundedUserDepositAmount.sub(
totalDepositAndInterestToFund
);
_fund(totalDeficit);
}
function fundMultiple(uint256 toDepositID) external nonReentrant {
require(
toDepositID > latestFundedDepositID,
"DInterest: Deposits already funded"
);
require(
toDepositID <= deposits.length,
"DInterest: Invalid toDepositID"
);
(bool isNegative, uint256 surplus) = surplus();
require(isNegative, "DInterest: No deficit available");
uint256 totalDeficit = 0;
uint256 totalSurplus = 0;
uint256 totalDepositAndInterestToFund = 0;
for (
uint256 id = latestFundedDepositID.add(1);
id <= toDepositID;
id = id.add(1)
) {
Deposit storage depositEntry = _getDeposit(id);
if (depositEntry.active) {
(isNegative, surplus) = surplusOfDeposit(id);
(isNegative, surplus) = (
depositEntry.finalSurplusIsNegative,
depositEntry.finalSurplusAmount
);
}
if (isNegative) {
totalDeficit = totalDeficit.add(surplus);
totalSurplus = totalSurplus.add(surplus);
}
if (depositEntry.active) {
totalDepositAndInterestToFund = totalDepositAndInterestToFund
.add(depositEntry.amount)
.add(depositEntry.interestOwed);
}
}
if (totalSurplus >= totalDeficit) {
revert("DInterest: Selected deposits in surplus");
totalDeficit = totalDeficit.sub(totalSurplus);
}
require(incomeIndex > 0, "DInterest: incomeIndex == 0");
fundingList.push(
Funding({
fromDepositID: latestFundedDepositID,
toDepositID: toDepositID,
recordedFundedDepositAmount: totalDepositAndInterestToFund,
recordedMoneyMarketIncomeIndex: incomeIndex,
creationTimestamp: now
})
);
.add(
totalDepositAndInterestToFund.mul(EXTRA_PRECISION).div(incomeIndex)
);
latestFundedDepositID = toDepositID;
unfundedUserDepositAmount = unfundedUserDepositAmount.sub(
totalDepositAndInterestToFund
);
_fund(totalDeficit);
}
function fundMultiple(uint256 toDepositID) external nonReentrant {
require(
toDepositID > latestFundedDepositID,
"DInterest: Deposits already funded"
);
require(
toDepositID <= deposits.length,
"DInterest: Invalid toDepositID"
);
(bool isNegative, uint256 surplus) = surplus();
require(isNegative, "DInterest: No deficit available");
uint256 totalDeficit = 0;
uint256 totalSurplus = 0;
uint256 totalDepositAndInterestToFund = 0;
for (
uint256 id = latestFundedDepositID.add(1);
id <= toDepositID;
id = id.add(1)
) {
Deposit storage depositEntry = _getDeposit(id);
if (depositEntry.active) {
(isNegative, surplus) = surplusOfDeposit(id);
(isNegative, surplus) = (
depositEntry.finalSurplusIsNegative,
depositEntry.finalSurplusAmount
);
}
if (isNegative) {
totalDeficit = totalDeficit.add(surplus);
totalSurplus = totalSurplus.add(surplus);
}
if (depositEntry.active) {
totalDepositAndInterestToFund = totalDepositAndInterestToFund
.add(depositEntry.amount)
.add(depositEntry.interestOwed);
}
}
if (totalSurplus >= totalDeficit) {
revert("DInterest: Selected deposits in surplus");
totalDeficit = totalDeficit.sub(totalSurplus);
}
require(incomeIndex > 0, "DInterest: incomeIndex == 0");
fundingList.push(
Funding({
fromDepositID: latestFundedDepositID,
toDepositID: toDepositID,
recordedFundedDepositAmount: totalDepositAndInterestToFund,
recordedMoneyMarketIncomeIndex: incomeIndex,
creationTimestamp: now
})
);
.add(
totalDepositAndInterestToFund.mul(EXTRA_PRECISION).div(incomeIndex)
);
latestFundedDepositID = toDepositID;
unfundedUserDepositAmount = unfundedUserDepositAmount.sub(
totalDepositAndInterestToFund
);
_fund(totalDeficit);
}
} else {
function fundMultiple(uint256 toDepositID) external nonReentrant {
require(
toDepositID > latestFundedDepositID,
"DInterest: Deposits already funded"
);
require(
toDepositID <= deposits.length,
"DInterest: Invalid toDepositID"
);
(bool isNegative, uint256 surplus) = surplus();
require(isNegative, "DInterest: No deficit available");
uint256 totalDeficit = 0;
uint256 totalSurplus = 0;
uint256 totalDepositAndInterestToFund = 0;
for (
uint256 id = latestFundedDepositID.add(1);
id <= toDepositID;
id = id.add(1)
) {
Deposit storage depositEntry = _getDeposit(id);
if (depositEntry.active) {
(isNegative, surplus) = surplusOfDeposit(id);
(isNegative, surplus) = (
depositEntry.finalSurplusIsNegative,
depositEntry.finalSurplusAmount
);
}
if (isNegative) {
totalDeficit = totalDeficit.add(surplus);
totalSurplus = totalSurplus.add(surplus);
}
if (depositEntry.active) {
totalDepositAndInterestToFund = totalDepositAndInterestToFund
.add(depositEntry.amount)
.add(depositEntry.interestOwed);
}
}
if (totalSurplus >= totalDeficit) {
revert("DInterest: Selected deposits in surplus");
totalDeficit = totalDeficit.sub(totalSurplus);
}
require(incomeIndex > 0, "DInterest: incomeIndex == 0");
fundingList.push(
Funding({
fromDepositID: latestFundedDepositID,
toDepositID: toDepositID,
recordedFundedDepositAmount: totalDepositAndInterestToFund,
recordedMoneyMarketIncomeIndex: incomeIndex,
creationTimestamp: now
})
);
.add(
totalDepositAndInterestToFund.mul(EXTRA_PRECISION).div(incomeIndex)
);
latestFundedDepositID = toDepositID;
unfundedUserDepositAmount = unfundedUserDepositAmount.sub(
totalDepositAndInterestToFund
);
_fund(totalDeficit);
}
} else {
function fundMultiple(uint256 toDepositID) external nonReentrant {
require(
toDepositID > latestFundedDepositID,
"DInterest: Deposits already funded"
);
require(
toDepositID <= deposits.length,
"DInterest: Invalid toDepositID"
);
(bool isNegative, uint256 surplus) = surplus();
require(isNegative, "DInterest: No deficit available");
uint256 totalDeficit = 0;
uint256 totalSurplus = 0;
uint256 totalDepositAndInterestToFund = 0;
for (
uint256 id = latestFundedDepositID.add(1);
id <= toDepositID;
id = id.add(1)
) {
Deposit storage depositEntry = _getDeposit(id);
if (depositEntry.active) {
(isNegative, surplus) = surplusOfDeposit(id);
(isNegative, surplus) = (
depositEntry.finalSurplusIsNegative,
depositEntry.finalSurplusAmount
);
}
if (isNegative) {
totalDeficit = totalDeficit.add(surplus);
totalSurplus = totalSurplus.add(surplus);
}
if (depositEntry.active) {
totalDepositAndInterestToFund = totalDepositAndInterestToFund
.add(depositEntry.amount)
.add(depositEntry.interestOwed);
}
}
if (totalSurplus >= totalDeficit) {
revert("DInterest: Selected deposits in surplus");
totalDeficit = totalDeficit.sub(totalSurplus);
}
require(incomeIndex > 0, "DInterest: incomeIndex == 0");
fundingList.push(
Funding({
fromDepositID: latestFundedDepositID,
toDepositID: toDepositID,
recordedFundedDepositAmount: totalDepositAndInterestToFund,
recordedMoneyMarketIncomeIndex: incomeIndex,
creationTimestamp: now
})
);
.add(
totalDepositAndInterestToFund.mul(EXTRA_PRECISION).div(incomeIndex)
);
latestFundedDepositID = toDepositID;
unfundedUserDepositAmount = unfundedUserDepositAmount.sub(
totalDepositAndInterestToFund
);
_fund(totalDeficit);
}
function fundMultiple(uint256 toDepositID) external nonReentrant {
require(
toDepositID > latestFundedDepositID,
"DInterest: Deposits already funded"
);
require(
toDepositID <= deposits.length,
"DInterest: Invalid toDepositID"
);
(bool isNegative, uint256 surplus) = surplus();
require(isNegative, "DInterest: No deficit available");
uint256 totalDeficit = 0;
uint256 totalSurplus = 0;
uint256 totalDepositAndInterestToFund = 0;
for (
uint256 id = latestFundedDepositID.add(1);
id <= toDepositID;
id = id.add(1)
) {
Deposit storage depositEntry = _getDeposit(id);
if (depositEntry.active) {
(isNegative, surplus) = surplusOfDeposit(id);
(isNegative, surplus) = (
depositEntry.finalSurplusIsNegative,
depositEntry.finalSurplusAmount
);
}
if (isNegative) {
totalDeficit = totalDeficit.add(surplus);
totalSurplus = totalSurplus.add(surplus);
}
if (depositEntry.active) {
totalDepositAndInterestToFund = totalDepositAndInterestToFund
.add(depositEntry.amount)
.add(depositEntry.interestOwed);
}
}
if (totalSurplus >= totalDeficit) {
revert("DInterest: Selected deposits in surplus");
totalDeficit = totalDeficit.sub(totalSurplus);
}
require(incomeIndex > 0, "DInterest: incomeIndex == 0");
fundingList.push(
Funding({
fromDepositID: latestFundedDepositID,
toDepositID: toDepositID,
recordedFundedDepositAmount: totalDepositAndInterestToFund,
recordedMoneyMarketIncomeIndex: incomeIndex,
creationTimestamp: now
})
);
.add(
totalDepositAndInterestToFund.mul(EXTRA_PRECISION).div(incomeIndex)
);
latestFundedDepositID = toDepositID;
unfundedUserDepositAmount = unfundedUserDepositAmount.sub(
totalDepositAndInterestToFund
);
_fund(totalDeficit);
}
} else {
uint256 incomeIndex = moneyMarket.incomeIndex();
function fundMultiple(uint256 toDepositID) external nonReentrant {
require(
toDepositID > latestFundedDepositID,
"DInterest: Deposits already funded"
);
require(
toDepositID <= deposits.length,
"DInterest: Invalid toDepositID"
);
(bool isNegative, uint256 surplus) = surplus();
require(isNegative, "DInterest: No deficit available");
uint256 totalDeficit = 0;
uint256 totalSurplus = 0;
uint256 totalDepositAndInterestToFund = 0;
for (
uint256 id = latestFundedDepositID.add(1);
id <= toDepositID;
id = id.add(1)
) {
Deposit storage depositEntry = _getDeposit(id);
if (depositEntry.active) {
(isNegative, surplus) = surplusOfDeposit(id);
(isNegative, surplus) = (
depositEntry.finalSurplusIsNegative,
depositEntry.finalSurplusAmount
);
}
if (isNegative) {
totalDeficit = totalDeficit.add(surplus);
totalSurplus = totalSurplus.add(surplus);
}
if (depositEntry.active) {
totalDepositAndInterestToFund = totalDepositAndInterestToFund
.add(depositEntry.amount)
.add(depositEntry.interestOwed);
}
}
if (totalSurplus >= totalDeficit) {
revert("DInterest: Selected deposits in surplus");
totalDeficit = totalDeficit.sub(totalSurplus);
}
require(incomeIndex > 0, "DInterest: incomeIndex == 0");
fundingList.push(
Funding({
fromDepositID: latestFundedDepositID,
toDepositID: toDepositID,
recordedFundedDepositAmount: totalDepositAndInterestToFund,
recordedMoneyMarketIncomeIndex: incomeIndex,
creationTimestamp: now
})
);
.add(
totalDepositAndInterestToFund.mul(EXTRA_PRECISION).div(incomeIndex)
);
latestFundedDepositID = toDepositID;
unfundedUserDepositAmount = unfundedUserDepositAmount.sub(
totalDepositAndInterestToFund
);
_fund(totalDeficit);
}
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
function payInterestToFunder(uint256 fundingID)
external
returns (uint256 interestAmount)
{
address funder = fundingNFT.ownerOf(fundingID);
require(funder == msg.sender, "DInterest: not funder");
Funding storage f = _getFunding(fundingID);
uint256 currentMoneyMarketIncomeIndex = moneyMarket.incomeIndex();
interestAmount = f
.recordedFundedDepositAmount
.mul(currentMoneyMarketIncomeIndex)
.div(f.recordedMoneyMarketIncomeIndex)
.sub(f.recordedFundedDepositAmount);
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
.sub(
f.recordedFundedDepositAmount.mul(EXTRA_PRECISION).div(
f.recordedMoneyMarketIncomeIndex
)
);
f.recordedMoneyMarketIncomeIndex = currentMoneyMarketIncomeIndex;
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
.add(
f.recordedFundedDepositAmount.mul(EXTRA_PRECISION).div(
f.recordedMoneyMarketIncomeIndex
)
);
if (interestAmount > 0) {
interestAmount = moneyMarket.withdraw(interestAmount);
if (interestAmount > 0) {
stablecoin.safeTransfer(funder, interestAmount);
}
}
}
function payInterestToFunder(uint256 fundingID)
external
returns (uint256 interestAmount)
{
address funder = fundingNFT.ownerOf(fundingID);
require(funder == msg.sender, "DInterest: not funder");
Funding storage f = _getFunding(fundingID);
uint256 currentMoneyMarketIncomeIndex = moneyMarket.incomeIndex();
interestAmount = f
.recordedFundedDepositAmount
.mul(currentMoneyMarketIncomeIndex)
.div(f.recordedMoneyMarketIncomeIndex)
.sub(f.recordedFundedDepositAmount);
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
.sub(
f.recordedFundedDepositAmount.mul(EXTRA_PRECISION).div(
f.recordedMoneyMarketIncomeIndex
)
);
f.recordedMoneyMarketIncomeIndex = currentMoneyMarketIncomeIndex;
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
.add(
f.recordedFundedDepositAmount.mul(EXTRA_PRECISION).div(
f.recordedMoneyMarketIncomeIndex
)
);
if (interestAmount > 0) {
interestAmount = moneyMarket.withdraw(interestAmount);
if (interestAmount > 0) {
stablecoin.safeTransfer(funder, interestAmount);
}
}
}
function payInterestToFunder(uint256 fundingID)
external
returns (uint256 interestAmount)
{
address funder = fundingNFT.ownerOf(fundingID);
require(funder == msg.sender, "DInterest: not funder");
Funding storage f = _getFunding(fundingID);
uint256 currentMoneyMarketIncomeIndex = moneyMarket.incomeIndex();
interestAmount = f
.recordedFundedDepositAmount
.mul(currentMoneyMarketIncomeIndex)
.div(f.recordedMoneyMarketIncomeIndex)
.sub(f.recordedFundedDepositAmount);
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
.sub(
f.recordedFundedDepositAmount.mul(EXTRA_PRECISION).div(
f.recordedMoneyMarketIncomeIndex
)
);
f.recordedMoneyMarketIncomeIndex = currentMoneyMarketIncomeIndex;
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
.add(
f.recordedFundedDepositAmount.mul(EXTRA_PRECISION).div(
f.recordedMoneyMarketIncomeIndex
)
);
if (interestAmount > 0) {
interestAmount = moneyMarket.withdraw(interestAmount);
if (interestAmount > 0) {
stablecoin.safeTransfer(funder, interestAmount);
}
}
}
Public getters
function calculateInterestAmount(
uint256 depositAmount,
uint256 depositPeriodInSeconds
) public returns (uint256 interestAmount) {
(, uint256 moneyMarketInterestRatePerSecond) =
interestOracle.updateAndQuery();
(bool surplusIsNegative, uint256 surplusAmount) = surplus();
return
interestModel.calculateInterestAmount(
depositAmount,
depositPeriodInSeconds,
moneyMarketInterestRatePerSecond,
surplusIsNegative,
surplusAmount
);
}
when a funded deposit is withdrawn.
Formula: \sum_i recordedFundedDepositAmount_i * (incomeIndex / recordedMoneyMarketIncomeIndex_i - 1)
= incomeIndex * (\sum_i recordedFundedDepositAmount_i / recordedMoneyMarketIncomeIndex_i)
- (totalDeposit + totalInterestOwed - unfundedUserDepositAmount)
where i refers to a funding
@notice Computes the floating interest amount owed to deficit funders, which will be paid out
function totalInterestOwedToFunders()
public
returns (uint256 interestOwed)
{
uint256 currentValue =
moneyMarket
.incomeIndex()
.mul(
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
)
.div(EXTRA_PRECISION);
uint256 initialValue =
totalDeposit.add(totalInterestOwed).sub(unfundedUserDepositAmount);
if (currentValue < initialValue) {
return 0;
}
return currentValue.sub(initialValue);
}
function totalInterestOwedToFunders()
public
returns (uint256 interestOwed)
{
uint256 currentValue =
moneyMarket
.incomeIndex()
.mul(
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
)
.div(EXTRA_PRECISION);
uint256 initialValue =
totalDeposit.add(totalInterestOwed).sub(unfundedUserDepositAmount);
if (currentValue < initialValue) {
return 0;
}
return currentValue.sub(initialValue);
}
function surplus() public returns (bool isNegative, uint256 surplusAmount) {
uint256 totalValue = moneyMarket.totalValue();
uint256 totalOwed =
totalDeposit.add(totalInterestOwed).add(
totalInterestOwedToFunders()
);
if (totalValue >= totalOwed) {
isNegative = false;
surplusAmount = totalValue.sub(totalOwed);
isNegative = true;
surplusAmount = totalOwed.sub(totalValue);
}
}
function surplus() public returns (bool isNegative, uint256 surplusAmount) {
uint256 totalValue = moneyMarket.totalValue();
uint256 totalOwed =
totalDeposit.add(totalInterestOwed).add(
totalInterestOwedToFunders()
);
if (totalValue >= totalOwed) {
isNegative = false;
surplusAmount = totalValue.sub(totalOwed);
isNegative = true;
surplusAmount = totalOwed.sub(totalValue);
}
}
} else {
function surplusOfDeposit(uint256 depositID)
public
returns (bool isNegative, uint256 surplusAmount)
{
Deposit storage depositEntry = _getDeposit(depositID);
uint256 currentMoneyMarketIncomeIndex = moneyMarket.incomeIndex();
uint256 currentDepositValue =
depositEntry.amount.mul(currentMoneyMarketIncomeIndex).div(
depositEntry.initialMoneyMarketIncomeIndex
);
uint256 owed = depositEntry.amount.add(depositEntry.interestOwed);
if (currentDepositValue >= owed) {
isNegative = false;
surplusAmount = currentDepositValue.sub(owed);
isNegative = true;
surplusAmount = owed.sub(currentDepositValue);
}
}
function surplusOfDeposit(uint256 depositID)
public
returns (bool isNegative, uint256 surplusAmount)
{
Deposit storage depositEntry = _getDeposit(depositID);
uint256 currentMoneyMarketIncomeIndex = moneyMarket.incomeIndex();
uint256 currentDepositValue =
depositEntry.amount.mul(currentMoneyMarketIncomeIndex).div(
depositEntry.initialMoneyMarketIncomeIndex
);
uint256 owed = depositEntry.amount.add(depositEntry.interestOwed);
if (currentDepositValue >= owed) {
isNegative = false;
surplusAmount = currentDepositValue.sub(owed);
isNegative = true;
surplusAmount = owed.sub(currentDepositValue);
}
}
} else {
function depositIsFunded(uint256 id) public view returns (bool) {
return (id <= latestFundedDepositID);
}
function depositsLength() external view returns (uint256) {
return deposits.length;
}
function fundingListLength() external view returns (uint256) {
return fundingList.length;
}
function getDeposit(uint256 depositID)
external
view
returns (Deposit memory)
{
return deposits[depositID.sub(1)];
}
function getFunding(uint256 fundingID)
external
view
returns (Funding memory)
{
return fundingList[fundingID.sub(1)];
}
function moneyMarketIncomeIndex() external returns (uint256) {
return moneyMarket.incomeIndex();
}
Param setters
function setFeeModel(address newValue) external onlyOwner {
require(newValue.isContract(), "DInterest: not contract");
feeModel = IFeeModel(newValue);
emit ESetParamAddress(msg.sender, "feeModel", newValue);
}
function setInterestModel(address newValue) external onlyOwner {
require(newValue.isContract(), "DInterest: not contract");
interestModel = IInterestModel(newValue);
emit ESetParamAddress(msg.sender, "interestModel", newValue);
}
function setInterestOracle(address newValue) external onlyOwner {
require(newValue.isContract(), "DInterest: not contract");
interestOracle = IInterestOracle(newValue);
require(
interestOracle.moneyMarket() == address(moneyMarket),
"DInterest: moneyMarket mismatch"
);
emit ESetParamAddress(msg.sender, "interestOracle", newValue);
}
function setRewards(address newValue) external onlyOwner {
require(newValue.isContract(), "DInterest: not contract");
moneyMarket.setRewards(newValue);
emit ESetParamAddress(msg.sender, "moneyMarket.rewards", newValue);
}
function setMPHMinter(address newValue) external onlyOwner {
require(newValue.isContract(), "DInterest: not contract");
mphMinter = MPHMinter(newValue);
emit ESetParamAddress(msg.sender, "mphMinter", newValue);
}
function setMinDepositPeriod(uint256 newValue) external onlyOwner {
require(newValue <= MaxDepositPeriod, "DInterest: invalid value");
MinDepositPeriod = newValue;
emit ESetParamUint(msg.sender, "MinDepositPeriod", newValue);
}
function setMaxDepositPeriod(uint256 newValue) external onlyOwner {
require(
newValue >= MinDepositPeriod && newValue > 0,
"DInterest: invalid value"
);
MaxDepositPeriod = newValue;
emit ESetParamUint(msg.sender, "MaxDepositPeriod", newValue);
}
function setMinDepositAmount(uint256 newValue) external onlyOwner {
require(
newValue <= MaxDepositAmount && newValue > 0,
"DInterest: invalid value"
);
MinDepositAmount = newValue;
emit ESetParamUint(msg.sender, "MinDepositAmount", newValue);
}
function setMaxDepositAmount(uint256 newValue) external onlyOwner {
require(
newValue >= MinDepositAmount && newValue > 0,
"DInterest: invalid value"
);
MaxDepositAmount = newValue;
emit ESetParamUint(msg.sender, "MaxDepositAmount", newValue);
}
function setDepositFee(uint256 newValue) external onlyOwner {
require(
newValue < PRECISION,
"DInterest: invalid value"
);
DepositFee = newValue;
emit ESetParamUint(msg.sender, "DepositFee", newValue);
}
function setDepositNFTTokenURI(uint256 tokenId, string calldata newURI)
external
onlyOwner
{
depositNFT.setTokenURI(tokenId, newURI);
}
function setDepositNFTBaseURI(string calldata newURI) external onlyOwner {
depositNFT.setBaseURI(newURI);
}
function setDepositNFTContractURI(string calldata newURI)
external
onlyOwner
{
depositNFT.setContractURI(newURI);
}
function setFundingNFTTokenURI(uint256 tokenId, string calldata newURI)
external
onlyOwner
{
fundingNFT.setTokenURI(tokenId, newURI);
}
function setFundingNFTBaseURI(string calldata newURI) external onlyOwner {
fundingNFT.setBaseURI(newURI);
}
function setFundingNFTContractURI(string calldata newURI)
external
onlyOwner
{
fundingNFT.setContractURI(newURI);
}
Internal getters
function _getDeposit(uint256 depositID)
internal
view
returns (Deposit storage)
{
return deposits[depositID.sub(1)];
}
function _getFunding(uint256 fundingID)
internal
view
returns (Funding storage)
{
return fundingList[fundingID.sub(1)];
}
function _applyDepositFee(uint256 depositAmount)
internal
view
returns (uint256)
{
return depositAmount.mul(PRECISION.sub(DepositFee)).div(PRECISION);
}
Internals
function _deposit(uint256 amount, uint256 maturationTimestamp) internal {
require(
amount >= MinDepositAmount && amount <= MaxDepositAmount,
"DInterest: Deposit amount out of range"
);
uint256 depositPeriod = maturationTimestamp.sub(now);
require(
depositPeriod >= MinDepositPeriod &&
depositPeriod <= MaxDepositPeriod,
"DInterest: Deposit period out of range"
);
amount = _applyDepositFee(amount);
totalDeposit = totalDeposit.add(amount);
uint256 interestAmount = calculateInterestAmount(amount, depositPeriod);
require(interestAmount > 0, "DInterest: interestAmount == 0");
uint256 id = deposits.length.add(1);
unfundedUserDepositAmount = unfundedUserDepositAmount.add(amount).add(
interestAmount
);
totalInterestOwed = totalInterestOwed.add(interestAmount);
uint256 mintMPHAmount =
mphMinter.mintDepositorReward(
msg.sender,
amount,
depositPeriod,
interestAmount
);
deposits.push(
Deposit({
amount: amount,
maturationTimestamp: maturationTimestamp,
interestOwed: interestAmount,
initialMoneyMarketIncomeIndex: moneyMarket.incomeIndex(),
active: true,
finalSurplusIsNegative: false,
finalSurplusAmount: 0,
mintMPHAmount: mintMPHAmount,
depositTimestamp: now
})
);
moneyMarket.deposit(amount);
msg.sender,
id,
amount,
maturationTimestamp,
interestAmount,
mintMPHAmount
);
}
function _deposit(uint256 amount, uint256 maturationTimestamp) internal {
require(
amount >= MinDepositAmount && amount <= MaxDepositAmount,
"DInterest: Deposit amount out of range"
);
uint256 depositPeriod = maturationTimestamp.sub(now);
require(
depositPeriod >= MinDepositPeriod &&
depositPeriod <= MaxDepositPeriod,
"DInterest: Deposit period out of range"
);
amount = _applyDepositFee(amount);
totalDeposit = totalDeposit.add(amount);
uint256 interestAmount = calculateInterestAmount(amount, depositPeriod);
require(interestAmount > 0, "DInterest: interestAmount == 0");
uint256 id = deposits.length.add(1);
unfundedUserDepositAmount = unfundedUserDepositAmount.add(amount).add(
interestAmount
);
totalInterestOwed = totalInterestOwed.add(interestAmount);
uint256 mintMPHAmount =
mphMinter.mintDepositorReward(
msg.sender,
amount,
depositPeriod,
interestAmount
);
deposits.push(
Deposit({
amount: amount,
maturationTimestamp: maturationTimestamp,
interestOwed: interestAmount,
initialMoneyMarketIncomeIndex: moneyMarket.incomeIndex(),
active: true,
finalSurplusIsNegative: false,
finalSurplusAmount: 0,
mintMPHAmount: mintMPHAmount,
depositTimestamp: now
})
);
moneyMarket.deposit(amount);
msg.sender,
id,
amount,
maturationTimestamp,
interestAmount,
mintMPHAmount
);
}
stablecoin.safeTransferFrom(msg.sender, address(this), amount);
stablecoin.safeIncreaseAllowance(address(moneyMarket), amount);
depositNFT.mint(msg.sender, id);
emit EDeposit(
function _withdraw(
uint256 depositID,
uint256 fundingID,
bool early
) internal {
Deposit storage depositEntry = _getDeposit(depositID);
require(depositEntry.active, "DInterest: Deposit not active");
depositEntry.active = false;
if (early) {
require(
now < depositEntry.maturationTimestamp,
"DInterest: Deposit mature, use withdraw() instead"
);
require(
now > depositEntry.depositTimestamp,
"DInterest: Deposited in same block"
);
require(
now >= depositEntry.maturationTimestamp,
"DInterest: Deposit not mature"
);
}
depositNFT.ownerOf(depositID) == msg.sender,
"DInterest: Sender doesn't own depositNFT"
);
{
uint256 takeBackMPHAmount =
mphMinter.takeBackDepositorReward(
msg.sender,
depositEntry.mintMPHAmount,
early
);
emit EWithdraw(
msg.sender,
depositID,
fundingID,
early,
takeBackMPHAmount
);
}
require(
currentMoneyMarketIncomeIndex > 0,
"DInterest: currentMoneyMarketIncomeIndex == 0"
);
(bool depositSurplusIsNegative, uint256 depositSurplus) =
surplusOfDeposit(depositID);
{
uint256 feeAmount;
uint256 withdrawAmount;
if (early) {
withdrawAmount = depositEntry.amount;
feeAmount = feeModel.getFee(depositEntry.interestOwed);
withdrawAmount = depositEntry.amount.add(
depositEntry.interestOwed
);
}
withdrawAmount = moneyMarket.withdraw(withdrawAmount);
if (feeAmount > 0) {
stablecoin.safeTransfer(feeModel.beneficiary(), feeAmount);
}
}
if (depositIsFunded(depositID)) {
_payInterestToFunder(
fundingID,
depositID,
depositEntry.amount,
depositEntry.maturationTimestamp,
depositEntry.interestOwed,
depositSurplusIsNegative,
depositSurplus,
currentMoneyMarketIncomeIndex,
early
);
unfundedUserDepositAmount = unfundedUserDepositAmount.sub(
depositEntry.amount.add(depositEntry.interestOwed)
);
depositEntry.finalSurplusIsNegative = depositSurplusIsNegative;
depositEntry.finalSurplusAmount = depositSurplus;
}
}
function _withdraw(
uint256 depositID,
uint256 fundingID,
bool early
) internal {
Deposit storage depositEntry = _getDeposit(depositID);
require(depositEntry.active, "DInterest: Deposit not active");
depositEntry.active = false;
if (early) {
require(
now < depositEntry.maturationTimestamp,
"DInterest: Deposit mature, use withdraw() instead"
);
require(
now > depositEntry.depositTimestamp,
"DInterest: Deposited in same block"
);
require(
now >= depositEntry.maturationTimestamp,
"DInterest: Deposit not mature"
);
}
depositNFT.ownerOf(depositID) == msg.sender,
"DInterest: Sender doesn't own depositNFT"
);
{
uint256 takeBackMPHAmount =
mphMinter.takeBackDepositorReward(
msg.sender,
depositEntry.mintMPHAmount,
early
);
emit EWithdraw(
msg.sender,
depositID,
fundingID,
early,
takeBackMPHAmount
);
}
require(
currentMoneyMarketIncomeIndex > 0,
"DInterest: currentMoneyMarketIncomeIndex == 0"
);
(bool depositSurplusIsNegative, uint256 depositSurplus) =
surplusOfDeposit(depositID);
{
uint256 feeAmount;
uint256 withdrawAmount;
if (early) {
withdrawAmount = depositEntry.amount;
feeAmount = feeModel.getFee(depositEntry.interestOwed);
withdrawAmount = depositEntry.amount.add(
depositEntry.interestOwed
);
}
withdrawAmount = moneyMarket.withdraw(withdrawAmount);
if (feeAmount > 0) {
stablecoin.safeTransfer(feeModel.beneficiary(), feeAmount);
}
}
if (depositIsFunded(depositID)) {
_payInterestToFunder(
fundingID,
depositID,
depositEntry.amount,
depositEntry.maturationTimestamp,
depositEntry.interestOwed,
depositSurplusIsNegative,
depositSurplus,
currentMoneyMarketIncomeIndex,
early
);
unfundedUserDepositAmount = unfundedUserDepositAmount.sub(
depositEntry.amount.add(depositEntry.interestOwed)
);
depositEntry.finalSurplusIsNegative = depositSurplusIsNegative;
depositEntry.finalSurplusAmount = depositSurplus;
}
}
} else {
require(
function _withdraw(
uint256 depositID,
uint256 fundingID,
bool early
) internal {
Deposit storage depositEntry = _getDeposit(depositID);
require(depositEntry.active, "DInterest: Deposit not active");
depositEntry.active = false;
if (early) {
require(
now < depositEntry.maturationTimestamp,
"DInterest: Deposit mature, use withdraw() instead"
);
require(
now > depositEntry.depositTimestamp,
"DInterest: Deposited in same block"
);
require(
now >= depositEntry.maturationTimestamp,
"DInterest: Deposit not mature"
);
}
depositNFT.ownerOf(depositID) == msg.sender,
"DInterest: Sender doesn't own depositNFT"
);
{
uint256 takeBackMPHAmount =
mphMinter.takeBackDepositorReward(
msg.sender,
depositEntry.mintMPHAmount,
early
);
emit EWithdraw(
msg.sender,
depositID,
fundingID,
early,
takeBackMPHAmount
);
}
require(
currentMoneyMarketIncomeIndex > 0,
"DInterest: currentMoneyMarketIncomeIndex == 0"
);
(bool depositSurplusIsNegative, uint256 depositSurplus) =
surplusOfDeposit(depositID);
{
uint256 feeAmount;
uint256 withdrawAmount;
if (early) {
withdrawAmount = depositEntry.amount;
feeAmount = feeModel.getFee(depositEntry.interestOwed);
withdrawAmount = depositEntry.amount.add(
depositEntry.interestOwed
);
}
withdrawAmount = moneyMarket.withdraw(withdrawAmount);
if (feeAmount > 0) {
stablecoin.safeTransfer(feeModel.beneficiary(), feeAmount);
}
}
if (depositIsFunded(depositID)) {
_payInterestToFunder(
fundingID,
depositID,
depositEntry.amount,
depositEntry.maturationTimestamp,
depositEntry.interestOwed,
depositSurplusIsNegative,
depositSurplus,
currentMoneyMarketIncomeIndex,
early
);
unfundedUserDepositAmount = unfundedUserDepositAmount.sub(
depositEntry.amount.add(depositEntry.interestOwed)
);
depositEntry.finalSurplusIsNegative = depositSurplusIsNegative;
depositEntry.finalSurplusAmount = depositSurplus;
}
}
totalDeposit = totalDeposit.sub(depositEntry.amount);
totalInterestOwed = totalInterestOwed.sub(depositEntry.interestOwed);
uint256 currentMoneyMarketIncomeIndex = moneyMarket.incomeIndex();
function _withdraw(
uint256 depositID,
uint256 fundingID,
bool early
) internal {
Deposit storage depositEntry = _getDeposit(depositID);
require(depositEntry.active, "DInterest: Deposit not active");
depositEntry.active = false;
if (early) {
require(
now < depositEntry.maturationTimestamp,
"DInterest: Deposit mature, use withdraw() instead"
);
require(
now > depositEntry.depositTimestamp,
"DInterest: Deposited in same block"
);
require(
now >= depositEntry.maturationTimestamp,
"DInterest: Deposit not mature"
);
}
depositNFT.ownerOf(depositID) == msg.sender,
"DInterest: Sender doesn't own depositNFT"
);
{
uint256 takeBackMPHAmount =
mphMinter.takeBackDepositorReward(
msg.sender,
depositEntry.mintMPHAmount,
early
);
emit EWithdraw(
msg.sender,
depositID,
fundingID,
early,
takeBackMPHAmount
);
}
require(
currentMoneyMarketIncomeIndex > 0,
"DInterest: currentMoneyMarketIncomeIndex == 0"
);
(bool depositSurplusIsNegative, uint256 depositSurplus) =
surplusOfDeposit(depositID);
{
uint256 feeAmount;
uint256 withdrawAmount;
if (early) {
withdrawAmount = depositEntry.amount;
feeAmount = feeModel.getFee(depositEntry.interestOwed);
withdrawAmount = depositEntry.amount.add(
depositEntry.interestOwed
);
}
withdrawAmount = moneyMarket.withdraw(withdrawAmount);
if (feeAmount > 0) {
stablecoin.safeTransfer(feeModel.beneficiary(), feeAmount);
}
}
if (depositIsFunded(depositID)) {
_payInterestToFunder(
fundingID,
depositID,
depositEntry.amount,
depositEntry.maturationTimestamp,
depositEntry.interestOwed,
depositSurplusIsNegative,
depositSurplus,
currentMoneyMarketIncomeIndex,
early
);
unfundedUserDepositAmount = unfundedUserDepositAmount.sub(
depositEntry.amount.add(depositEntry.interestOwed)
);
depositEntry.finalSurplusIsNegative = depositSurplusIsNegative;
depositEntry.finalSurplusAmount = depositSurplus;
}
}
function _withdraw(
uint256 depositID,
uint256 fundingID,
bool early
) internal {
Deposit storage depositEntry = _getDeposit(depositID);
require(depositEntry.active, "DInterest: Deposit not active");
depositEntry.active = false;
if (early) {
require(
now < depositEntry.maturationTimestamp,
"DInterest: Deposit mature, use withdraw() instead"
);
require(
now > depositEntry.depositTimestamp,
"DInterest: Deposited in same block"
);
require(
now >= depositEntry.maturationTimestamp,
"DInterest: Deposit not mature"
);
}
depositNFT.ownerOf(depositID) == msg.sender,
"DInterest: Sender doesn't own depositNFT"
);
{
uint256 takeBackMPHAmount =
mphMinter.takeBackDepositorReward(
msg.sender,
depositEntry.mintMPHAmount,
early
);
emit EWithdraw(
msg.sender,
depositID,
fundingID,
early,
takeBackMPHAmount
);
}
require(
currentMoneyMarketIncomeIndex > 0,
"DInterest: currentMoneyMarketIncomeIndex == 0"
);
(bool depositSurplusIsNegative, uint256 depositSurplus) =
surplusOfDeposit(depositID);
{
uint256 feeAmount;
uint256 withdrawAmount;
if (early) {
withdrawAmount = depositEntry.amount;
feeAmount = feeModel.getFee(depositEntry.interestOwed);
withdrawAmount = depositEntry.amount.add(
depositEntry.interestOwed
);
}
withdrawAmount = moneyMarket.withdraw(withdrawAmount);
if (feeAmount > 0) {
stablecoin.safeTransfer(feeModel.beneficiary(), feeAmount);
}
}
if (depositIsFunded(depositID)) {
_payInterestToFunder(
fundingID,
depositID,
depositEntry.amount,
depositEntry.maturationTimestamp,
depositEntry.interestOwed,
depositSurplusIsNegative,
depositSurplus,
currentMoneyMarketIncomeIndex,
early
);
unfundedUserDepositAmount = unfundedUserDepositAmount.sub(
depositEntry.amount.add(depositEntry.interestOwed)
);
depositEntry.finalSurplusIsNegative = depositSurplusIsNegative;
depositEntry.finalSurplusAmount = depositSurplus;
}
}
} else {
stablecoin.safeTransfer(msg.sender, withdrawAmount.sub(feeAmount));
function _withdraw(
uint256 depositID,
uint256 fundingID,
bool early
) internal {
Deposit storage depositEntry = _getDeposit(depositID);
require(depositEntry.active, "DInterest: Deposit not active");
depositEntry.active = false;
if (early) {
require(
now < depositEntry.maturationTimestamp,
"DInterest: Deposit mature, use withdraw() instead"
);
require(
now > depositEntry.depositTimestamp,
"DInterest: Deposited in same block"
);
require(
now >= depositEntry.maturationTimestamp,
"DInterest: Deposit not mature"
);
}
depositNFT.ownerOf(depositID) == msg.sender,
"DInterest: Sender doesn't own depositNFT"
);
{
uint256 takeBackMPHAmount =
mphMinter.takeBackDepositorReward(
msg.sender,
depositEntry.mintMPHAmount,
early
);
emit EWithdraw(
msg.sender,
depositID,
fundingID,
early,
takeBackMPHAmount
);
}
require(
currentMoneyMarketIncomeIndex > 0,
"DInterest: currentMoneyMarketIncomeIndex == 0"
);
(bool depositSurplusIsNegative, uint256 depositSurplus) =
surplusOfDeposit(depositID);
{
uint256 feeAmount;
uint256 withdrawAmount;
if (early) {
withdrawAmount = depositEntry.amount;
feeAmount = feeModel.getFee(depositEntry.interestOwed);
withdrawAmount = depositEntry.amount.add(
depositEntry.interestOwed
);
}
withdrawAmount = moneyMarket.withdraw(withdrawAmount);
if (feeAmount > 0) {
stablecoin.safeTransfer(feeModel.beneficiary(), feeAmount);
}
}
if (depositIsFunded(depositID)) {
_payInterestToFunder(
fundingID,
depositID,
depositEntry.amount,
depositEntry.maturationTimestamp,
depositEntry.interestOwed,
depositSurplusIsNegative,
depositSurplus,
currentMoneyMarketIncomeIndex,
early
);
unfundedUserDepositAmount = unfundedUserDepositAmount.sub(
depositEntry.amount.add(depositEntry.interestOwed)
);
depositEntry.finalSurplusIsNegative = depositSurplusIsNegative;
depositEntry.finalSurplusAmount = depositSurplus;
}
}
function _withdraw(
uint256 depositID,
uint256 fundingID,
bool early
) internal {
Deposit storage depositEntry = _getDeposit(depositID);
require(depositEntry.active, "DInterest: Deposit not active");
depositEntry.active = false;
if (early) {
require(
now < depositEntry.maturationTimestamp,
"DInterest: Deposit mature, use withdraw() instead"
);
require(
now > depositEntry.depositTimestamp,
"DInterest: Deposited in same block"
);
require(
now >= depositEntry.maturationTimestamp,
"DInterest: Deposit not mature"
);
}
depositNFT.ownerOf(depositID) == msg.sender,
"DInterest: Sender doesn't own depositNFT"
);
{
uint256 takeBackMPHAmount =
mphMinter.takeBackDepositorReward(
msg.sender,
depositEntry.mintMPHAmount,
early
);
emit EWithdraw(
msg.sender,
depositID,
fundingID,
early,
takeBackMPHAmount
);
}
require(
currentMoneyMarketIncomeIndex > 0,
"DInterest: currentMoneyMarketIncomeIndex == 0"
);
(bool depositSurplusIsNegative, uint256 depositSurplus) =
surplusOfDeposit(depositID);
{
uint256 feeAmount;
uint256 withdrawAmount;
if (early) {
withdrawAmount = depositEntry.amount;
feeAmount = feeModel.getFee(depositEntry.interestOwed);
withdrawAmount = depositEntry.amount.add(
depositEntry.interestOwed
);
}
withdrawAmount = moneyMarket.withdraw(withdrawAmount);
if (feeAmount > 0) {
stablecoin.safeTransfer(feeModel.beneficiary(), feeAmount);
}
}
if (depositIsFunded(depositID)) {
_payInterestToFunder(
fundingID,
depositID,
depositEntry.amount,
depositEntry.maturationTimestamp,
depositEntry.interestOwed,
depositSurplusIsNegative,
depositSurplus,
currentMoneyMarketIncomeIndex,
early
);
unfundedUserDepositAmount = unfundedUserDepositAmount.sub(
depositEntry.amount.add(depositEntry.interestOwed)
);
depositEntry.finalSurplusIsNegative = depositSurplusIsNegative;
depositEntry.finalSurplusAmount = depositSurplus;
}
}
} else {
function _payInterestToFunder(
uint256 fundingID,
uint256 depositID,
uint256 depositAmount,
uint256 depositMaturationTimestamp,
uint256 depositInterestOwed,
bool depositSurplusIsNegative,
uint256 depositSurplus,
uint256 currentMoneyMarketIncomeIndex,
bool early
) internal {
Funding storage f = _getFunding(fundingID);
require(
depositID > f.fromDepositID && depositID <= f.toDepositID,
"DInterest: Deposit not funded by fundingID"
);
uint256 interestAmount =
f
.recordedFundedDepositAmount
.mul(currentMoneyMarketIncomeIndex)
.div(f.recordedMoneyMarketIncomeIndex)
.sub(f.recordedFundedDepositAmount);
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
.sub(
f.recordedFundedDepositAmount.mul(EXTRA_PRECISION).div(
f.recordedMoneyMarketIncomeIndex
)
);
f.recordedFundedDepositAmount = f.recordedFundedDepositAmount.sub(
depositAmount.add(depositInterestOwed)
);
f.recordedMoneyMarketIncomeIndex = currentMoneyMarketIncomeIndex;
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
.add(
f.recordedFundedDepositAmount.mul(EXTRA_PRECISION).div(
f.recordedMoneyMarketIncomeIndex
)
);
address funder = fundingNFT.ownerOf(fundingID);
uint256 transferToFunderAmount =
(early && depositSurplusIsNegative)
? interestAmount.add(depositSurplus)
: interestAmount;
if (transferToFunderAmount > 0) {
transferToFunderAmount = moneyMarket.withdraw(
transferToFunderAmount
);
if (transferToFunderAmount > 0) {
stablecoin.safeTransfer(funder, transferToFunderAmount);
}
}
funder,
depositAmount,
f.creationTimestamp,
depositMaturationTimestamp,
interestAmount,
early
);
}
function _payInterestToFunder(
uint256 fundingID,
uint256 depositID,
uint256 depositAmount,
uint256 depositMaturationTimestamp,
uint256 depositInterestOwed,
bool depositSurplusIsNegative,
uint256 depositSurplus,
uint256 currentMoneyMarketIncomeIndex,
bool early
) internal {
Funding storage f = _getFunding(fundingID);
require(
depositID > f.fromDepositID && depositID <= f.toDepositID,
"DInterest: Deposit not funded by fundingID"
);
uint256 interestAmount =
f
.recordedFundedDepositAmount
.mul(currentMoneyMarketIncomeIndex)
.div(f.recordedMoneyMarketIncomeIndex)
.sub(f.recordedFundedDepositAmount);
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
.sub(
f.recordedFundedDepositAmount.mul(EXTRA_PRECISION).div(
f.recordedMoneyMarketIncomeIndex
)
);
f.recordedFundedDepositAmount = f.recordedFundedDepositAmount.sub(
depositAmount.add(depositInterestOwed)
);
f.recordedMoneyMarketIncomeIndex = currentMoneyMarketIncomeIndex;
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
.add(
f.recordedFundedDepositAmount.mul(EXTRA_PRECISION).div(
f.recordedMoneyMarketIncomeIndex
)
);
address funder = fundingNFT.ownerOf(fundingID);
uint256 transferToFunderAmount =
(early && depositSurplusIsNegative)
? interestAmount.add(depositSurplus)
: interestAmount;
if (transferToFunderAmount > 0) {
transferToFunderAmount = moneyMarket.withdraw(
transferToFunderAmount
);
if (transferToFunderAmount > 0) {
stablecoin.safeTransfer(funder, transferToFunderAmount);
}
}
funder,
depositAmount,
f.creationTimestamp,
depositMaturationTimestamp,
interestAmount,
early
);
}
function _payInterestToFunder(
uint256 fundingID,
uint256 depositID,
uint256 depositAmount,
uint256 depositMaturationTimestamp,
uint256 depositInterestOwed,
bool depositSurplusIsNegative,
uint256 depositSurplus,
uint256 currentMoneyMarketIncomeIndex,
bool early
) internal {
Funding storage f = _getFunding(fundingID);
require(
depositID > f.fromDepositID && depositID <= f.toDepositID,
"DInterest: Deposit not funded by fundingID"
);
uint256 interestAmount =
f
.recordedFundedDepositAmount
.mul(currentMoneyMarketIncomeIndex)
.div(f.recordedMoneyMarketIncomeIndex)
.sub(f.recordedFundedDepositAmount);
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
.sub(
f.recordedFundedDepositAmount.mul(EXTRA_PRECISION).div(
f.recordedMoneyMarketIncomeIndex
)
);
f.recordedFundedDepositAmount = f.recordedFundedDepositAmount.sub(
depositAmount.add(depositInterestOwed)
);
f.recordedMoneyMarketIncomeIndex = currentMoneyMarketIncomeIndex;
sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex
.add(
f.recordedFundedDepositAmount.mul(EXTRA_PRECISION).div(
f.recordedMoneyMarketIncomeIndex
)
);
address funder = fundingNFT.ownerOf(fundingID);
uint256 transferToFunderAmount =
(early && depositSurplusIsNegative)
? interestAmount.add(depositSurplus)
: interestAmount;
if (transferToFunderAmount > 0) {
transferToFunderAmount = moneyMarket.withdraw(
transferToFunderAmount
);
if (transferToFunderAmount > 0) {
stablecoin.safeTransfer(funder, transferToFunderAmount);
}
}
funder,
depositAmount,
f.creationTimestamp,
depositMaturationTimestamp,
interestAmount,
early
);
}
mphMinter.mintFunderReward(
function _fund(uint256 totalDeficit) internal {
stablecoin.safeTransferFrom(msg.sender, address(this), totalDeficit);
stablecoin.safeIncreaseAllowance(address(moneyMarket), totalDeficit);
moneyMarket.deposit(totalDeficit);
fundingNFT.mint(msg.sender, fundingList.length);
uint256 fundingID = fundingList.length;
emit EFund(msg.sender, fundingID, totalDeficit);
}
}
| 1,202,152 | [
1,
758,
48,
479,
304,
5294,
395,
1493,
2597,
1807,
19283,
1473,
628,
326,
3563,
5,
14801,
453,
7474,
3492,
43,
1457,
51,
6712,
30,
2285,
10241,
1940,
511,
1395,
13329,
30,
306,
3652,
131,
259,
1117,
65,
5245,
2177,
443,
1724,
501,
8315,
443,
1724,
711,
392,
1599,
1399,
316,
326,
443,
1724,
50,
4464,
16,
1492,
353,
3959,
358,
2097,
770,
316,
1375,
323,
917,
1282,
68,
8737,
404,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16351,
463,
29281,
1190,
758,
1724,
14667,
353,
868,
8230,
12514,
16709,
16,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
3416,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
14060,
654,
39,
3462,
364,
4232,
39,
3462,
31,
203,
565,
1450,
5267,
364,
1758,
31,
203,
203,
565,
2254,
5034,
2713,
5381,
7071,
26913,
273,
1728,
636,
2643,
31,
203,
565,
2254,
5034,
2713,
5381,
15623,
273,
1728,
636,
2643,
31,
203,
203,
565,
1958,
4019,
538,
305,
288,
203,
3639,
1426,
727,
7719,
10103,
2520,
14959,
31,
203,
565,
289,
203,
565,
4019,
538,
305,
8526,
2713,
443,
917,
1282,
31,
203,
203,
565,
1958,
478,
14351,
288,
203,
3639,
2254,
5034,
628,
758,
1724,
734,
31,
203,
3639,
2254,
5034,
358,
758,
1724,
734,
31,
203,
565,
289,
203,
565,
478,
14351,
8526,
2713,
22058,
682,
31,
203,
3639,
1071,
2142,
951,
426,
3850,
785,
42,
12254,
758,
1724,
1876,
29281,
6275,
7244,
426,
3850,
785,
382,
5624,
1016,
31,
203,
203,
565,
2254,
5034,
1071,
2078,
29281,
3494,
329,
31,
203,
203,
565,
4232,
39,
3462,
1071,
14114,
12645,
31,
203,
565,
11083,
1340,
1488,
1071,
14036,
1488,
31,
203,
565,
467,
29281,
1488,
1071,
16513,
1488,
31,
203,
565,
467,
29281,
23601,
1071,
16513,
23601,
31,
203,
565,
423,
4464,
1071,
443,
1724,
50,
4464,
31,
203,
565,
423,
4464,
1071,
22058,
50,
4464,
31,
203,
565,
490,
8939,
49,
2761,
1071,
312,
844,
49,
2761,
31,
203,
203,
3639,
1758,
8808,
2
] |
// A Ponzi scheme where old investors are payed with the funds received from new investors.
// Unlike what is out there in the market, the contract creator received no funds - if you
// don't do work, you cannot expect to be paid. People who put in the funds receive all the
// returns. Owners can particiapte themselves, there is no leaching off the top and slowing
// down payouts for the participants.
contract ZeroPonzi {
// minimum & maxium entry values
uint public constant MIN_VALUE = 100 finney;
uint public constant MAX_VALUE = 10 ether;
// the return multiplier & divisors, yielding 1.25 (125%) returns
uint public constant RET_MUL = 125;
uint public constant RET_DIV = 100;
// entry structure, storing the address & yield
struct Payout {
address addr;
uint yield;
}
// our actual queued payouts, index of current & total distributed
Payout[] public payouts;
uint public payoutIndex = 0;
uint public payoutTotal = 0;
// construtor, no additional requirements
function ZeroPonzi() {
}
// single entry point, add entry & pay what we can
function() {
// we only accept values in range
if ((msg.value < MIN_VALUE) || (msg.value > MAX_VALUE)) {
throw;
}
// queue the current entry as a future payout recipient
uint entryIndex = payouts.length;
payouts.length += 1;
payouts[entryIndex].addr = msg.sender;
payouts[entryIndex].yield = (msg.value * RET_MUL) / RET_DIV;
// send payouts while we can afford to do so
while (payouts[payoutIndex].yield < this.balance) {
payoutTotal += payouts[payoutIndex].yield;
payouts[payoutIndex].addr.send(payouts[payoutIndex].yield);
payoutIndex += 1;
}
}
} | single entry point, add entry & pay what we can we only accept values in range send payouts while we can afford to do so | function() {
if ((msg.value < MIN_VALUE) || (msg.value > MAX_VALUE)) {
throw;
}
payouts.length += 1;
payouts[entryIndex].addr = msg.sender;
payouts[entryIndex].yield = (msg.value * RET_MUL) / RET_DIV;
while (payouts[payoutIndex].yield < this.balance) {
payoutTotal += payouts[payoutIndex].yield;
payouts[payoutIndex].addr.send(payouts[payoutIndex].yield);
payoutIndex += 1;
}
}
| 12,765,100 | [
1,
7526,
1241,
1634,
16,
527,
1241,
473,
8843,
4121,
732,
848,
732,
1338,
2791,
924,
316,
1048,
1366,
293,
2012,
87,
1323,
732,
848,
7103,
517,
358,
741,
1427,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1435,
288,
203,
565,
309,
14015,
3576,
18,
1132,
411,
6989,
67,
4051,
13,
747,
261,
3576,
18,
1132,
405,
4552,
67,
4051,
3719,
288,
203,
1377,
604,
31,
203,
565,
289,
203,
203,
565,
293,
2012,
87,
18,
2469,
1011,
404,
31,
203,
565,
293,
2012,
87,
63,
4099,
1016,
8009,
4793,
273,
1234,
18,
15330,
31,
203,
565,
293,
2012,
87,
63,
4099,
1016,
8009,
23604,
273,
261,
3576,
18,
1132,
380,
10366,
67,
49,
1506,
13,
342,
10366,
67,
31901,
31,
203,
203,
565,
1323,
261,
84,
2012,
87,
63,
84,
2012,
1016,
8009,
23604,
411,
333,
18,
12296,
13,
288,
203,
1377,
293,
2012,
5269,
1011,
293,
2012,
87,
63,
84,
2012,
1016,
8009,
23604,
31,
203,
1377,
293,
2012,
87,
63,
84,
2012,
1016,
8009,
4793,
18,
4661,
12,
84,
2012,
87,
63,
84,
2012,
1016,
8009,
23604,
1769,
203,
1377,
293,
2012,
1016,
1011,
404,
31,
203,
565,
289,
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
] |
pragma solidity ^0.4.23;
// File: contracts\utils\SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// File: contracts\utils\Serialize.sol
contract Serialize {
using SafeMath for uint256;
function addAddress(uint _offst, bytes memory _output, address _input) internal pure returns(uint _offset) {
assembly {
mstore(add(_output, _offst), _input)
}
return _offst.sub(20);
}
function addUint(uint _offst, bytes memory _output, uint _input) internal pure returns (uint _offset) {
assembly {
mstore(add(_output, _offst), _input)
}
return _offst.sub(32);
}
function addUint8(uint _offst, bytes memory _output, uint _input) internal pure returns (uint _offset) {
assembly {
mstore(add(_output, _offst), _input)
}
return _offst.sub(1);
}
function addUint16(uint _offst, bytes memory _output, uint _input) internal pure returns (uint _offset) {
assembly {
mstore(add(_output, _offst), _input)
}
return _offst.sub(2);
}
function addUint64(uint _offst, bytes memory _output, uint _input) internal pure returns (uint _offset) {
assembly {
mstore(add(_output, _offst), _input)
}
return _offst.sub(8);
}
function getAddress(uint _offst, bytes memory _input) internal pure returns (address _output, uint _offset) {
assembly {
_output := mload(add(_input, _offst))
}
return (_output, _offst.sub(20));
}
function getUint(uint _offst, bytes memory _input) internal pure returns (uint _output, uint _offset) {
assembly {
_output := mload(add(_input, _offst))
}
return (_output, _offst.sub(32));
}
function getUint8(uint _offst, bytes memory _input) internal pure returns (uint8 _output, uint _offset) {
assembly {
_output := mload(add(_input, _offst))
}
return (_output, _offst.sub(1));
}
function getUint16(uint _offst, bytes memory _input) internal pure returns (uint16 _output, uint _offset) {
assembly {
_output := mload(add(_input, _offst))
}
return (_output, _offst.sub(2));
}
function getUint64(uint _offst, bytes memory _input) internal pure returns (uint64 _output, uint _offset) {
assembly {
_output := mload(add(_input, _offst))
}
return (_output, _offst.sub(8));
}
}
// File: contracts\utils\AddressUtils.sol
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param addr address to check
* @return whether the target address is a contract
*/
function isContract(address addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
assembly { size := extcodesize(addr) } // solium-disable-line security/no-inline-assembly
return size > 0;
}
}
// File: contracts\utils\Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: contracts\utils\Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
// File: contracts\ERC721\ERC721Basic.sol
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Basic {
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _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 exists(uint256 _tokenId) public view returns (bool _exists);
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 _data
)
public;
}
// File: contracts\ERC721\ERC721Receiver.sol
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. This function MUST use 50,000 gas or less. Return of other
* than the magic value MUST result in the transaction being reverted.
* Note: the contract address is always the message sender.
* @param _from The sending address
* @param _tokenId The NFT identifier which is being transfered
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
*/
function onERC721Received(address _from, uint256 _tokenId, bytes _data) public returns(bytes4);
}
// File: contracts\ERC721\ERC721BasicToken.sol
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721BasicToken is ERC721Basic, Pausable {
using SafeMath for uint256;
using AddressUtils for address;
// Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
// which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
// Mapping from token ID to owner
mapping (uint256 => address) internal tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) internal tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) internal ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) internal operatorApprovals;
/**
* @dev Guarantees msg.sender is owner of the given token
* @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender
*/
modifier onlyOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender);
_;
}
/**
* @dev Checks msg.sender can transfer a token, by being owner, approved, or operator
* @param _tokenId uint256 ID of the token to validate
*/
modifier canTransfer(uint256 _tokenId) {
require(isApprovedOrOwner(msg.sender, _tokenId));
_;
}
/**
* @dev Gets the balance of the specified address
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256) {
require(_owner != address(0));
return ownedTokensCount[_owner];
}
/**
* @dev Gets the owner of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
/**
* @dev Returns whether the specified token exists
* @param _tokenId uint256 ID of the token to query the existance of
* @return whether the token exists
*/
function exists(uint256 _tokenId) public view returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
/**
* @dev Approves another address to transfer the given token ID
* @dev The zero address indicates there is no approved address.
* @dev There can only be one approved address per token at a given time.
* @dev Can only be called by the token owner or an approved operator.
* @param _to address to be approved for the given token ID
* @param _tokenId uint256 ID of the token to be approved
*/
function approve(address _to, uint256 _tokenId) public {
address owner = ownerOf(_tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
if (getApproved(_tokenId) != address(0) || _to != address(0)) {
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved for a the given token ID
*/
function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* @dev An operator is allowed to transfer all tokens of the sender on their behalf
* @param _to operator address to set the approval
* @param _approved representing the status of the approval to be set
*/
function setApprovalForAll(address _to, bool _approved) public {
require(_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param _owner owner address which you want to query the approval of
* @param _operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address _owner, address _operator) public view returns (bool) {
return operatorApprovals[_owner][_operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId) {
require(_from != address(0));
require(_to != address(0));
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
function transferBatch(address _from, address _to, uint[] _tokenIds) public {
require(_from != address(0));
require(_to != address(0));
for(uint i=0; i<_tokenIds.length; i++) {
require(isApprovedOrOwner(msg.sender, _tokenIds[i]));
clearApproval(_from, _tokenIds[i]);
removeTokenFrom(_from, _tokenIds[i]);
addTokenTo(_to, _tokenIds[i]);
emit Transfer(_from, _to, _tokenIds[i]);
}
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* @dev If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
canTransfer(_tokenId)
{
// solium-disable-next-line arg-overflow
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* @dev If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
canTransfer(_tokenId)
{
transferFrom(_from, _to, _tokenId);
// solium-disable-next-line arg-overflow
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param _spender address of the spender to query
* @param _tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool) {
address owner = ownerOf(_tokenId);
return _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender);
}
/**
* @dev Internal function to mint a new token
* @dev Reverts if the given token ID already exists
* @param _to The address that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addTokenTo(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
/**
* @dev Internal function to burn a specific token
* @dev Reverts if the token does not exist
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
clearApproval(_owner, _tokenId);
removeTokenFrom(_owner, _tokenId);
emit Transfer(_owner, address(0), _tokenId);
}
/**
* @dev Internal function to clear current approval of a given token ID
* @dev Reverts if the given address is not indeed the owner of the token
* @param _owner owner of the token
* @param _tokenId uint256 ID of the token to be transferred
*/
function clearApproval(address _owner, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
emit Approval(_owner, address(0), _tokenId);
}
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @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 addTokenTo(address _to, uint256 _tokenId) internal whenNotPaused {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
ownedTokensCount[_to] = ownedTokensCount[_to].add(1);
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @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 removeTokenFrom(address _from, uint256 _tokenId) internal whenNotPaused{
require(ownerOf(_tokenId) == _from);
ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);
tokenOwner[_tokenId] = address(0);
}
/**
* @dev Internal function to invoke `onERC721Received` on a target address
* @dev 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 whether the call correctly returned the expected magic value
*/
function checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal
returns (bool)
{
if (!_to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(_from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
}
// File: contracts\ERC721\GirlBasicToken.sol
// add atomic swap feature in the token contract.
contract GirlBasicToken is ERC721BasicToken, Serialize {
event CreateGirl(address owner, uint256 tokenID, uint256 genes, uint64 birthTime, uint64 cooldownEndTime, uint16 starLevel);
event CoolDown(uint256 tokenId, uint64 cooldownEndTime);
event GirlUpgrade(uint256 tokenId, uint64 starLevel);
struct Girl{
/**
少女基因,生成以后不会改变
**/
uint genes;
/*
出生时间 少女创建时候的时间戳
*/
uint64 birthTime;
/*
冷却结束时间
*/
uint64 cooldownEndTime;
/*
star level
*/
uint16 starLevel;
}
Girl[] girls;
function totalSupply() public view returns (uint256) {
return girls.length;
}
function getGirlGene(uint _index) public view returns (uint) {
return girls[_index].genes;
}
function getGirlBirthTime(uint _index) public view returns (uint64) {
return girls[_index].birthTime;
}
function getGirlCoolDownEndTime(uint _index) public view returns (uint64) {
return girls[_index].cooldownEndTime;
}
function getGirlStarLevel(uint _index) public view returns (uint16) {
return girls[_index].starLevel;
}
function isNotCoolDown(uint _girlId) public view returns(bool) {
return uint64(now) > girls[_girlId].cooldownEndTime;
}
function _createGirl(
uint _genes,
address _owner,
uint16 _starLevel
) internal returns (uint){
Girl memory _girl = Girl({
genes:_genes,
birthTime:uint64(now),
cooldownEndTime:0,
starLevel:_starLevel
});
uint256 girlId = girls.push(_girl) - 1;
_mint(_owner, girlId);
emit CreateGirl(_owner, girlId, _genes, _girl.birthTime, _girl.cooldownEndTime, _girl.starLevel);
return girlId;
}
function _setCoolDownTime(uint _tokenId, uint _coolDownTime) internal {
girls[_tokenId].cooldownEndTime = uint64(now.add(_coolDownTime));
emit CoolDown(_tokenId, girls[_tokenId].cooldownEndTime);
}
function _LevelUp(uint _tokenId) internal {
require(girls[_tokenId].starLevel < 65535);
girls[_tokenId].starLevel = girls[_tokenId].starLevel + 1;
emit GirlUpgrade(_tokenId, girls[_tokenId].starLevel);
}
// ---------------
// this is atomic swap for girl to be set cross chain.
// ---------------
uint8 constant public GIRLBUFFERSIZE = 50; // buffer size need to serialize girl data; used for cross chain sync
struct HashLockContract {
address sender;
address receiver;
uint tokenId;
bytes32 hashlock;
uint timelock;
bytes32 secret;
States state;
bytes extraData;
}
enum States {
INVALID,
OPEN,
CLOSED,
REFUNDED
}
mapping (bytes32 => HashLockContract) private contracts;
modifier contractExists(bytes32 _contractId) {
require(_contractExists(_contractId));
_;
}
modifier hashlockMatches(bytes32 _contractId, bytes32 _secret) {
require(contracts[_contractId].hashlock == keccak256(_secret));
_;
}
modifier closable(bytes32 _contractId) {
require(contracts[_contractId].state == States.OPEN);
require(contracts[_contractId].timelock > now);
_;
}
modifier refundable(bytes32 _contractId) {
require(contracts[_contractId].state == States.OPEN);
require(contracts[_contractId].timelock <= now);
_;
}
event NewHashLockContract (
bytes32 indexed contractId,
address indexed sender,
address indexed receiver,
uint tokenId,
bytes32 hashlock,
uint timelock,
bytes extraData
);
event SwapClosed(bytes32 indexed contractId);
event SwapRefunded(bytes32 indexed contractId);
function open (
address _receiver,
bytes32 _hashlock,
uint _duration,
uint _tokenId
) public
onlyOwnerOf(_tokenId)
returns (bytes32 contractId)
{
uint _timelock = now.add(_duration);
// compute girl data;
bytes memory _extraData = new bytes(GIRLBUFFERSIZE);
uint offset = GIRLBUFFERSIZE;
offset = addUint16(offset, _extraData, girls[_tokenId].starLevel);
offset = addUint64(offset, _extraData, girls[_tokenId].cooldownEndTime);
offset = addUint64(offset, _extraData, girls[_tokenId].birthTime);
offset = addUint(offset, _extraData, girls[_tokenId].genes);
contractId = keccak256 (
msg.sender,
_receiver,
_tokenId,
_hashlock,
_timelock,
_extraData
);
// the new contract must not exist
require(!_contractExists(contractId));
// temporary change the ownership to this contract address.
// the ownership will be change to user when close is called.
clearApproval(msg.sender, _tokenId);
removeTokenFrom(msg.sender, _tokenId);
addTokenTo(address(this), _tokenId);
contracts[contractId] = HashLockContract(
msg.sender,
_receiver,
_tokenId,
_hashlock,
_timelock,
0x0,
States.OPEN,
_extraData
);
emit NewHashLockContract(contractId, msg.sender, _receiver, _tokenId, _hashlock, _timelock, _extraData);
}
function close(bytes32 _contractId, bytes32 _secret)
public
contractExists(_contractId)
hashlockMatches(_contractId, _secret)
closable(_contractId)
returns (bool)
{
HashLockContract storage c = contracts[_contractId];
c.secret = _secret;
c.state = States.CLOSED;
// transfer token ownership from this contract address to receiver.
// clearApproval(address(this), c.tokenId);
removeTokenFrom(address(this), c.tokenId);
addTokenTo(c.receiver, c.tokenId);
emit SwapClosed(_contractId);
return true;
}
function refund(bytes32 _contractId)
public
contractExists(_contractId)
refundable(_contractId)
returns (bool)
{
HashLockContract storage c = contracts[_contractId];
c.state = States.REFUNDED;
// transfer token ownership from this contract address to receiver.
// clearApproval(address(this), c.tokenId);
removeTokenFrom(address(this), c.tokenId);
addTokenTo(c.sender, c.tokenId);
emit SwapRefunded(_contractId);
return true;
}
function _contractExists(bytes32 _contractId) internal view returns (bool exists) {
exists = (contracts[_contractId].sender != address(0));
}
function checkContract(bytes32 _contractId)
public
view
contractExists(_contractId)
returns (
address sender,
address receiver,
uint amount,
bytes32 hashlock,
uint timelock,
bytes32 secret,
bytes extraData
)
{
HashLockContract memory c = contracts[_contractId];
return (
c.sender,
c.receiver,
c.tokenId,
c.hashlock,
c.timelock,
c.secret,
c.extraData
);
}
}
// File: contracts\GenesFactory.sol
contract GenesFactory{
function mixGenes(uint256 gene1, uint gene2) public returns(uint256);
function getPerson(uint256 genes) public pure returns (uint256 person);
function getRace(uint256 genes) public pure returns (uint256);
function getRarity(uint256 genes) public pure returns (uint256);
function getBaseStrengthenPoint(uint256 genesMain,uint256 genesSub) public pure returns (uint256);
function getCanBorn(uint256 genes) public pure returns (uint256 canBorn,uint256 cooldown);
}
// File: contracts\equipments\ERC20Basic.sol
/**
* @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);
}
// File: contracts\equipments\BasicToken.sol
/**
* @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];
}
}
// File: contracts\equipments\ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: contracts\equipments\StandardToken.sol
/**
* @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;
}
}
// File: contracts\equipments\AtomicSwappableToken.sol
contract AtomicSwappableToken is StandardToken {
struct HashLockContract {
address sender;
address receiver;
uint amount;
bytes32 hashlock;
uint timelock;
bytes32 secret;
States state;
}
enum States {
INVALID,
OPEN,
CLOSED,
REFUNDED
}
mapping (bytes32 => HashLockContract) private contracts;
modifier futureTimelock(uint _time) {
// only requirement is the timelock time is after the last blocktime (now).
// probably want something a bit further in the future then this.
// but this is still a useful sanity check:
require(_time > now);
_;
}
modifier contractExists(bytes32 _contractId) {
require(_contractExists(_contractId));
_;
}
modifier hashlockMatches(bytes32 _contractId, bytes32 _secret) {
require(contracts[_contractId].hashlock == keccak256(_secret));
_;
}
modifier closable(bytes32 _contractId) {
require(contracts[_contractId].state == States.OPEN);
require(contracts[_contractId].timelock > now);
_;
}
modifier refundable(bytes32 _contractId) {
require(contracts[_contractId].state == States.OPEN);
require(contracts[_contractId].timelock <= now);
_;
}
event NewHashLockContract (
bytes32 indexed contractId,
address indexed sender,
address indexed receiver,
uint amount,
bytes32 hashlock,
uint timelock
);
event SwapClosed(bytes32 indexed contractId);
event SwapRefunded(bytes32 indexed contractId);
function open (
address _receiver,
bytes32 _hashlock,
uint _timelock,
uint _amount
) public
futureTimelock(_timelock)
returns (bytes32 contractId)
{
contractId = keccak256 (
msg.sender,
_receiver,
_amount,
_hashlock,
_timelock
);
// the new contract must not exist
require(!_contractExists(contractId));
// transfer token to this contract
require(transfer(address(this), _amount));
contracts[contractId] = HashLockContract(
msg.sender,
_receiver,
_amount,
_hashlock,
_timelock,
0x0,
States.OPEN
);
emit NewHashLockContract(contractId, msg.sender, _receiver, _amount, _hashlock, _timelock);
}
function close(bytes32 _contractId, bytes32 _secret)
public
contractExists(_contractId)
hashlockMatches(_contractId, _secret)
closable(_contractId)
returns (bool)
{
HashLockContract storage c = contracts[_contractId];
c.secret = _secret;
c.state = States.CLOSED;
require(this.transfer(c.receiver, c.amount));
emit SwapClosed(_contractId);
return true;
}
function refund(bytes32 _contractId)
public
contractExists(_contractId)
refundable(_contractId)
returns (bool)
{
HashLockContract storage c = contracts[_contractId];
c.state = States.REFUNDED;
require(this.transfer(c.sender, c.amount));
emit SwapRefunded(_contractId);
return true;
}
function _contractExists(bytes32 _contractId) internal view returns (bool exists) {
exists = (contracts[_contractId].sender != address(0));
}
function checkContract(bytes32 _contractId)
public
view
contractExists(_contractId)
returns (
address sender,
address receiver,
uint amount,
bytes32 hashlock,
uint timelock,
bytes32 secret
)
{
HashLockContract memory c = contracts[_contractId];
return (
c.sender,
c.receiver,
c.amount,
c.hashlock,
c.timelock,
c.secret
);
}
}
// File: contracts\equipments\TokenReceiver.sol
contract TokenReceiver {
function receiveApproval(address from, uint amount, address tokenAddress, bytes data) public;
}
// File: contracts\equipments\BaseEquipment.sol
contract BaseEquipment is Ownable, AtomicSwappableToken {
event Mint(address indexed to, uint256 amount);
//cap==0 means no limits
uint256 public cap;
/**
properties = [
0, //validationDuration
1, //location
2, //applicableType
];
**/
uint[] public properties;
address public controller;
modifier onlyController { require(msg.sender == controller); _; }
function setController(address _newController) public onlyOwner {
controller = _newController;
}
constructor(uint256 _cap, uint[] _properties) public {
cap = _cap;
properties = _properties;
}
function setProperty(uint256[] _properties) public onlyOwner {
properties = _properties;
}
function _mint(address _to, uint _amount) internal {
require(cap==0 || totalSupply_.add(_amount) <= cap);
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(address(0), _to, _amount);
}
function mint(address _to, uint256 _amount) onlyController public returns (bool) {
_mint(_to, _amount);
return true;
}
function mintFromOwner(address _to, uint256 _amount) onlyOwner public returns (bool) {
_mint(_to, _amount);
return true;
}
function approveAndCall(address _spender, uint _amount, bytes _data) public {
if(approve(_spender, _amount)) {
TokenReceiver(_spender).receiveApproval(msg.sender, _amount, address(this), _data);
}
}
function checkCap(uint256 _amount) public view returns (bool) {
return (cap==0 || totalSupply_.add(_amount) <= cap);
}
}
// File: contracts\AvatarEquipments.sol
contract AvatarEquipments is Pausable{
event SetEquipment(address user, uint256 girlId, address tokenAddress, uint256 amount, uint validationDuration);
struct Equipment {
address BackgroundAddress;
uint BackgroundAmount;
uint64 BackgroundEndTime;
address photoFrameAddress;
uint photoFrameAmount;
uint64 photoFrameEndTime;
address armsAddress;
uint armsAmount;
uint64 armsEndTime;
address petAddress;
uint petAmount;
uint64 petEndTime;
}
GirlBasicToken girlBasicToken;
GenesFactory genesFactory;
/// @dev A mapping from girl IDs to their current equipment.
mapping (uint256 => Equipment) public GirlIndexToEquipment;
mapping (address => bool) public equipmentToStatus;
constructor(address _girlBasicToken, address _GenesFactory) public{
require(_girlBasicToken != address(0x0));
girlBasicToken = GirlBasicToken(_girlBasicToken);
genesFactory = GenesFactory(_GenesFactory);
}
/* if the list goes to hundreds of equipment this transaction may out of gas.
function managerEquipment(address[] addressList, bool[] statusList) public onlyOwner {
require(addressList.length == statusList.length);
require(addressList.length > 0);
for (uint i = 0; i < addressList.length; i ++) {
equipmentToStatus[addressList[i]] = statusList[i];
}
}
*/
function addTokenToWhitelist(address _eq) public onlyOwner {
equipmentToStatus[_eq] = true;
}
function removeFromWhitelist(address _eq) public onlyOwner {
equipmentToStatus[_eq] = false;
}
function addManyToWhitelist(address[] _eqs) public onlyOwner {
for(uint i=0; i<_eqs.length; i++) {
equipmentToStatus[_eqs[i]] = true;
}
}
// 新需求: 永久道具(validDuration=18446744073709551615)可拆卸 (18446744073709551615 is max of uint64 )
function withdrawEquipment(uint _girlId, address _equipmentAddress) public {
BaseEquipment baseEquipment = BaseEquipment(_equipmentAddress);
uint _validationDuration = baseEquipment.properties(0);
require(_validationDuration == 18446744073709551615); // the token must have infinite duration. validation duration 0 indicate infinite duration
Equipment storage equipment = GirlIndexToEquipment[_girlId];
uint location = baseEquipment.properties(1);
address owner = girlBasicToken.ownerOf(_girlId);
uint amount;
if (location == 1 && equipment.BackgroundAddress == _equipmentAddress) {
amount = equipment.BackgroundAmount;
equipment.BackgroundAddress = address(0);
equipment.BackgroundAmount = 0;
equipment.BackgroundEndTime = 0;
} else if (location == 2 && equipment.photoFrameAddress == _equipmentAddress) {
amount = equipment.photoFrameAmount;
equipment.photoFrameAddress = address(0);
equipment.photoFrameAmount= 0;
equipment.photoFrameEndTime = 0;
} else if (location == 3 && equipment.armsAddress == _equipmentAddress) {
amount = equipment.armsAmount;
equipment.armsAddress = address(0);
equipment.armsAmount = 0;
equipment.armsEndTime = 0;
} else if (location == 4 && equipment.petAddress == _equipmentAddress) {
amount = equipment.petAmount;
equipment.petAddress = address(0);
equipment.petAmount = 0;
equipment.petEndTime = 0;
} else {
revert();
}
require(amount > 0);
baseEquipment.transfer(owner, amount);
}
function setEquipment(address _sender, uint _girlId, uint _amount, address _equipmentAddress, uint256[] _properties) whenNotPaused public {
require(isValid(_sender, _girlId , _amount, _equipmentAddress));
Equipment storage equipment = GirlIndexToEquipment[_girlId];
require(_properties.length >= 3);
uint _validationDuration = _properties[0];
uint _location = _properties[1];
uint _applicableType = _properties[2];
if(_applicableType < 16){
uint genes = girlBasicToken.getGirlGene(_girlId);
uint race = genesFactory.getRace(genes);
require(race == uint256(_applicableType));
}
uint _count = _amount / (1 ether);
if (_location == 1) {
if(_validationDuration == 18446744073709551615) { // 根据永久道具需求更改
equipment.BackgroundEndTime = 18446744073709551615;
} else if((equipment.BackgroundAddress == _equipmentAddress) && equipment.BackgroundEndTime > now ) {
equipment.BackgroundEndTime += uint64(_count * _validationDuration);
} else {
equipment.BackgroundEndTime = uint64(now + (_count * _validationDuration));
}
equipment.BackgroundAddress = _equipmentAddress;
equipment.BackgroundAmount = _amount;
} else if (_location == 2){
if(_validationDuration == 18446744073709551615) {
equipment.photoFrameEndTime = 18446744073709551615;
} else if((equipment.photoFrameAddress == _equipmentAddress) && equipment.photoFrameEndTime > now ) {
equipment.photoFrameEndTime += uint64(_count * _validationDuration);
} else {
equipment.photoFrameEndTime = uint64(now + (_count * _validationDuration));
}
equipment.photoFrameAddress = _equipmentAddress;
equipment.photoFrameAmount = _amount;
} else if (_location == 3) {
if(_validationDuration == 18446744073709551615) {
equipment.armsEndTime = 18446744073709551615;
} else if((equipment.armsAddress == _equipmentAddress) && equipment.armsEndTime > now ) {
equipment.armsEndTime += uint64(_count * _validationDuration);
} else {
equipment.armsEndTime = uint64(now + (_count * _validationDuration));
}
equipment.armsAddress = _equipmentAddress;
equipment.armsAmount = _count;
} else if (_location == 4) {
if(_validationDuration == 18446744073709551615) {
equipment.petEndTime = 18446744073709551615;
} else if((equipment.petAddress == _equipmentAddress) && equipment.petEndTime > now ) {
equipment.petEndTime += uint64(_count * _validationDuration);
} else {
equipment.petEndTime = uint64(now + (_count * _validationDuration));
}
equipment.petAddress = _equipmentAddress;
equipment.petAmount = _amount;
} else{
revert();
}
emit SetEquipment(_sender, _girlId, _equipmentAddress, _amount, _validationDuration);
}
function isValid (address _from, uint _GirlId, uint _amount, address _tokenContract) public returns (bool) {
BaseEquipment baseEquipment = BaseEquipment(_tokenContract);
require(equipmentToStatus[_tokenContract]);
// must send at least 1 token
require(_amount >= 1 ether);
require(_amount % 1 ether == 0); // basic unit is 1 token;
require(girlBasicToken.ownerOf(_GirlId) == _from || owner == _from); // must from girl owner or the owner of contract.
require(baseEquipment.transferFrom(_from, this, _amount));
return true;
}
function getGirlEquipmentStatus(uint256 _girlId) public view returns(
address BackgroundAddress,
uint BackgroundAmount,
uint BackgroundEndTime,
address photoFrameAddress,
uint photoFrameAmount,
uint photoFrameEndTime,
address armsAddress,
uint armsAmount,
uint armsEndTime,
address petAddress,
uint petAmount,
uint petEndTime
){
Equipment storage equipment = GirlIndexToEquipment[_girlId];
if (equipment.BackgroundEndTime >= now) {
BackgroundAddress = equipment.BackgroundAddress;
BackgroundAmount = equipment.BackgroundAmount;
BackgroundEndTime = equipment.BackgroundEndTime;
}
if (equipment.photoFrameEndTime >= now) {
photoFrameAddress = equipment.photoFrameAddress;
photoFrameAmount = equipment.photoFrameAmount;
photoFrameEndTime = equipment.photoFrameEndTime;
}
if (equipment.armsEndTime >= now) {
armsAddress = equipment.armsAddress;
armsAmount = equipment.armsAmount;
armsEndTime = equipment.armsEndTime;
}
if (equipment.petEndTime >= now) {
petAddress = equipment.petAddress;
petAmount = equipment.petAmount;
petEndTime = equipment.petEndTime;
}
}
}
// File: contracts\equipments\EquipmentToken.sol
contract EquipmentToken is BaseEquipment {
string public name; //The shoes name: e.g. shining shoes
string public symbol; //The shoes symbol: e.g. SS
uint8 public decimals; //Number of decimals of the smallest unit
constructor (
string _name,
string _symbol,
uint256 _cap,
uint[] _properties
) public BaseEquipment(_cap, _properties) {
name = _name;
symbol = _symbol;
decimals = 18; // set as default
}
function setEquipment(address _target, uint _GirlId, uint256 _amount) public returns (bool success) {
AvatarEquipments eq = AvatarEquipments(_target);
if (approve(_target, _amount)) {
eq.setEquipment(msg.sender, _GirlId, _amount, this, properties);
return true;
}
}
} | must from girl owner or the owner of contract.
| require(girlBasicToken.ownerOf(_GirlId) == _from || owner == _from); | 12,669,200 | [
1,
11926,
628,
314,
481,
80,
3410,
578,
326,
3410,
434,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2583,
12,
75,
481,
80,
8252,
1345,
18,
8443,
951,
24899,
43,
481,
80,
548,
13,
422,
389,
2080,
747,
3410,
422,
389,
2080,
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
] |
./full_match/80001/0xd0878207b6c70961DB534C7a53C9F29c590c1AA6/sources/contracts/module/UserStorage.sol | Structure that represents a staked team. | struct StakeTeam {
}
Stake Item Storage
| 9,522,424 | [
1,
6999,
716,
8686,
279,
384,
9477,
5927,
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,
1958,
934,
911,
8689,
288,
203,
565,
289,
203,
203,
203,
7682,
934,
911,
4342,
5235,
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
] |
./partial_match/4/0xF34f7a9a4280c7B05AaE067147aF9D92369988CF/sources/GovTreasurer.sol | WITHDRAW | FARMING ASSETS (TOKENS) | RE-ENTRANCY DEFENSE | function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accGDAOPerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accGDAOPerShare).div(1e12);
safeGDAOTransfer(msg.sender, pending);
pool.lpToken.safeTransfer(address(msg.sender), _amount.sub(_amount.div(pool.taxRate)));
emit Withdraw(msg.sender, _pid, _amount);
}
| 8,628,777 | [
1,
9147,
40,
10821,
571,
478,
26120,
1360,
5355,
28092,
261,
8412,
55,
13,
571,
2438,
17,
2222,
54,
1258,
16068,
25957,
23396,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
598,
9446,
12,
11890,
5034,
389,
6610,
16,
2254,
5034,
389,
8949,
13,
1071,
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,
3576,
18,
15330,
15533,
203,
3639,
2583,
12,
1355,
18,
8949,
1545,
389,
8949,
16,
315,
1918,
9446,
30,
486,
7494,
8863,
203,
3639,
1089,
2864,
24899,
6610,
1769,
203,
3639,
2254,
5034,
4634,
273,
729,
18,
8949,
18,
16411,
12,
6011,
18,
8981,
43,
18485,
2173,
9535,
2934,
2892,
12,
21,
73,
2138,
2934,
1717,
12,
1355,
18,
266,
2913,
758,
23602,
1769,
203,
203,
3639,
729,
18,
8949,
273,
729,
18,
8949,
18,
1717,
24899,
8949,
1769,
203,
3639,
729,
18,
266,
2913,
758,
23602,
273,
729,
18,
8949,
18,
16411,
12,
6011,
18,
8981,
43,
18485,
2173,
9535,
2934,
2892,
12,
21,
73,
2138,
1769,
203,
203,
3639,
4183,
43,
18485,
5912,
12,
3576,
18,
15330,
16,
4634,
1769,
203,
3639,
2845,
18,
9953,
1345,
18,
4626,
5912,
12,
2867,
12,
3576,
18,
15330,
3631,
389,
8949,
18,
1717,
24899,
8949,
18,
2892,
12,
6011,
18,
8066,
4727,
3719,
1769,
203,
203,
3639,
3626,
3423,
9446,
12,
3576,
18,
15330,
16,
389,
6610,
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
] |
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./Lockable.sol";
/**
* @title A contract to track a whitelist of addresses.
*/
contract AddressWhitelist is Ownable, Lockable {
enum Status { None, In, Out }
mapping(address => Status) public whitelist;
address[] public whitelistIndices;
event AddedToWhitelist(address indexed addedAddress);
event RemovedFromWhitelist(address indexed removedAddress);
/**
* @notice Adds an address to the whitelist.
* @param newElement the new address to add.
*/
function addToWhitelist(address newElement) external nonReentrant() onlyOwner {
// Ignore if address is already included
if (whitelist[newElement] == Status.In) {
return;
}
// Only append new addresses to the array, never a duplicate
if (whitelist[newElement] == Status.None) {
whitelistIndices.push(newElement);
}
whitelist[newElement] = Status.In;
emit AddedToWhitelist(newElement);
}
/**
* @notice Removes an address from the whitelist.
* @param elementToRemove the existing address to remove.
*/
function removeFromWhitelist(address elementToRemove) external nonReentrant() onlyOwner {
if (whitelist[elementToRemove] != Status.Out) {
whitelist[elementToRemove] = Status.Out;
emit RemovedFromWhitelist(elementToRemove);
}
}
/**
* @notice Checks whether an address is on the whitelist.
* @param elementToCheck the address to check.
* @return True if `elementToCheck` is on the whitelist, or False.
*/
function isOnWhitelist(address elementToCheck) external view nonReentrantView() returns (bool) {
return whitelist[elementToCheck] == Status.In;
}
/**
* @notice Gets all addresses that are currently included in the whitelist.
* @dev Note: This method skips over, but still iterates through addresses. It is possible for this call to run out
* of gas if a large number of addresses have been removed. To reduce the likelihood of this unlikely scenario, we
* can modify the implementation so that when addresses are removed, the last addresses in the array is moved to
* the empty index.
* @return activeWhitelist the list of addresses on the whitelist.
*/
function getWhitelist() external view nonReentrantView() returns (address[] memory activeWhitelist) {
// Determine size of whitelist first
uint256 activeCount = 0;
for (uint256 i = 0; i < whitelistIndices.length; i++) {
if (whitelist[whitelistIndices[i]] == Status.In) {
activeCount++;
}
}
// Populate whitelist
activeWhitelist = new address[](activeCount);
activeCount = 0;
for (uint256 i = 0; i < whitelistIndices.length; i++) {
address addr = whitelistIndices[i];
if (whitelist[addr] == Status.In) {
activeWhitelist[activeCount] = addr;
activeCount++;
}
}
}
}
pragma solidity ^0.6.0;
import "../GSN/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title A contract that provides modifiers to prevent reentrancy to state-changing and view-only methods. This contract
* is inspired by https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol
* and https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol.
*/
contract Lockable {
bool private _notEntered;
constructor() internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_preEntranceCheck();
_preEntranceSet();
_;
_postEntranceReset();
}
/**
* @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method.
*/
modifier nonReentrantView() {
_preEntranceCheck();
_;
}
// Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method.
// On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being re-entered.
// Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and then call `_postEntranceReset()`.
// View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered.
function _preEntranceCheck() internal view {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
}
function _preEntranceSet() internal {
// Any calls to nonReentrant after this point will fail
_notEntered = false;
}
function _postEntranceReset() internal {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./MultiRole.sol";
import "../interfaces/ExpandedIERC20.sol";
/**
* @title An ERC20 with permissioned burning and minting. The contract deployer will initially
* be the owner who is capable of adding new roles.
*/
contract ExpandedERC20 is ExpandedIERC20, ERC20, MultiRole {
enum Roles {
// Can set the minter and burner.
Owner,
// Addresses that can mint new tokens.
Minter,
// Addresses that can burn tokens that address owns.
Burner
}
/**
* @notice Constructs the ExpandedERC20.
* @param _tokenName The name which describes the new token.
* @param _tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param _tokenDecimals The number of decimals to define token precision.
*/
constructor(
string memory _tokenName,
string memory _tokenSymbol,
uint8 _tokenDecimals
) public ERC20(_tokenName, _tokenSymbol) {
_setupDecimals(_tokenDecimals);
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
_createSharedRole(uint256(Roles.Minter), uint256(Roles.Owner), new address[](0));
_createSharedRole(uint256(Roles.Burner), uint256(Roles.Owner), new address[](0));
}
/**
* @dev Mints `value` tokens to `recipient`, returning true on success.
* @param recipient address to mint to.
* @param value amount of tokens to mint.
* @return True if the mint succeeded, or False.
*/
function mint(address recipient, uint256 value)
external
override
onlyRoleHolder(uint256(Roles.Minter))
returns (bool)
{
_mint(recipient, value);
return true;
}
/**
* @dev Burns `value` tokens owned by `msg.sender`.
* @param value amount of tokens to burn.
*/
function burn(uint256 value) external override onlyRoleHolder(uint256(Roles.Burner)) {
_burn(msg.sender, value);
}
/**
* @notice Add Minter role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Minter role is added.
*/
function addMinter(address account) external virtual override {
addMember(uint256(Roles.Minter), account);
}
/**
* @notice Add Burner role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Burner role is added.
*/
function addBurner(address account) external virtual override {
addMember(uint256(Roles.Burner), account);
}
/**
* @notice Reset Owner role to account.
* @dev The caller must have the Owner role.
* @param account The new holder of the Owner role.
*/
function resetOwner(address account) external virtual override {
resetMember(uint256(Roles.Owner), account);
}
}
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20MinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
library Exclusive {
struct RoleMembership {
address member;
}
function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) {
return roleMembership.member == memberToCheck;
}
function resetMember(RoleMembership storage roleMembership, address newMember) internal {
require(newMember != address(0x0), "Cannot set an exclusive role to 0x0");
roleMembership.member = newMember;
}
function getMember(RoleMembership storage roleMembership) internal view returns (address) {
return roleMembership.member;
}
function init(RoleMembership storage roleMembership, address initialMember) internal {
resetMember(roleMembership, initialMember);
}
}
library Shared {
struct RoleMembership {
mapping(address => bool) members;
}
function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) {
return roleMembership.members[memberToCheck];
}
function addMember(RoleMembership storage roleMembership, address memberToAdd) internal {
require(memberToAdd != address(0x0), "Cannot add 0x0 to a shared role");
roleMembership.members[memberToAdd] = true;
}
function removeMember(RoleMembership storage roleMembership, address memberToRemove) internal {
roleMembership.members[memberToRemove] = false;
}
function init(RoleMembership storage roleMembership, address[] memory initialMembers) internal {
for (uint256 i = 0; i < initialMembers.length; i++) {
addMember(roleMembership, initialMembers[i]);
}
}
}
/**
* @title Base class to manage permissions for the derived class.
*/
abstract contract MultiRole {
using Exclusive for Exclusive.RoleMembership;
using Shared for Shared.RoleMembership;
enum RoleType { Invalid, Exclusive, Shared }
struct Role {
uint256 managingRole;
RoleType roleType;
Exclusive.RoleMembership exclusiveRoleMembership;
Shared.RoleMembership sharedRoleMembership;
}
mapping(uint256 => Role) private roles;
event ResetExclusiveMember(uint256 indexed roleId, address indexed newMember, address indexed manager);
event AddedSharedMember(uint256 indexed roleId, address indexed newMember, address indexed manager);
event RemovedSharedMember(uint256 indexed roleId, address indexed oldMember, address indexed manager);
/**
* @notice Reverts unless the caller is a member of the specified roleId.
*/
modifier onlyRoleHolder(uint256 roleId) {
require(holdsRole(roleId, msg.sender), "Sender does not hold required role");
_;
}
/**
* @notice Reverts unless the caller is a member of the manager role for the specified roleId.
*/
modifier onlyRoleManager(uint256 roleId) {
require(holdsRole(roles[roleId].managingRole, msg.sender), "Can only be called by a role manager");
_;
}
/**
* @notice Reverts unless the roleId represents an initialized, exclusive roleId.
*/
modifier onlyExclusive(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role");
_;
}
/**
* @notice Reverts unless the roleId represents an initialized, shared roleId.
*/
modifier onlyShared(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role");
_;
}
/**
* @notice Whether `memberToCheck` is a member of roleId.
* @dev Reverts if roleId does not correspond to an initialized role.
* @param roleId the Role to check.
* @param memberToCheck the address to check.
* @return True if `memberToCheck` is a member of `roleId`.
*/
function holdsRole(uint256 roleId, address memberToCheck) public view returns (bool) {
Role storage role = roles[roleId];
if (role.roleType == RoleType.Exclusive) {
return role.exclusiveRoleMembership.isMember(memberToCheck);
} else if (role.roleType == RoleType.Shared) {
return role.sharedRoleMembership.isMember(memberToCheck);
}
revert("Invalid roleId");
}
/**
* @notice Changes the exclusive role holder of `roleId` to `newMember`.
* @dev Reverts if the caller is not a member of the managing role for `roleId` or if `roleId` is not an
* initialized, ExclusiveRole.
* @param roleId the ExclusiveRole membership to modify.
* @param newMember the new ExclusiveRole member.
*/
function resetMember(uint256 roleId, address newMember) public onlyExclusive(roleId) onlyRoleManager(roleId) {
roles[roleId].exclusiveRoleMembership.resetMember(newMember);
emit ResetExclusiveMember(roleId, newMember, msg.sender);
}
/**
* @notice Gets the current holder of the exclusive role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, exclusive role.
* @param roleId the ExclusiveRole membership to check.
* @return the address of the current ExclusiveRole member.
*/
function getMember(uint256 roleId) public view onlyExclusive(roleId) returns (address) {
return roles[roleId].exclusiveRoleMembership.getMember();
}
/**
* @notice Adds `newMember` to the shared role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the
* managing role for `roleId`.
* @param roleId the SharedRole membership to modify.
* @param newMember the new SharedRole member.
*/
function addMember(uint256 roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) {
roles[roleId].sharedRoleMembership.addMember(newMember);
emit AddedSharedMember(roleId, newMember, msg.sender);
}
/**
* @notice Removes `memberToRemove` from the shared role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the
* managing role for `roleId`.
* @param roleId the SharedRole membership to modify.
* @param memberToRemove the current SharedRole member to remove.
*/
function removeMember(uint256 roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) {
roles[roleId].sharedRoleMembership.removeMember(memberToRemove);
emit RemovedSharedMember(roleId, memberToRemove, msg.sender);
}
/**
* @notice Removes caller from the role, `roleId`.
* @dev Reverts if the caller is not a member of the role for `roleId` or if `roleId` is not an
* initialized, SharedRole.
* @param roleId the SharedRole membership to modify.
*/
function renounceMembership(uint256 roleId) public onlyShared(roleId) onlyRoleHolder(roleId) {
roles[roleId].sharedRoleMembership.removeMember(msg.sender);
emit RemovedSharedMember(roleId, msg.sender, msg.sender);
}
/**
* @notice Reverts if `roleId` is not initialized.
*/
modifier onlyValidRole(uint256 roleId) {
require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId");
_;
}
/**
* @notice Reverts if `roleId` is initialized.
*/
modifier onlyInvalidRole(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Invalid, "Cannot use a pre-existing role");
_;
}
/**
* @notice Internal method to initialize a shared role, `roleId`, which will be managed by `managingRoleId`.
* `initialMembers` will be immediately added to the role.
* @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already
* initialized.
*/
function _createSharedRole(
uint256 roleId,
uint256 managingRoleId,
address[] memory initialMembers
) internal onlyInvalidRole(roleId) {
Role storage role = roles[roleId];
role.roleType = RoleType.Shared;
role.managingRole = managingRoleId;
role.sharedRoleMembership.init(initialMembers);
require(
roles[managingRoleId].roleType != RoleType.Invalid,
"Attempted to use an invalid role to manage a shared role"
);
}
/**
* @notice Internal method to initialize an exclusive role, `roleId`, which will be managed by `managingRoleId`.
* `initialMember` will be immediately added to the role.
* @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already
* initialized.
*/
function _createExclusiveRole(
uint256 roleId,
uint256 managingRoleId,
address initialMember
) internal onlyInvalidRole(roleId) {
Role storage role = roles[roleId];
role.roleType = RoleType.Exclusive;
role.managingRole = managingRoleId;
role.exclusiveRoleMembership.init(initialMember);
require(
roles[managingRoleId].roleType != RoleType.Invalid,
"Attempted to use an invalid role to manage an exclusive role"
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ERC20 interface that includes burn and mint methods.
*/
abstract contract ExpandedIERC20 is IERC20 {
/**
* @notice Burns a specific amount of the caller's tokens.
* @dev Only burns the caller's tokens, so it is safe to leave this method permissionless.
*/
function burn(uint256 value) external virtual;
/**
* @notice Mints tokens and adds them to the balance of the `to` address.
* @dev This method should be permissioned to only allow designated parties to mint tokens.
*/
function mint(address to, uint256 value) external virtual returns (bool);
function addMinter(address account) external virtual;
function addBurner(address account) external virtual;
function resetOwner(address account) external virtual;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/SignedSafeMath.sol";
/**
* @title Library for fixed point arithmetic on uints
*/
library FixedPoint {
using SafeMath for uint256;
using SignedSafeMath for int256;
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For unsigned values:
// This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77.
uint256 private constant FP_SCALING_FACTOR = 10**18;
// --------------------------------------- UNSIGNED -----------------------------------------------------------------------------
struct Unsigned {
uint256 rawValue;
}
/**
* @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5*(10**18)`.
* @param a uint to convert into a FixedPoint.
* @return the converted FixedPoint.
*/
function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) {
return Unsigned(a.mul(FP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the minimum of `a` and `b`.
*/
function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the maximum of `a` and `b`.
*/
function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return add(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return sub(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow.
* @param a a uint256.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return sub(fromUnscaledUint(a), b);
}
/**
* @notice Multiplies two `Unsigned`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as a uint256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because FP_SCALING_FACTOR != 0.
return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a uint256.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 mulRaw = a.rawValue.mul(b.rawValue);
uint256 mulFloor = mulRaw / FP_SCALING_FACTOR;
uint256 mod = mulRaw.mod(FP_SCALING_FACTOR);
if (mod != 0) {
return Unsigned(mulFloor.add(1));
} else {
return Unsigned(mulFloor);
}
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as a uint256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a uint256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return div(fromUnscaledUint(a), b);
}
/**
* @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR);
uint256 divFloor = aScaled.div(b.rawValue);
uint256 mod = aScaled.mod(b.rawValue);
if (mod != 0) {
return Unsigned(divFloor.add(1));
} else {
return Unsigned(divFloor);
}
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))"
// similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned.
// This creates the possibility of overflow if b is very large.
return divCeil(a, fromUnscaledUint(b));
}
/**
* @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return output is `a` to the power of `b`.
*/
function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) {
output = fromUnscaledUint(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
// ------------------------------------------------- SIGNED -------------------------------------------------------------
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For signed values:
// This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76.
int256 private constant SFP_SCALING_FACTOR = 10**18;
struct Signed {
int256 rawValue;
}
function fromSigned(Signed memory a) internal pure returns (Unsigned memory) {
require(a.rawValue >= 0, "Negative value provided");
return Unsigned(uint256(a.rawValue));
}
function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) {
require(a.rawValue <= uint256(type(int256).max), "Unsigned too large");
return Signed(int256(a.rawValue));
}
/**
* @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5*(10**18)`.
* @param a int to convert into a FixedPoint.Signed.
* @return the converted FixedPoint.Signed.
*/
function fromUnscaledInt(int256 a) internal pure returns (Signed memory) {
return Signed(a.mul(SFP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a int256.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the minimum of `a` and `b`.
*/
function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the maximum of `a` and `b`.
*/
function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Signed` to an unscaled int, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, int256 b) internal pure returns (Signed memory) {
return add(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, int256 b) internal pure returns (Signed memory) {
return sub(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(int256 a, Signed memory b) internal pure returns (Signed memory) {
return sub(fromUnscaledInt(a), b);
}
/**
* @notice Multiplies two `Signed`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as an int256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because SFP_SCALING_FACTOR != 0.
return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 mulRaw = a.rawValue.mul(b.rawValue);
int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR;
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = mulRaw % SFP_SCALING_FACTOR;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(mulTowardsZero.add(valueToAdd));
} else {
return Signed(mulTowardsZero);
}
}
/**
* @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Signed(a.rawValue.mul(b));
}
/**
* @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as an int256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a an int256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(int256 a, Signed memory b) internal pure returns (Signed memory) {
return div(fromUnscaledInt(a), b);
}
/**
* @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR);
int256 divTowardsZero = aScaled.div(b.rawValue);
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = aScaled % b.rawValue;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(divTowardsZero.add(valueToAdd));
} else {
return Signed(divTowardsZero);
}
}
/**
* @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))"
// similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed.
// This creates the possibility of overflow if b is very large.
return divAwayFromZero(a, fromUnscaledInt(b));
}
/**
* @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint.Signed.
* @param b a uint256 (negative exponents are not allowed).
* @return output is `a` to the power of `b`.
*/
function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) {
output = fromUnscaledInt(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
}
pragma solidity ^0.6.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Multiplies two signed integers, reverts on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Integer division of two signed integers truncating the quotient, reverts on division by zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Subtracts two signed integers, reverts on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Adds two signed integers, reverts on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "./Timer.sol";
/**
* @title Base class that provides time overrides, but only if being run in test mode.
*/
abstract contract Testable {
// If the contract is being run on the test network, then `timerAddress` will be the 0x0 address.
// Note: this variable should be set on construction and never modified.
address public timerAddress;
/**
* @notice Constructs the Testable contract. Called by child contracts.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(address _timerAddress) internal {
timerAddress = _timerAddress;
}
/**
* @notice Reverts if not running in test mode.
*/
modifier onlyIfTest {
require(timerAddress != address(0x0));
_;
}
/**
* @notice Sets the current time.
* @dev Will revert if not running in test mode.
* @param time timestamp to set current Testable time to.
*/
function setCurrentTime(uint256 time) external onlyIfTest {
Timer(timerAddress).setCurrentTime(time);
}
/**
* @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode.
* Otherwise, it will return the block timestamp.
* @return uint for the current Testable timestamp.
*/
function getCurrentTime() public view returns (uint256) {
if (timerAddress != address(0x0)) {
return Timer(timerAddress).getCurrentTime();
} else {
return now; // solhint-disable-line not-rely-on-time
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Universal store of current contract time for testing environments.
*/
contract Timer {
uint256 private currentTime;
constructor() public {
currentTime = now; // solhint-disable-line not-rely-on-time
}
/**
* @notice Sets the current time.
* @dev Will revert if not running in test mode.
* @param time timestamp to set `currentTime` to.
*/
function setCurrentTime(uint256 time) external {
currentTime = time;
}
/**
* @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode.
* Otherwise, it will return the block timestamp.
* @return uint256 for the current Testable timestamp.
*/
function getCurrentTime() public view returns (uint256) {
return currentTime;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/**
* @title An implementation of ERC20 with the same interface as the Compound project's testnet tokens (mainly DAI)
* @dev This contract can be deployed or the interface can be used to communicate with Compound's ERC20 tokens. Note:
* this token should never be used to store real value since it allows permissionless minting.
*/
contract TestnetERC20 is ERC20 {
/**
* @notice Constructs the TestnetERC20.
* @param _name The name which describes the new token.
* @param _symbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param _decimals The number of decimals to define token precision.
*/
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) public ERC20(_name, _symbol) {
_setupDecimals(_decimals);
}
// Sample token information.
/**
* @notice Mints value tokens to the owner address.
* @param ownerAddress the address to mint to.
* @param value the amount of tokens to mint.
*/
function allocateTo(address ownerAddress, uint256 value) external {
_mint(ownerAddress, value);
}
}
/**
* Withdrawable contract.
*/
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./MultiRole.sol";
/**
* @title Base contract that allows a specific role to withdraw any ETH and/or ERC20 tokens that the contract holds.
*/
abstract contract Withdrawable is MultiRole {
using SafeERC20 for IERC20;
uint256 private roleId;
/**
* @notice Withdraws ETH from the contract.
*/
function withdraw(uint256 amount) external onlyRoleHolder(roleId) {
Address.sendValue(msg.sender, amount);
}
/**
* @notice Withdraws ERC20 tokens from the contract.
* @param erc20Address ERC20 token to withdraw.
* @param amount amount of tokens to withdraw.
*/
function withdrawErc20(address erc20Address, uint256 amount) external onlyRoleHolder(roleId) {
IERC20 erc20 = IERC20(erc20Address);
erc20.safeTransfer(msg.sender, amount);
}
/**
* @notice Internal method that allows derived contracts to create a role for withdrawal.
* @dev Either this method or `_setWithdrawRole` must be called by the derived class for this contract to function
* properly.
* @param newRoleId ID corresponding to role whose members can withdraw.
* @param managingRoleId ID corresponding to managing role who can modify the withdrawable role's membership.
* @param withdrawerAddress new manager of withdrawable role.
*/
function _createWithdrawRole(
uint256 newRoleId,
uint256 managingRoleId,
address withdrawerAddress
) internal {
roleId = newRoleId;
_createExclusiveRole(newRoleId, managingRoleId, withdrawerAddress);
}
/**
* @notice Internal method that allows derived contracts to choose the role for withdrawal.
* @dev The role `setRoleId` must exist. Either this method or `_createWithdrawRole` must be
* called by the derived class for this contract to function properly.
* @param setRoleId ID corresponding to role whose members can withdraw.
*/
function _setWithdrawRole(uint256 setRoleId) internal onlyValidRole(setRoleId) {
roleId = setRoleId;
}
}
pragma solidity ^0.6.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Interface for Balancer.
* @dev This only contains the methods/events that we use in our contracts or offchain infrastructure.
*/
abstract contract Balancer {
function getSpotPriceSansFee(address tokenIn, address tokenOut) external view virtual returns (uint256 spotPrice);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ERC20 interface that includes the decimals read only method.
*/
interface IERC20Standard is IERC20 {
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5,05`
* (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the value
* {ERC20} uses, unless {_setupDecimals} is called.
*
* NOTE: This information is only used for _display_ purposes: it in no way affects any of the arithmetic
* of the contract, including {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
abstract contract OneSplit {
function getExpectedReturn(
address fromToken,
address destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
) public view virtual returns (uint256 returnAmount, uint256[] memory distribution);
function swap(
address fromToken,
address destToken,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256 flags
) public payable virtual returns (uint256 returnAmount);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
// This is an interface to interact with a deployed implementation by https://github.com/kleros/action-callback-bots for
// batching on-chain transactions.
// See deployed implementation here: https://etherscan.io/address/0x82458d1c812d7c930bb3229c9e159cbabd9aa8cb.
abstract contract TransactionBatcher {
function batchSend(
address[] memory targets,
uint256[] memory values,
bytes[] memory datas
) public payable virtual;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Interface for Uniswap v2.
* @dev This only contains the methods/events that we use in our contracts or offchain infrastructure.
*/
abstract contract Uniswap {
// Called after every swap showing the new uniswap "price" for this token pair.
event Sync(uint112 reserve0, uint112 reserve1);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/Balancer.sol";
/**
* @title Balancer Mock
*/
contract BalancerMock is Balancer {
uint256 price = 0;
// these params arent used in the mock, but this is to maintain compatibility with balancer API
function getSpotPriceSansFee(address tokenIn, address tokenOut)
external
view
virtual
override
returns (uint256 spotPrice)
{
return price;
}
// this is not a balancer call, but for testing for changing price.
function setPrice(uint256 newPrice) external {
price = newPrice;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Implements only the required ERC20 methods. This contract is used
* test how contracts handle ERC20 contracts that have not implemented `decimals()`
* @dev Mostly copied from Consensys EIP-20 implementation:
* https://github.com/ConsenSys/Tokens/blob/fdf687c69d998266a95f15216b1955a4965a0a6d/contracts/eip20/EIP20.sol
*/
contract BasicERC20 is IERC20 {
uint256 private constant MAX_UINT256 = 2**256 - 1;
mapping(address => uint256) public balances;
mapping(address => mapping(address => uint256)) public allowed;
uint256 private _totalSupply;
constructor(uint256 _initialAmount) public {
balances[msg.sender] = _initialAmount;
_totalSupply = _initialAmount;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function transfer(address _to, uint256 _value) public override returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(
address _from,
address _to,
uint256 _value
) public override returns (bool success) {
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && allowance >= _value);
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function balanceOf(address _owner) public view override returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public override returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function allowance(address _owner, address _spender) public view override returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/*
MultiRoleTest contract.
*/
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/MultiRole.sol";
// The purpose of this contract is to make the MultiRole creation methods externally callable for testing purposes.
contract MultiRoleTest is MultiRole {
function createSharedRole(
uint256 roleId,
uint256 managingRoleId,
address[] calldata initialMembers
) external {
_createSharedRole(roleId, managingRoleId, initialMembers);
}
function createExclusiveRole(
uint256 roleId,
uint256 managingRoleId,
address initialMember
) external {
_createExclusiveRole(roleId, managingRoleId, initialMember);
}
// solhint-disable-next-line no-empty-blocks
function revertIfNotHoldingRole(uint256 roleId) external view onlyRoleHolder(roleId) {}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/OneSplit.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title OneSplit Mock that allows manual price injection.
*/
contract OneSplitMock is OneSplit {
address constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
mapping(bytes32 => uint256) prices;
receive() external payable {}
// Sets price of 1 FROM = <PRICE> TO
function setPrice(
address from,
address to,
uint256 price
) external {
prices[keccak256(abi.encodePacked(from, to))] = price;
}
function getExpectedReturn(
address fromToken,
address destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
) public view override returns (uint256 returnAmount, uint256[] memory distribution) {
returnAmount = prices[keccak256(abi.encodePacked(fromToken, destToken))] * amount;
return (returnAmount, distribution);
}
function swap(
address fromToken,
address destToken,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256 flags
) public payable override returns (uint256 returnAmount) {
uint256 amountReturn = prices[keccak256(abi.encodePacked(fromToken, destToken))] * amount;
require(amountReturn >= minReturn, "Min Amount not reached");
if (destToken == ETH_ADDRESS) {
msg.sender.transfer(amountReturn);
} else {
require(IERC20(destToken).transfer(msg.sender, amountReturn), "erc20-send-failed");
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
// Tests reentrancy guards defined in Lockable.sol.
// Copied from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyAttack.sol.
contract ReentrancyAttack {
function callSender(bytes4 data) public {
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = msg.sender.call(abi.encodeWithSelector(data));
require(success, "ReentrancyAttack: failed call");
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
// The Reentrancy Checker causes failures if it is successfully able to re-enter a contract.
// How to use:
// 1. Call setTransactionData with the transaction data you want the Reentrancy Checker to reenter the calling
// contract with.
// 2. Get the calling contract to call into the reentrancy checker with any call. The fallback function will receive
// this call and reenter the contract with the transaction data provided in 1. If that reentrancy call does not
// revert, then the reentrancy checker reverts the initial call, likely causeing the entire transaction to revert.
//
// Note: the reentrancy checker has a guard to prevent an infinite cycle of reentrancy. Inifinite cycles will run out
// of gas in all cases, potentially causing a revert when the contract is adequately protected from reentrancy.
contract ReentrancyChecker {
bytes public txnData;
bool hasBeenCalled;
// Used to prevent infinite cycles where the reentrancy is cycled forever.
modifier skipIfReentered {
if (hasBeenCalled) {
return;
}
hasBeenCalled = true;
_;
hasBeenCalled = false;
}
function setTransactionData(bytes memory _txnData) public {
txnData = _txnData;
}
function _executeCall(
address to,
uint256 value,
bytes memory data
) private returns (bool success) {
// Mostly copied from:
// solhint-disable-next-line max-line-length
// https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31
// solhint-disable-next-line no-inline-assembly
assembly {
let inputData := add(data, 0x20)
let inputDataSize := mload(data)
success := call(gas(), to, value, inputData, inputDataSize, 0, 0)
}
}
fallback() external skipIfReentered {
// Attampt to re-enter with the set txnData.
bool success = _executeCall(msg.sender, 0, txnData);
// Fail if the call succeeds because that means the re-entrancy was successful.
require(!success, "Re-entrancy was successful");
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/Lockable.sol";
import "./ReentrancyAttack.sol";
// Tests reentrancy guards defined in Lockable.sol.
// Extends https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyMock.sol.
contract ReentrancyMock is Lockable {
uint256 public counter;
constructor() public {
counter = 0;
}
function callback() external nonReentrant {
_count();
}
function countAndSend(ReentrancyAttack attacker) external nonReentrant {
_count();
bytes4 func = bytes4(keccak256("callback()"));
attacker.callSender(func);
}
function countAndCall(ReentrancyAttack attacker) external nonReentrant {
_count();
bytes4 func = bytes4(keccak256("getCount()"));
attacker.callSender(func);
}
function countLocalRecursive(uint256 n) public nonReentrant {
if (n > 0) {
_count();
countLocalRecursive(n - 1);
}
}
function countThisRecursive(uint256 n) public nonReentrant {
if (n > 0) {
_count();
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = address(this).call(abi.encodeWithSignature("countThisRecursive(uint256)", n - 1));
require(success, "ReentrancyMock: failed call");
}
}
function countLocalCall() public nonReentrant {
getCount();
}
function countThisCall() public nonReentrant {
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = address(this).call(abi.encodeWithSignature("getCount()"));
require(success, "ReentrancyMock: failed call");
}
function getCount() public view nonReentrantView returns (uint256) {
return counter;
}
function _count() private {
counter += 1;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/FixedPoint.sol";
// Wraps the FixedPoint library for testing purposes.
contract SignedFixedPointTest {
using FixedPoint for FixedPoint.Signed;
using FixedPoint for int256;
using SafeMath for int256;
function wrapFromSigned(int256 a) external pure returns (uint256) {
return FixedPoint.fromSigned(FixedPoint.Signed(a)).rawValue;
}
function wrapFromUnsigned(uint256 a) external pure returns (int256) {
return FixedPoint.fromUnsigned(FixedPoint.Unsigned(a)).rawValue;
}
function wrapFromUnscaledInt(int256 a) external pure returns (int256) {
return FixedPoint.fromUnscaledInt(a).rawValue;
}
function wrapIsEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isEqual(FixedPoint.Signed(b));
}
function wrapMixedIsEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isEqual(b);
}
function wrapIsGreaterThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThan(FixedPoint.Signed(b));
}
function wrapIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThanOrEqual(FixedPoint.Signed(b));
}
function wrapMixedIsGreaterThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThan(b);
}
function wrapMixedIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThanOrEqual(b);
}
function wrapMixedIsGreaterThanOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isGreaterThan(FixedPoint.Signed(b));
}
function wrapMixedIsGreaterThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isGreaterThanOrEqual(FixedPoint.Signed(b));
}
function wrapIsLessThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThan(FixedPoint.Signed(b));
}
function wrapIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThanOrEqual(FixedPoint.Signed(b));
}
function wrapMixedIsLessThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThan(b);
}
function wrapMixedIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThanOrEqual(b);
}
function wrapMixedIsLessThanOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isLessThan(FixedPoint.Signed(b));
}
function wrapMixedIsLessThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isLessThanOrEqual(FixedPoint.Signed(b));
}
function wrapMin(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).min(FixedPoint.Signed(b)).rawValue;
}
function wrapMax(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).max(FixedPoint.Signed(b)).rawValue;
}
function wrapAdd(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).add(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedAdd(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).add(b).rawValue;
}
function wrapSub(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).sub(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSub(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).sub(b).rawValue;
}
// The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSubOpposite(int256 a, int256 b) external pure returns (int256) {
return a.sub(FixedPoint.Signed(b)).rawValue;
}
function wrapMul(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mul(FixedPoint.Signed(b)).rawValue;
}
function wrapMulAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mulAwayFromZero(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedMul(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mul(b).rawValue;
}
function wrapMixedMulAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mulAwayFromZero(b).rawValue;
}
function wrapDiv(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).div(FixedPoint.Signed(b)).rawValue;
}
function wrapDivAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).divAwayFromZero(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDiv(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).div(b).rawValue;
}
function wrapMixedDivAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).divAwayFromZero(b).rawValue;
}
// The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDivOpposite(int256 a, int256 b) external pure returns (int256) {
return a.div(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapPow(int256 a, uint256 b) external pure returns (int256) {
return FixedPoint.Signed(a).pow(b).rawValue;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/Testable.sol";
// TestableTest is derived from the abstract contract Testable for testing purposes.
contract TestableTest is Testable {
// solhint-disable-next-line no-empty-blocks
constructor(address _timerAddress) public Testable(_timerAddress) {}
function getTestableTimeAndBlockTime() external view returns (uint256 testableTime, uint256 blockTime) {
// solhint-disable-next-line not-rely-on-time
return (getCurrentTime(), now);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/Uniswap.sol";
/**
* @title Uniswap v2 Mock that allows manual price injection.
*/
contract UniswapMock is Uniswap {
function setPrice(uint112 reserve0, uint112 reserve1) external {
emit Sync(reserve0, reserve1);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/FixedPoint.sol";
// Wraps the FixedPoint library for testing purposes.
contract UnsignedFixedPointTest {
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for uint256;
using SafeMath for uint256;
function wrapFromUnscaledUint(uint256 a) external pure returns (uint256) {
return FixedPoint.fromUnscaledUint(a).rawValue;
}
function wrapIsEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isEqual(FixedPoint.Unsigned(b));
}
function wrapMixedIsEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isEqual(b);
}
function wrapIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThan(FixedPoint.Unsigned(b));
}
function wrapIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapMixedIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThan(b);
}
function wrapMixedIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThanOrEqual(b);
}
function wrapMixedIsGreaterThanOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isGreaterThan(FixedPoint.Unsigned(b));
}
function wrapMixedIsGreaterThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isGreaterThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapIsLessThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThan(FixedPoint.Unsigned(b));
}
function wrapIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapMixedIsLessThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThan(b);
}
function wrapMixedIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThanOrEqual(b);
}
function wrapMixedIsLessThanOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isLessThan(FixedPoint.Unsigned(b));
}
function wrapMixedIsLessThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isLessThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapMin(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).min(FixedPoint.Unsigned(b)).rawValue;
}
function wrapMax(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).max(FixedPoint.Unsigned(b)).rawValue;
}
function wrapAdd(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).add(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedAdd(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).add(b).rawValue;
}
function wrapSub(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).sub(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSub(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).sub(b).rawValue;
}
// The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSubOpposite(uint256 a, uint256 b) external pure returns (uint256) {
return a.sub(FixedPoint.Unsigned(b)).rawValue;
}
function wrapMul(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mul(FixedPoint.Unsigned(b)).rawValue;
}
function wrapMulCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mulCeil(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedMul(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mul(b).rawValue;
}
function wrapMixedMulCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mulCeil(b).rawValue;
}
function wrapDiv(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).div(FixedPoint.Unsigned(b)).rawValue;
}
function wrapDivCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).divCeil(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDiv(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).div(b).rawValue;
}
function wrapMixedDivCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).divCeil(b).rawValue;
}
// The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDivOpposite(uint256 a, uint256 b) external pure returns (uint256) {
return a.div(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapPow(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).pow(b).rawValue;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/Withdrawable.sol";
// WithdrawableTest is derived from the abstract contract Withdrawable for testing purposes.
contract WithdrawableTest is Withdrawable {
enum Roles { Governance, Withdraw }
// solhint-disable-next-line no-empty-blocks
constructor() public {
_createExclusiveRole(uint256(Roles.Governance), uint256(Roles.Governance), msg.sender);
_createWithdrawRole(uint256(Roles.Withdraw), uint256(Roles.Governance), msg.sender);
}
function pay() external payable {
require(msg.value > 0);
}
function setInternalWithdrawRole(uint256 setRoleId) public {
_setWithdrawRole(setRoleId);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title EmergencyShutdownable contract.
* @notice Any contract that inherits this contract will have an emergency shutdown timestamp state variable.
* This contract provides modifiers that can be used by children contracts to determine if the contract is
* in the shutdown state. The child contract is expected to implement the logic that happens
* once a shutdown occurs.
*/
abstract contract EmergencyShutdownable {
using SafeMath for uint256;
/****************************************
* EMERGENCY SHUTDOWN DATA STRUCTURES *
****************************************/
// Timestamp used in case of emergency shutdown. 0 if no shutdown has been triggered.
uint256 public emergencyShutdownTimestamp;
/****************************************
* MODIFIERS *
****************************************/
modifier notEmergencyShutdown() {
_notEmergencyShutdown();
_;
}
modifier isEmergencyShutdown() {
_isEmergencyShutdown();
_;
}
/****************************************
* EXTERNAL FUNCTIONS *
****************************************/
constructor() public {
emergencyShutdownTimestamp = 0;
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
function _notEmergencyShutdown() internal view {
// Note: removed require string to save bytecode.
require(emergencyShutdownTimestamp == 0);
}
function _isEmergencyShutdown() internal view {
// Note: removed require string to save bytecode.
require(emergencyShutdownTimestamp != 0);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../../oracle/interfaces/StoreInterface.sol";
import "../../oracle/interfaces/FinderInterface.sol";
import "../../oracle/interfaces/AdministrateeInterface.sol";
import "../../oracle/implementation/Constants.sol";
/**
* @title FeePayer contract.
* @notice Provides fee payment functionality for the ExpiringMultiParty contract.
* contract is abstract as each derived contract that inherits `FeePayer` must implement `pfc()`.
*/
abstract contract FeePayer is AdministrateeInterface, Testable, Lockable {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
/****************************************
* FEE PAYER DATA STRUCTURES *
****************************************/
// The collateral currency used to back the positions in this contract.
IERC20 public collateralCurrency;
// Finder contract used to look up addresses for UMA system contracts.
FinderInterface public finder;
// Tracks the last block time when the fees were paid.
uint256 private lastPaymentTime;
// Tracks the cumulative fees that have been paid by the contract for use by derived contracts.
// The multiplier starts at 1, and is updated by computing cumulativeFeeMultiplier * (1 - effectiveFee).
// Put another way, the cumulativeFeeMultiplier is (1 - effectiveFee1) * (1 - effectiveFee2) ...
// For example:
// The cumulativeFeeMultiplier should start at 1.
// If a 1% fee is charged, the multiplier should update to .99.
// If another 1% fee is charged, the multiplier should be 0.99^2 (0.9801).
FixedPoint.Unsigned public cumulativeFeeMultiplier;
/****************************************
* EVENTS *
****************************************/
event RegularFeesPaid(uint256 indexed regularFee, uint256 indexed lateFee);
event FinalFeesPaid(uint256 indexed amount);
/****************************************
* MODIFIERS *
****************************************/
// modifier that calls payRegularFees().
modifier fees virtual {
// Note: the regular fee is applied on every fee-accruing transaction, where the total change is simply the
// regular fee applied linearly since the last update. This implies that the compounding rate depends on the
// frequency of update transactions that have this modifier, and it never reaches the ideal of continuous
// compounding. This approximate-compounding pattern is common in the Ethereum ecosystem because of the
// complexity of compounding data on-chain.
payRegularFees();
_;
}
/**
* @notice Constructs the FeePayer contract. Called by child contracts.
* @param _collateralAddress ERC20 token that is used as the underlying collateral for the synthetic.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
address _collateralAddress,
address _finderAddress,
address _timerAddress
) public Testable(_timerAddress) {
collateralCurrency = IERC20(_collateralAddress);
finder = FinderInterface(_finderAddress);
lastPaymentTime = getCurrentTime();
cumulativeFeeMultiplier = FixedPoint.fromUnscaledUint(1);
}
/****************************************
* FEE PAYMENT FUNCTIONS *
****************************************/
/**
* @notice Pays UMA DVM regular fees (as a % of the collateral pool) to the Store contract.
* @dev These must be paid periodically for the life of the contract. If the contract has not paid its regular fee
* in a week or more then a late penalty is applied which is sent to the caller. If the amount of
* fees owed are greater than the pfc, then this will pay as much as possible from the available collateral.
* An event is only fired if the fees charged are greater than 0.
* @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller).
* This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0.
*/
function payRegularFees() public nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) {
StoreInterface store = _getStore();
uint256 time = getCurrentTime();
FixedPoint.Unsigned memory collateralPool = _pfc();
// Exit early if there is no collateral from which to pay fees.
if (collateralPool.isEqual(0)) {
// Note: set the lastPaymentTime in this case so the contract is credited for paying during periods when it
// has no locked collateral.
lastPaymentTime = time;
return totalPaid;
}
// Exit early if fees were already paid during this block.
if (lastPaymentTime == time) {
return totalPaid;
}
(FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) =
store.computeRegularFee(lastPaymentTime, time, collateralPool);
lastPaymentTime = time;
totalPaid = regularFee.add(latePenalty);
if (totalPaid.isEqual(0)) {
return totalPaid;
}
// If the effective fees paid as a % of the pfc is > 100%, then we need to reduce it and make the contract pay
// as much of the fee that it can (up to 100% of its pfc). We'll reduce the late penalty first and then the
// regular fee, which has the effect of paying the store first, followed by the caller if there is any fee remaining.
if (totalPaid.isGreaterThan(collateralPool)) {
FixedPoint.Unsigned memory deficit = totalPaid.sub(collateralPool);
FixedPoint.Unsigned memory latePenaltyReduction = FixedPoint.min(latePenalty, deficit);
latePenalty = latePenalty.sub(latePenaltyReduction);
deficit = deficit.sub(latePenaltyReduction);
regularFee = regularFee.sub(FixedPoint.min(regularFee, deficit));
totalPaid = collateralPool;
}
emit RegularFeesPaid(regularFee.rawValue, latePenalty.rawValue);
_adjustCumulativeFeeMultiplier(totalPaid, collateralPool);
if (regularFee.isGreaterThan(0)) {
collateralCurrency.safeIncreaseAllowance(address(store), regularFee.rawValue);
store.payOracleFeesErc20(address(collateralCurrency), regularFee);
}
if (latePenalty.isGreaterThan(0)) {
collateralCurrency.safeTransfer(msg.sender, latePenalty.rawValue);
}
return totalPaid;
}
/**
* @notice Gets the current profit from corruption for this contract in terms of the collateral currency.
* @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are
* expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC.
* @return pfc value for equal to the current profit from corruption denominated in collateral currency.
*/
function pfc() external view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _pfc();
}
/**
* @notice Removes excess collateral balance not counted in the PfC by distributing it out pro-rata to all sponsors.
* @dev Multiplying the `cumulativeFeeMultiplier` by the ratio of non-PfC-collateral :: PfC-collateral effectively
* pays all sponsors a pro-rata portion of the excess collateral.
* @dev This will revert if PfC is 0 and this contract's collateral balance > 0.
*/
function gulp() external nonReentrant() {
_gulp();
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee
// charged for each price request. If payer is the contract, adjusts internal bookkeeping variables. If payer is not
// the contract, pulls in `amount` of collateral currency.
function _payFinalFees(address payer, FixedPoint.Unsigned memory amount) internal {
if (amount.isEqual(0)) {
return;
}
if (payer != address(this)) {
// If the payer is not the contract pull the collateral from the payer.
collateralCurrency.safeTransferFrom(payer, address(this), amount.rawValue);
} else {
// If the payer is the contract, adjust the cumulativeFeeMultiplier to compensate.
FixedPoint.Unsigned memory collateralPool = _pfc();
// The final fee must be < available collateral or the fee will be larger than 100%.
// Note: revert reason removed to save bytecode.
require(collateralPool.isGreaterThan(amount));
_adjustCumulativeFeeMultiplier(amount, collateralPool);
}
emit FinalFeesPaid(amount.rawValue);
StoreInterface store = _getStore();
collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue);
store.payOracleFeesErc20(address(collateralCurrency), amount);
}
function _gulp() internal {
FixedPoint.Unsigned memory currentPfc = _pfc();
FixedPoint.Unsigned memory currentBalance = FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this)));
if (currentPfc.isLessThan(currentBalance)) {
cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(currentBalance.div(currentPfc));
}
}
function _pfc() internal view virtual returns (FixedPoint.Unsigned memory);
function _getStore() internal view returns (StoreInterface) {
return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store));
}
function _computeFinalFees() internal view returns (FixedPoint.Unsigned memory finalFees) {
StoreInterface store = _getStore();
return store.computeFinalFee(address(collateralCurrency));
}
// Returns the user's collateral minus any fees that have been subtracted since it was originally
// deposited into the contract. Note: if the contract has paid fees since it was deployed, the raw
// value should be larger than the returned value.
function _getFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral)
internal
view
returns (FixedPoint.Unsigned memory collateral)
{
return rawCollateral.mul(cumulativeFeeMultiplier);
}
// Converts a user-readable collateral value into a raw value that accounts for already-assessed fees. If any fees
// have been taken from this contract in the past, then the raw value will be larger than the user-readable value.
function _convertToRawCollateral(FixedPoint.Unsigned memory collateral)
internal
view
returns (FixedPoint.Unsigned memory rawCollateral)
{
return collateral.div(cumulativeFeeMultiplier);
}
// Decrease rawCollateral by a fee-adjusted collateralToRemove amount. Fee adjustment scales up collateralToRemove
// by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore
// rawCollateral is decreased by less than expected. Because this method is usually called in conjunction with an
// actual removal of collateral from this contract, return the fee-adjusted amount that the rawCollateral is
// decreased by so that the caller can minimize error between collateral removed and rawCollateral debited.
function _removeCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToRemove)
internal
returns (FixedPoint.Unsigned memory removedCollateral)
{
FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral);
FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToRemove);
rawCollateral.rawValue = rawCollateral.sub(adjustedCollateral).rawValue;
removedCollateral = initialBalance.sub(_getFeeAdjustedCollateral(rawCollateral));
}
// Increase rawCollateral by a fee-adjusted collateralToAdd amount. Fee adjustment scales up collateralToAdd
// by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore
// rawCollateral is increased by less than expected. Because this method is usually called in conjunction with an
// actual addition of collateral to this contract, return the fee-adjusted amount that the rawCollateral is
// increased by so that the caller can minimize error between collateral added and rawCollateral credited.
// NOTE: This return value exists only for the sake of symmetry with _removeCollateral. We don't actually use it
// because we are OK if more collateral is stored in the contract than is represented by rawTotalPositionCollateral.
function _addCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToAdd)
internal
returns (FixedPoint.Unsigned memory addedCollateral)
{
FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral);
FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToAdd);
rawCollateral.rawValue = rawCollateral.add(adjustedCollateral).rawValue;
addedCollateral = _getFeeAdjustedCollateral(rawCollateral).sub(initialBalance);
}
// Scale the cumulativeFeeMultiplier by the ratio of fees paid to the current available collateral.
function _adjustCumulativeFeeMultiplier(FixedPoint.Unsigned memory amount, FixedPoint.Unsigned memory currentPfc)
internal
{
FixedPoint.Unsigned memory effectiveFee = amount.divCeil(currentPfc);
cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveFee));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title Interface that allows financial contracts to pay oracle fees for their use of the system.
*/
interface StoreInterface {
/**
* @notice Pays Oracle fees in ETH to the store.
* @dev To be used by contracts whose margin currency is ETH.
*/
function payOracleFees() external payable;
/**
* @notice Pays oracle fees in the margin currency, erc20Address, to the store.
* @dev To be used if the margin currency is an ERC20 token rather than ETH.
* @param erc20Address address of the ERC20 token used to pay the fee.
* @param amount number of tokens to transfer. An approval for at least this amount must exist.
*/
function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external;
/**
* @notice Computes the regular oracle fees that a contract should pay for a period.
* @param startTime defines the beginning time from which the fee is paid.
* @param endTime end time until which the fee is paid.
* @param pfc "profit from corruption", or the maximum amount of margin currency that a
* token sponsor could extract from the contract through corrupting the price feed in their favor.
* @return regularFee amount owed for the duration from start to end time for the given pfc.
* @return latePenalty for paying the fee after the deadline.
*/
function computeRegularFee(
uint256 startTime,
uint256 endTime,
FixedPoint.Unsigned calldata pfc
) external view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty);
/**
* @notice Computes the final oracle fees that a contract should pay at settlement.
* @param currency token used to pay the final fee.
* @return finalFee amount due.
*/
function computeFinalFee(address currency) external view returns (FixedPoint.Unsigned memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Provides addresses of the live contracts implementing certain interfaces.
* @dev Examples are the Oracle or Store interfaces.
*/
interface FinderInterface {
/**
* @notice Updates the address of the contract that implements `interfaceName`.
* @param interfaceName bytes32 encoding of the interface name that is either changed or registered.
* @param implementationAddress address of the deployed contract that implements the interface.
*/
function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external;
/**
* @notice Gets the address of the contract that implements the given `interfaceName`.
* @param interfaceName queried interface.
* @return implementationAddress address of the deployed contract that implements the interface.
*/
function getImplementationAddress(bytes32 interfaceName) external view returns (address);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Interface that all financial contracts expose to the admin.
*/
interface AdministrateeInterface {
/**
* @notice Initiates the shutdown process, in case of an emergency.
*/
function emergencyShutdown() external;
/**
* @notice A core contract method called independently or as a part of other financial contract transactions.
* @dev It pays fees and moves money between margin accounts to make sure they reflect the NAV of the contract.
*/
function remargin() external;
/**
* @notice Gets the current profit from corruption for this contract in terms of the collateral currency.
* @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are
* expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC.
* @return pfc value for equal to the current profit from corruption denominated in collateral currency.
*/
function pfc() external view returns (FixedPoint.Unsigned memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Stores common interface names used throughout the DVM by registration in the Finder.
*/
library OracleInterfaces {
bytes32 public constant Oracle = "Oracle";
bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist";
bytes32 public constant Store = "Store";
bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin";
bytes32 public constant Registry = "Registry";
bytes32 public constant CollateralWhitelist = "CollateralWhitelist";
bytes32 public constant OptimisticOracle = "OptimisticOracle";
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../../common/implementation/FixedPoint.sol";
interface ExpiringContractInterface {
function expirationTimestamp() external view returns (uint256);
}
/**
* @title Financial product library contract
* @notice Provides price and collateral requirement transformation interfaces that can be overridden by custom
* Financial product library implementations.
*/
abstract contract FinancialProductLibrary {
using FixedPoint for FixedPoint.Unsigned;
/**
* @notice Transforms a given oracle price using the financial product libraries transformation logic.
* @param oraclePrice input price returned by the DVM to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedOraclePrice input oraclePrice with the transformation function applied.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
virtual
returns (FixedPoint.Unsigned memory)
{
return oraclePrice;
}
/**
* @notice Transforms a given collateral requirement using the financial product libraries transformation logic.
* @param oraclePrice input price returned by DVM used to transform the collateral requirement.
* @param collateralRequirement input collateral requirement to be transformed.
* @return transformedCollateralRequirement input collateral requirement with the transformation function applied.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view virtual returns (FixedPoint.Unsigned memory) {
return collateralRequirement;
}
/**
* @notice Transforms a given price identifier using the financial product libraries transformation logic.
* @param priceIdentifier input price identifier defined for the financial contract.
* @param requestTime timestamp the identifier is to be used at. EG the time that a price request would be sent using this identifier.
* @return transformedPriceIdentifier input price identifier with the transformation function applied.
*/
function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime)
public
view
virtual
returns (bytes32)
{
return priceIdentifier;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title Pre-Expiration Identifier Transformation Financial Product Library
* @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending
* on when a price request is made. If the request is made before expiration then a transformation is made to the identifier
* & if it is at or after expiration then the original identifier is returned. This library enables self referential
* TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration.
*/
contract PreExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Ownable, Lockable {
mapping(address => bytes32) financialProductTransformedIdentifiers;
/**
* @notice Enables the deployer of the library to set the transformed identifier for an associated financial product.
* @param financialProduct address of the financial product.
* @param transformedIdentifier the identifier for the financial product to be used if the contract is post expiration.
* @dev Note: a) Only the owner (deployer) of this library can set identifier transformations b) The identifier can't
* be set to blank. c) A transformed price can only be set once to prevent the deployer from changing it after the fact.
* d) financialProduct must expose an expirationTimestamp method.
*/
function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier)
public
onlyOwner
nonReentrant()
{
require(transformedIdentifier != "", "Cant set to empty transformation");
require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier;
}
/**
* @notice Returns the transformed identifier associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return transformed identifier for the associated financial product.
*/
function getTransformedIdentifierForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (bytes32)
{
return financialProductTransformedIdentifiers[financialProduct];
}
/**
* @notice Returns a transformed price identifier if the contract is pre-expiration and no transformation if post.
* @param identifier input price identifier to be transformed.
* @param requestTime timestamp the identifier is to be used at.
* @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it.
*/
function transformPriceIdentifier(bytes32 identifier, uint256 requestTime)
public
view
override
nonReentrantView()
returns (bytes32)
{
require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation");
// If the request time is before contract expiration then return the transformed identifier. Else, return the
// original price identifier.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return financialProductTransformedIdentifiers[msg.sender];
} else {
return identifier;
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title Structured Note Financial Product Library
* @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The
* contract holds say 1 WETH in collateral and pays out that 1 WETH if, at expiry, ETHUSD is below a set strike. If
* ETHUSD is above that strike, the contract pays out a given dollar amount of ETH.
* Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH
* If ETHUSD < $400 at expiry, token is redeemed for 1 ETH.
* If ETHUSD >= $400 at expiry, token is redeemed for $400 worth of ETH, as determined by the DVM.
*/
contract StructuredNoteFinancialProductLibrary is FinancialProductLibrary, Ownable, Lockable {
mapping(address => FixedPoint.Unsigned) financialProductStrikes;
/**
* @notice Enables the deployer of the library to set the strike price for an associated financial product.
* @param financialProduct address of the financial product.
* @param strikePrice the strike price for the structured note to be applied to the financial product.
* @dev Note: a) Only the owner (deployer) of this library can set new strike prices b) A strike price cannot be 0.
* c) A strike price can only be set once to prevent the deployer from changing the strike after the fact.
* d) financialProduct must exposes an expirationTimestamp method.
*/
function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice)
public
onlyOwner
nonReentrant()
{
require(strikePrice.isGreaterThan(0), "Cant set 0 strike");
require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductStrikes[financialProduct] = strikePrice;
}
/**
* @notice Returns the strike price associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return strikePrice for the associated financial product.
*/
function getStrikeForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return financialProductStrikes[financialProduct];
}
/**
* @notice Returns a transformed price by applying the structured note payout structure.
* @param oraclePrice price from the oracle to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice the input oracle price with the price transformation logic applied to it.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with
// each token backed 1:1 by collateral currency.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return FixedPoint.fromUnscaledUint(1);
}
if (oraclePrice.isLessThan(strike)) {
return FixedPoint.fromUnscaledUint(1);
} else {
// Token expires to be worth strike $ worth of collateral.
// eg if ETHUSD is $500 and strike is $400, token is redeemable for 400/500 = 0.8 WETH.
return strike.div(oraclePrice);
}
}
/**
* @notice Returns a transformed collateral requirement by applying the structured note payout structure. If the price
* of the structured note is greater than the strike then the collateral requirement scales down accordingly.
* @param oraclePrice price from the oracle to transform the collateral requirement.
* @param collateralRequirement financial products collateral requirement to be scaled according to price and strike.
* @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// If the price is less than the strike than the original collateral requirement is used.
if (oraclePrice.isLessThan(strike)) {
return collateralRequirement;
} else {
// If the price is more than the strike then the collateral requirement is scaled by the strike. For example
// a strike of $400 and a CR of 1.2 would yield:
// ETHUSD = $350, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2
// ETHUSD = $400, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2
// ETHUSD = $425, payout is 0.941 WETH (worth $400). CR is multiplied by 0.941. resulting CR = 1.1292
// ETHUSD = $500, payout is 0.8 WETH (worth $400). CR multiplied by 0.8. resulting CR = 0.96
return collateralRequirement.mul(strike.div(oraclePrice));
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/utils/SafeCast.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../../oracle/implementation/Constants.sol";
import "../../oracle/interfaces/OptimisticOracleInterface.sol";
import "../perpetual-multiparty/ConfigStoreInterface.sol";
import "./EmergencyShutdownable.sol";
import "./FeePayer.sol";
/**
* @title FundingRateApplier contract.
* @notice Provides funding rate payment functionality for the Perpetual contract.
*/
abstract contract FundingRateApplier is EmergencyShutdownable, FeePayer {
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for FixedPoint.Signed;
using SafeERC20 for IERC20;
using SafeMath for uint256;
/****************************************
* FUNDING RATE APPLIER DATA STRUCTURES *
****************************************/
struct FundingRate {
// Current funding rate value.
FixedPoint.Signed rate;
// Identifier to retrieve the funding rate.
bytes32 identifier;
// Tracks the cumulative funding payments that have been paid to the sponsors.
// The multiplier starts at 1, and is updated by computing cumulativeFundingRateMultiplier * (1 + effectivePayment).
// Put another way, the cumulativeFeeMultiplier is (1 + effectivePayment1) * (1 + effectivePayment2) ...
// For example:
// The cumulativeFundingRateMultiplier should start at 1.
// If a 1% funding payment is paid to sponsors, the multiplier should update to 1.01.
// If another 1% fee is charged, the multiplier should be 1.01^2 (1.0201).
FixedPoint.Unsigned cumulativeMultiplier;
// Most recent time that the funding rate was updated.
uint256 updateTime;
// Most recent time that the funding rate was applied and changed the cumulative multiplier.
uint256 applicationTime;
// The time for the active (if it exists) funding rate proposal. 0 otherwise.
uint256 proposalTime;
}
FundingRate public fundingRate;
// Remote config store managed an owner.
ConfigStoreInterface public configStore;
/****************************************
* EVENTS *
****************************************/
event FundingRateUpdated(int256 newFundingRate, uint256 indexed updateTime, uint256 reward);
/****************************************
* MODIFIERS *
****************************************/
// This is overridden to both pay fees (which is done by applyFundingRate()) and apply the funding rate.
modifier fees override {
// Note: the funding rate is applied on every fee-accruing transaction, where the total change is simply the
// rate applied linearly since the last update. This implies that the compounding rate depends on the frequency
// of update transactions that have this modifier, and it never reaches the ideal of continuous compounding.
// This approximate-compounding pattern is common in the Ethereum ecosystem because of the complexity of
// compounding data on-chain.
applyFundingRate();
_;
}
// Note: this modifier is intended to be used if the caller intends to _only_ pay regular fees.
modifier regularFees {
payRegularFees();
_;
}
/**
* @notice Constructs the FundingRateApplier contract. Called by child contracts.
* @param _fundingRateIdentifier identifier that tracks the funding rate of this contract.
* @param _collateralAddress address of the collateral token.
* @param _finderAddress Finder used to discover financial-product-related contracts.
* @param _configStoreAddress address of the remote configuration store managed by an external owner.
* @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index).
* @param _timerAddress address of the timer contract in test envs, otherwise 0x0.
*/
constructor(
bytes32 _fundingRateIdentifier,
address _collateralAddress,
address _finderAddress,
address _configStoreAddress,
FixedPoint.Unsigned memory _tokenScaling,
address _timerAddress
) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) EmergencyShutdownable() {
uint256 currentTime = getCurrentTime();
fundingRate.updateTime = currentTime;
fundingRate.applicationTime = currentTime;
// Seed the cumulative multiplier with the token scaling, from which it will be scaled as funding rates are
// applied over time.
fundingRate.cumulativeMultiplier = _tokenScaling;
fundingRate.identifier = _fundingRateIdentifier;
configStore = ConfigStoreInterface(_configStoreAddress);
}
/**
* @notice This method takes 3 distinct actions:
* 1. Pays out regular fees.
* 2. If possible, resolves the outstanding funding rate proposal, pulling the result in and paying out the rewards.
* 3. Applies the prevailing funding rate over the most recent period.
*/
function applyFundingRate() public regularFees() nonReentrant() {
_applyEffectiveFundingRate();
}
/**
* @notice Proposes a new funding rate. Proposer receives a reward if correct.
* @param rate funding rate being proposed.
* @param timestamp time at which the funding rate was computed.
*/
function proposeNewRate(FixedPoint.Signed memory rate, uint256 timestamp)
external
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalBond)
{
require(fundingRate.proposalTime == 0, "Proposal in progress");
_validateFundingRate(rate);
// Timestamp must be after the last funding rate update time, within the last 30 minutes.
uint256 currentTime = getCurrentTime();
uint256 updateTime = fundingRate.updateTime;
require(
timestamp > updateTime && timestamp >= currentTime.sub(_getConfig().proposalTimePastLimit),
"Invalid proposal time"
);
// Set the proposal time in order to allow this contract to track this request.
fundingRate.proposalTime = timestamp;
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
// Set up optimistic oracle.
bytes32 identifier = fundingRate.identifier;
bytes memory ancillaryData = _getAncillaryData();
// Note: requestPrice will revert if `timestamp` is less than the current block timestamp.
optimisticOracle.requestPrice(identifier, timestamp, ancillaryData, collateralCurrency, 0);
totalBond = FixedPoint.Unsigned(
optimisticOracle.setBond(
identifier,
timestamp,
ancillaryData,
_pfc().mul(_getConfig().proposerBondPct).rawValue
)
);
// Pull bond from caller and send to optimistic oracle.
if (totalBond.isGreaterThan(0)) {
collateralCurrency.safeTransferFrom(msg.sender, address(this), totalBond.rawValue);
collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), totalBond.rawValue);
}
optimisticOracle.proposePriceFor(
msg.sender,
address(this),
identifier,
timestamp,
ancillaryData,
rate.rawValue
);
}
// Returns a token amount scaled by the current funding rate multiplier.
// Note: if the contract has paid fees since it was deployed, the raw value should be larger than the returned value.
function _getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt)
internal
view
returns (FixedPoint.Unsigned memory tokenDebt)
{
return rawTokenDebt.mul(fundingRate.cumulativeMultiplier);
}
function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) {
return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle));
}
function _getConfig() internal returns (ConfigStoreInterface.ConfigSettings memory) {
return configStore.updateAndGetCurrentConfig();
}
function _getLatestFundingRate() internal returns (FixedPoint.Signed memory) {
uint256 proposalTime = fundingRate.proposalTime;
// If there is no pending proposal then return the current funding rate, otherwise
// check to see if we can update the funding rate.
if (proposalTime != 0) {
// Attempt to update the funding rate.
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
bytes32 identifier = fundingRate.identifier;
bytes memory ancillaryData = _getAncillaryData();
// Try to get the price from the optimistic oracle. This call will revert if the request has not resolved
// yet. If the request has not resolved yet, then we need to do additional checks to see if we should
// "forget" the pending proposal and allow new proposals to update the funding rate.
try optimisticOracle.getPrice(identifier, proposalTime, ancillaryData) returns (int256 price) {
// If successful, determine if the funding rate state needs to be updated.
// If the request is more recent than the last update then we should update it.
uint256 lastUpdateTime = fundingRate.updateTime;
if (proposalTime >= lastUpdateTime) {
// Update funding rates
fundingRate.rate = FixedPoint.Signed(price);
fundingRate.updateTime = proposalTime;
// If there was no dispute, send a reward.
FixedPoint.Unsigned memory reward = FixedPoint.fromUnscaledUint(0);
OptimisticOracleInterface.Request memory request =
optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData);
if (request.disputer == address(0)) {
reward = _pfc().mul(_getConfig().rewardRatePerSecond).mul(proposalTime.sub(lastUpdateTime));
if (reward.isGreaterThan(0)) {
_adjustCumulativeFeeMultiplier(reward, _pfc());
collateralCurrency.safeTransfer(request.proposer, reward.rawValue);
}
}
// This event will only be emitted after the fundingRate struct's "updateTime" has been set
// to the latest proposal's proposalTime, indicating that the proposal has been published.
// So, it suffices to just emit fundingRate.updateTime here.
emit FundingRateUpdated(fundingRate.rate.rawValue, fundingRate.updateTime, reward.rawValue);
}
// Set proposal time to 0 since this proposal has now been resolved.
fundingRate.proposalTime = 0;
} catch {
// Stop tracking and allow other proposals to come in if:
// - The requester address is empty, indicating that the Oracle does not know about this funding rate
// request. This is possible if the Oracle is replaced while the price request is still pending.
// - The request has been disputed.
OptimisticOracleInterface.Request memory request =
optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData);
if (request.disputer != address(0) || request.proposer == address(0)) {
fundingRate.proposalTime = 0;
}
}
}
return fundingRate.rate;
}
// Constraining the range of funding rates limits the PfC for any dishonest proposer and enhances the
// perpetual's security. For example, let's examine the case where the max and min funding rates
// are equivalent to +/- 500%/year. This 1000% funding rate range allows a 8.6% profit from corruption for a
// proposer who can deter honest proposers for 74 hours:
// 1000%/year / 360 days / 24 hours * 74 hours max attack time = ~ 8.6%.
// How would attack work? Imagine that the market is very volatile currently and that the "true" funding
// rate for the next 74 hours is -500%, but a dishonest proposer successfully proposes a rate of +500%
// (after a two hour liveness) and disputes honest proposers for the next 72 hours. This results in a funding
// rate error of 1000% for 74 hours, until the DVM can set the funding rate back to its correct value.
function _validateFundingRate(FixedPoint.Signed memory rate) internal {
require(
rate.isLessThanOrEqual(_getConfig().maxFundingRate) &&
rate.isGreaterThanOrEqual(_getConfig().minFundingRate)
);
}
// Fetches a funding rate from the Store, determines the period over which to compute an effective fee,
// and multiplies the current multiplier by the effective fee.
// A funding rate < 1 will reduce the multiplier, and a funding rate of > 1 will increase the multiplier.
// Note: 1 is set as the neutral rate because there are no negative numbers in FixedPoint, so we decide to treat
// values < 1 as "negative".
function _applyEffectiveFundingRate() internal {
// If contract is emergency shutdown, then the funding rate multiplier should no longer change.
if (emergencyShutdownTimestamp != 0) {
return;
}
uint256 currentTime = getCurrentTime();
uint256 paymentPeriod = currentTime.sub(fundingRate.applicationTime);
fundingRate.cumulativeMultiplier = _calculateEffectiveFundingRate(
paymentPeriod,
_getLatestFundingRate(),
fundingRate.cumulativeMultiplier
);
fundingRate.applicationTime = currentTime;
}
function _calculateEffectiveFundingRate(
uint256 paymentPeriodSeconds,
FixedPoint.Signed memory fundingRatePerSecond,
FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier
) internal pure returns (FixedPoint.Unsigned memory newCumulativeFundingRateMultiplier) {
// Note: this method uses named return variables to save a little bytecode.
// The overall formula that this function is performing:
// newCumulativeFundingRateMultiplier =
// (1 + (fundingRatePerSecond * paymentPeriodSeconds)) * currentCumulativeFundingRateMultiplier.
FixedPoint.Signed memory ONE = FixedPoint.fromUnscaledInt(1);
// Multiply the per-second rate over the number of seconds that have elapsed to get the period rate.
FixedPoint.Signed memory periodRate = fundingRatePerSecond.mul(SafeCast.toInt256(paymentPeriodSeconds));
// Add one to create the multiplier to scale the existing fee multiplier.
FixedPoint.Signed memory signedPeriodMultiplier = ONE.add(periodRate);
// Max with 0 to ensure the multiplier isn't negative, then cast to an Unsigned.
FixedPoint.Unsigned memory unsignedPeriodMultiplier =
FixedPoint.fromSigned(FixedPoint.max(signedPeriodMultiplier, FixedPoint.fromUnscaledInt(0)));
// Multiply the existing cumulative funding rate multiplier by the computed period multiplier to get the new
// cumulative funding rate multiplier.
newCumulativeFundingRateMultiplier = currentCumulativeFundingRateMultiplier.mul(unsignedPeriodMultiplier);
}
function _getAncillaryData() internal view returns (bytes memory) {
// Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address
// whose funding rate it's trying to get.
return abi.encodePacked(_getTokenAddress());
}
function _getTokenAddress() internal view virtual returns (address);
}
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's uintXX casting operators with added overflow
* checks.
*
* Downcasting from uint256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} to extend it to smaller types, by performing
* all math on `uint256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OptimisticOracleInterface {
// Struct representing the state of a price request.
enum State {
Invalid, // Never requested.
Requested, // Requested, no other actions taken.
Proposed, // Proposed, but not expired or disputed yet.
Expired, // Proposed, not disputed, past liveness.
Disputed, // Disputed, but no DVM price returned yet.
Resolved, // Disputed and DVM price is available.
Settled // Final price has been set in the contract (can get here from Expired or Resolved).
}
// Struct representing a price request.
struct Request {
address proposer; // Address of the proposer.
address disputer; // Address of the disputer.
IERC20 currency; // ERC20 token used to pay rewards and fees.
bool settled; // True if the request is settled.
bool refundOnDispute; // True if the requester should be refunded their reward on dispute.
int256 proposedPrice; // Price that the proposer submitted.
int256 resolvedPrice; // Price resolved once the request is settled.
uint256 expirationTime; // Time at which the request auto-settles without a dispute.
uint256 reward; // Amount of the currency to pay to the proposer on settlement.
uint256 finalFee; // Final fee to pay to the Store upon request to the DVM.
uint256 bond; // Bond that the proposer and disputer must pay on top of the final fee.
uint256 customLiveness; // Custom liveness value set by the requester.
}
// This value must be <= the Voting contract's `ancillaryBytesLimit` value otherwise it is possible
// that a price can be requested to this contract successfully, but cannot be disputed because the DVM refuses
// to accept a price request made with ancillary data length of a certain size.
uint256 public constant ancillaryBytesLimit = 8192;
/**
* @notice Requests a new price.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data representing additional args being passed with the price request.
* @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM.
* @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0,
* which could make sense if the contract requests and proposes the value in the same call or
* provides its own reward system.
* @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay.
* This can be changed with a subsequent call to setBond().
*/
function requestPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
IERC20 currency,
uint256 reward
) external virtual returns (uint256 totalBond);
/**
* @notice Set the proposal bond associated with a price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param bond custom bond amount to set.
* @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be
* changed again with a subsequent call to setBond().
*/
function setBond(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 bond
) external virtual returns (uint256 totalBond);
/**
* @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller
* in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's
* bond, so there is still profit to be made even if the reward is refunded.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
*/
function setRefundOnDispute(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual;
/**
* @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before
* being auto-resolved.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param customLiveness new custom liveness.
*/
function setCustomLiveness(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 customLiveness
) external virtual;
/**
* @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come
* from this proposal. However, any bonds are pulled from the caller.
* @param proposer address to set as the proposer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePriceFor(
address proposer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) public virtual returns (uint256 totalBond);
/**
* @notice Proposes a price value for an existing price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) external virtual returns (uint256 totalBond);
/**
* @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will
* receive any rewards that come from this dispute. However, any bonds are pulled from the caller.
* @param disputer address to set as the disputer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was value (the proposal was incorrect).
*/
function disputePriceFor(
address disputer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public virtual returns (uint256 totalBond);
/**
* @notice Disputes a price value for an existing price request with an active proposal.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (uint256 totalBond);
/**
* @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled
* or settleable. Note: this method is not view so that this call may actually settle the price request if it
* hasn't been settled.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return resolved price.
*/
function getPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (int256);
/**
* @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes
* the returned bonds as well as additional rewards.
*/
function settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (uint256 payout);
/**
* @notice Gets the current data structure containing all information about a price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the Request data structure.
*/
function getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (Request memory);
function getState(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (State);
/**
* @notice Checks if a given request has resolved or been settled (i.e the optimistic oracle has a price).
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the State.
*/
function hasPrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
interface ConfigStoreInterface {
// All of the configuration settings available for querying by a perpetual.
struct ConfigSettings {
// Liveness period (in seconds) for an update to currentConfig to become official.
uint256 timelockLiveness;
// Reward rate paid to successful proposers. Percentage of 1 E.g., .1 is 10%.
FixedPoint.Unsigned rewardRatePerSecond;
// Bond % (of given contract's PfC) that must be staked by proposers. Percentage of 1, e.g. 0.0005 is 0.05%.
FixedPoint.Unsigned proposerBondPct;
// Maximum funding rate % per second that can be proposed.
FixedPoint.Signed maxFundingRate;
// Minimum funding rate % per second that can be proposed.
FixedPoint.Signed minFundingRate;
// Funding rate proposal timestamp cannot be more than this amount of seconds in the past from the latest
// update time.
uint256 proposalTimePastLimit;
}
function updateAndGetCurrentConfig() external returns (ConfigSettings memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../common/implementation/ExpandedERC20.sol";
import "../../common/implementation/Lockable.sol";
/**
* @title Burnable and mintable ERC20.
* @dev The contract deployer will initially be the only minter, burner and owner capable of adding new roles.
*/
contract SyntheticToken is ExpandedERC20, Lockable {
/**
* @notice Constructs the SyntheticToken.
* @param tokenName The name which describes the new token.
* @param tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param tokenDecimals The number of decimals to define token precision.
*/
constructor(
string memory tokenName,
string memory tokenSymbol,
uint8 tokenDecimals
) public ExpandedERC20(tokenName, tokenSymbol, tokenDecimals) nonReentrant() {}
/**
* @notice Add Minter role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Minter role is added.
*/
function addMinter(address account) external override nonReentrant() {
addMember(uint256(Roles.Minter), account);
}
/**
* @notice Remove Minter role from account.
* @dev The caller must have the Owner role.
* @param account The address from which the Minter role is removed.
*/
function removeMinter(address account) external nonReentrant() {
removeMember(uint256(Roles.Minter), account);
}
/**
* @notice Add Burner role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Burner role is added.
*/
function addBurner(address account) external override nonReentrant() {
addMember(uint256(Roles.Burner), account);
}
/**
* @notice Removes Burner role from account.
* @dev The caller must have the Owner role.
* @param account The address from which the Burner role is removed.
*/
function removeBurner(address account) external nonReentrant() {
removeMember(uint256(Roles.Burner), account);
}
/**
* @notice Reset Owner role to account.
* @dev The caller must have the Owner role.
* @param account The new holder of the Owner role.
*/
function resetOwner(address account) external override nonReentrant() {
resetMember(uint256(Roles.Owner), account);
}
/**
* @notice Checks if a given account holds the Minter role.
* @param account The address which is checked for the Minter role.
* @return bool True if the provided account is a Minter.
*/
function isMinter(address account) public view nonReentrantView() returns (bool) {
return holdsRole(uint256(Roles.Minter), account);
}
/**
* @notice Checks if a given account holds the Burner role.
* @param account The address which is checked for the Burner role.
* @return bool True if the provided account is a Burner.
*/
function isBurner(address account) public view nonReentrantView() returns (bool) {
return holdsRole(uint256(Roles.Burner), account);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "./SyntheticToken.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/implementation/Lockable.sol";
/**
* @title Factory for creating new mintable and burnable tokens.
*/
contract TokenFactory is Lockable {
/**
* @notice Create a new token and return it to the caller.
* @dev The caller will become the only minter and burner and the new owner capable of assigning the roles.
* @param tokenName used to describe the new token.
* @param tokenSymbol short ticker abbreviation of the name. Ideally < 5 chars.
* @param tokenDecimals used to define the precision used in the token's numerical representation.
* @return newToken an instance of the newly created token interface.
*/
function createToken(
string calldata tokenName,
string calldata tokenSymbol,
uint8 tokenDecimals
) external nonReentrant() returns (ExpandedIERC20 newToken) {
SyntheticToken mintableToken = new SyntheticToken(tokenName, tokenSymbol, tokenDecimals);
mintableToken.addMinter(msg.sender);
mintableToken.addBurner(msg.sender);
mintableToken.resetOwner(msg.sender);
newToken = ExpandedIERC20(address(mintableToken));
}
}
/**
*Submitted for verification at Etherscan.io on 2017-12-12
*/
// Copyright (C) 2015, 2016, 2017 Dapphub
// 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/>.
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
// Copied from the verified code from Etherscan:
// https://etherscan.io/address/0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2#code
// And then updated for Solidity version 0.6. Specific changes:
// * Change `function() public` into `receive() external` and `fallback() external`
// * Change `this.balance` to `address(this).balance`
// * Ran prettier
contract WETH9 {
string public name = "Wrapped Ether";
string public symbol = "WETH";
uint8 public decimals = 18;
event Approval(address indexed src, address indexed guy, uint256 wad);
event Transfer(address indexed src, address indexed dst, uint256 wad);
event Deposit(address indexed dst, uint256 wad);
event Withdrawal(address indexed src, uint256 wad);
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
receive() external payable {
deposit();
}
fallback() external payable {
deposit();
}
function deposit() public payable {
balanceOf[msg.sender] += msg.value;
emit Deposit(msg.sender, msg.value);
}
function withdraw(uint256 wad) public {
require(balanceOf[msg.sender] >= wad);
balanceOf[msg.sender] -= wad;
msg.sender.transfer(wad);
emit Withdrawal(msg.sender, wad);
}
function totalSupply() public view returns (uint256) {
return address(this).balance;
}
function approve(address guy, uint256 wad) public returns (bool) {
allowance[msg.sender][guy] = wad;
emit Approval(msg.sender, guy, wad);
return true;
}
function transfer(address dst, uint256 wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(
address src,
address dst,
uint256 wad
) public returns (bool) {
require(balanceOf[src] >= wad);
if (src != msg.sender && allowance[src][msg.sender] != uint256(-1)) {
require(allowance[src][msg.sender] >= wad);
allowance[src][msg.sender] -= wad;
}
balanceOf[src] -= wad;
balanceOf[dst] += wad;
emit Transfer(src, dst, wad);
return true;
}
}
/*
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../common/FeePayer.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../oracle/interfaces/IdentifierWhitelistInterface.sol";
import "../../oracle/interfaces/OracleInterface.sol";
import "../../oracle/implementation/ContractCreator.sol";
/**
* @title Token Deposit Box
* @notice This is a minimal example of a financial template that depends on price requests from the DVM.
* This contract should be thought of as a "Deposit Box" into which the user deposits some ERC20 collateral.
* The main feature of this box is that the user can withdraw their ERC20 corresponding to a desired USD amount.
* When the user wants to make a withdrawal, a price request is enqueued with the UMA DVM.
* For simplicty, the user is constrained to have one outstanding withdrawal request at any given time.
* Regular fees are charged on the collateral in the deposit box throughout the lifetime of the deposit box,
* and final fees are charged on each price request.
*
* This example is intended to accompany a technical tutorial for how to integrate the DVM into a project.
* The main feature this demo serves to showcase is how to build a financial product on-chain that "pulls" price
* requests from the DVM on-demand, which is an implementation of the "priceless" oracle framework.
*
* The typical user flow would be:
* - User sets up a deposit box for the (wETH - USD) price-identifier. The "collateral currency" in this deposit
* box is therefore wETH.
* The user can subsequently make withdrawal requests for USD-denominated amounts of wETH.
* - User deposits 10 wETH into their deposit box.
* - User later requests to withdraw $100 USD of wETH.
* - DepositBox asks DVM for latest wETH/USD exchange rate.
* - DVM resolves the exchange rate at: 1 wETH is worth 200 USD.
* - DepositBox transfers 0.5 wETH to user.
*/
contract DepositBox is FeePayer, ContractCreator {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
// Represents a single caller's deposit box. All collateral is held by this contract.
struct DepositBoxData {
// Requested amount of collateral, denominated in quote asset of the price identifier.
// Example: If the price identifier is wETH-USD, and the `withdrawalRequestAmount = 100`, then
// this represents a withdrawal request for 100 USD worth of wETH.
FixedPoint.Unsigned withdrawalRequestAmount;
// Timestamp of the latest withdrawal request. A withdrawal request is pending if `requestPassTimestamp != 0`.
uint256 requestPassTimestamp;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
FixedPoint.Unsigned rawCollateral;
}
// Maps addresses to their deposit boxes. Each address can have only one position.
mapping(address => DepositBoxData) private depositBoxes;
// Unique identifier for DVM price feed ticker.
bytes32 private priceIdentifier;
// Similar to the rawCollateral in DepositBoxData, this value should not be used directly.
// _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned private rawTotalDepositBoxCollateral;
// This blocks every public state-modifying method until it flips to true, via the `initialize()` method.
bool private initialized;
/****************************************
* EVENTS *
****************************************/
event NewDepositBox(address indexed user);
event EndedDepositBox(address indexed user);
event Deposit(address indexed user, uint256 indexed collateralAmount);
event RequestWithdrawal(address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp);
event RequestWithdrawalExecuted(
address indexed user,
uint256 indexed collateralAmount,
uint256 exchangeRate,
uint256 requestPassTimestamp
);
event RequestWithdrawalCanceled(
address indexed user,
uint256 indexed collateralAmount,
uint256 requestPassTimestamp
);
/****************************************
* MODIFIERS *
****************************************/
modifier noPendingWithdrawal(address user) {
_depositBoxHasNoPendingWithdrawal(user);
_;
}
modifier isInitialized() {
_isInitialized();
_;
}
/****************************************
* PUBLIC FUNCTIONS *
****************************************/
/**
* @notice Construct the DepositBox.
* @param _collateralAddress ERC20 token to be deposited.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM, used to price the ERC20 deposited.
* The price identifier consists of a "base" asset and a "quote" asset. The "base" asset corresponds to the collateral ERC20
* currency deposited into this account, and it is denominated in the "quote" asset on withdrawals.
* An example price identifier would be "ETH-USD" which will resolve and return the USD price of ETH.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
address _collateralAddress,
address _finderAddress,
bytes32 _priceIdentifier,
address _timerAddress
)
public
ContractCreator(_finderAddress)
FeePayer(_collateralAddress, _finderAddress, _timerAddress)
nonReentrant()
{
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier");
priceIdentifier = _priceIdentifier;
}
/**
* @notice This should be called after construction of the DepositBox and handles registration with the Registry, which is required
* to make price requests in production environments.
* @dev This contract must hold the `ContractCreator` role with the Registry in order to register itself as a financial-template with the DVM.
* Note that `_registerContract` cannot be called from the constructor because this contract first needs to be given the `ContractCreator` role
* in order to register with the `Registry`. But, its address is not known until after deployment.
*/
function initialize() public nonReentrant() {
initialized = true;
_registerContract(new address[](0), address(this));
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into caller's deposit box.
* @dev This contract must be approved to spend at least `collateralAmount` of `collateralCurrency`.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function deposit(FixedPoint.Unsigned memory collateralAmount) public isInitialized() fees() nonReentrant() {
require(collateralAmount.isGreaterThan(0), "Invalid collateral amount");
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
if (_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isEqual(0)) {
emit NewDepositBox(msg.sender);
}
// Increase the individual deposit box and global collateral balance by collateral amount.
_incrementCollateralBalances(depositBoxData, collateralAmount);
emit Deposit(msg.sender, collateralAmount.rawValue);
// Move collateral currency from sender to contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
}
/**
* @notice Starts a withdrawal request that allows the sponsor to withdraw `denominatedCollateralAmount`
* from their position denominated in the quote asset of the price identifier, following a DVM price resolution.
* @dev The request will be pending for the duration of the DVM vote and can be cancelled at any time.
* Only one withdrawal request can exist for the user.
* @param denominatedCollateralAmount the quote-asset denominated amount of collateral requested to withdraw.
*/
function requestWithdrawal(FixedPoint.Unsigned memory denominatedCollateralAmount)
public
isInitialized()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
require(denominatedCollateralAmount.isGreaterThan(0), "Invalid collateral amount");
// Update the position object for the user.
depositBoxData.withdrawalRequestAmount = denominatedCollateralAmount;
depositBoxData.requestPassTimestamp = getCurrentTime();
emit RequestWithdrawal(msg.sender, denominatedCollateralAmount.rawValue, depositBoxData.requestPassTimestamp);
// Every price request costs a fixed fee. Check that this user has enough deposited to cover the final fee.
FixedPoint.Unsigned memory finalFee = _computeFinalFees();
require(
_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isGreaterThanOrEqual(finalFee),
"Cannot pay final fee"
);
_payFinalFees(address(this), finalFee);
// A price request is sent for the current timestamp.
_requestOraclePrice(depositBoxData.requestPassTimestamp);
}
/**
* @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and subsequent DVM price resolution),
* withdraws `depositBoxData.withdrawalRequestAmount` of collateral currency denominated in the quote asset.
* @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested
* amount exceeds the collateral in the position (due to paying fees).
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function executeWithdrawal()
external
isInitialized()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
require(
depositBoxData.requestPassTimestamp != 0 && depositBoxData.requestPassTimestamp <= getCurrentTime(),
"Invalid withdraw request"
);
// Get the resolved price or revert.
FixedPoint.Unsigned memory exchangeRate = _getOraclePrice(depositBoxData.requestPassTimestamp);
// Calculate denomated amount of collateral based on resolved exchange rate.
// Example 1: User wants to withdraw $100 of ETH, exchange rate is $200/ETH, therefore user to receive 0.5 ETH.
// Example 2: User wants to withdraw $250 of ETH, exchange rate is $200/ETH, therefore user to receive 1.25 ETH.
FixedPoint.Unsigned memory denominatedAmountToWithdraw =
depositBoxData.withdrawalRequestAmount.div(exchangeRate);
// If withdrawal request amount is > collateral, then withdraw the full collateral amount and delete the deposit box data.
if (denominatedAmountToWithdraw.isGreaterThan(_getFeeAdjustedCollateral(depositBoxData.rawCollateral))) {
denominatedAmountToWithdraw = _getFeeAdjustedCollateral(depositBoxData.rawCollateral);
// Reset the position state as all the value has been removed after settlement.
emit EndedDepositBox(msg.sender);
}
// Decrease the individual deposit box and global collateral balance.
amountWithdrawn = _decrementCollateralBalances(depositBoxData, denominatedAmountToWithdraw);
emit RequestWithdrawalExecuted(
msg.sender,
amountWithdrawn.rawValue,
exchangeRate.rawValue,
depositBoxData.requestPassTimestamp
);
// Reset withdrawal request by setting withdrawal request timestamp to 0.
_resetWithdrawalRequest(depositBoxData);
// Transfer approved withdrawal amount from the contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Cancels a pending withdrawal request.
*/
function cancelWithdrawal() external isInitialized() nonReentrant() {
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
require(depositBoxData.requestPassTimestamp != 0, "No pending withdrawal");
emit RequestWithdrawalCanceled(
msg.sender,
depositBoxData.withdrawalRequestAmount.rawValue,
depositBoxData.requestPassTimestamp
);
// Reset withdrawal request by setting withdrawal request timestamp to 0.
_resetWithdrawalRequest(depositBoxData);
}
/**
* @notice `emergencyShutdown` and `remargin` are required to be implemented by all financial contracts and exposed to the DVM, but
* because this is a minimal demo they will simply exit silently.
*/
function emergencyShutdown() external override isInitialized() nonReentrant() {
return;
}
/**
* @notice Same comment as `emergencyShutdown`. For the sake of simplicity, this will simply exit silently.
*/
function remargin() external override isInitialized() nonReentrant() {
return;
}
/**
* @notice Accessor method for a user's collateral.
* @dev This is necessary because the struct returned by the depositBoxes() method shows
* rawCollateral, which isn't a user-readable value.
* @param user address whose collateral amount is retrieved.
* @return the fee-adjusted collateral amount in the deposit box (i.e. available for withdrawal).
*/
function getCollateral(address user) external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(depositBoxes[user].rawCollateral);
}
/**
* @notice Accessor method for the total collateral stored within the entire contract.
* @return the total fee-adjusted collateral amount in the contract (i.e. across all users).
*/
function totalDepositBoxCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Requests a price for `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePrice(uint256 requestedTime) internal {
OracleInterface oracle = _getOracle();
oracle.requestPrice(priceIdentifier, requestedTime);
}
// Ensure individual and global consistency when increasing collateral balances. Returns the change to the position.
function _incrementCollateralBalances(
DepositBoxData storage depositBoxData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_addCollateral(depositBoxData.rawCollateral, collateralAmount);
return _addCollateral(rawTotalDepositBoxCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the
// position. We elect to return the amount that the global collateral is decreased by, rather than the individual
// position's collateral, because we need to maintain the invariant that the global collateral is always
// <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn.
function _decrementCollateralBalances(
DepositBoxData storage depositBoxData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(depositBoxData.rawCollateral, collateralAmount);
return _removeCollateral(rawTotalDepositBoxCollateral, collateralAmount);
}
function _resetWithdrawalRequest(DepositBoxData storage depositBoxData) internal {
depositBoxData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0);
depositBoxData.requestPassTimestamp = 0;
}
function _depositBoxHasNoPendingWithdrawal(address user) internal view {
require(depositBoxes[user].requestPassTimestamp == 0, "Pending withdrawal");
}
function _isInitialized() internal view {
require(initialized, "Uninitialized contract");
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getOracle() internal view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) {
OracleInterface oracle = _getOracle();
require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price");
int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime);
// For simplicity we don't want to deal with negative prices.
if (oraclePrice < 0) {
oraclePrice = 0;
}
return FixedPoint.Unsigned(uint256(oraclePrice));
}
// `_pfc()` is inherited from FeePayer and must be implemented to return the available pool of collateral from
// which fees can be charged. For this contract, the available fee pool is simply all of the collateral locked up in the
// contract.
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/**
* @title Interface for whitelists of supported identifiers that the oracle can provide prices for.
*/
interface IdentifierWhitelistInterface {
/**
* @notice Adds the provided identifier as a supported identifier.
* @dev Price requests using this identifier will succeed after this call.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
*/
function addSupportedIdentifier(bytes32 identifier) external;
/**
* @notice Removes the identifier from the whitelist.
* @dev Price requests using this identifier will no longer succeed after this call.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
*/
function removeSupportedIdentifier(bytes32 identifier) external;
/**
* @notice Checks whether an identifier is on the whitelist.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
* @return bool if the identifier is supported (or not).
*/
function isIdentifierSupported(bytes32 identifier) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OracleInterface {
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
*/
function requestPrice(bytes32 identifier, uint256 time) public virtual;
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @return bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(bytes32 identifier, uint256 time) public view virtual returns (bool);
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(bytes32 identifier, uint256 time) public view virtual returns (int256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/FinderInterface.sol";
import "../../common/implementation/AddressWhitelist.sol";
import "./Registry.sol";
import "./Constants.sol";
/**
* @title Base contract for all financial contract creators
*/
abstract contract ContractCreator {
address internal finderAddress;
constructor(address _finderAddress) public {
finderAddress = _finderAddress;
}
function _requireWhitelistedCollateral(address collateralAddress) internal view {
FinderInterface finder = FinderInterface(finderAddress);
AddressWhitelist collateralWhitelist =
AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist));
require(collateralWhitelist.isOnWhitelist(collateralAddress), "Collateral not whitelisted");
}
function _registerContract(address[] memory parties, address contractToRegister) internal {
FinderInterface finder = FinderInterface(finderAddress);
Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry));
registry.registerContract(parties, contractToRegister);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/MultiRole.sol";
import "../interfaces/RegistryInterface.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title Registry for financial contracts and approved financial contract creators.
* @dev Maintains a whitelist of financial contract creators that are allowed
* to register new financial contracts and stores party members of a financial contract.
*/
contract Registry is RegistryInterface, MultiRole {
using SafeMath for uint256;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Owner, // The owner manages the set of ContractCreators.
ContractCreator // Can register financial contracts.
}
// This enum is required because a `WasValid` state is required
// to ensure that financial contracts cannot be re-registered.
enum Validity { Invalid, Valid }
// Local information about a contract.
struct FinancialContract {
Validity valid;
uint128 index;
}
struct Party {
address[] contracts; // Each financial contract address is stored in this array.
// The address of each financial contract is mapped to its index for constant time look up and deletion.
mapping(address => uint256) contractIndex;
}
// Array of all contracts that are approved to use the UMA Oracle.
address[] public registeredContracts;
// Map of financial contract contracts to the associated FinancialContract struct.
mapping(address => FinancialContract) public contractMap;
// Map each party member to their their associated Party struct.
mapping(address => Party) private partyMap;
/****************************************
* EVENTS *
****************************************/
event NewContractRegistered(address indexed contractAddress, address indexed creator, address[] parties);
event PartyAdded(address indexed contractAddress, address indexed party);
event PartyRemoved(address indexed contractAddress, address indexed party);
/**
* @notice Construct the Registry contract.
*/
constructor() public {
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
// Start with no contract creators registered.
_createSharedRole(uint256(Roles.ContractCreator), uint256(Roles.Owner), new address[](0));
}
/****************************************
* REGISTRATION FUNCTIONS *
****************************************/
/**
* @notice Registers a new financial contract.
* @dev Only authorized contract creators can call this method.
* @param parties array of addresses who become parties in the contract.
* @param contractAddress address of the contract against which the parties are registered.
*/
function registerContract(address[] calldata parties, address contractAddress)
external
override
onlyRoleHolder(uint256(Roles.ContractCreator))
{
FinancialContract storage financialContract = contractMap[contractAddress];
require(contractMap[contractAddress].valid == Validity.Invalid, "Can only register once");
// Store contract address as a registered contract.
registeredContracts.push(contractAddress);
// No length check necessary because we should never hit (2^127 - 1) contracts.
financialContract.index = uint128(registeredContracts.length.sub(1));
// For all parties in the array add them to the contract's parties.
financialContract.valid = Validity.Valid;
for (uint256 i = 0; i < parties.length; i = i.add(1)) {
_addPartyToContract(parties[i], contractAddress);
}
emit NewContractRegistered(contractAddress, msg.sender, parties);
}
/**
* @notice Adds a party member to the calling contract.
* @dev msg.sender will be used to determine the contract that this party is added to.
* @param party new party for the calling contract.
*/
function addPartyToContract(address party) external override {
address contractAddress = msg.sender;
require(contractMap[contractAddress].valid == Validity.Valid, "Can only add to valid contract");
_addPartyToContract(party, contractAddress);
}
/**
* @notice Removes a party member from the calling contract.
* @dev msg.sender will be used to determine the contract that this party is removed from.
* @param partyAddress address to be removed from the calling contract.
*/
function removePartyFromContract(address partyAddress) external override {
address contractAddress = msg.sender;
Party storage party = partyMap[partyAddress];
uint256 numberOfContracts = party.contracts.length;
require(numberOfContracts != 0, "Party has no contracts");
require(contractMap[contractAddress].valid == Validity.Valid, "Remove only from valid contract");
require(isPartyMemberOfContract(partyAddress, contractAddress), "Can only remove existing party");
// Index of the current location of the contract to remove.
uint256 deleteIndex = party.contractIndex[contractAddress];
// Store the last contract's address to update the lookup map.
address lastContractAddress = party.contracts[numberOfContracts - 1];
// Swap the contract to be removed with the last contract.
party.contracts[deleteIndex] = lastContractAddress;
// Update the lookup index with the new location.
party.contractIndex[lastContractAddress] = deleteIndex;
// Pop the last contract from the array and update the lookup map.
party.contracts.pop();
delete party.contractIndex[contractAddress];
emit PartyRemoved(contractAddress, partyAddress);
}
/****************************************
* REGISTRY STATE GETTERS *
****************************************/
/**
* @notice Returns whether the contract has been registered with the registry.
* @dev If it is registered, it is an authorized participant in the UMA system.
* @param contractAddress address of the financial contract.
* @return bool indicates whether the contract is registered.
*/
function isContractRegistered(address contractAddress) external view override returns (bool) {
return contractMap[contractAddress].valid == Validity.Valid;
}
/**
* @notice Returns a list of all contracts that are associated with a particular party.
* @param party address of the party.
* @return an array of the contracts the party is registered to.
*/
function getRegisteredContracts(address party) external view override returns (address[] memory) {
return partyMap[party].contracts;
}
/**
* @notice Returns all registered contracts.
* @return all registered contract addresses within the system.
*/
function getAllRegisteredContracts() external view override returns (address[] memory) {
return registeredContracts;
}
/**
* @notice checks if an address is a party of a contract.
* @param party party to check.
* @param contractAddress address to check against the party.
* @return bool indicating if the address is a party of the contract.
*/
function isPartyMemberOfContract(address party, address contractAddress) public view override returns (bool) {
uint256 index = partyMap[party].contractIndex[contractAddress];
return partyMap[party].contracts.length > index && partyMap[party].contracts[index] == contractAddress;
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
function _addPartyToContract(address party, address contractAddress) internal {
require(!isPartyMemberOfContract(party, contractAddress), "Can only register a party once");
uint256 contractIndex = partyMap[party].contracts.length;
partyMap[party].contracts.push(contractAddress);
partyMap[party].contractIndex[contractAddress] = contractIndex;
emit PartyAdded(contractAddress, party);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/**
* @title Interface for a registry of contracts and contract creators.
*/
interface RegistryInterface {
/**
* @notice Registers a new contract.
* @dev Only authorized contract creators can call this method.
* @param parties an array of addresses who become parties in the contract.
* @param contractAddress defines the address of the deployed contract.
*/
function registerContract(address[] calldata parties, address contractAddress) external;
/**
* @notice Returns whether the contract has been registered with the registry.
* @dev If it is registered, it is an authorized participant in the UMA system.
* @param contractAddress address of the contract.
* @return bool indicates whether the contract is registered.
*/
function isContractRegistered(address contractAddress) external view returns (bool);
/**
* @notice Returns a list of all contracts that are associated with a particular party.
* @param party address of the party.
* @return an array of the contracts the party is registered to.
*/
function getRegisteredContracts(address party) external view returns (address[] memory);
/**
* @notice Returns all registered contracts.
* @return all registered contract addresses within the system.
*/
function getAllRegisteredContracts() external view returns (address[] memory);
/**
* @notice Adds a party to the calling contract.
* @dev msg.sender must be the contract to which the party member is added.
* @param party address to be added to the contract.
*/
function addPartyToContract(address party) external;
/**
* @notice Removes a party member to the calling contract.
* @dev msg.sender must be the contract to which the party member is added.
* @param party address to be removed from the contract.
*/
function removePartyFromContract(address party) external;
/**
* @notice checks if an address is a party in a contract.
* @param party party to check.
* @param contractAddress address to check against the party.
* @return bool indicating if the address is a party of the contract.
*/
function isPartyMemberOfContract(address party, address contractAddress) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./Liquidatable.sol";
/**
* @title Expiring Multi Party.
* @notice Convenient wrapper for Liquidatable.
*/
contract ExpiringMultiParty is Liquidatable {
/**
* @notice Constructs the ExpiringMultiParty contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PricelessPositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
Liquidatable(params)
// Note: since there is no logic here, there is no need to add a re-entrancy guard.
{
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "./PricelessPositionManager.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title Liquidatable
* @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position.
* @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the
* liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on
* a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false
* liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a
* prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute.
*/
contract Liquidatable is PricelessPositionManager {
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
/****************************************
* LIQUIDATION DATA STRUCTURES *
****************************************/
// Because of the check in withdrawable(), the order of these enum values should not change.
enum Status { Uninitialized, PreDispute, PendingDispute, DisputeSucceeded, DisputeFailed }
struct LiquidationData {
// Following variables set upon creation of liquidation:
address sponsor; // Address of the liquidated position's sponsor
address liquidator; // Address who created this liquidation
Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved
uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle
// Following variables determined by the position that is being liquidated:
FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute
FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute
// Amount of collateral being liquidated, which could be different from
// lockedCollateral if there were pending withdrawals at the time of liquidation
FixedPoint.Unsigned liquidatedCollateral;
// Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation.
FixedPoint.Unsigned rawUnitCollateral;
// Following variable set upon initiation of a dispute:
address disputer; // Person who is disputing a liquidation
// Following variable set upon a resolution of a dispute:
FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute
FixedPoint.Unsigned finalFee;
}
// Define the contract's constructor parameters as a struct to enable more variables to be specified.
// This is required to enable more params, over and above Solidity's limits.
struct ConstructorParams {
// Params for PricelessPositionManager only.
uint256 expirationTimestamp;
uint256 withdrawalLiveness;
address collateralAddress;
address tokenAddress;
address finderAddress;
address timerAddress;
address financialProductLibraryAddress;
bytes32 priceFeedIdentifier;
FixedPoint.Unsigned minSponsorTokens;
// Params specifically for Liquidatable.
uint256 liquidationLiveness;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPct;
FixedPoint.Unsigned sponsorDisputeRewardPct;
FixedPoint.Unsigned disputerDisputeRewardPct;
}
// This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards.
// `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ
// from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the
// fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error.
struct RewardsData {
FixedPoint.Unsigned payToSponsor;
FixedPoint.Unsigned payToLiquidator;
FixedPoint.Unsigned payToDisputer;
FixedPoint.Unsigned paidToSponsor;
FixedPoint.Unsigned paidToLiquidator;
FixedPoint.Unsigned paidToDisputer;
}
// Liquidations are unique by ID per sponsor
mapping(address => LiquidationData[]) public liquidations;
// Total collateral in liquidation.
FixedPoint.Unsigned public rawLiquidationCollateral;
// Immutable contract parameters:
// Amount of time for pending liquidation before expiry.
// !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors.
// Extremely low liveness values increase the chance that opportunistic invalid liquidations
// expire without dispute, thereby decreasing the usability for sponsors and increasing the risk
// for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic
// token holder for the contract.
uint256 public liquidationLiveness;
// Required collateral:TRV ratio for a position to be considered sufficiently collateralized.
FixedPoint.Unsigned public collateralRequirement;
// Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer
// Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%"
FixedPoint.Unsigned public disputeBondPct;
// Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public sponsorDisputeRewardPct;
// Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public disputerDisputeRewardPct;
/****************************************
* EVENTS *
****************************************/
event LiquidationCreated(
address indexed sponsor,
address indexed liquidator,
uint256 indexed liquidationId,
uint256 tokensOutstanding,
uint256 lockedCollateral,
uint256 liquidatedCollateral,
uint256 liquidationTime
);
event LiquidationDisputed(
address indexed sponsor,
address indexed liquidator,
address indexed disputer,
uint256 liquidationId,
uint256 disputeBondAmount
);
event DisputeSettled(
address indexed caller,
address indexed sponsor,
address indexed liquidator,
address disputer,
uint256 liquidationId,
bool disputeSucceeded
);
event LiquidationWithdrawn(
address indexed caller,
uint256 paidToLiquidator,
uint256 paidToDisputer,
uint256 paidToSponsor,
Status indexed liquidationStatus,
uint256 settlementPrice
);
/****************************************
* MODIFIERS *
****************************************/
modifier disputable(uint256 liquidationId, address sponsor) {
_disputable(liquidationId, sponsor);
_;
}
modifier withdrawable(uint256 liquidationId, address sponsor) {
_withdrawable(liquidationId, sponsor);
_;
}
/**
* @notice Constructs the liquidatable contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PricelessPositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
PricelessPositionManager(
params.expirationTimestamp,
params.withdrawalLiveness,
params.collateralAddress,
params.tokenAddress,
params.finderAddress,
params.priceFeedIdentifier,
params.minSponsorTokens,
params.timerAddress,
params.financialProductLibraryAddress
)
nonReentrant()
{
require(params.collateralRequirement.isGreaterThan(1), "CR must be more than 100%");
require(
params.sponsorDisputeRewardPct.add(params.disputerDisputeRewardPct).isLessThan(1),
"Rewards are more than 100%"
);
// Set liquidatable specific variables.
liquidationLiveness = params.liquidationLiveness;
collateralRequirement = params.collateralRequirement;
disputeBondPct = params.disputeBondPct;
sponsorDisputeRewardPct = params.sponsorDisputeRewardPct;
disputerDisputeRewardPct = params.disputerDisputeRewardPct;
}
/****************************************
* LIQUIDATION FUNCTIONS *
****************************************/
/**
* @notice Liquidates the sponsor's position if the caller has enough
* synthetic tokens to retire the position's outstanding tokens. Liquidations above
* a minimum size also reset an ongoing "slow withdrawal"'s liveness.
* @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be
* approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param sponsor address of the sponsor to liquidate.
* @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value.
* @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value.
* @param maxTokensToLiquidate max number of tokens to liquidate.
* @param deadline abort the liquidation if the transaction is mined after this timestamp.
* @return liquidationId ID of the newly created liquidation.
* @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position.
* @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully.
*/
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
fees()
onlyPreExpiration()
nonReentrant()
returns (
uint256 liquidationId,
FixedPoint.Unsigned memory tokensLiquidated,
FixedPoint.Unsigned memory finalFeeBond
)
{
// Check that this transaction was mined pre-deadline.
require(getCurrentTime() <= deadline, "Mined after deadline");
// Retrieve Position data for sponsor
PositionData storage positionToLiquidate = _getPositionData(sponsor);
tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding);
require(tokensLiquidated.isGreaterThan(0));
// Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral,
// then set this to 0, otherwise set it to (startCollateral - withdrawal request amount).
FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral);
FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0);
if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) {
startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount);
}
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding;
// The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken].
// maxCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal),
"CR is more than max liq. price"
);
// minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal),
"CR is less than min liq. price"
);
}
// Compute final fee at time of liquidation.
finalFeeBond = _computeFinalFees();
// These will be populated within the scope below.
FixedPoint.Unsigned memory lockedCollateral;
FixedPoint.Unsigned memory liquidatedCollateral;
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding);
// The actual amount of collateral that gets moved to the liquidation.
lockedCollateral = startCollateral.mul(ratio);
// For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of
// withdrawal requests.
liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio);
// Part of the withdrawal request is also removed. Ideally:
// liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral.
FixedPoint.Unsigned memory withdrawalAmountToRemove =
positionToLiquidate.withdrawalRequestAmount.mul(ratio);
_reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove);
}
// Add to the global liquidation collateral count.
_addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond));
// Construct liquidation object.
// Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new
// LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push.
liquidationId = liquidations[sponsor].length;
liquidations[sponsor].push(
LiquidationData({
sponsor: sponsor,
liquidator: msg.sender,
state: Status.PreDispute,
liquidationTime: getCurrentTime(),
tokensOutstanding: tokensLiquidated,
lockedCollateral: lockedCollateral,
liquidatedCollateral: liquidatedCollateral,
rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)),
disputer: address(0),
settlementPrice: FixedPoint.fromUnscaledUint(0),
finalFee: finalFeeBond
})
);
// If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than
// some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be
// "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold
// is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal.
// We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter
// denominated in token currency units and we can avoid adding another parameter.
FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens;
if (
positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal.
positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired.
tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold".
) {
positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness);
}
emit LiquidationCreated(
sponsor,
msg.sender,
liquidationId,
tokensLiquidated.rawValue,
lockedCollateral.rawValue,
liquidatedCollateral.rawValue,
getCurrentTime()
);
// Destroy tokens
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue);
tokenCurrency.burn(tokensLiquidated.rawValue);
// Pull final fee from liquidator.
collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue);
}
/**
* @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond
* and pay a fixed final fee charged on each price request.
* @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes.
* This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute
* bond amount is calculated from `disputeBondPct` times the collateral in the liquidation.
* @param liquidationId of the disputed liquidation.
* @param sponsor the address of the sponsor whose liquidation is being disputed.
* @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond).
*/
function dispute(uint256 liquidationId, address sponsor)
external
disputable(liquidationId, sponsor)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalPaid)
{
LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId);
// Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees.
FixedPoint.Unsigned memory disputeBondAmount =
disputedLiquidation.lockedCollateral.mul(disputeBondPct).mul(
_getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral)
);
_addCollateral(rawLiquidationCollateral, disputeBondAmount);
// Request a price from DVM. Liquidation is pending dispute until DVM returns a price.
disputedLiquidation.state = Status.PendingDispute;
disputedLiquidation.disputer = msg.sender;
// Enqueue a request with the DVM.
_requestOraclePriceLiquidation(disputedLiquidation.liquidationTime);
emit LiquidationDisputed(
sponsor,
disputedLiquidation.liquidator,
msg.sender,
liquidationId,
disputeBondAmount.rawValue
);
totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee);
// Pay the final fee for requesting price from the DVM.
_payFinalFees(msg.sender, disputedLiquidation.finalFee);
// Transfer the dispute bond amount from the caller to this contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue);
}
/**
* @notice After a dispute has settled or after a non-disputed liquidation has expired,
* anyone can call this method to disperse payments to the sponsor, liquidator, and disdputer.
* @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment.
* If the dispute FAILED: only the liquidator can receive payment.
* This method will revert if rewards have already been dispersed.
* @param liquidationId uniquely identifies the sponsor's liquidation.
* @param sponsor address of the sponsor associated with the liquidation.
* @return data about rewards paid out.
*/
function withdrawLiquidation(uint256 liquidationId, address sponsor)
public
withdrawable(liquidationId, sponsor)
fees()
nonReentrant()
returns (RewardsData memory)
{
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settles the liquidation if necessary. This call will revert if the price has not resolved yet.
_settle(liquidationId, sponsor);
// Calculate rewards as a function of the TRV.
// Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata.
FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral);
FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice;
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation);
FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation);
FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPct.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPct.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPct);
FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation);
// There are three main outcome states: either the dispute succeeded, failed or was not updated.
// Based on the state, different parties of a liquidation receive different amounts.
// After assigning rewards based on the liquidation status, decrease the total collateral held in this contract
// by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes
// precision loss.
RewardsData memory rewards;
if (liquidation.state == Status.DisputeSucceeded) {
// If the dispute is successful then all three users should receive rewards:
// Pay DISPUTER: disputer reward + dispute bond + returned final fee
rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee);
// Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward
rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue));
// Pay LIQUIDATOR: TRV - dispute reward - sponsor reward
// If TRV > Collateral, then subtract rewards from collateral
// NOTE: This should never be below zero since we prevent (sponsorDisputePct+disputerDisputePct) >= 0 in
// the constructor when these params are set.
rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor);
rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer);
collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue);
// In the case of a failed dispute only the liquidator can withdraw.
} else if (liquidation.state == Status.DisputeFailed) {
// Pay LIQUIDATOR: collateral + dispute bond + returned final fee
rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
// If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this
// state as a dispute failed and the liquidator can withdraw.
} else if (liquidation.state == Status.PreDispute) {
// Pay LIQUIDATOR: collateral + returned final fee
rewards.payToLiquidator = collateral.add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
}
emit LiquidationWithdrawn(
msg.sender,
rewards.paidToLiquidator.rawValue,
rewards.paidToDisputer.rawValue,
rewards.paidToSponsor.rawValue,
liquidation.state,
settlementPrice.rawValue
);
// Free up space after collateral is withdrawn by removing the liquidation object from the array.
delete liquidations[sponsor][liquidationId];
return rewards;
}
/**
* @notice Gets all liquidation information for a given sponsor address.
* @param sponsor address of the position sponsor.
* @return liquidationData array of all liquidation information for the given sponsor address.
*/
function getLiquidations(address sponsor)
external
view
nonReentrantView()
returns (LiquidationData[] memory liquidationData)
{
return liquidations[sponsor];
}
/**
* @notice Accessor method to calculate a transformed collateral requirement using the finanical product library
specified during contract deployment. If no library was provided then no modification to the collateral requirement is done.
* @param price input price used as an input to transform the collateral requirement.
* @return transformedCollateralRequirement collateral requirement with transformation applied to it.
* @dev This method should never revert.
*/
function transformCollateralRequirement(FixedPoint.Unsigned memory price)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return _transformCollateralRequirement(price);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// This settles a liquidation if it is in the PendingDispute state. If not, it will immediately return.
// If the liquidation is in the PendingDispute state, but a price is not available, this will revert.
function _settle(uint256 liquidationId, address sponsor) internal {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settlement only happens when state == PendingDispute and will only happen once per liquidation.
// If this liquidation is not ready to be settled, this method should return immediately.
if (liquidation.state != Status.PendingDispute) {
return;
}
// Get the returned price from the oracle. If this has not yet resolved will revert.
liquidation.settlementPrice = _getOraclePriceLiquidation(liquidation.liquidationTime);
// Find the value of the tokens in the underlying collateral.
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(liquidation.settlementPrice);
// The required collateral is the value of the tokens in underlying * required collateral ratio. The Transform
// Collateral requirement method applies a from the financial Product library to change the scaled the collateral
// requirement based on the settlement price. If no library was specified when deploying the emp then this makes no change.
FixedPoint.Unsigned memory requiredCollateral =
tokenRedemptionValue.mul(_transformCollateralRequirement(liquidation.settlementPrice));
// If the position has more than the required collateral it is solvent and the dispute is valid(liquidation is invalid)
// Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals.
bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral);
liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed;
emit DisputeSettled(
msg.sender,
sponsor,
liquidation.liquidator,
liquidation.disputer,
liquidationId,
disputeSucceeded
);
}
function _pfc() internal view override returns (FixedPoint.Unsigned memory) {
return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral));
}
function _getLiquidationData(address sponsor, uint256 liquidationId)
internal
view
returns (LiquidationData storage liquidation)
{
LiquidationData[] storage liquidationArray = liquidations[sponsor];
// Revert if the caller is attempting to access an invalid liquidation
// (one that has never been created or one has never been initialized).
require(
liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized,
"Invalid liquidation ID"
);
return liquidationArray[liquidationId];
}
function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) {
return liquidation.liquidationTime.add(liquidationLiveness);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _disputable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
require(
(getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.PreDispute),
"Liquidation not disputable"
);
}
function _withdrawable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
Status state = liquidation.state;
// Must be disputed or the liquidation has passed expiry.
require(
(state > Status.PreDispute) ||
((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.PreDispute)),
"Liquidation not withdrawable"
);
}
function _transformCollateralRequirement(FixedPoint.Unsigned memory price)
internal
view
returns (FixedPoint.Unsigned memory)
{
if (!address(financialProductLibrary).isContract()) return collateralRequirement;
try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns (
FixedPoint.Unsigned memory transformedCollateralRequirement
) {
return transformedCollateralRequirement;
} catch {
return collateralRequirement;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/interfaces/IERC20Standard.sol";
import "../../oracle/interfaces/OracleInterface.sol";
import "../../oracle/interfaces/OptimisticOracleInterface.sol";
import "../../oracle/interfaces/IdentifierWhitelistInterface.sol";
import "../../oracle/implementation/Constants.sol";
import "../common/FeePayer.sol";
import "../common/financial-product-libraries/FinancialProductLibrary.sol";
/**
* @title Financial contract with priceless position management.
* @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying
* on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token.
*/
contract PricelessPositionManager is FeePayer {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
using SafeERC20 for ExpandedIERC20;
using Address for address;
/****************************************
* PRICELESS POSITION DATA STRUCTURES *
****************************************/
// Stores the state of the PricelessPositionManager. Set on expiration, emergency shutdown, or settlement.
enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived }
ContractState public contractState;
// Represents a single sponsor's position. All collateral is held by this contract.
// This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor.
struct PositionData {
FixedPoint.Unsigned tokensOutstanding;
// Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`.
uint256 withdrawalRequestPassTimestamp;
FixedPoint.Unsigned withdrawalRequestAmount;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
FixedPoint.Unsigned rawCollateral;
// Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`.
uint256 transferPositionRequestPassTimestamp;
}
// Maps sponsor addresses to their positions. Each sponsor can have only one position.
mapping(address => PositionData) public positions;
// Keep track of the total collateral and tokens across all positions to enable calculating the
// global collateralization ratio without iterating over all positions.
FixedPoint.Unsigned public totalTokensOutstanding;
// Similar to the rawCollateral in PositionData, this value should not be used directly.
// _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned public rawTotalPositionCollateral;
// Synthetic token created by this contract.
ExpandedIERC20 public tokenCurrency;
// Unique identifier for DVM price feed ticker.
bytes32 public priceIdentifier;
// Time that this contract expires. Should not change post-construction unless an emergency shutdown occurs.
uint256 public expirationTimestamp;
// Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur.
// !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract.
// Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests
// expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent
// contract is extremely risky for any sponsor or synthetic token holder for the contract.
uint256 public withdrawalLiveness;
// Minimum number of tokens in a sponsor's position.
FixedPoint.Unsigned public minSponsorTokens;
// The expiry price pulled from the DVM.
FixedPoint.Unsigned public expiryPrice;
// Instance of FinancialProductLibrary to provide custom price and collateral requirement transformations to extend
// the functionality of the EMP to support a wider range of financial products.
FinancialProductLibrary public financialProductLibrary;
/****************************************
* EVENTS *
****************************************/
event RequestTransferPosition(address indexed oldSponsor);
event RequestTransferPositionExecuted(address indexed oldSponsor, address indexed newSponsor);
event RequestTransferPositionCanceled(address indexed oldSponsor);
event Deposit(address indexed sponsor, uint256 indexed collateralAmount);
event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount);
event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event NewSponsor(address indexed sponsor);
event EndedSponsorPosition(address indexed sponsor);
event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount);
event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event ContractExpired(address indexed caller);
event SettleExpiredPosition(
address indexed caller,
uint256 indexed collateralReturned,
uint256 indexed tokensBurned
);
event EmergencyShutdown(address indexed caller, uint256 originalExpirationTimestamp, uint256 shutdownTimestamp);
/****************************************
* MODIFIERS *
****************************************/
modifier onlyPreExpiration() {
_onlyPreExpiration();
_;
}
modifier onlyPostExpiration() {
_onlyPostExpiration();
_;
}
modifier onlyCollateralizedPosition(address sponsor) {
_onlyCollateralizedPosition(sponsor);
_;
}
// Check that the current state of the pricelessPositionManager is Open.
// This prevents multiple calls to `expire` and `EmergencyShutdown` post expiration.
modifier onlyOpenState() {
_onlyOpenState();
_;
}
modifier noPendingWithdrawal(address sponsor) {
_positionHasNoPendingWithdrawal(sponsor);
_;
}
/**
* @notice Construct the PricelessPositionManager
* @dev Deployer of this contract should consider carefully which parties have ability to mint and burn
* the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts
* can mint new tokens, which could be used to steal all of this contract's locked collateral.
* We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles)
* is assigned to this contract, whose sole Minter role is assigned to this contract, and whose
* total supply is 0 prior to construction of this contract.
* @param _expirationTimestamp unix timestamp of when the contract will expire.
* @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals.
* @param _collateralAddress ERC20 token used as collateral for all positions.
* @param _tokenAddress ERC20 token used as synthetic token.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM for the synthetic.
* @param _minSponsorTokens minimum amount of collateral that must exist at any time in a position.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
* @param _financialProductLibraryAddress Contract providing contract state transformations.
*/
constructor(
uint256 _expirationTimestamp,
uint256 _withdrawalLiveness,
address _collateralAddress,
address _tokenAddress,
address _finderAddress,
bytes32 _priceIdentifier,
FixedPoint.Unsigned memory _minSponsorTokens,
address _timerAddress,
address _financialProductLibraryAddress
) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() {
require(_expirationTimestamp > getCurrentTime());
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier));
expirationTimestamp = _expirationTimestamp;
withdrawalLiveness = _withdrawalLiveness;
tokenCurrency = ExpandedIERC20(_tokenAddress);
minSponsorTokens = _minSponsorTokens;
priceIdentifier = _priceIdentifier;
// Initialize the financialProductLibrary at the provided address.
financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress);
}
/****************************************
* POSITION FUNCTIONS *
****************************************/
/**
* @notice Requests to transfer ownership of the caller's current position to a new sponsor address.
* Once the request liveness is passed, the sponsor can execute the transfer and specify the new sponsor.
* @dev The liveness length is the same as the withdrawal liveness.
*/
function requestTransferPosition() public onlyPreExpiration() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.transferPositionRequestPassTimestamp == 0);
// Make sure the proposed expiration of this request is not post-expiry.
uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness);
require(requestPassTime < expirationTimestamp);
// Update the position object for the user.
positionData.transferPositionRequestPassTimestamp = requestPassTime;
emit RequestTransferPosition(msg.sender);
}
/**
* @notice After a passed transfer position request (i.e., by a call to `requestTransferPosition` and waiting
* `withdrawalLiveness`), transfers ownership of the caller's current position to `newSponsorAddress`.
* @dev Transferring positions can only occur if the recipient does not already have a position.
* @param newSponsorAddress is the address to which the position will be transferred.
*/
function transferPositionPassedRequest(address newSponsorAddress)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
require(
_getFeeAdjustedCollateral(positions[newSponsorAddress].rawCollateral).isEqual(
FixedPoint.fromUnscaledUint(0)
)
);
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.transferPositionRequestPassTimestamp != 0 &&
positionData.transferPositionRequestPassTimestamp <= getCurrentTime()
);
// Reset transfer request.
positionData.transferPositionRequestPassTimestamp = 0;
positions[newSponsorAddress] = positionData;
delete positions[msg.sender];
emit RequestTransferPositionExecuted(msg.sender, newSponsorAddress);
emit NewSponsor(newSponsorAddress);
emit EndedSponsorPosition(msg.sender);
}
/**
* @notice Cancels a pending transfer position request.
*/
function cancelTransferPosition() external onlyPreExpiration() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.transferPositionRequestPassTimestamp != 0);
emit RequestTransferPositionCanceled(msg.sender);
// Reset withdrawal request.
positionData.transferPositionRequestPassTimestamp = 0;
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param sponsor the sponsor to credit the deposit to.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(sponsor)
fees()
nonReentrant()
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(sponsor);
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
emit Deposit(sponsor, collateralAmount.rawValue);
// Move collateral currency from sender to contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function deposit(FixedPoint.Unsigned memory collateralAmount) public {
// This is just a thin wrapper over depositTo that specified the sender as the sponsor.
depositTo(msg.sender, collateralAmount);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor.
* @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization
* ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss.
* @param collateralAmount is the amount of collateral to withdraw.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdraw(FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(msg.sender);
// Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure
// position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request.
amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount);
emit Withdrawal(msg.sender, amountWithdrawn.rawValue);
// Move collateral currency from contract to sender.
// Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees)
// instead of the user requested amount. This eliminates precision loss that could occur
// where the user withdraws more collateral than rawCollateral is decremented by.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw` from their position.
* @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated.
* @param collateralAmount the amount of collateral requested to withdraw
*/
function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
collateralAmount.isGreaterThan(0) &&
collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral))
);
// Make sure the proposed expiration of this request is not post-expiry.
uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness);
require(requestPassTime < expirationTimestamp, "Request expires post-expiry");
// Update the position object for the user.
positionData.withdrawalRequestPassTimestamp = requestPassTime;
positionData.withdrawalRequestAmount = collateralAmount;
emit RequestWithdrawal(msg.sender, collateralAmount.rawValue);
}
/**
* @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting
* `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency.
* @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested
* amount exceeds the collateral in the position (due to paying fees).
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdrawPassedRequest()
external
onlyPreExpiration()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.withdrawalRequestPassTimestamp != 0 &&
positionData.withdrawalRequestPassTimestamp <= getCurrentTime(),
"Invalid withdraw request"
);
// If withdrawal request amount is > position collateral, then withdraw the full collateral amount.
// This situation is possible due to fees charged since the withdrawal was originally requested.
FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount;
if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) {
amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral);
}
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
// Transfer approved withdrawal amount from the contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Cancels a pending withdrawal request.
*/
function cancelWithdrawal() external nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.withdrawalRequestPassTimestamp != 0, "No pending withdrawal");
emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
}
/**
* @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount` into the sponsor's position and mints `numTokens` of `tokenCurrency`.
* @dev Reverts if minting these tokens would put the position's collateralization ratio below the
* global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of
* `collateralCurrency`.
* @dev This contract must have the Minter role for the `tokenCurrency`.
* @param collateralAmount is the number of collateral tokens to collateralize the position with
* @param numTokens is the number of tokens to mint from the position.
*/
function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens)
public
onlyPreExpiration()
fees()
nonReentrant()
{
PositionData storage positionData = positions[msg.sender];
// Either the new create ratio or the resultant position CR must be above the current GCR.
require(
(_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount),
positionData.tokensOutstanding.add(numTokens)
) || _checkCollateralization(collateralAmount, numTokens)),
"Insufficient collateral"
);
require(positionData.withdrawalRequestPassTimestamp == 0, "Pending withdrawal");
if (positionData.tokensOutstanding.isEqual(0)) {
require(numTokens.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
emit NewSponsor(msg.sender);
}
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
// Add the number of tokens created to the position's outstanding tokens.
positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens);
totalTokensOutstanding = totalTokensOutstanding.add(numTokens);
emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue);
// Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
require(tokenCurrency.mint(msg.sender, numTokens.rawValue));
}
/**
* @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`.
* This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens.
* @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt from the sponsor's debt position.
*/
function repay(FixedPoint.Unsigned memory numTokens)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding));
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens));
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue);
// Transfer the tokens back from the sponsor and burn them.
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`.
* @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral
* in order to account for precision loss. This contract must be approved to spend at least `numTokens` of
* `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function redeem(FixedPoint.Unsigned memory numTokens)
public
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(!numTokens.isGreaterThan(positionData.tokensOutstanding));
FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding);
FixedPoint.Unsigned memory collateralRedeemed =
fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral));
// If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize.
if (positionData.tokensOutstanding.isEqual(numTokens)) {
amountWithdrawn = _deleteSponsorPosition(msg.sender);
} else {
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed);
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
}
emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue);
// Transfer collateral from contract to caller and burn callers synthetic tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice After a contract has passed expiry all token holders can redeem their tokens for underlying at the
* prevailing price defined by the DVM from the `expire` function.
* @dev This burns all tokens from the caller of `tokenCurrency` and sends back the proportional amount of
* `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for
* precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function settleExpired()
external
onlyPostExpiration()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
// If the contract state is open and onlyPostExpiration passed then `expire()` has not yet been called.
require(contractState != ContractState.Open, "Unexpired position");
// Get the current settlement price and store it. If it is not resolved will revert.
if (contractState != ContractState.ExpiredPriceReceived) {
expiryPrice = _getOraclePriceExpiration(expirationTimestamp);
contractState = ContractState.ExpiredPriceReceived;
}
// Get caller's tokens balance and calculate amount of underlying entitled to them.
FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender));
FixedPoint.Unsigned memory totalRedeemableCollateral = tokensToRedeem.mul(expiryPrice);
// If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt.
PositionData storage positionData = positions[msg.sender];
if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) {
// Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying.
FixedPoint.Unsigned memory tokenDebtValueInCollateral = positionData.tokensOutstanding.mul(expiryPrice);
FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral);
// If the debt is greater than the remaining collateral, they cannot redeem anything.
FixedPoint.Unsigned memory positionRedeemableCollateral =
tokenDebtValueInCollateral.isLessThan(positionCollateral)
? positionCollateral.sub(tokenDebtValueInCollateral)
: FixedPoint.Unsigned(0);
// Add the number of redeemable tokens for the sponsor to their total redeemable collateral.
totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral);
// Reset the position state as all the value has been removed after settlement.
delete positions[msg.sender];
emit EndedSponsorPosition(msg.sender);
}
// Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized,
// the caller will get as much collateral as the contract can pay out.
FixedPoint.Unsigned memory payout =
FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral);
// Decrement total contract collateral and outstanding debt.
amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout);
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem);
emit SettleExpiredPosition(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue);
// Transfer tokens & collateral and burn the redeemed tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue);
tokenCurrency.burn(tokensToRedeem.rawValue);
}
/****************************************
* GLOBAL STATE FUNCTIONS *
****************************************/
/**
* @notice Locks contract state in expired and requests oracle price.
* @dev this function can only be called once the contract is expired and can't be re-called.
*/
function expire() external onlyPostExpiration() onlyOpenState() fees() nonReentrant() {
contractState = ContractState.ExpiredPriceRequested;
// Final fees do not need to be paid when sending a request to the optimistic oracle.
_requestOraclePriceExpiration(expirationTimestamp);
emit ContractExpired(msg.sender);
}
/**
* @notice Premature contract settlement under emergency circumstances.
* @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`.
* Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal
* to occur via the standard `settleExpired` function. Contract state is set to `ExpiredPriceRequested`
* which prevents re-entry into this function or the `expire` function. No fees are paid when calling
* `emergencyShutdown` as the governor who would call the function would also receive the fees.
*/
function emergencyShutdown() external override onlyPreExpiration() onlyOpenState() nonReentrant() {
require(msg.sender == _getFinancialContractsAdminAddress());
contractState = ContractState.ExpiredPriceRequested;
// Expiratory time now becomes the current time (emergency shutdown time).
// Price requested at this time stamp. `settleExpired` can now withdraw at this timestamp.
uint256 oldExpirationTimestamp = expirationTimestamp;
expirationTimestamp = getCurrentTime();
_requestOraclePriceExpiration(expirationTimestamp);
emit EmergencyShutdown(msg.sender, oldExpirationTimestamp, expirationTimestamp);
}
/**
* @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they
* reflect the NAV of the contract. However, this functionality doesn't apply to this contract.
* @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable
* only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing.
*/
function remargin() external override onlyPreExpiration() nonReentrant() {
return;
}
/**
* @notice Accessor method for a sponsor's collateral.
* @dev This is necessary because the struct returned by the positions() method shows
* rawCollateral, which isn't a user-readable value.
* @dev TODO: This method does not account for any pending regular fees that have not yet been withdrawn
* from this contract, for example if the `lastPaymentTime != currentTime`. Future work should be to add
* logic to this method to account for any such pending fees.
* @param sponsor address whose collateral amount is retrieved.
* @return collateralAmount amount of collateral within a sponsors position.
*/
function getCollateral(address sponsor)
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory collateralAmount)
{
// Note: do a direct access to avoid the validity check.
return _getFeeAdjustedCollateral(positions[sponsor].rawCollateral);
}
/**
* @notice Accessor method for the total collateral stored within the PricelessPositionManager.
* @return totalCollateral amount of all collateral within the Expiring Multi Party Contract.
*/
function totalPositionCollateral()
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory totalCollateral)
{
return _getFeeAdjustedCollateral(rawTotalPositionCollateral);
}
/**
* @notice Accessor method to compute a transformed price using the finanicalProductLibrary specified at contract
* deployment. If no library was provided then no modification to the price is done.
* @param price input price to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice price with the transformation function applied to it.
* @dev This method should never revert.
*/
function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return _transformPrice(price, requestTime);
}
/**
* @notice Accessor method to compute a transformed price identifier using the finanicalProductLibrary specified
* at contract deployment. If no library was provided then no modification to the identifier is done.
* @param requestTime timestamp the identifier is to be used at.
* @return transformedPrice price with the transformation function applied to it.
* @dev This method should never revert.
*/
function transformPriceIdentifier(uint256 requestTime) public view nonReentrantView() returns (bytes32) {
return _transformPriceIdentifier(requestTime);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire
// position if the entire position is being removed. Does not make any external transfers.
function _reduceSponsorPosition(
address sponsor,
FixedPoint.Unsigned memory tokensToRemove,
FixedPoint.Unsigned memory collateralToRemove,
FixedPoint.Unsigned memory withdrawalAmountToRemove
) internal {
PositionData storage positionData = _getPositionData(sponsor);
// If the entire position is being removed, delete it instead.
if (
tokensToRemove.isEqual(positionData.tokensOutstanding) &&
_getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove)
) {
_deleteSponsorPosition(sponsor);
return;
}
// Decrement the sponsor's collateral and global collateral amounts.
_decrementCollateralBalances(positionData, collateralToRemove);
// Ensure that the sponsor will meet the min position size after the reduction.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(tokensToRemove);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
positionData.tokensOutstanding = newTokenCount;
// Decrement the position's withdrawal amount.
positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove);
// Decrement the total outstanding tokens in the overall contract.
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove);
}
// Deletes a sponsor's position and updates global counters. Does not make any external transfers.
function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) {
PositionData storage positionToLiquidate = _getPositionData(sponsor);
FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral);
// Remove the collateral and outstanding from the overall total position.
FixedPoint.Unsigned memory remainingRawCollateral = positionToLiquidate.rawCollateral;
rawTotalPositionCollateral = rawTotalPositionCollateral.sub(remainingRawCollateral);
totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding);
// Reset the sponsors position to have zero outstanding and collateral.
delete positions[sponsor];
emit EndedSponsorPosition(sponsor);
// Return fee-adjusted amount of collateral deleted from position.
return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalPositionCollateral);
}
function _getPositionData(address sponsor)
internal
view
onlyCollateralizedPosition(sponsor)
returns (PositionData storage)
{
return positions[sponsor];
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getOracle() internal view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) {
return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle));
}
function _getFinancialContractsAdminAddress() internal view returns (address) {
return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin);
}
// Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePriceExpiration(uint256 requestedTime) internal {
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
// Increase token allowance to enable the optimistic oracle reward transfer.
FixedPoint.Unsigned memory reward = _computeFinalFees();
collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), reward.rawValue);
optimisticOracle.requestPrice(
_transformPriceIdentifier(requestedTime),
requestedTime,
_getAncillaryData(),
collateralCurrency,
reward.rawValue // Reward is equal to the final fee
);
// Apply haircut to all sponsors by decrementing the cumlativeFeeMultiplier by the amount lost from the final fee.
_adjustCumulativeFeeMultiplier(reward, _pfc());
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePriceExpiration(uint256 requestedTime) internal returns (FixedPoint.Unsigned memory) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
require(
optimisticOracle.hasPrice(
address(this),
_transformPriceIdentifier(requestedTime),
requestedTime,
_getAncillaryData()
),
"Unresolved oracle price"
);
int256 optimisticOraclePrice =
optimisticOracle.getPrice(_transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData());
// For now we don't want to deal with negative prices in positions.
if (optimisticOraclePrice < 0) {
optimisticOraclePrice = 0;
}
return _transformPrice(FixedPoint.Unsigned(uint256(optimisticOraclePrice)), requestedTime);
}
// Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePriceLiquidation(uint256 requestedTime) internal {
OracleInterface oracle = _getOracle();
oracle.requestPrice(_transformPriceIdentifier(requestedTime), requestedTime);
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePriceLiquidation(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
OracleInterface oracle = _getOracle();
require(oracle.hasPrice(_transformPriceIdentifier(requestedTime), requestedTime), "Unresolved oracle price");
int256 oraclePrice = oracle.getPrice(_transformPriceIdentifier(requestedTime), requestedTime);
// For now we don't want to deal with negative prices in positions.
if (oraclePrice < 0) {
oraclePrice = 0;
}
return _transformPrice(FixedPoint.Unsigned(uint256(oraclePrice)), requestedTime);
}
// Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0.
function _resetWithdrawalRequest(PositionData storage positionData) internal {
positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0);
positionData.withdrawalRequestPassTimestamp = 0;
}
// Ensure individual and global consistency when increasing collateral balances. Returns the change to the position.
function _incrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_addCollateral(positionData.rawCollateral, collateralAmount);
return _addCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the
// position. We elect to return the amount that the global collateral is decreased by, rather than the individual
// position's collateral, because we need to maintain the invariant that the global collateral is always
// <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn.
function _decrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position.
// This function is similar to the _decrementCollateralBalances function except this function checks position GCR
// between the decrements. This ensures that collateral removal will not leave the position undercollateralized.
function _decrementCollateralBalancesCheckGCR(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
require(_checkPositionCollateralization(positionData), "CR below GCR");
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _onlyOpenState() internal view {
require(contractState == ContractState.Open, "Contract state is not OPEN");
}
function _onlyPreExpiration() internal view {
require(getCurrentTime() < expirationTimestamp, "Only callable pre-expiry");
}
function _onlyPostExpiration() internal view {
require(getCurrentTime() >= expirationTimestamp, "Only callable post-expiry");
}
function _onlyCollateralizedPosition(address sponsor) internal view {
require(
_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0),
"Position has no collateral"
);
}
// Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the
// `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral
// or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`.
function _positionHasNoPendingWithdrawal(address sponsor) internal view {
require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0, "Pending withdrawal");
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) {
return
_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral),
positionData.tokensOutstanding
);
}
// Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global
// collateralization ratio.
function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
view
returns (bool)
{
FixedPoint.Unsigned memory global =
_getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding);
FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens);
return !global.isGreaterThan(thisChange);
}
function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
pure
returns (FixedPoint.Unsigned memory ratio)
{
if (!numTokens.isGreaterThan(0)) {
return FixedPoint.fromUnscaledUint(0);
} else {
return collateral.div(numTokens);
}
}
// IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method,
// which is possible since the method is only an OPTIONAL method in the ERC20 standard:
// https://eips.ethereum.org/EIPS/eip-20#methods.
function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) {
try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) {
return _decimals;
} catch {
return 18;
}
}
function _transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime)
internal
view
returns (FixedPoint.Unsigned memory)
{
if (!address(financialProductLibrary).isContract()) return price;
try financialProductLibrary.transformPrice(price, requestTime) returns (
FixedPoint.Unsigned memory transformedPrice
) {
return transformedPrice;
} catch {
return price;
}
}
function _transformPriceIdentifier(uint256 requestTime) internal view returns (bytes32) {
if (!address(financialProductLibrary).isContract()) return priceIdentifier;
try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns (
bytes32 transformedIdentifier
) {
return transformedIdentifier;
} catch {
return priceIdentifier;
}
}
function _getAncillaryData() internal view returns (bytes memory) {
// Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address
// whose funding rate it's trying to get.
return abi.encodePacked(address(tokenCurrency));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/interfaces/IERC20Standard.sol";
import "../../oracle/implementation/ContractCreator.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/AddressWhitelist.sol";
import "../../common/implementation/Lockable.sol";
import "../common/TokenFactory.sol";
import "../common/SyntheticToken.sol";
import "./ExpiringMultiPartyLib.sol";
/**
* @title Expiring Multi Party Contract creator.
* @notice Factory contract to create and register new instances of expiring multiparty contracts.
* Responsible for constraining the parameters used to construct a new EMP. This creator contains a number of constraints
* that are applied to newly created expiring multi party contract. These constraints can evolve over time and are
* initially constrained to conservative values in this first iteration. Technically there is nothing in the
* ExpiringMultiParty contract requiring these constraints. However, because `createExpiringMultiParty()` is intended
* to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract),
we can enforce deployment configurations here.
*/
contract ExpiringMultiPartyCreator is ContractCreator, Testable, Lockable {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* EMP CREATOR DATA STRUCTURES *
****************************************/
struct Params {
uint256 expirationTimestamp;
address collateralAddress;
bytes32 priceFeedIdentifier;
string syntheticName;
string syntheticSymbol;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPct;
FixedPoint.Unsigned sponsorDisputeRewardPct;
FixedPoint.Unsigned disputerDisputeRewardPct;
FixedPoint.Unsigned minSponsorTokens;
uint256 withdrawalLiveness;
uint256 liquidationLiveness;
address financialProductLibraryAddress;
}
// Address of TokenFactory used to create a new synthetic token.
address public tokenFactoryAddress;
event CreatedExpiringMultiParty(address indexed expiringMultiPartyAddress, address indexed deployerAddress);
/**
* @notice Constructs the ExpiringMultiPartyCreator contract.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances.
* @param _timerAddress Contract that stores the current time in a testing environment.
*/
constructor(
address _finderAddress,
address _tokenFactoryAddress,
address _timerAddress
) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() {
tokenFactoryAddress = _tokenFactoryAddress;
}
/**
* @notice Creates an instance of expiring multi party and registers it within the registry.
* @param params is a `ConstructorParams` object from ExpiringMultiParty.
* @return address of the deployed ExpiringMultiParty contract.
*/
function createExpiringMultiParty(Params memory params) public nonReentrant() returns (address) {
// Create a new synthetic token using the params.
require(bytes(params.syntheticName).length != 0, "Missing synthetic name");
require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol");
TokenFactory tf = TokenFactory(tokenFactoryAddress);
// If the collateral token does not have a `decimals()` method, then a default precision of 18 will be
// applied to the newly created synthetic token.
uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress);
ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals);
address derivative = ExpiringMultiPartyLib.deploy(_convertParams(params, tokenCurrency));
// Give permissions to new derivative contract and then hand over ownership.
tokenCurrency.addMinter(derivative);
tokenCurrency.addBurner(derivative);
tokenCurrency.resetOwner(derivative);
_registerContract(new address[](0), derivative);
emit CreatedExpiringMultiParty(derivative, msg.sender);
return derivative;
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
// Converts createExpiringMultiParty params to ExpiringMultiParty constructor params.
function _convertParams(Params memory params, ExpandedIERC20 newTokenCurrency)
private
view
returns (ExpiringMultiParty.ConstructorParams memory constructorParams)
{
// Known from creator deployment.
constructorParams.finderAddress = finderAddress;
constructorParams.timerAddress = timerAddress;
// Enforce configuration constraints.
require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0");
require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0");
require(params.expirationTimestamp > now, "Invalid expiration time");
_requireWhitelistedCollateral(params.collateralAddress);
// We don't want EMP deployers to be able to intentionally or unintentionally set
// liveness periods that could induce arithmetic overflow, but we also don't want
// to be opinionated about what livenesses are "correct", so we will somewhat
// arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness
// periods even greater than a few days would make the EMP unusable for most users.
require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large");
require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large");
// Input from function call.
constructorParams.tokenAddress = address(newTokenCurrency);
constructorParams.expirationTimestamp = params.expirationTimestamp;
constructorParams.collateralAddress = params.collateralAddress;
constructorParams.priceFeedIdentifier = params.priceFeedIdentifier;
constructorParams.collateralRequirement = params.collateralRequirement;
constructorParams.disputeBondPct = params.disputeBondPct;
constructorParams.sponsorDisputeRewardPct = params.sponsorDisputeRewardPct;
constructorParams.disputerDisputeRewardPct = params.disputerDisputeRewardPct;
constructorParams.minSponsorTokens = params.minSponsorTokens;
constructorParams.withdrawalLiveness = params.withdrawalLiveness;
constructorParams.liquidationLiveness = params.liquidationLiveness;
constructorParams.financialProductLibraryAddress = params.financialProductLibraryAddress;
}
// IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method,
// which is possible since the method is only an OPTIONAL method in the ERC20 standard:
// https://eips.ethereum.org/EIPS/eip-20#methods.
function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) {
try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) {
return _decimals;
} catch {
return 18;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./ExpiringMultiParty.sol";
/**
* @title Provides convenient Expiring Multi Party contract utilities.
* @dev Using this library to deploy EMP's allows calling contracts to avoid importing the full EMP bytecode.
*/
library ExpiringMultiPartyLib {
/**
* @notice Returns address of new EMP deployed with given `params` configuration.
* @dev Caller will need to register new EMP with the Registry to begin requesting prices. Caller is also
* responsible for enforcing constraints on `params`.
* @param params is a `ConstructorParams` object from ExpiringMultiParty.
* @return address of the deployed ExpiringMultiParty contract
*/
function deploy(ExpiringMultiParty.ConstructorParams memory params) public returns (address) {
ExpiringMultiParty derivative = new ExpiringMultiParty(params);
return address(derivative);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./ConfigStoreInterface.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @notice ConfigStore stores configuration settings for a perpetual contract and provides an interface for it
* to query settings such as reward rates, proposal bond sizes, etc. The configuration settings can be upgraded
* by a privileged account and the upgraded changes are timelocked.
*/
contract ConfigStore is ConfigStoreInterface, Testable, Lockable, Ownable {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* STORE DATA STRUCTURES *
****************************************/
// Make currentConfig private to force user to call getCurrentConfig, which returns the pendingConfig
// if its liveness has expired.
ConfigStoreInterface.ConfigSettings private currentConfig;
// Beginning on `pendingPassedTimestamp`, the `pendingConfig` can be published as the current config.
ConfigStoreInterface.ConfigSettings public pendingConfig;
uint256 public pendingPassedTimestamp;
/****************************************
* EVENTS *
****************************************/
event ProposedNewConfigSettings(
address indexed proposer,
uint256 rewardRate,
uint256 proposerBond,
uint256 timelockLiveness,
int256 maxFundingRate,
int256 minFundingRate,
uint256 proposalTimePastLimit,
uint256 proposalPassedTimestamp
);
event ChangedConfigSettings(
uint256 rewardRate,
uint256 proposerBond,
uint256 timelockLiveness,
int256 maxFundingRate,
int256 minFundingRate,
uint256 proposalTimePastLimit
);
/****************************************
* MODIFIERS *
****************************************/
// Update config settings if possible.
modifier updateConfig() {
_updateConfig();
_;
}
/**
* @notice Construct the Config Store. An initial configuration is provided and set on construction.
* @param _initialConfig Configuration settings to initialize `currentConfig` with.
* @param _timerAddress Address of testable Timer contract.
*/
constructor(ConfigSettings memory _initialConfig, address _timerAddress) public Testable(_timerAddress) {
_validateConfig(_initialConfig);
currentConfig = _initialConfig;
}
/**
* @notice Returns current config or pending config if pending liveness has expired.
* @return ConfigSettings config settings that calling financial contract should view as "live".
*/
function updateAndGetCurrentConfig()
external
override
updateConfig()
nonReentrant()
returns (ConfigStoreInterface.ConfigSettings memory)
{
return currentConfig;
}
/**
* @notice Propose new configuration settings. New settings go into effect after a liveness period passes.
* @param newConfig Configuration settings to publish after `currentConfig.timelockLiveness` passes from now.
* @dev Callable only by owner. Calling this while there is already a pending proposal will overwrite the pending proposal.
*/
function proposeNewConfig(ConfigSettings memory newConfig) external onlyOwner() nonReentrant() updateConfig() {
_validateConfig(newConfig);
// Warning: This overwrites a pending proposal!
pendingConfig = newConfig;
// Use current config's liveness period to timelock this proposal.
pendingPassedTimestamp = getCurrentTime().add(currentConfig.timelockLiveness);
emit ProposedNewConfigSettings(
msg.sender,
newConfig.rewardRatePerSecond.rawValue,
newConfig.proposerBondPct.rawValue,
newConfig.timelockLiveness,
newConfig.maxFundingRate.rawValue,
newConfig.minFundingRate.rawValue,
newConfig.proposalTimePastLimit,
pendingPassedTimestamp
);
}
/**
* @notice Publish any pending configuration settings if there is a pending proposal that has passed liveness.
*/
function publishPendingConfig() external nonReentrant() updateConfig() {}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Check if pending proposal can overwrite the current config.
function _updateConfig() internal {
// If liveness has passed, publish proposed configuration settings.
if (_pendingProposalPassed()) {
currentConfig = pendingConfig;
_deletePendingConfig();
emit ChangedConfigSettings(
currentConfig.rewardRatePerSecond.rawValue,
currentConfig.proposerBondPct.rawValue,
currentConfig.timelockLiveness,
currentConfig.maxFundingRate.rawValue,
currentConfig.minFundingRate.rawValue,
currentConfig.proposalTimePastLimit
);
}
}
function _deletePendingConfig() internal {
delete pendingConfig;
pendingPassedTimestamp = 0;
}
function _pendingProposalPassed() internal view returns (bool) {
return (pendingPassedTimestamp != 0 && pendingPassedTimestamp <= getCurrentTime());
}
// Use this method to constrain values with which you can set ConfigSettings.
function _validateConfig(ConfigStoreInterface.ConfigSettings memory config) internal pure {
// We don't set limits on proposal timestamps because there are already natural limits:
// - Future: price requests to the OptimisticOracle must be in the past---we can't add further constraints.
// - Past: proposal times must always be after the last update time, and a reasonable past limit would be 30
// mins, meaning that no proposal timestamp can be more than 30 minutes behind the current time.
// Make sure timelockLiveness is not too long, otherwise contract might not be able to fix itself
// before a vulnerability drains its collateral.
require(config.timelockLiveness <= 7 days && config.timelockLiveness >= 1 days, "Invalid timelockLiveness");
// The reward rate should be modified as needed to incentivize honest proposers appropriately.
// Additionally, the rate should be less than 100% a year => 100% / 360 days / 24 hours / 60 mins / 60 secs
// = 0.0000033
FixedPoint.Unsigned memory maxRewardRatePerSecond = FixedPoint.fromUnscaledUint(33).div(1e7);
require(config.rewardRatePerSecond.isLessThan(maxRewardRatePerSecond), "Invalid rewardRatePerSecond");
// We don't set a limit on the proposer bond because it is a defense against dishonest proposers. If a proposer
// were to successfully propose a very high or low funding rate, then their PfC would be very high. The proposer
// could theoretically keep their "evil" funding rate alive indefinitely by continuously disputing honest
// proposers, so we would want to be able to set the proposal bond (equal to the dispute bond) higher than their
// PfC for each proposal liveness window. The downside of not limiting this is that the config store owner
// can set it arbitrarily high and preclude a new funding rate from ever coming in. We suggest setting the
// proposal bond based on the configuration's funding rate range like in this discussion:
// https://github.com/UMAprotocol/protocol/issues/2039#issuecomment-719734383
// We also don't set a limit on the funding rate max/min because we might need to allow very high magnitude
// funding rates in extraordinarily volatile market situations. Note, that even though we do not bound
// the max/min, we still recommend that the deployer of this contract set the funding rate max/min values
// to bound the PfC of a dishonest proposer. A reasonable range might be the equivalent of [+200%/year, -200%/year].
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./PerpetualLiquidatable.sol";
/**
* @title Perpetual Multiparty Contract.
* @notice Convenient wrapper for Liquidatable.
*/
contract Perpetual is PerpetualLiquidatable {
/**
* @notice Constructs the Perpetual contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
PerpetualLiquidatable(params)
// Note: since there is no logic here, there is no need to add a re-entrancy guard.
{
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./PerpetualPositionManager.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title PerpetualLiquidatable
* @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position.
* @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the
* liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on
* a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false
* liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a
* prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute.
*/
contract PerpetualLiquidatable is PerpetualPositionManager {
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using SafeERC20 for IERC20;
/****************************************
* LIQUIDATION DATA STRUCTURES *
****************************************/
// Because of the check in withdrawable(), the order of these enum values should not change.
enum Status { Uninitialized, PreDispute, PendingDispute, DisputeSucceeded, DisputeFailed }
struct LiquidationData {
// Following variables set upon creation of liquidation:
address sponsor; // Address of the liquidated position's sponsor
address liquidator; // Address who created this liquidation
Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved
uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle
// Following variables determined by the position that is being liquidated:
FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute
FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute
// Amount of collateral being liquidated, which could be different from
// lockedCollateral if there were pending withdrawals at the time of liquidation
FixedPoint.Unsigned liquidatedCollateral;
// Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation.
FixedPoint.Unsigned rawUnitCollateral;
// Following variable set upon initiation of a dispute:
address disputer; // Person who is disputing a liquidation
// Following variable set upon a resolution of a dispute:
FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute
FixedPoint.Unsigned finalFee;
}
// Define the contract's constructor parameters as a struct to enable more variables to be specified.
// This is required to enable more params, over and above Solidity's limits.
struct ConstructorParams {
// Params for PerpetualPositionManager only.
uint256 withdrawalLiveness;
address configStoreAddress;
address collateralAddress;
address tokenAddress;
address finderAddress;
address timerAddress;
bytes32 priceFeedIdentifier;
bytes32 fundingRateIdentifier;
FixedPoint.Unsigned minSponsorTokens;
FixedPoint.Unsigned tokenScaling;
// Params specifically for PerpetualLiquidatable.
uint256 liquidationLiveness;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPct;
FixedPoint.Unsigned sponsorDisputeRewardPct;
FixedPoint.Unsigned disputerDisputeRewardPct;
}
// This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards.
// `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ
// from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the
// fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error.
struct RewardsData {
FixedPoint.Unsigned payToSponsor;
FixedPoint.Unsigned payToLiquidator;
FixedPoint.Unsigned payToDisputer;
FixedPoint.Unsigned paidToSponsor;
FixedPoint.Unsigned paidToLiquidator;
FixedPoint.Unsigned paidToDisputer;
}
// Liquidations are unique by ID per sponsor
mapping(address => LiquidationData[]) public liquidations;
// Total collateral in liquidation.
FixedPoint.Unsigned public rawLiquidationCollateral;
// Immutable contract parameters:
// Amount of time for pending liquidation before expiry.
// !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors.
// Extremely low liveness values increase the chance that opportunistic invalid liquidations
// expire without dispute, thereby decreasing the usability for sponsors and increasing the risk
// for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic
// token holder for the contract.
uint256 public liquidationLiveness;
// Required collateral:TRV ratio for a position to be considered sufficiently collateralized.
FixedPoint.Unsigned public collateralRequirement;
// Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer
// Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%"
FixedPoint.Unsigned public disputeBondPct;
// Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public sponsorDisputeRewardPct;
// Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public disputerDisputeRewardPct;
/****************************************
* EVENTS *
****************************************/
event LiquidationCreated(
address indexed sponsor,
address indexed liquidator,
uint256 indexed liquidationId,
uint256 tokensOutstanding,
uint256 lockedCollateral,
uint256 liquidatedCollateral,
uint256 liquidationTime
);
event LiquidationDisputed(
address indexed sponsor,
address indexed liquidator,
address indexed disputer,
uint256 liquidationId,
uint256 disputeBondAmount
);
event DisputeSettled(
address indexed caller,
address indexed sponsor,
address indexed liquidator,
address disputer,
uint256 liquidationId,
bool disputeSucceeded
);
event LiquidationWithdrawn(
address indexed caller,
uint256 paidToLiquidator,
uint256 paidToDisputer,
uint256 paidToSponsor,
Status indexed liquidationStatus,
uint256 settlementPrice
);
/****************************************
* MODIFIERS *
****************************************/
modifier disputable(uint256 liquidationId, address sponsor) {
_disputable(liquidationId, sponsor);
_;
}
modifier withdrawable(uint256 liquidationId, address sponsor) {
_withdrawable(liquidationId, sponsor);
_;
}
/**
* @notice Constructs the liquidatable contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
PerpetualPositionManager(
params.withdrawalLiveness,
params.collateralAddress,
params.tokenAddress,
params.finderAddress,
params.priceFeedIdentifier,
params.fundingRateIdentifier,
params.minSponsorTokens,
params.configStoreAddress,
params.tokenScaling,
params.timerAddress
)
{
require(params.collateralRequirement.isGreaterThan(1));
require(params.sponsorDisputeRewardPct.add(params.disputerDisputeRewardPct).isLessThan(1));
// Set liquidatable specific variables.
liquidationLiveness = params.liquidationLiveness;
collateralRequirement = params.collateralRequirement;
disputeBondPct = params.disputeBondPct;
sponsorDisputeRewardPct = params.sponsorDisputeRewardPct;
disputerDisputeRewardPct = params.disputerDisputeRewardPct;
}
/****************************************
* LIQUIDATION FUNCTIONS *
****************************************/
/**
* @notice Liquidates the sponsor's position if the caller has enough
* synthetic tokens to retire the position's outstanding tokens. Liquidations above
* a minimum size also reset an ongoing "slow withdrawal"'s liveness.
* @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be
* approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param sponsor address of the sponsor to liquidate.
* @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value.
* @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value.
* @param maxTokensToLiquidate max number of tokens to liquidate.
* @param deadline abort the liquidation if the transaction is mined after this timestamp.
* @return liquidationId ID of the newly created liquidation.
* @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position.
* @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully.
*/
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
notEmergencyShutdown()
fees()
nonReentrant()
returns (
uint256 liquidationId,
FixedPoint.Unsigned memory tokensLiquidated,
FixedPoint.Unsigned memory finalFeeBond
)
{
// Check that this transaction was mined pre-deadline.
require(getCurrentTime() <= deadline, "Mined after deadline");
// Retrieve Position data for sponsor
PositionData storage positionToLiquidate = _getPositionData(sponsor);
tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding);
require(tokensLiquidated.isGreaterThan(0));
// Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral,
// then set this to 0, otherwise set it to (startCollateral - withdrawal request amount).
FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral);
FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0);
if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) {
startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount);
}
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding;
// The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken].
require(
maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal),
"CR is more than max liq. price"
);
// minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal),
"CR is less than min liq. price"
);
}
// Compute final fee at time of liquidation.
finalFeeBond = _computeFinalFees();
// These will be populated within the scope below.
FixedPoint.Unsigned memory lockedCollateral;
FixedPoint.Unsigned memory liquidatedCollateral;
// Scoping to get rid of a stack too deep error. The amount of tokens to remove from the position
// are not funding-rate adjusted because the multiplier only affects their redemption value, not their
// notional.
{
FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding);
// The actual amount of collateral that gets moved to the liquidation.
lockedCollateral = startCollateral.mul(ratio);
// For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of
// withdrawal requests.
liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio);
// Part of the withdrawal request is also removed. Ideally:
// liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral.
FixedPoint.Unsigned memory withdrawalAmountToRemove =
positionToLiquidate.withdrawalRequestAmount.mul(ratio);
_reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove);
}
// Add to the global liquidation collateral count.
_addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond));
// Construct liquidation object.
// Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new
// LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push.
liquidationId = liquidations[sponsor].length;
liquidations[sponsor].push(
LiquidationData({
sponsor: sponsor,
liquidator: msg.sender,
state: Status.PreDispute,
liquidationTime: getCurrentTime(),
tokensOutstanding: _getFundingRateAppliedTokenDebt(tokensLiquidated),
lockedCollateral: lockedCollateral,
liquidatedCollateral: liquidatedCollateral,
rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)),
disputer: address(0),
settlementPrice: FixedPoint.fromUnscaledUint(0),
finalFee: finalFeeBond
})
);
// If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than
// some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be
// "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold
// is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal.
// We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter
// denominated in token currency units and we can avoid adding another parameter.
FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens;
if (
positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal.
positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired.
tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold".
) {
positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness);
}
emit LiquidationCreated(
sponsor,
msg.sender,
liquidationId,
_getFundingRateAppliedTokenDebt(tokensLiquidated).rawValue,
lockedCollateral.rawValue,
liquidatedCollateral.rawValue,
getCurrentTime()
);
// Destroy tokens
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue);
tokenCurrency.burn(tokensLiquidated.rawValue);
// Pull final fee from liquidator.
collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue);
}
/**
* @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond
* and pay a fixed final fee charged on each price request.
* @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes.
* This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute
* bond amount is calculated from `disputeBondPct` times the collateral in the liquidation.
* @param liquidationId of the disputed liquidation.
* @param sponsor the address of the sponsor whose liquidation is being disputed.
* @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond).
*/
function dispute(uint256 liquidationId, address sponsor)
external
disputable(liquidationId, sponsor)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalPaid)
{
LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId);
// Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees.
FixedPoint.Unsigned memory disputeBondAmount =
disputedLiquidation.lockedCollateral.mul(disputeBondPct).mul(
_getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral)
);
_addCollateral(rawLiquidationCollateral, disputeBondAmount);
// Request a price from DVM. Liquidation is pending dispute until DVM returns a price.
disputedLiquidation.state = Status.PendingDispute;
disputedLiquidation.disputer = msg.sender;
// Enqueue a request with the DVM.
_requestOraclePrice(disputedLiquidation.liquidationTime);
emit LiquidationDisputed(
sponsor,
disputedLiquidation.liquidator,
msg.sender,
liquidationId,
disputeBondAmount.rawValue
);
totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee);
// Pay the final fee for requesting price from the DVM.
_payFinalFees(msg.sender, disputedLiquidation.finalFee);
// Transfer the dispute bond amount from the caller to this contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue);
}
/**
* @notice After a dispute has settled or after a non-disputed liquidation has expired,
* anyone can call this method to disperse payments to the sponsor, liquidator, and disputer.
* @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment.
* If the dispute FAILED: only the liquidator receives payment. This method deletes the liquidation data.
* This method will revert if rewards have already been dispersed.
* @param liquidationId uniquely identifies the sponsor's liquidation.
* @param sponsor address of the sponsor associated with the liquidation.
* @return data about rewards paid out.
*/
function withdrawLiquidation(uint256 liquidationId, address sponsor)
public
withdrawable(liquidationId, sponsor)
fees()
nonReentrant()
returns (RewardsData memory)
{
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settles the liquidation if necessary. This call will revert if the price has not resolved yet.
_settle(liquidationId, sponsor);
// Calculate rewards as a function of the TRV.
// Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata.
// TODO: Do we also need to apply some sort of funding rate adjustment to account for multiplier changes
// since liquidation time?
FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral);
FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice;
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation);
FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation);
FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPct.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPct.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPct);
FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation);
// There are three main outcome states: either the dispute succeeded, failed or was not updated.
// Based on the state, different parties of a liquidation receive different amounts.
// After assigning rewards based on the liquidation status, decrease the total collateral held in this contract
// by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes
// precision loss.
RewardsData memory rewards;
if (liquidation.state == Status.DisputeSucceeded) {
// If the dispute is successful then all three users should receive rewards:
// Pay DISPUTER: disputer reward + dispute bond + returned final fee
rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee);
// Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward
rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue));
// Pay LIQUIDATOR: TRV - dispute reward - sponsor reward
// If TRV > Collateral, then subtract rewards from collateral
// NOTE: This should never be below zero since we prevent (sponsorDisputePct+disputerDisputePct) >= 0 in
// the constructor when these params are set.
rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor);
rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer);
collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue);
// In the case of a failed dispute only the liquidator can withdraw.
} else if (liquidation.state == Status.DisputeFailed) {
// Pay LIQUIDATOR: collateral + dispute bond + returned final fee
rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
// If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this
// state as a dispute failed and the liquidator can withdraw.
} else if (liquidation.state == Status.PreDispute) {
// Pay LIQUIDATOR: collateral + returned final fee
rewards.payToLiquidator = collateral.add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
}
emit LiquidationWithdrawn(
msg.sender,
rewards.paidToLiquidator.rawValue,
rewards.paidToDisputer.rawValue,
rewards.paidToSponsor.rawValue,
liquidation.state,
settlementPrice.rawValue
);
// Free up space after collateral is withdrawn by removing the liquidation object from the array.
delete liquidations[sponsor][liquidationId];
return rewards;
}
/**
* @notice Gets all liquidation information for a given sponsor address.
* @param sponsor address of the position sponsor.
* @return liquidationData array of all liquidation information for the given sponsor address.
*/
function getLiquidations(address sponsor)
external
view
nonReentrantView()
returns (LiquidationData[] memory liquidationData)
{
return liquidations[sponsor];
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// This settles a liquidation if it is in the PendingDispute state. If not, it will immediately return.
// If the liquidation is in the PendingDispute state, but a price is not available, this will revert.
function _settle(uint256 liquidationId, address sponsor) internal {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settlement only happens when state == PendingDispute and will only happen once per liquidation.
// If this liquidation is not ready to be settled, this method should return immediately.
if (liquidation.state != Status.PendingDispute) {
return;
}
// Get the returned price from the oracle. If this has not yet resolved will revert.
liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime);
// Find the value of the tokens in the underlying collateral.
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(liquidation.settlementPrice);
// The required collateral is the value of the tokens in underlying * required collateral ratio.
FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(collateralRequirement);
// If the position has more than the required collateral it is solvent and the dispute is valid (liquidation is invalid)
// Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals.
bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral);
liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed;
emit DisputeSettled(
msg.sender,
sponsor,
liquidation.liquidator,
liquidation.disputer,
liquidationId,
disputeSucceeded
);
}
function _pfc() internal view override returns (FixedPoint.Unsigned memory) {
return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral));
}
function _getLiquidationData(address sponsor, uint256 liquidationId)
internal
view
returns (LiquidationData storage liquidation)
{
LiquidationData[] storage liquidationArray = liquidations[sponsor];
// Revert if the caller is attempting to access an invalid liquidation
// (one that has never been created or one has never been initialized).
require(
liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized
);
return liquidationArray[liquidationId];
}
function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) {
return liquidation.liquidationTime.add(liquidationLiveness);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _disputable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
require(
(getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.PreDispute),
"Liquidation not disputable"
);
}
function _withdrawable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
Status state = liquidation.state;
// Must be disputed or the liquidation has passed expiry.
require(
(state > Status.PreDispute) ||
((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.PreDispute)),
"Liquidation not withdrawable"
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../oracle/interfaces/OracleInterface.sol";
import "../../oracle/interfaces/IdentifierWhitelistInterface.sol";
import "../../oracle/implementation/Constants.sol";
import "../common/FundingRateApplier.sol";
/**
* @title Financial contract with priceless position management.
* @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying
* on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token.
*/
contract PerpetualPositionManager is FundingRateApplier {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
using SafeERC20 for ExpandedIERC20;
/****************************************
* PRICELESS POSITION DATA STRUCTURES *
****************************************/
// Represents a single sponsor's position. All collateral is held by this contract.
// This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor.
struct PositionData {
FixedPoint.Unsigned tokensOutstanding;
// Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`.
uint256 withdrawalRequestPassTimestamp;
FixedPoint.Unsigned withdrawalRequestAmount;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
FixedPoint.Unsigned rawCollateral;
}
// Maps sponsor addresses to their positions. Each sponsor can have only one position.
mapping(address => PositionData) public positions;
// Keep track of the total collateral and tokens across all positions to enable calculating the
// global collateralization ratio without iterating over all positions.
FixedPoint.Unsigned public totalTokensOutstanding;
// Similar to the rawCollateral in PositionData, this value should not be used directly.
// _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned public rawTotalPositionCollateral;
// Synthetic token created by this contract.
ExpandedIERC20 public tokenCurrency;
// Unique identifier for DVM price feed ticker.
bytes32 public priceIdentifier;
// Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur.
// !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract.
// Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests
// expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent
// contract is extremely risky for any sponsor or synthetic token holder for the contract.
uint256 public withdrawalLiveness;
// Minimum number of tokens in a sponsor's position.
FixedPoint.Unsigned public minSponsorTokens;
// Expiry price pulled from the DVM in the case of an emergency shutdown.
FixedPoint.Unsigned public emergencyShutdownPrice;
/****************************************
* EVENTS *
****************************************/
event Deposit(address indexed sponsor, uint256 indexed collateralAmount);
event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount);
event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event NewSponsor(address indexed sponsor);
event EndedSponsorPosition(address indexed sponsor);
event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount);
event EmergencyShutdown(address indexed caller, uint256 shutdownTimestamp);
event SettleEmergencyShutdown(
address indexed caller,
uint256 indexed collateralReturned,
uint256 indexed tokensBurned
);
/****************************************
* MODIFIERS *
****************************************/
modifier onlyCollateralizedPosition(address sponsor) {
_onlyCollateralizedPosition(sponsor);
_;
}
modifier noPendingWithdrawal(address sponsor) {
_positionHasNoPendingWithdrawal(sponsor);
_;
}
/**
* @notice Construct the PerpetualPositionManager.
* @dev Deployer of this contract should consider carefully which parties have ability to mint and burn
* the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts
* can mint new tokens, which could be used to steal all of this contract's locked collateral.
* We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles)
* is assigned to this contract, whose sole Minter role is assigned to this contract, and whose
* total supply is 0 prior to construction of this contract.
* @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals.
* @param _collateralAddress ERC20 token used as collateral for all positions.
* @param _tokenAddress ERC20 token used as synthetic token.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM for the synthetic.
* @param _fundingRateIdentifier Unique identifier for DVM price feed ticker for child financial contract.
* @param _minSponsorTokens minimum amount of collateral that must exist at any time in a position.
* @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index).
* @param _timerAddress Contract that stores the current time in a testing environment. Set to 0x0 for production.
*/
constructor(
uint256 _withdrawalLiveness,
address _collateralAddress,
address _tokenAddress,
address _finderAddress,
bytes32 _priceIdentifier,
bytes32 _fundingRateIdentifier,
FixedPoint.Unsigned memory _minSponsorTokens,
address _configStoreAddress,
FixedPoint.Unsigned memory _tokenScaling,
address _timerAddress
)
public
FundingRateApplier(
_fundingRateIdentifier,
_collateralAddress,
_finderAddress,
_configStoreAddress,
_tokenScaling,
_timerAddress
)
{
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier));
withdrawalLiveness = _withdrawalLiveness;
tokenCurrency = ExpandedIERC20(_tokenAddress);
minSponsorTokens = _minSponsorTokens;
priceIdentifier = _priceIdentifier;
}
/****************************************
* POSITION FUNCTIONS *
****************************************/
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param sponsor the sponsor to credit the deposit to.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount)
public
notEmergencyShutdown()
noPendingWithdrawal(sponsor)
fees()
nonReentrant()
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(sponsor);
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
emit Deposit(sponsor, collateralAmount.rawValue);
// Move collateral currency from sender to contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function deposit(FixedPoint.Unsigned memory collateralAmount) public {
// This is just a thin wrapper over depositTo that specified the sender as the sponsor.
depositTo(msg.sender, collateralAmount);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor.
* @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization
* ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss.
* @param collateralAmount is the amount of collateral to withdraw.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdraw(FixedPoint.Unsigned memory collateralAmount)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(msg.sender);
// Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure
// position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request.
amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount);
emit Withdrawal(msg.sender, amountWithdrawn.rawValue);
// Move collateral currency from contract to sender.
// Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees)
// instead of the user requested amount. This eliminates precision loss that could occur
// where the user withdraws more collateral than rawCollateral is decremented by.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw from their position.
* @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated.
* @param collateralAmount the amount of collateral requested to withdraw
*/
function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
collateralAmount.isGreaterThan(0) &&
collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral))
);
// Update the position object for the user.
positionData.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness);
positionData.withdrawalRequestAmount = collateralAmount;
emit RequestWithdrawal(msg.sender, collateralAmount.rawValue);
}
/**
* @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting
* `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency.
* @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested
* amount exceeds the collateral in the position (due to paying fees).
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdrawPassedRequest()
external
notEmergencyShutdown()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.withdrawalRequestPassTimestamp != 0 &&
positionData.withdrawalRequestPassTimestamp <= getCurrentTime(),
"Invalid withdraw request"
);
// If withdrawal request amount is > position collateral, then withdraw the full collateral amount.
// This situation is possible due to fees charged since the withdrawal was originally requested.
FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount;
if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) {
amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral);
}
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
// Transfer approved withdrawal amount from the contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Cancels a pending withdrawal request.
*/
function cancelWithdrawal() external notEmergencyShutdown() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
// No pending withdrawal require message removed to save bytecode.
require(positionData.withdrawalRequestPassTimestamp != 0);
emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
}
/**
* @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount
* ` into the sponsor's position and mints `numTokens` of `tokenCurrency`.
* @dev This contract must have the Minter role for the `tokenCurrency`.
* @dev Reverts if minting these tokens would put the position's collateralization ratio below the
* global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of
* `collateralCurrency`.
* @param collateralAmount is the number of collateral tokens to collateralize the position with
* @param numTokens is the number of tokens to mint from the position.
*/
function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens)
public
notEmergencyShutdown()
fees()
nonReentrant()
{
PositionData storage positionData = positions[msg.sender];
// Either the new create ratio or the resultant position CR must be above the current GCR.
require(
(_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount),
positionData.tokensOutstanding.add(numTokens)
) || _checkCollateralization(collateralAmount, numTokens)),
"Insufficient collateral"
);
require(positionData.withdrawalRequestPassTimestamp == 0);
if (positionData.tokensOutstanding.isEqual(0)) {
require(numTokens.isGreaterThanOrEqual(minSponsorTokens));
emit NewSponsor(msg.sender);
}
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
// Add the number of tokens created to the position's outstanding tokens.
positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens);
totalTokensOutstanding = totalTokensOutstanding.add(numTokens);
emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue);
// Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
// Note: revert reason removed to save bytecode.
require(tokenCurrency.mint(msg.sender, numTokens.rawValue));
}
/**
* @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`.
* @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral
* in order to account for precision loss. This contract must be approved to spend at least `numTokens` of
* `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function redeem(FixedPoint.Unsigned memory numTokens)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding));
FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding);
FixedPoint.Unsigned memory collateralRedeemed =
fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral));
// If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize.
if (positionData.tokensOutstanding.isEqual(numTokens)) {
amountWithdrawn = _deleteSponsorPosition(msg.sender);
} else {
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed);
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens));
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
}
emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue);
// Transfer collateral from contract to caller and burn callers synthetic tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`.
* This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens.
* @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt from the sponsor's debt position.
*/
function repay(FixedPoint.Unsigned memory numTokens)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding));
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens));
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue);
// Transfer the tokens back from the sponsor and burn them.
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice If the contract is emergency shutdown then all token holders and sponsors can redeem their tokens or
* remaining collateral for underlying at the prevailing price defined by a DVM vote.
* @dev This burns all tokens from the caller of `tokenCurrency` and sends back the resolved settlement value of
* `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for
* precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @dev Note that this function does not call the updateFundingRate modifier to update the funding rate as this
* function is only called after an emergency shutdown & there should be no funding rate updates after the shutdown.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function settleEmergencyShutdown()
external
isEmergencyShutdown()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
// Set the emergency shutdown price as resolved from the DVM. If DVM has not resolved will revert.
if (emergencyShutdownPrice.isEqual(FixedPoint.fromUnscaledUint(0))) {
emergencyShutdownPrice = _getOracleEmergencyShutdownPrice();
}
// Get caller's tokens balance and calculate amount of underlying entitled to them.
FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender));
FixedPoint.Unsigned memory totalRedeemableCollateral =
_getFundingRateAppliedTokenDebt(tokensToRedeem).mul(emergencyShutdownPrice);
// If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt.
PositionData storage positionData = positions[msg.sender];
if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) {
// Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying with
// the funding rate applied to the outstanding token debt.
FixedPoint.Unsigned memory tokenDebtValueInCollateral =
_getFundingRateAppliedTokenDebt(positionData.tokensOutstanding).mul(emergencyShutdownPrice);
FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral);
// If the debt is greater than the remaining collateral, they cannot redeem anything.
FixedPoint.Unsigned memory positionRedeemableCollateral =
tokenDebtValueInCollateral.isLessThan(positionCollateral)
? positionCollateral.sub(tokenDebtValueInCollateral)
: FixedPoint.Unsigned(0);
// Add the number of redeemable tokens for the sponsor to their total redeemable collateral.
totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral);
// Reset the position state as all the value has been removed after settlement.
delete positions[msg.sender];
emit EndedSponsorPosition(msg.sender);
}
// Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized,
// the caller will get as much collateral as the contract can pay out.
FixedPoint.Unsigned memory payout =
FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral);
// Decrement total contract collateral and outstanding debt.
amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout);
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem);
emit SettleEmergencyShutdown(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue);
// Transfer tokens & collateral and burn the redeemed tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue);
tokenCurrency.burn(tokensToRedeem.rawValue);
}
/****************************************
* GLOBAL STATE FUNCTIONS *
****************************************/
/**
* @notice Premature contract settlement under emergency circumstances.
* @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`.
* Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal
* to occur via the `settleEmergencyShutdown` function.
*/
function emergencyShutdown() external override notEmergencyShutdown() fees() nonReentrant() {
// Note: revert reason removed to save bytecode.
require(msg.sender == _getFinancialContractsAdminAddress());
emergencyShutdownTimestamp = getCurrentTime();
_requestOraclePrice(emergencyShutdownTimestamp);
emit EmergencyShutdown(msg.sender, emergencyShutdownTimestamp);
}
/**
* @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they
* reflect the NAV of the contract. However, this functionality doesn't apply to this contract.
* @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable
* only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing.
*/
function remargin() external override {
return;
}
/**
* @notice Accessor method for a sponsor's collateral.
* @dev This is necessary because the struct returned by the positions() method shows
* rawCollateral, which isn't a user-readable value.
* @dev TODO: This method does not account for any pending regular fees that have not yet been withdrawn
* from this contract, for example if the `lastPaymentTime != currentTime`. Future work should be to add
* logic to this method to account for any such pending fees.
* @param sponsor address whose collateral amount is retrieved.
* @return collateralAmount amount of collateral within a sponsors position.
*/
function getCollateral(address sponsor)
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory collateralAmount)
{
// Note: do a direct access to avoid the validity check.
return _getFeeAdjustedCollateral(positions[sponsor].rawCollateral);
}
/**
* @notice Accessor method for the total collateral stored within the PerpetualPositionManager.
* @return totalCollateral amount of all collateral within the position manager.
*/
function totalPositionCollateral()
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory totalCollateral)
{
return _getFeeAdjustedCollateral(rawTotalPositionCollateral);
}
function getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt)
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory totalCollateral)
{
return _getFundingRateAppliedTokenDebt(rawTokenDebt);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire
// position if the entire position is being removed. Does not make any external transfers.
function _reduceSponsorPosition(
address sponsor,
FixedPoint.Unsigned memory tokensToRemove,
FixedPoint.Unsigned memory collateralToRemove,
FixedPoint.Unsigned memory withdrawalAmountToRemove
) internal {
PositionData storage positionData = _getPositionData(sponsor);
// If the entire position is being removed, delete it instead.
if (
tokensToRemove.isEqual(positionData.tokensOutstanding) &&
_getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove)
) {
_deleteSponsorPosition(sponsor);
return;
}
// Decrement the sponsor's collateral and global collateral amounts.
_decrementCollateralBalances(positionData, collateralToRemove);
// Ensure that the sponsor will meet the min position size after the reduction.
positionData.tokensOutstanding = positionData.tokensOutstanding.sub(tokensToRemove);
require(positionData.tokensOutstanding.isGreaterThanOrEqual(minSponsorTokens));
// Decrement the position's withdrawal amount.
positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove);
// Decrement the total outstanding tokens in the overall contract.
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove);
}
// Deletes a sponsor's position and updates global counters. Does not make any external transfers.
function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) {
PositionData storage positionToLiquidate = _getPositionData(sponsor);
FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral);
// Remove the collateral and outstanding from the overall total position.
rawTotalPositionCollateral = rawTotalPositionCollateral.sub(positionToLiquidate.rawCollateral);
totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding);
// Reset the sponsors position to have zero outstanding and collateral.
delete positions[sponsor];
emit EndedSponsorPosition(sponsor);
// Return fee-adjusted amount of collateral deleted from position.
return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalPositionCollateral);
}
function _getPositionData(address sponsor)
internal
view
onlyCollateralizedPosition(sponsor)
returns (PositionData storage)
{
return positions[sponsor];
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getOracle() internal view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getFinancialContractsAdminAddress() internal view returns (address) {
return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin);
}
// Requests a price for `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePrice(uint256 requestedTime) internal {
_getOracle().requestPrice(priceIdentifier, requestedTime);
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory price) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
int256 oraclePrice = _getOracle().getPrice(priceIdentifier, requestedTime);
// For now we don't want to deal with negative prices in positions.
if (oraclePrice < 0) {
oraclePrice = 0;
}
return FixedPoint.Unsigned(uint256(oraclePrice));
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOracleEmergencyShutdownPrice() internal view returns (FixedPoint.Unsigned memory) {
return _getOraclePrice(emergencyShutdownTimestamp);
}
// Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0.
function _resetWithdrawalRequest(PositionData storage positionData) internal {
positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0);
positionData.withdrawalRequestPassTimestamp = 0;
}
// Ensure individual and global consistency when increasing collateral balances. Returns the change to the position.
function _incrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_addCollateral(positionData.rawCollateral, collateralAmount);
return _addCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the
// position. We elect to return the amount that the global collateral is decreased by, rather than the individual
// position's collateral, because we need to maintain the invariant that the global collateral is always
// <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn.
function _decrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position.
// This function is similar to the _decrementCollateralBalances function except this function checks position GCR
// between the decrements. This ensures that collateral removal will not leave the position undercollateralized.
function _decrementCollateralBalancesCheckGCR(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
require(_checkPositionCollateralization(positionData), "CR below GCR");
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _onlyCollateralizedPosition(address sponsor) internal view {
require(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0));
}
// Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the
// `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral
// or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`.
function _positionHasNoPendingWithdrawal(address sponsor) internal view {
require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0);
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) {
return
_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral),
positionData.tokensOutstanding
);
}
// Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global
// collateralization ratio.
function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
view
returns (bool)
{
FixedPoint.Unsigned memory global =
_getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding);
FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens);
return !global.isGreaterThan(thisChange);
}
function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
pure
returns (FixedPoint.Unsigned memory ratio)
{
return numTokens.isLessThanOrEqual(0) ? FixedPoint.fromUnscaledUint(0) : collateral.div(numTokens);
}
function _getTokenAddress() internal view override returns (address) {
return address(tokenCurrency);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/interfaces/IERC20Standard.sol";
import "../../oracle/implementation/ContractCreator.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/AddressWhitelist.sol";
import "../../common/implementation/Lockable.sol";
import "../common/TokenFactory.sol";
import "../common/SyntheticToken.sol";
import "./PerpetualLib.sol";
import "./ConfigStore.sol";
/**
* @title Perpetual Contract creator.
* @notice Factory contract to create and register new instances of perpetual contracts.
* Responsible for constraining the parameters used to construct a new perpetual. This creator contains a number of constraints
* that are applied to newly created contract. These constraints can evolve over time and are
* initially constrained to conservative values in this first iteration. Technically there is nothing in the
* Perpetual contract requiring these constraints. However, because `createPerpetual()` is intended
* to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract),
we can enforce deployment configurations here.
*/
contract PerpetualCreator is ContractCreator, Testable, Lockable {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* PERP CREATOR DATA STRUCTURES *
****************************************/
// Immutable params for perpetual contract.
struct Params {
address collateralAddress;
bytes32 priceFeedIdentifier;
bytes32 fundingRateIdentifier;
string syntheticName;
string syntheticSymbol;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPct;
FixedPoint.Unsigned sponsorDisputeRewardPct;
FixedPoint.Unsigned disputerDisputeRewardPct;
FixedPoint.Unsigned minSponsorTokens;
FixedPoint.Unsigned tokenScaling;
uint256 withdrawalLiveness;
uint256 liquidationLiveness;
}
// Address of TokenFactory used to create a new synthetic token.
address public tokenFactoryAddress;
event CreatedPerpetual(address indexed perpetualAddress, address indexed deployerAddress);
event CreatedConfigStore(address indexed configStoreAddress, address indexed ownerAddress);
/**
* @notice Constructs the Perpetual contract.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances.
* @param _timerAddress Contract that stores the current time in a testing environment.
*/
constructor(
address _finderAddress,
address _tokenFactoryAddress,
address _timerAddress
) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() {
tokenFactoryAddress = _tokenFactoryAddress;
}
/**
* @notice Creates an instance of perpetual and registers it within the registry.
* @param params is a `ConstructorParams` object from Perpetual.
* @return address of the deployed contract.
*/
function createPerpetual(Params memory params, ConfigStore.ConfigSettings memory configSettings)
public
nonReentrant()
returns (address)
{
require(bytes(params.syntheticName).length != 0, "Missing synthetic name");
require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol");
// Create new config settings store for this contract and reset ownership to the deployer.
ConfigStore configStore = new ConfigStore(configSettings, timerAddress);
configStore.transferOwnership(msg.sender);
emit CreatedConfigStore(address(configStore), configStore.owner());
// Create a new synthetic token using the params.
TokenFactory tf = TokenFactory(tokenFactoryAddress);
// If the collateral token does not have a `decimals()` method,
// then a default precision of 18 will be applied to the newly created synthetic token.
uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress);
ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals);
address derivative = PerpetualLib.deploy(_convertParams(params, tokenCurrency, address(configStore)));
// Give permissions to new derivative contract and then hand over ownership.
tokenCurrency.addMinter(derivative);
tokenCurrency.addBurner(derivative);
tokenCurrency.resetOwner(derivative);
_registerContract(new address[](0), derivative);
emit CreatedPerpetual(derivative, msg.sender);
return derivative;
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
// Converts createPerpetual params to Perpetual constructor params.
function _convertParams(
Params memory params,
ExpandedIERC20 newTokenCurrency,
address configStore
) private view returns (Perpetual.ConstructorParams memory constructorParams) {
// Known from creator deployment.
constructorParams.finderAddress = finderAddress;
constructorParams.timerAddress = timerAddress;
// Enforce configuration constraints.
require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0");
require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0");
_requireWhitelistedCollateral(params.collateralAddress);
// We don't want perpetual deployers to be able to intentionally or unintentionally set
// liveness periods that could induce arithmetic overflow, but we also don't want
// to be opinionated about what livenesses are "correct", so we will somewhat
// arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness
// periods even greater than a few days would make the perpetual unusable for most users.
require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large");
require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large");
// To avoid precision loss or overflows, prevent the token scaling from being too large or too small.
FixedPoint.Unsigned memory minScaling = FixedPoint.Unsigned(1e8); // 1e-10
FixedPoint.Unsigned memory maxScaling = FixedPoint.Unsigned(1e28); // 1e10
require(
params.tokenScaling.isGreaterThan(minScaling) && params.tokenScaling.isLessThan(maxScaling),
"Invalid tokenScaling"
);
// Input from function call.
constructorParams.configStoreAddress = configStore;
constructorParams.tokenAddress = address(newTokenCurrency);
constructorParams.collateralAddress = params.collateralAddress;
constructorParams.priceFeedIdentifier = params.priceFeedIdentifier;
constructorParams.fundingRateIdentifier = params.fundingRateIdentifier;
constructorParams.collateralRequirement = params.collateralRequirement;
constructorParams.disputeBondPct = params.disputeBondPct;
constructorParams.sponsorDisputeRewardPct = params.sponsorDisputeRewardPct;
constructorParams.disputerDisputeRewardPct = params.disputerDisputeRewardPct;
constructorParams.minSponsorTokens = params.minSponsorTokens;
constructorParams.withdrawalLiveness = params.withdrawalLiveness;
constructorParams.liquidationLiveness = params.liquidationLiveness;
constructorParams.tokenScaling = params.tokenScaling;
}
// IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method,
// which is possible since the method is only an OPTIONAL method in the ERC20 standard:
// https://eips.ethereum.org/EIPS/eip-20#methods.
function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) {
try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) {
return _decimals;
} catch {
return 18;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./Perpetual.sol";
/**
* @title Provides convenient Perpetual Multi Party contract utilities.
* @dev Using this library to deploy Perpetuals allows calling contracts to avoid importing the full bytecode.
*/
library PerpetualLib {
/**
* @notice Returns address of new Perpetual deployed with given `params` configuration.
* @dev Caller will need to register new Perpetual with the Registry to begin requesting prices. Caller is also
* responsible for enforcing constraints on `params`.
* @param params is a `ConstructorParams` object from Perpetual.
* @return address of the deployed Perpetual contract
*/
function deploy(Perpetual.ConstructorParams memory params) public returns (address) {
Perpetual derivative = new Perpetual(params);
return address(derivative);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Testable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../common/financial-product-libraries/FinancialProductLibrary.sol";
contract ExpiringMultiPartyMock is Testable {
using FixedPoint for FixedPoint.Unsigned;
FinancialProductLibrary public financialProductLibrary;
uint256 public expirationTimestamp;
FixedPoint.Unsigned public collateralRequirement;
bytes32 public priceIdentifier;
constructor(
address _financialProductLibraryAddress,
uint256 _expirationTimestamp,
FixedPoint.Unsigned memory _collateralRequirement,
bytes32 _priceIdentifier,
address _timerAddress
) public Testable(_timerAddress) {
expirationTimestamp = _expirationTimestamp;
collateralRequirement = _collateralRequirement;
financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress);
priceIdentifier = _priceIdentifier;
}
function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime)
public
view
returns (FixedPoint.Unsigned memory)
{
if (address(financialProductLibrary) == address(0)) return price;
try financialProductLibrary.transformPrice(price, requestTime) returns (
FixedPoint.Unsigned memory transformedPrice
) {
return transformedPrice;
} catch {
return price;
}
}
function transformCollateralRequirement(FixedPoint.Unsigned memory price)
public
view
returns (FixedPoint.Unsigned memory)
{
if (address(financialProductLibrary) == address(0)) return collateralRequirement;
try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns (
FixedPoint.Unsigned memory transformedCollateralRequirement
) {
return transformedCollateralRequirement;
} catch {
return collateralRequirement;
}
}
function transformPriceIdentifier(uint256 requestTime) public view returns (bytes32) {
if (address(financialProductLibrary) == address(0)) return priceIdentifier;
try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns (
bytes32 transformedIdentifier
) {
return transformedIdentifier;
} catch {
return priceIdentifier;
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../common/financial-product-libraries/FinancialProductLibrary.sol";
// Implements a simple FinancialProductLibrary to test price and collateral requirement transoformations.
contract FinancialProductLibraryTest is FinancialProductLibrary {
FixedPoint.Unsigned public priceTransformationScalar;
FixedPoint.Unsigned public collateralRequirementTransformationScalar;
bytes32 public transformedPriceIdentifier;
bool public shouldRevert;
constructor(
FixedPoint.Unsigned memory _priceTransformationScalar,
FixedPoint.Unsigned memory _collateralRequirementTransformationScalar,
bytes32 _transformedPriceIdentifier
) public {
priceTransformationScalar = _priceTransformationScalar;
collateralRequirementTransformationScalar = _collateralRequirementTransformationScalar;
transformedPriceIdentifier = _transformedPriceIdentifier;
}
// Set the mocked methods to revert to test failed library computation.
function setShouldRevert(bool _shouldRevert) public {
shouldRevert = _shouldRevert;
}
// Create a simple price transformation function that scales the input price by the scalar for testing.
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
returns (FixedPoint.Unsigned memory)
{
require(!shouldRevert, "set to always reverts");
return oraclePrice.mul(priceTransformationScalar);
}
// Create a simple collateral requirement transformation that doubles the input collateralRequirement.
function transformCollateralRequirement(
FixedPoint.Unsigned memory price,
FixedPoint.Unsigned memory collateralRequirement
) public view override returns (FixedPoint.Unsigned memory) {
require(!shouldRevert, "set to always reverts");
return collateralRequirement.mul(collateralRequirementTransformationScalar);
}
// Create a simple transformPriceIdentifier function that returns the transformed price identifier.
function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime)
public
view
override
returns (bytes32)
{
require(!shouldRevert, "set to always reverts");
return transformedPriceIdentifier;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../common/FundingRateApplier.sol";
import "../../common/implementation/FixedPoint.sol";
// Implements FundingRateApplier internal methods to enable unit testing.
contract FundingRateApplierTest is FundingRateApplier {
constructor(
bytes32 _fundingRateIdentifier,
address _collateralAddress,
address _finderAddress,
address _configStoreAddress,
FixedPoint.Unsigned memory _tokenScaling,
address _timerAddress
)
public
FundingRateApplier(
_fundingRateIdentifier,
_collateralAddress,
_finderAddress,
_configStoreAddress,
_tokenScaling,
_timerAddress
)
{}
function calculateEffectiveFundingRate(
uint256 paymentPeriodSeconds,
FixedPoint.Signed memory fundingRatePerSecond,
FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier
) public pure returns (FixedPoint.Unsigned memory) {
return
_calculateEffectiveFundingRate(
paymentPeriodSeconds,
fundingRatePerSecond,
currentCumulativeFundingRateMultiplier
);
}
// Required overrides.
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory currentPfc) {
return FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this)));
}
function emergencyShutdown() external override {}
function remargin() external override {}
function _getTokenAddress() internal view override returns (address) {
return address(collateralCurrency);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Used internally by Truffle migrations.
* @dev See https://www.trufflesuite.com/docs/truffle/getting-started/running-migrations#initial-migration for details.
*/
contract Migrations {
address public owner;
uint256 public last_completed_migration;
constructor() public {
owner = msg.sender;
}
modifier restricted() {
if (msg.sender == owner) _;
}
function setCompleted(uint256 completed) public restricted {
last_completed_migration = completed;
}
function upgrade(address new_address) public restricted {
Migrations upgraded = Migrations(new_address);
upgraded.setCompleted(last_completed_migration);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/MultiRole.sol";
import "../../common/implementation/Withdrawable.sol";
import "../interfaces/VotingInterface.sol";
import "../interfaces/FinderInterface.sol";
import "./Constants.sol";
/**
* @title Proxy to allow voting from another address.
* @dev Allows a UMA token holder to designate another address to vote on their behalf.
* Each voter must deploy their own instance of this contract.
*/
contract DesignatedVoting is Withdrawable {
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Owner, // Can set the Voter role. Is also permanently permissioned as the minter role.
Voter // Can vote through this contract.
}
// Reference to the UMA Finder contract, allowing Voting upgrades to be performed
// without requiring any calls to this contract.
FinderInterface private finder;
/**
* @notice Construct the DesignatedVoting contract.
* @param finderAddress keeps track of all contracts within the system based on their interfaceName.
* @param ownerAddress address of the owner of the DesignatedVoting contract.
* @param voterAddress address to which the owner has delegated their voting power.
*/
constructor(
address finderAddress,
address ownerAddress,
address voterAddress
) public {
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), ownerAddress);
_createExclusiveRole(uint256(Roles.Voter), uint256(Roles.Owner), voterAddress);
_setWithdrawRole(uint256(Roles.Owner));
finder = FinderInterface(finderAddress);
}
/****************************************
* VOTING AND REWARD FUNCTIONALITY *
****************************************/
/**
* @notice Forwards a commit to Voting.
* @param identifier uniquely identifies the feed for this vote. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price being voted on.
* @param hash the keccak256 hash of the price you want to vote for and a random integer salt value.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes32 hash
) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().commitVote(identifier, time, hash);
}
/**
* @notice Forwards a batch commit to Voting.
* @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(VotingInterface.Commitment[] calldata commits) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().batchCommit(commits);
}
/**
* @notice Forwards a reveal to Voting.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price being voted on.
* @param price used along with the `salt` to produce the `hash` during the commit phase.
* @param salt used along with the `price` to produce the `hash` during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
int256 salt
) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().revealVote(identifier, time, price, salt);
}
/**
* @notice Forwards a batch reveal to Voting.
* @param reveals is an array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(VotingInterface.Reveal[] calldata reveals) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().batchReveal(reveals);
}
/**
* @notice Forwards a reward retrieval to Voting.
* @dev Rewards are added to the tokens already held by this contract.
* @param roundId defines the round from which voting rewards will be retrieved from.
* @param toRetrieve an array of PendingRequests which rewards are retrieved from.
* @return amount of rewards that the user should receive.
*/
function retrieveRewards(uint256 roundId, VotingInterface.PendingRequest[] memory toRetrieve)
public
onlyRoleHolder(uint256(Roles.Voter))
returns (FixedPoint.Unsigned memory)
{
return _getVotingAddress().retrieveRewards(address(this), roundId, toRetrieve);
}
function _getVotingAddress() private view returns (VotingInterface) {
return VotingInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "./VotingAncillaryInterface.sol";
/**
* @title Interface that voters must use to Vote on price request resolutions.
*/
abstract contract VotingInterface {
struct PendingRequest {
bytes32 identifier;
uint256 time;
}
// Captures the necessary data for making a commitment.
// Used as a parameter when making batch commitments.
// Not used as a data structure for storage.
struct Commitment {
bytes32 identifier;
uint256 time;
bytes32 hash;
bytes encryptedVote;
}
// Captures the necessary data for revealing a vote.
// Used as a parameter when making batch reveals.
// Not used as a data structure for storage.
struct Reveal {
bytes32 identifier;
uint256 time;
int256 price;
int256 salt;
}
/**
* @notice Commit a vote for a price request for `identifier` at `time`.
* @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase.
* Commits can be changed.
* @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior,
* voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then
* they can determine the vote pre-reveal.
* @param identifier uniquely identifies the committed vote. EG BTC/USD price pair.
* @param time unix timestamp of the price being voted on.
* @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes32 hash
) external virtual;
/**
* @notice Submit a batch of commits in a single transaction.
* @dev Using `encryptedVote` is optional. If included then commitment is stored on chain.
* Look at `project-root/common/Constants.js` for the tested maximum number of
* commitments that can fit in one transaction.
* @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(Commitment[] memory commits) public virtual;
/**
* @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote
* @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to
* retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience.
* @param identifier unique price pair identifier. Eg: BTC/USD price pair.
* @param time unix timestamp of for the price request.
* @param hash keccak256 hash of the price you want to vote for and a `int256 salt`.
* @param encryptedVote offchain encrypted blob containing the voters amount, time and salt.
*/
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes32 hash,
bytes memory encryptedVote
) public virtual;
/**
* @notice snapshot the current round's token balances and lock in the inflation rate and GAT.
* @dev This function can be called multiple times but each round will only every have one snapshot at the
* time of calling `_freezeRoundVariables`.
* @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the
* snapshot.
*/
function snapshotCurrentRound(bytes calldata signature) external virtual;
/**
* @notice Reveal a previously committed vote for `identifier` at `time`.
* @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash`
* that `commitVote()` was called with. Only the committer can reveal their vote.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price is being voted on.
* @param price voted on during the commit phase.
* @param salt value used to hide the commitment price during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
int256 salt
) public virtual;
/**
* @notice Reveal multiple votes in a single transaction.
* Look at `project-root/common/Constants.js` for the tested maximum number of reveals.
* that can fit in one transaction.
* @dev For more information on reveals, review the comment for `revealVote`.
* @param reveals array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(Reveal[] memory reveals) public virtual;
/**
* @notice Gets the queries that are being voted on this round.
* @return pendingRequests `PendingRequest` array containing identifiers
* and timestamps for all pending requests.
*/
function getPendingRequests()
external
view
virtual
returns (VotingAncillaryInterface.PendingRequestAncillary[] memory);
/**
* @notice Returns the current voting phase, as a function of the current time.
* @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }.
*/
function getVotePhase() external view virtual returns (VotingAncillaryInterface.Phase);
/**
* @notice Returns the current round ID, as a function of the current time.
* @return uint256 representing the unique round ID.
*/
function getCurrentRoundId() external view virtual returns (uint256);
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
* @dev Can only retrieve rewards if calling for a valid round and if the
* call is done within the timeout threshold (not expired).
* @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller.
* @param roundId the round from which voting rewards will be retrieved from.
* @param toRetrieve array of PendingRequests which rewards are retrieved from.
* @return total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequest[] memory toRetrieve
) public virtual returns (FixedPoint.Unsigned memory);
// Voting Owner functions.
/**
* @notice Disables this Voting contract in favor of the migrated one.
* @dev Can only be called by the contract owner.
* @param newVotingAddress the newly migrated contract address.
*/
function setMigrated(address newVotingAddress) external virtual;
/**
* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newInflationRate sets the next round's inflation rate.
*/
function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual;
/**
* @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newGatPercentage sets the next round's Gat percentage.
*/
function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual;
/**
* @notice Resets the rewards expiration timeout.
* @dev This change only applies to rounds that have not yet begun.
* @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards.
*/
function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Interface that voters must use to Vote on price request resolutions.
*/
abstract contract VotingAncillaryInterface {
struct PendingRequestAncillary {
bytes32 identifier;
uint256 time;
bytes ancillaryData;
}
// Captures the necessary data for making a commitment.
// Used as a parameter when making batch commitments.
// Not used as a data structure for storage.
struct CommitmentAncillary {
bytes32 identifier;
uint256 time;
bytes ancillaryData;
bytes32 hash;
bytes encryptedVote;
}
// Captures the necessary data for revealing a vote.
// Used as a parameter when making batch reveals.
// Not used as a data structure for storage.
struct RevealAncillary {
bytes32 identifier;
uint256 time;
int256 price;
bytes ancillaryData;
int256 salt;
}
// Note: the phases must be in order. Meaning the first enum value must be the first phase, etc.
// `NUM_PHASES_PLACEHOLDER` is to get the number of phases. It isn't an actual phase, and it should always be last.
enum Phase { Commit, Reveal, NUM_PHASES_PLACEHOLDER }
/**
* @notice Commit a vote for a price request for `identifier` at `time`.
* @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase.
* Commits can be changed.
* @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior,
* voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then
* they can determine the vote pre-reveal.
* @param identifier uniquely identifies the committed vote. EG BTC/USD price pair.
* @param time unix timestamp of the price being voted on.
* @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash
) public virtual;
/**
* @notice Submit a batch of commits in a single transaction.
* @dev Using `encryptedVote` is optional. If included then commitment is stored on chain.
* Look at `project-root/common/Constants.js` for the tested maximum number of
* commitments that can fit in one transaction.
* @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(CommitmentAncillary[] memory commits) public virtual;
/**
* @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote
* @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to
* retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience.
* @param identifier unique price pair identifier. Eg: BTC/USD price pair.
* @param time unix timestamp of for the price request.
* @param hash keccak256 hash of the price you want to vote for and a `int256 salt`.
* @param encryptedVote offchain encrypted blob containing the voters amount, time and salt.
*/
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash,
bytes memory encryptedVote
) public virtual;
/**
* @notice snapshot the current round's token balances and lock in the inflation rate and GAT.
* @dev This function can be called multiple times but each round will only every have one snapshot at the
* time of calling `_freezeRoundVariables`.
* @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the
* snapshot.
*/
function snapshotCurrentRound(bytes calldata signature) external virtual;
/**
* @notice Reveal a previously committed vote for `identifier` at `time`.
* @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash`
* that `commitVote()` was called with. Only the committer can reveal their vote.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price is being voted on.
* @param price voted on during the commit phase.
* @param salt value used to hide the commitment price during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
bytes memory ancillaryData,
int256 salt
) public virtual;
/**
* @notice Reveal multiple votes in a single transaction.
* Look at `project-root/common/Constants.js` for the tested maximum number of reveals.
* that can fit in one transaction.
* @dev For more information on reveals, review the comment for `revealVote`.
* @param reveals array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(RevealAncillary[] memory reveals) public virtual;
/**
* @notice Gets the queries that are being voted on this round.
* @return pendingRequests `PendingRequest` array containing identifiers
* and timestamps for all pending requests.
*/
function getPendingRequests() external view virtual returns (PendingRequestAncillary[] memory);
/**
* @notice Returns the current voting phase, as a function of the current time.
* @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }.
*/
function getVotePhase() external view virtual returns (Phase);
/**
* @notice Returns the current round ID, as a function of the current time.
* @return uint256 representing the unique round ID.
*/
function getCurrentRoundId() external view virtual returns (uint256);
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
* @dev Can only retrieve rewards if calling for a valid round and if the
* call is done within the timeout threshold (not expired).
* @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller.
* @param roundId the round from which voting rewards will be retrieved from.
* @param toRetrieve array of PendingRequests which rewards are retrieved from.
* @return total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequestAncillary[] memory toRetrieve
) public virtual returns (FixedPoint.Unsigned memory);
// Voting Owner functions.
/**
* @notice Disables this Voting contract in favor of the migrated one.
* @dev Can only be called by the contract owner.
* @param newVotingAddress the newly migrated contract address.
*/
function setMigrated(address newVotingAddress) external virtual;
/**
* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newInflationRate sets the next round's inflation rate.
*/
function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual;
/**
* @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newGatPercentage sets the next round's Gat percentage.
*/
function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual;
/**
* @notice Resets the rewards expiration timeout.
* @dev This change only applies to rounds that have not yet begun.
* @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards.
*/
function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Withdrawable.sol";
import "./DesignatedVoting.sol";
/**
* @title Factory to deploy new instances of DesignatedVoting and look up previously deployed instances.
* @dev Allows off-chain infrastructure to look up a hot wallet's deployed DesignatedVoting contract.
*/
contract DesignatedVotingFactory is Withdrawable {
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Withdrawer // Can withdraw any ETH or ERC20 sent accidentally to this contract.
}
address private finder;
mapping(address => DesignatedVoting) public designatedVotingContracts;
/**
* @notice Construct the DesignatedVotingFactory contract.
* @param finderAddress keeps track of all contracts within the system based on their interfaceName.
*/
constructor(address finderAddress) public {
finder = finderAddress;
_createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Withdrawer), msg.sender);
}
/**
* @notice Deploys a new `DesignatedVoting` contract.
* @param ownerAddress defines who will own the deployed instance of the designatedVoting contract.
* @return designatedVoting a new DesignatedVoting contract.
*/
function newDesignatedVoting(address ownerAddress) external returns (DesignatedVoting) {
require(address(designatedVotingContracts[msg.sender]) == address(0), "Duplicate hot key not permitted");
DesignatedVoting designatedVoting = new DesignatedVoting(finder, ownerAddress, msg.sender);
designatedVotingContracts[msg.sender] = designatedVoting;
return designatedVoting;
}
/**
* @notice Associates a `DesignatedVoting` instance with `msg.sender`.
* @param designatedVotingAddress address to designate voting to.
* @dev This is generally only used if the owner of a `DesignatedVoting` contract changes their `voter`
* address and wants that reflected here.
*/
function setDesignatedVoting(address designatedVotingAddress) external {
require(address(designatedVotingContracts[msg.sender]) == address(0), "Duplicate hot key not permitted");
designatedVotingContracts[msg.sender] = DesignatedVoting(designatedVotingAddress);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/AdministrateeInterface.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title Admin for financial contracts in the UMA system.
* @dev Allows appropriately permissioned admin roles to interact with financial contracts.
*/
contract FinancialContractsAdmin is Ownable {
/**
* @notice Calls emergency shutdown on the provided financial contract.
* @param financialContract address of the FinancialContract to be shut down.
*/
function callEmergencyShutdown(address financialContract) external onlyOwner {
AdministrateeInterface administratee = AdministrateeInterface(financialContract);
administratee.emergencyShutdown();
}
/**
* @notice Calls remargin on the provided financial contract.
* @param financialContract address of the FinancialContract to be remargined.
*/
function callRemargin(address financialContract) external onlyOwner {
AdministrateeInterface administratee = AdministrateeInterface(financialContract);
administratee.remargin();
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "../interfaces/FinderInterface.sol";
/**
* @title Provides addresses of the live contracts implementing certain interfaces.
* @dev Examples of interfaces with implementations that Finder locates are the Oracle and Store interfaces.
*/
contract Finder is FinderInterface, Ownable {
mapping(bytes32 => address) public interfacesImplemented;
event InterfaceImplementationChanged(bytes32 indexed interfaceName, address indexed newImplementationAddress);
/**
* @notice Updates the address of the contract that implements `interfaceName`.
* @param interfaceName bytes32 of the interface name that is either changed or registered.
* @param implementationAddress address of the implementation contract.
*/
function changeImplementationAddress(bytes32 interfaceName, address implementationAddress)
external
override
onlyOwner
{
interfacesImplemented[interfaceName] = implementationAddress;
emit InterfaceImplementationChanged(interfaceName, implementationAddress);
}
/**
* @notice Gets the address of the contract that implements the given `interfaceName`.
* @param interfaceName queried interface.
* @return implementationAddress address of the defined interface.
*/
function getImplementationAddress(bytes32 interfaceName) external view override returns (address) {
address implementationAddress = interfacesImplemented[interfaceName];
require(implementationAddress != address(0x0), "Implementation not found");
return implementationAddress;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/MultiRole.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/FinderInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/OracleInterface.sol";
import "./Constants.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
/**
* @title Takes proposals for certain governance actions and allows UMA token holders to vote on them.
*/
contract Governor is MultiRole, Testable {
using SafeMath for uint256;
using Address for address;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Owner, // Can set the proposer.
Proposer // Address that can make proposals.
}
struct Transaction {
address to;
uint256 value;
bytes data;
}
struct Proposal {
Transaction[] transactions;
uint256 requestTime;
}
FinderInterface private finder;
Proposal[] public proposals;
/****************************************
* EVENTS *
****************************************/
// Emitted when a new proposal is created.
event NewProposal(uint256 indexed id, Transaction[] transactions);
// Emitted when an existing proposal is executed.
event ProposalExecuted(uint256 indexed id, uint256 transactionIndex);
/**
* @notice Construct the Governor contract.
* @param _finderAddress keeps track of all contracts within the system based on their interfaceName.
* @param _startingId the initial proposal id that the contract will begin incrementing from.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
address _finderAddress,
uint256 _startingId,
address _timerAddress
) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
_createExclusiveRole(uint256(Roles.Proposer), uint256(Roles.Owner), msg.sender);
// Ensure the startingId is not set unreasonably high to avoid it being set such that new proposals overwrite
// other storage slots in the contract.
uint256 maxStartingId = 10**18;
require(_startingId <= maxStartingId, "Cannot set startingId larger than 10^18");
// This just sets the initial length of the array to the startingId since modifying length directly has been
// disallowed in solidity 0.6.
assembly {
sstore(proposals_slot, _startingId)
}
}
/****************************************
* PROPOSAL ACTIONS *
****************************************/
/**
* @notice Proposes a new governance action. Can only be called by the holder of the Proposer role.
* @param transactions list of transactions that are being proposed.
* @dev You can create the data portion of each transaction by doing the following:
* ```
* const truffleContractInstance = await TruffleContract.deployed()
* const data = truffleContractInstance.methods.methodToCall(arg1, arg2).encodeABI()
* ```
* Note: this method must be public because of a solidity limitation that
* disallows structs arrays to be passed to external functions.
*/
function propose(Transaction[] memory transactions) public onlyRoleHolder(uint256(Roles.Proposer)) {
uint256 id = proposals.length;
uint256 time = getCurrentTime();
// Note: doing all of this array manipulation manually is necessary because directly setting an array of
// structs in storage to an an array of structs in memory is currently not implemented in solidity :/.
// Add a zero-initialized element to the proposals array.
proposals.push();
// Initialize the new proposal.
Proposal storage proposal = proposals[id];
proposal.requestTime = time;
// Initialize the transaction array.
for (uint256 i = 0; i < transactions.length; i++) {
require(transactions[i].to != address(0), "The `to` address cannot be 0x0");
// If the transaction has any data with it the recipient must be a contract, not an EOA.
if (transactions[i].data.length > 0) {
require(transactions[i].to.isContract(), "EOA can't accept tx with data");
}
proposal.transactions.push(transactions[i]);
}
bytes32 identifier = _constructIdentifier(id);
// Request a vote on this proposal in the DVM.
OracleInterface oracle = _getOracle();
IdentifierWhitelistInterface supportedIdentifiers = _getIdentifierWhitelist();
supportedIdentifiers.addSupportedIdentifier(identifier);
oracle.requestPrice(identifier, time);
supportedIdentifiers.removeSupportedIdentifier(identifier);
emit NewProposal(id, transactions);
}
/**
* @notice Executes a proposed governance action that has been approved by voters.
* @dev This can be called by any address. Caller is expected to send enough ETH to execute payable transactions.
* @param id unique id for the executed proposal.
* @param transactionIndex unique transaction index for the executed proposal.
*/
function executeProposal(uint256 id, uint256 transactionIndex) external payable {
Proposal storage proposal = proposals[id];
int256 price = _getOracle().getPrice(_constructIdentifier(id), proposal.requestTime);
Transaction memory transaction = proposal.transactions[transactionIndex];
require(
transactionIndex == 0 || proposal.transactions[transactionIndex.sub(1)].to == address(0),
"Previous tx not yet executed"
);
require(transaction.to != address(0), "Tx already executed");
require(price != 0, "Proposal was rejected");
require(msg.value == transaction.value, "Must send exact amount of ETH");
// Delete the transaction before execution to avoid any potential re-entrancy issues.
delete proposal.transactions[transactionIndex];
require(_executeCall(transaction.to, transaction.value, transaction.data), "Tx execution failed");
emit ProposalExecuted(id, transactionIndex);
}
/****************************************
* GOVERNOR STATE GETTERS *
****************************************/
/**
* @notice Gets the total number of proposals (includes executed and non-executed).
* @return uint256 representing the current number of proposals.
*/
function numProposals() external view returns (uint256) {
return proposals.length;
}
/**
* @notice Gets the proposal data for a particular id.
* @dev after a proposal is executed, its data will be zeroed out, except for the request time.
* @param id uniquely identify the identity of the proposal.
* @return proposal struct containing transactions[] and requestTime.
*/
function getProposal(uint256 id) external view returns (Proposal memory) {
return proposals[id];
}
/****************************************
* PRIVATE GETTERS AND FUNCTIONS *
****************************************/
function _executeCall(
address to,
uint256 value,
bytes memory data
) private returns (bool) {
// Mostly copied from:
// solhint-disable-next-line max-line-length
// https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31
// solhint-disable-next-line no-inline-assembly
bool success;
assembly {
let inputData := add(data, 0x20)
let inputDataSize := mload(data)
success := call(gas(), to, value, inputData, inputDataSize, 0, 0)
}
return success;
}
function _getOracle() private view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
// Returns a UTF-8 identifier representing a particular admin proposal.
// The identifier is of the form "Admin n", where n is the proposal id provided.
function _constructIdentifier(uint256 id) internal pure returns (bytes32) {
bytes32 bytesId = _uintToUtf8(id);
return _addPrefix(bytesId, "Admin ", 6);
}
// This method converts the integer `v` into a base-10, UTF-8 representation stored in a `bytes32` type.
// If the input cannot be represented by 32 base-10 digits, it returns only the highest 32 digits.
// This method is based off of this code: https://ethereum.stackexchange.com/a/6613/47801.
function _uintToUtf8(uint256 v) internal pure returns (bytes32) {
bytes32 ret;
if (v == 0) {
// Handle 0 case explicitly.
ret = "0";
} else {
// Constants.
uint256 bitsPerByte = 8;
uint256 base = 10; // Note: the output should be base-10. The below implementation will not work for bases > 10.
uint256 utf8NumberOffset = 48;
while (v > 0) {
// Downshift the entire bytes32 to allow the new digit to be added at the "front" of the bytes32, which
// translates to the beginning of the UTF-8 representation.
ret = ret >> bitsPerByte;
// Separate the last digit that remains in v by modding by the base of desired output representation.
uint256 leastSignificantDigit = v % base;
// Digits 0-9 are represented by 48-57 in UTF-8, so an offset must be added to create the character.
bytes32 utf8Digit = bytes32(leastSignificantDigit + utf8NumberOffset);
// The top byte of ret has already been cleared to make room for the new digit.
// Upshift by 31 bytes to put it in position, and OR it with ret to leave the other characters untouched.
ret |= utf8Digit << (31 * bitsPerByte);
// Divide v by the base to remove the digit that was just added.
v /= base;
}
}
return ret;
}
// This method takes two UTF-8 strings represented as bytes32 and outputs one as a prefixed by the other.
// `input` is the UTF-8 that should have the prefix prepended.
// `prefix` is the UTF-8 that should be prepended onto input.
// `prefixLength` is number of UTF-8 characters represented by `prefix`.
// Notes:
// 1. If the resulting UTF-8 is larger than 32 characters, then only the first 32 characters will be represented
// by the bytes32 output.
// 2. If `prefix` has more characters than `prefixLength`, the function will produce an invalid result.
function _addPrefix(
bytes32 input,
bytes32 prefix,
uint256 prefixLength
) internal pure returns (bytes32) {
// Downshift `input` to open space at the "front" of the bytes32
bytes32 shiftedInput = input >> (prefixLength * 8);
return shiftedInput | prefix;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/IdentifierWhitelistInterface.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title Stores a whitelist of supported identifiers that the oracle can provide prices for.
*/
contract IdentifierWhitelist is IdentifierWhitelistInterface, Ownable {
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
mapping(bytes32 => bool) private supportedIdentifiers;
/****************************************
* EVENTS *
****************************************/
event SupportedIdentifierAdded(bytes32 indexed identifier);
event SupportedIdentifierRemoved(bytes32 indexed identifier);
/****************************************
* ADMIN STATE MODIFYING FUNCTIONS *
****************************************/
/**
* @notice Adds the provided identifier as a supported identifier.
* @dev Price requests using this identifier will succeed after this call.
* @param identifier unique UTF-8 representation for the feed being added. Eg: BTC/USD.
*/
function addSupportedIdentifier(bytes32 identifier) external override onlyOwner {
if (!supportedIdentifiers[identifier]) {
supportedIdentifiers[identifier] = true;
emit SupportedIdentifierAdded(identifier);
}
}
/**
* @notice Removes the identifier from the whitelist.
* @dev Price requests using this identifier will no longer succeed after this call.
* @param identifier unique UTF-8 representation for the feed being removed. Eg: BTC/USD.
*/
function removeSupportedIdentifier(bytes32 identifier) external override onlyOwner {
if (supportedIdentifiers[identifier]) {
supportedIdentifiers[identifier] = false;
emit SupportedIdentifierRemoved(identifier);
}
}
/****************************************
* WHITELIST GETTERS FUNCTIONS *
****************************************/
/**
* @notice Checks whether an identifier is on the whitelist.
* @param identifier unique UTF-8 representation for the feed being queried. Eg: BTC/USD.
* @return bool if the identifier is supported (or not).
*/
function isIdentifierSupported(bytes32 identifier) external view override returns (bool) {
return supportedIdentifiers[identifier];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../interfaces/StoreInterface.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/FinderInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/OptimisticOracleInterface.sol";
import "./Constants.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/AddressWhitelist.sol";
/**
* @title Optimistic Requester.
* @notice Optional interface that requesters can implement to receive callbacks.
*/
interface OptimisticRequester {
/**
* @notice Callback for proposals.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data of the price being requested.
*/
function priceProposed(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external;
/**
* @notice Callback for disputes.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data of the price being requested.
* @param refund refund received in the case that refundOnDispute was enabled.
*/
function priceDisputed(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 refund
) external;
/**
* @notice Callback for settlement.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data of the price being requested.
* @param price price that was resolved by the escalation process.
*/
function priceSettled(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 price
) external;
}
/**
* @title Optimistic Oracle.
* @notice Pre-DVM escalation contract that allows faster settlement.
*/
contract OptimisticOracle is OptimisticOracleInterface, Testable, Lockable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
event RequestPrice(
address indexed requester,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
address currency,
uint256 reward,
uint256 finalFee
);
event ProposePrice(
address indexed requester,
address indexed proposer,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
int256 proposedPrice
);
event DisputePrice(
address indexed requester,
address indexed proposer,
address indexed disputer,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData
);
event Settle(
address indexed requester,
address indexed proposer,
address indexed disputer,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
int256 price,
uint256 payout
);
mapping(bytes32 => Request) public requests;
// Finder to provide addresses for DVM contracts.
FinderInterface public finder;
// Default liveness value for all price requests.
uint256 public defaultLiveness;
/**
* @notice Constructor.
* @param _liveness default liveness applied to each price request.
* @param _finderAddress finder to use to get addresses of DVM contracts.
* @param _timerAddress address of the timer contract. Should be 0x0 in prod.
*/
constructor(
uint256 _liveness,
address _finderAddress,
address _timerAddress
) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
_validateLiveness(_liveness);
defaultLiveness = _liveness;
}
/**
* @notice Requests a new price.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data representing additional args being passed with the price request.
* @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM.
* @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0,
* which could make sense if the contract requests and proposes the value in the same call or
* provides its own reward system.
* @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay.
* This can be changed with a subsequent call to setBond().
*/
function requestPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
IERC20 currency,
uint256 reward
) external override nonReentrant() returns (uint256 totalBond) {
require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Invalid, "requestPrice: Invalid");
require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier");
require(_getCollateralWhitelist().isOnWhitelist(address(currency)), "Unsupported currency");
require(timestamp <= getCurrentTime(), "Timestamp in future");
require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data");
uint256 finalFee = _getStore().computeFinalFee(address(currency)).rawValue;
requests[_getId(msg.sender, identifier, timestamp, ancillaryData)] = Request({
proposer: address(0),
disputer: address(0),
currency: currency,
settled: false,
refundOnDispute: false,
proposedPrice: 0,
resolvedPrice: 0,
expirationTime: 0,
reward: reward,
finalFee: finalFee,
bond: finalFee,
customLiveness: 0
});
if (reward > 0) {
currency.safeTransferFrom(msg.sender, address(this), reward);
}
emit RequestPrice(msg.sender, identifier, timestamp, ancillaryData, address(currency), reward, finalFee);
// This function returns the initial proposal bond for this request, which can be customized by calling
// setBond() with the same identifier and timestamp.
return finalFee.mul(2);
}
/**
* @notice Set the proposal bond associated with a price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param bond custom bond amount to set.
* @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be
* changed again with a subsequent call to setBond().
*/
function setBond(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 bond
) external override nonReentrant() returns (uint256 totalBond) {
require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setBond: Requested");
Request storage request = _getRequest(msg.sender, identifier, timestamp, ancillaryData);
request.bond = bond;
// Total bond is the final fee + the newly set bond.
return bond.add(request.finalFee);
}
/**
* @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller
* in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's
* bond, so there is still profit to be made even if the reward is refunded.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
*/
function setRefundOnDispute(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override nonReentrant() {
require(
getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested,
"setRefundOnDispute: Requested"
);
_getRequest(msg.sender, identifier, timestamp, ancillaryData).refundOnDispute = true;
}
/**
* @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before
* being auto-resolved.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param customLiveness new custom liveness.
*/
function setCustomLiveness(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 customLiveness
) external override nonReentrant() {
require(
getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested,
"setCustomLiveness: Requested"
);
_validateLiveness(customLiveness);
_getRequest(msg.sender, identifier, timestamp, ancillaryData).customLiveness = customLiveness;
}
/**
* @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come
* from this proposal. However, any bonds are pulled from the caller.
* @param proposer address to set as the proposer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePriceFor(
address proposer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) public override nonReentrant() returns (uint256 totalBond) {
require(proposer != address(0), "proposer address must be non 0");
require(
getState(requester, identifier, timestamp, ancillaryData) == State.Requested,
"proposePriceFor: Requested"
);
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
request.proposer = proposer;
request.proposedPrice = proposedPrice;
// If a custom liveness has been set, use it instead of the default.
request.expirationTime = getCurrentTime().add(
request.customLiveness != 0 ? request.customLiveness : defaultLiveness
);
totalBond = request.bond.add(request.finalFee);
if (totalBond > 0) {
request.currency.safeTransferFrom(msg.sender, address(this), totalBond);
}
// Event.
emit ProposePrice(requester, proposer, identifier, timestamp, ancillaryData, proposedPrice);
// Callback.
if (address(requester).isContract())
try OptimisticRequester(requester).priceProposed(identifier, timestamp, ancillaryData) {} catch {}
}
/**
* @notice Proposes a price value for an existing price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) external override returns (uint256 totalBond) {
// Note: re-entrancy guard is done in the inner call.
return proposePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData, proposedPrice);
}
/**
* @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will
* receive any rewards that come from this dispute. However, any bonds are pulled from the caller.
* @param disputer address to set as the disputer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePriceFor(
address disputer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public override nonReentrant() returns (uint256 totalBond) {
require(disputer != address(0), "disputer address must be non 0");
require(
getState(requester, identifier, timestamp, ancillaryData) == State.Proposed,
"disputePriceFor: Proposed"
);
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
request.disputer = disputer;
uint256 finalFee = request.finalFee;
totalBond = request.bond.add(finalFee);
if (totalBond > 0) {
request.currency.safeTransferFrom(msg.sender, address(this), totalBond);
}
StoreInterface store = _getStore();
if (finalFee > 0) {
request.currency.safeIncreaseAllowance(address(store), finalFee);
_getStore().payOracleFeesErc20(address(request.currency), FixedPoint.Unsigned(finalFee));
}
_getOracle().requestPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester));
// Compute refund.
uint256 refund = 0;
if (request.reward > 0 && request.refundOnDispute) {
refund = request.reward;
request.reward = 0;
request.currency.safeTransfer(requester, refund);
}
// Event.
emit DisputePrice(requester, request.proposer, disputer, identifier, timestamp, ancillaryData);
// Callback.
if (address(requester).isContract())
try OptimisticRequester(requester).priceDisputed(identifier, timestamp, ancillaryData, refund) {} catch {}
}
/**
* @notice Disputes a price value for an existing price request with an active proposal.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override returns (uint256 totalBond) {
// Note: re-entrancy guard is done in the inner call.
return disputePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData);
}
/**
* @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled
* or settleable. Note: this method is not view so that this call may actually settle the price request if it
* hasn't been settled.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return resolved price.
*/
function getPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override nonReentrant() returns (int256) {
if (getState(msg.sender, identifier, timestamp, ancillaryData) != State.Settled) {
_settle(msg.sender, identifier, timestamp, ancillaryData);
}
return _getRequest(msg.sender, identifier, timestamp, ancillaryData).resolvedPrice;
}
/**
* @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes
* the returned bonds as well as additional rewards.
*/
function settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override nonReentrant() returns (uint256 payout) {
return _settle(requester, identifier, timestamp, ancillaryData);
}
/**
* @notice Gets the current data structure containing all information about a price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the Request data structure.
*/
function getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view override returns (Request memory) {
return _getRequest(requester, identifier, timestamp, ancillaryData);
}
/**
* @notice Computes the current state of a price request. See the State enum for more details.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the State.
*/
function getState(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view override returns (State) {
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
if (address(request.currency) == address(0)) {
return State.Invalid;
}
if (request.proposer == address(0)) {
return State.Requested;
}
if (request.settled) {
return State.Settled;
}
if (request.disputer == address(0)) {
return request.expirationTime <= getCurrentTime() ? State.Expired : State.Proposed;
}
return
_getOracle().hasPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester))
? State.Resolved
: State.Disputed;
}
/**
* @notice Checks if a given request has resolved, expired or been settled (i.e the optimistic oracle has a price).
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return boolean indicating true if price exists and false if not.
*/
function hasPrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view override returns (bool) {
State state = getState(requester, identifier, timestamp, ancillaryData);
return state == State.Settled || state == State.Resolved || state == State.Expired;
}
/**
* @notice Generates stamped ancillary data in the format that it would be used in the case of a price dispute.
* @param ancillaryData ancillary data of the price being requested.
* @param requester sender of the initial price request.
* @return the stampped ancillary bytes.
*/
function stampAncillaryData(bytes memory ancillaryData, address requester) public pure returns (bytes memory) {
return _stampAncillaryData(ancillaryData, requester);
}
function _getId(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) private pure returns (bytes32) {
return keccak256(abi.encodePacked(requester, identifier, timestamp, ancillaryData));
}
function _settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) private returns (uint256 payout) {
State state = getState(requester, identifier, timestamp, ancillaryData);
// Set it to settled so this function can never be entered again.
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
request.settled = true;
if (state == State.Expired) {
// In the expiry case, just pay back the proposer's bond and final fee along with the reward.
request.resolvedPrice = request.proposedPrice;
payout = request.bond.add(request.finalFee).add(request.reward);
request.currency.safeTransfer(request.proposer, payout);
} else if (state == State.Resolved) {
// In the Resolved case, pay either the disputer or the proposer the entire payout (+ bond and reward).
request.resolvedPrice = _getOracle().getPrice(
identifier,
timestamp,
_stampAncillaryData(ancillaryData, requester)
);
bool disputeSuccess = request.resolvedPrice != request.proposedPrice;
payout = request.bond.mul(2).add(request.finalFee).add(request.reward);
request.currency.safeTransfer(disputeSuccess ? request.disputer : request.proposer, payout);
} else {
revert("_settle: not settleable");
}
// Event.
emit Settle(
requester,
request.proposer,
request.disputer,
identifier,
timestamp,
ancillaryData,
request.resolvedPrice,
payout
);
// Callback.
if (address(requester).isContract())
try
OptimisticRequester(requester).priceSettled(identifier, timestamp, ancillaryData, request.resolvedPrice)
{} catch {}
}
function _getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) private view returns (Request storage) {
return requests[_getId(requester, identifier, timestamp, ancillaryData)];
}
function _validateLiveness(uint256 _liveness) private pure {
require(_liveness < 5200 weeks, "Liveness too large");
require(_liveness > 0, "Liveness cannot be 0");
}
function _getOracle() internal view returns (OracleAncillaryInterface) {
return OracleAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getCollateralWhitelist() internal view returns (AddressWhitelist) {
return AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist));
}
function _getStore() internal view returns (StoreInterface) {
return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store));
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
// Stamps the ancillary data blob with the optimistic oracle tag denoting what contract requested it.
function _stampAncillaryData(bytes memory ancillaryData, address requester) internal pure returns (bytes memory) {
return abi.encodePacked(ancillaryData, "OptimisticOracle", requester);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OracleAncillaryInterface {
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param time unix timestamp for the price request.
*/
function requestPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public virtual;
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view virtual returns (bool);
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view virtual returns (int256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Computes vote results.
* @dev The result is the mode of the added votes. Otherwise, the vote is unresolved.
*/
library ResultComputation {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* INTERNAL LIBRARY DATA STRUCTURE *
****************************************/
struct Data {
// Maps price to number of tokens that voted for that price.
mapping(int256 => FixedPoint.Unsigned) voteFrequency;
// The total votes that have been added.
FixedPoint.Unsigned totalVotes;
// The price that is the current mode, i.e., the price with the highest frequency in `voteFrequency`.
int256 currentMode;
}
/****************************************
* VOTING FUNCTIONS *
****************************************/
/**
* @notice Adds a new vote to be used when computing the result.
* @param data contains information to which the vote is applied.
* @param votePrice value specified in the vote for the given `numberTokens`.
* @param numberTokens number of tokens that voted on the `votePrice`.
*/
function addVote(
Data storage data,
int256 votePrice,
FixedPoint.Unsigned memory numberTokens
) internal {
data.totalVotes = data.totalVotes.add(numberTokens);
data.voteFrequency[votePrice] = data.voteFrequency[votePrice].add(numberTokens);
if (
votePrice != data.currentMode &&
data.voteFrequency[votePrice].isGreaterThan(data.voteFrequency[data.currentMode])
) {
data.currentMode = votePrice;
}
}
/****************************************
* VOTING STATE GETTERS *
****************************************/
/**
* @notice Returns whether the result is resolved, and if so, what value it resolved to.
* @dev `price` should be ignored if `isResolved` is false.
* @param data contains information against which the `minVoteThreshold` is applied.
* @param minVoteThreshold min (exclusive) number of tokens that must have voted for the result to be valid. Can be
* used to enforce a minimum voter participation rate, regardless of how the votes are distributed.
* @return isResolved indicates if the price has been resolved correctly.
* @return price the price that the dvm resolved to.
*/
function getResolvedPrice(Data storage data, FixedPoint.Unsigned memory minVoteThreshold)
internal
view
returns (bool isResolved, int256 price)
{
FixedPoint.Unsigned memory modeThreshold = FixedPoint.fromUnscaledUint(50).div(100);
if (
data.totalVotes.isGreaterThan(minVoteThreshold) &&
data.voteFrequency[data.currentMode].div(data.totalVotes).isGreaterThan(modeThreshold)
) {
// `modeThreshold` and `minVoteThreshold` are exceeded, so the current mode is the resolved price.
isResolved = true;
price = data.currentMode;
} else {
isResolved = false;
}
}
/**
* @notice Checks whether a `voteHash` is considered correct.
* @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`.
* @param data contains information against which the `voteHash` is checked.
* @param voteHash committed hash submitted by the voter.
* @return bool true if the vote was correct.
*/
function wasVoteCorrect(Data storage data, bytes32 voteHash) internal view returns (bool) {
return voteHash == keccak256(abi.encode(data.currentMode));
}
/**
* @notice Gets the total number of tokens whose votes are considered correct.
* @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`.
* @param data contains all votes against which the correctly voted tokens are counted.
* @return FixedPoint.Unsigned which indicates the frequency of the correctly voted tokens.
*/
function getTotalCorrectlyVotedTokens(Data storage data) internal view returns (FixedPoint.Unsigned memory) {
return data.voteFrequency[data.currentMode];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/MultiRole.sol";
import "../../common/implementation/Withdrawable.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/StoreInterface.sol";
/**
* @title An implementation of Store that can accept Oracle fees in ETH or any arbitrary ERC20 token.
*/
contract Store is StoreInterface, Withdrawable, Testable {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for uint256;
using SafeERC20 for IERC20;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles { Owner, Withdrawer }
FixedPoint.Unsigned public fixedOracleFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% Oracle fee.
FixedPoint.Unsigned public weeklyDelayFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% weekly delay fee.
mapping(address => FixedPoint.Unsigned) public finalFees;
uint256 public constant SECONDS_PER_WEEK = 604800;
/****************************************
* EVENTS *
****************************************/
event NewFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned newOracleFee);
event NewWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned newWeeklyDelayFeePerSecondPerPfc);
event NewFinalFee(FixedPoint.Unsigned newFinalFee);
/**
* @notice Construct the Store contract.
*/
constructor(
FixedPoint.Unsigned memory _fixedOracleFeePerSecondPerPfc,
FixedPoint.Unsigned memory _weeklyDelayFeePerSecondPerPfc,
address _timerAddress
) public Testable(_timerAddress) {
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
_createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Owner), msg.sender);
setFixedOracleFeePerSecondPerPfc(_fixedOracleFeePerSecondPerPfc);
setWeeklyDelayFeePerSecondPerPfc(_weeklyDelayFeePerSecondPerPfc);
}
/****************************************
* ORACLE FEE CALCULATION AND PAYMENT *
****************************************/
/**
* @notice Pays Oracle fees in ETH to the store.
* @dev To be used by contracts whose margin currency is ETH.
*/
function payOracleFees() external payable override {
require(msg.value > 0, "Value sent can't be zero");
}
/**
* @notice Pays oracle fees in the margin currency, erc20Address, to the store.
* @dev To be used if the margin currency is an ERC20 token rather than ETH.
* @param erc20Address address of the ERC20 token used to pay the fee.
* @param amount number of tokens to transfer. An approval for at least this amount must exist.
*/
function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external override {
IERC20 erc20 = IERC20(erc20Address);
require(amount.isGreaterThan(0), "Amount sent can't be zero");
erc20.safeTransferFrom(msg.sender, address(this), amount.rawValue);
}
/**
* @notice Computes the regular oracle fees that a contract should pay for a period.
* @dev The late penalty is similar to the regular fee in that is is charged per second over the period between
* startTime and endTime.
*
* The late penalty percentage increases over time as follows:
*
* - 0-1 week since startTime: no late penalty
*
* - 1-2 weeks since startTime: 1x late penalty percentage is applied
*
* - 2-3 weeks since startTime: 2x late penalty percentage is applied
*
* - ...
*
* @param startTime defines the beginning time from which the fee is paid.
* @param endTime end time until which the fee is paid.
* @param pfc "profit from corruption", or the maximum amount of margin currency that a
* token sponsor could extract from the contract through corrupting the price feed in their favor.
* @return regularFee amount owed for the duration from start to end time for the given pfc.
* @return latePenalty penalty percentage, if any, for paying the fee after the deadline.
*/
function computeRegularFee(
uint256 startTime,
uint256 endTime,
FixedPoint.Unsigned calldata pfc
) external view override returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) {
uint256 timeDiff = endTime.sub(startTime);
// Multiply by the unscaled `timeDiff` first, to get more accurate results.
regularFee = pfc.mul(timeDiff).mul(fixedOracleFeePerSecondPerPfc);
// Compute how long ago the start time was to compute the delay penalty.
uint256 paymentDelay = getCurrentTime().sub(startTime);
// Compute the additional percentage (per second) that will be charged because of the penalty.
// Note: if less than a week has gone by since the startTime, paymentDelay / SECONDS_PER_WEEK will truncate to
// 0, causing no penalty to be charged.
FixedPoint.Unsigned memory penaltyPercentagePerSecond =
weeklyDelayFeePerSecondPerPfc.mul(paymentDelay.div(SECONDS_PER_WEEK));
// Apply the penaltyPercentagePerSecond to the payment period.
latePenalty = pfc.mul(timeDiff).mul(penaltyPercentagePerSecond);
}
/**
* @notice Computes the final oracle fees that a contract should pay at settlement.
* @param currency token used to pay the final fee.
* @return finalFee amount due denominated in units of `currency`.
*/
function computeFinalFee(address currency) external view override returns (FixedPoint.Unsigned memory) {
return finalFees[currency];
}
/****************************************
* ADMIN STATE MODIFYING FUNCTIONS *
****************************************/
/**
* @notice Sets a new oracle fee per second.
* @param newFixedOracleFeePerSecondPerPfc new fee per second charged to use the oracle.
*/
function setFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned memory newFixedOracleFeePerSecondPerPfc)
public
onlyRoleHolder(uint256(Roles.Owner))
{
// Oracle fees at or over 100% don't make sense.
require(newFixedOracleFeePerSecondPerPfc.isLessThan(1), "Fee must be < 100% per second.");
fixedOracleFeePerSecondPerPfc = newFixedOracleFeePerSecondPerPfc;
emit NewFixedOracleFeePerSecondPerPfc(newFixedOracleFeePerSecondPerPfc);
}
/**
* @notice Sets a new weekly delay fee.
* @param newWeeklyDelayFeePerSecondPerPfc fee escalation per week of late fee payment.
*/
function setWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned memory newWeeklyDelayFeePerSecondPerPfc)
public
onlyRoleHolder(uint256(Roles.Owner))
{
require(newWeeklyDelayFeePerSecondPerPfc.isLessThan(1), "weekly delay fee must be < 100%");
weeklyDelayFeePerSecondPerPfc = newWeeklyDelayFeePerSecondPerPfc;
emit NewWeeklyDelayFeePerSecondPerPfc(newWeeklyDelayFeePerSecondPerPfc);
}
/**
* @notice Sets a new final fee for a particular currency.
* @param currency defines the token currency used to pay the final fee.
* @param newFinalFee final fee amount.
*/
function setFinalFee(address currency, FixedPoint.Unsigned memory newFinalFee)
public
onlyRoleHolder(uint256(Roles.Owner))
{
finalFees[currency] = newFinalFee;
emit NewFinalFee(newFinalFee);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../Governor.sol";
// GovernorTest exposes internal methods in the Governor for testing.
contract GovernorTest is Governor {
constructor(address _timerAddress) public Governor(address(0), 0, _timerAddress) {}
function addPrefix(
bytes32 input,
bytes32 prefix,
uint256 prefixLength
) external pure returns (bytes32) {
return _addPrefix(input, prefix, prefixLength);
}
function uintToUtf8(uint256 v) external pure returns (bytes32 ret) {
return _uintToUtf8(v);
}
function constructIdentifier(uint256 id) external pure returns (bytes32 identifier) {
return _constructIdentifier(id);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../interfaces/AdministrateeInterface.sol";
// A mock implementation of AdministrateeInterface, taking the place of a financial contract.
contract MockAdministratee is AdministrateeInterface {
uint256 public timesRemargined;
uint256 public timesEmergencyShutdown;
function remargin() external override {
timesRemargined++;
}
function emergencyShutdown() external override {
timesEmergencyShutdown++;
}
function pfc() external view override returns (FixedPoint.Unsigned memory) {
return FixedPoint.fromUnscaledUint(0);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../OptimisticOracle.sol";
// This is just a test contract to make requests to the optimistic oracle.
contract OptimisticRequesterTest is OptimisticRequester {
OptimisticOracle optimisticOracle;
bool public shouldRevert = false;
// State variables to track incoming calls.
bytes32 public identifier;
uint256 public timestamp;
bytes public ancillaryData;
uint256 public refund;
int256 public price;
constructor(OptimisticOracle _optimisticOracle) public {
optimisticOracle = _optimisticOracle;
}
function requestPrice(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
IERC20 currency,
uint256 reward
) external {
currency.approve(address(optimisticOracle), reward);
optimisticOracle.requestPrice(_identifier, _timestamp, _ancillaryData, currency, reward);
}
function getPrice(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData
) external returns (int256) {
return optimisticOracle.getPrice(_identifier, _timestamp, _ancillaryData);
}
function setBond(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
uint256 bond
) external {
optimisticOracle.setBond(_identifier, _timestamp, _ancillaryData, bond);
}
function setRefundOnDispute(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData
) external {
optimisticOracle.setRefundOnDispute(_identifier, _timestamp, _ancillaryData);
}
function setCustomLiveness(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
uint256 customLiveness
) external {
optimisticOracle.setCustomLiveness(_identifier, _timestamp, _ancillaryData, customLiveness);
}
function setRevert(bool _shouldRevert) external {
shouldRevert = _shouldRevert;
}
function clearState() external {
delete identifier;
delete timestamp;
delete refund;
delete price;
}
function priceProposed(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData
) external override {
require(!shouldRevert);
identifier = _identifier;
timestamp = _timestamp;
ancillaryData = _ancillaryData;
}
function priceDisputed(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
uint256 _refund
) external override {
require(!shouldRevert);
identifier = _identifier;
timestamp = _timestamp;
ancillaryData = _ancillaryData;
refund = _refund;
}
function priceSettled(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
int256 _price
) external override {
require(!shouldRevert);
identifier = _identifier;
timestamp = _timestamp;
ancillaryData = _ancillaryData;
price = _price;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../ResultComputation.sol";
import "../../../common/implementation/FixedPoint.sol";
// Wraps the library ResultComputation for testing purposes.
contract ResultComputationTest {
using ResultComputation for ResultComputation.Data;
ResultComputation.Data public data;
function wrapAddVote(int256 votePrice, uint256 numberTokens) external {
data.addVote(votePrice, FixedPoint.Unsigned(numberTokens));
}
function wrapGetResolvedPrice(uint256 minVoteThreshold) external view returns (bool isResolved, int256 price) {
return data.getResolvedPrice(FixedPoint.Unsigned(minVoteThreshold));
}
function wrapWasVoteCorrect(bytes32 revealHash) external view returns (bool) {
return data.wasVoteCorrect(revealHash);
}
function wrapGetTotalCorrectlyVotedTokens() external view returns (uint256) {
return data.getTotalCorrectlyVotedTokens().rawValue;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../interfaces/VotingInterface.sol";
import "../VoteTiming.sol";
// Wraps the library VoteTiming for testing purposes.
contract VoteTimingTest {
using VoteTiming for VoteTiming.Data;
VoteTiming.Data public voteTiming;
constructor(uint256 phaseLength) public {
wrapInit(phaseLength);
}
function wrapComputeCurrentRoundId(uint256 currentTime) external view returns (uint256) {
return voteTiming.computeCurrentRoundId(currentTime);
}
function wrapComputeCurrentPhase(uint256 currentTime) external view returns (VotingAncillaryInterface.Phase) {
return voteTiming.computeCurrentPhase(currentTime);
}
function wrapInit(uint256 phaseLength) public {
voteTiming.init(phaseLength);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../interfaces/VotingInterface.sol";
/**
* @title Library to compute rounds and phases for an equal length commit-reveal voting cycle.
*/
library VoteTiming {
using SafeMath for uint256;
struct Data {
uint256 phaseLength;
}
/**
* @notice Initializes the data object. Sets the phase length based on the input.
*/
function init(Data storage data, uint256 phaseLength) internal {
// This should have a require message but this results in an internal Solidity error.
require(phaseLength > 0);
data.phaseLength = phaseLength;
}
/**
* @notice Computes the roundID based off the current time as floor(timestamp/roundLength).
* @dev The round ID depends on the global timestamp but not on the lifetime of the system.
* The consequence is that the initial round ID starts at an arbitrary number (that increments, as expected, for subsequent rounds) instead of zero or one.
* @param data input data object.
* @param currentTime input unix timestamp used to compute the current roundId.
* @return roundId defined as a function of the currentTime and `phaseLength` from `data`.
*/
function computeCurrentRoundId(Data storage data, uint256 currentTime) internal view returns (uint256) {
uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER));
return currentTime.div(roundLength);
}
/**
* @notice compute the round end time as a function of the round Id.
* @param data input data object.
* @param roundId uniquely identifies the current round.
* @return timestamp unix time of when the current round will end.
*/
function computeRoundEndTime(Data storage data, uint256 roundId) internal view returns (uint256) {
uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER));
return roundLength.mul(roundId.add(1));
}
/**
* @notice Computes the current phase based only on the current time.
* @param data input data object.
* @param currentTime input unix timestamp used to compute the current roundId.
* @return current voting phase based on current time and vote phases configuration.
*/
function computeCurrentPhase(Data storage data, uint256 currentTime)
internal
view
returns (VotingAncillaryInterface.Phase)
{
// This employs some hacky casting. We could make this an if-statement if we're worried about type safety.
return
VotingAncillaryInterface.Phase(
currentTime.div(data.phaseLength).mod(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER))
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../Voting.sol";
import "../../../common/implementation/FixedPoint.sol";
// Test contract used to access internal variables in the Voting contract.
contract VotingTest is Voting {
constructor(
uint256 _phaseLength,
FixedPoint.Unsigned memory _gatPercentage,
FixedPoint.Unsigned memory _inflationRate,
uint256 _rewardsExpirationTimeout,
address _votingToken,
address _finder,
address _timerAddress
)
public
Voting(
_phaseLength,
_gatPercentage,
_inflationRate,
_rewardsExpirationTimeout,
_votingToken,
_finder,
_timerAddress
)
{}
function getPendingPriceRequestsArray() external view returns (bytes32[] memory) {
return pendingPriceRequests;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/FinderInterface.sol";
import "../interfaces/OracleInterface.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/VotingInterface.sol";
import "../interfaces/VotingAncillaryInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "./Registry.sol";
import "./ResultComputation.sol";
import "./VoteTiming.sol";
import "./VotingToken.sol";
import "./Constants.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
/**
* @title Voting system for Oracle.
* @dev Handles receiving and resolving price requests via a commit-reveal voting scheme.
*/
contract Voting is
Testable,
Ownable,
OracleInterface,
OracleAncillaryInterface, // Interface to support ancillary data with price requests.
VotingInterface,
VotingAncillaryInterface // Interface to support ancillary data with voting rounds.
{
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using VoteTiming for VoteTiming.Data;
using ResultComputation for ResultComputation.Data;
/****************************************
* VOTING DATA STRUCTURES *
****************************************/
// Identifies a unique price request for which the Oracle will always return the same value.
// Tracks ongoing votes as well as the result of the vote.
struct PriceRequest {
bytes32 identifier;
uint256 time;
// A map containing all votes for this price in various rounds.
mapping(uint256 => VoteInstance) voteInstances;
// If in the past, this was the voting round where this price was resolved. If current or the upcoming round,
// this is the voting round where this price will be voted on, but not necessarily resolved.
uint256 lastVotingRound;
// The index in the `pendingPriceRequests` that references this PriceRequest. A value of UINT_MAX means that
// this PriceRequest is resolved and has been cleaned up from `pendingPriceRequests`.
uint256 index;
bytes ancillaryData;
}
struct VoteInstance {
// Maps (voterAddress) to their submission.
mapping(address => VoteSubmission) voteSubmissions;
// The data structure containing the computed voting results.
ResultComputation.Data resultComputation;
}
struct VoteSubmission {
// A bytes32 of `0` indicates no commit or a commit that was already revealed.
bytes32 commit;
// The hash of the value that was revealed.
// Note: this is only used for computation of rewards.
bytes32 revealHash;
}
struct Round {
uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken.
FixedPoint.Unsigned inflationRate; // Inflation rate set for this round.
FixedPoint.Unsigned gatPercentage; // Gat rate set for this round.
uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until.
}
// Represents the status a price request has.
enum RequestStatus {
NotRequested, // Was never requested.
Active, // Is being voted on in the current round.
Resolved, // Was resolved in a previous round.
Future // Is scheduled to be voted on in a future round.
}
// Only used as a return value in view methods -- never stored in the contract.
struct RequestState {
RequestStatus status;
uint256 lastVotingRound;
}
/****************************************
* INTERNAL TRACKING *
****************************************/
// Maps round numbers to the rounds.
mapping(uint256 => Round) public rounds;
// Maps price request IDs to the PriceRequest struct.
mapping(bytes32 => PriceRequest) private priceRequests;
// Price request ids for price requests that haven't yet been marked as resolved.
// These requests may be for future rounds.
bytes32[] internal pendingPriceRequests;
VoteTiming.Data public voteTiming;
// Percentage of the total token supply that must be used in a vote to
// create a valid price resolution. 1 == 100%.
FixedPoint.Unsigned public gatPercentage;
// Global setting for the rate of inflation per vote. This is the percentage of the snapshotted total supply that
// should be split among the correct voters.
// Note: this value is used to set per-round inflation at the beginning of each round. 1 = 100%.
FixedPoint.Unsigned public inflationRate;
// Time in seconds from the end of the round in which a price request is
// resolved that voters can still claim their rewards.
uint256 public rewardsExpirationTimeout;
// Reference to the voting token.
VotingToken public votingToken;
// Reference to the Finder.
FinderInterface private finder;
// If non-zero, this contract has been migrated to this address. All voters and
// financial contracts should query the new address only.
address public migratedAddress;
// Max value of an unsigned integer.
uint256 private constant UINT_MAX = ~uint256(0);
// Max length in bytes of ancillary data that can be appended to a price request.
// As of December 2020, the current Ethereum gas limit is 12.5 million. This requestPrice function's gas primarily
// comes from computing a Keccak-256 hash in _encodePriceRequest and writing a new PriceRequest to
// storage. We have empirically determined an ancillary data limit of 8192 bytes that keeps this function
// well within the gas limit at ~8 million gas. To learn more about the gas limit and EVM opcode costs go here:
// - https://etherscan.io/chart/gaslimit
// - https://github.com/djrtwo/evm-opcode-gas-costs
uint256 public constant ancillaryBytesLimit = 8192;
bytes32 public snapshotMessageHash = ECDSA.toEthSignedMessageHash(keccak256(bytes("Sign For Snapshot")));
/***************************************
* EVENTS *
****************************************/
event VoteCommitted(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData
);
event EncryptedVote(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
bytes encryptedVote
);
event VoteRevealed(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData,
uint256 numTokens
);
event RewardsRetrieved(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
uint256 numTokens
);
event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event PriceResolved(
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData
);
/**
* @notice Construct the Voting contract.
* @param _phaseLength length of the commit and reveal phases in seconds.
* @param _gatPercentage of the total token supply that must be used in a vote to create a valid price resolution.
* @param _inflationRate percentage inflation per round used to increase token supply of correct voters.
* @param _rewardsExpirationTimeout timeout, in seconds, within which rewards must be claimed.
* @param _votingToken address of the UMA token contract used to commit votes.
* @param _finder keeps track of all contracts within the system based on their interfaceName.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
uint256 _phaseLength,
FixedPoint.Unsigned memory _gatPercentage,
FixedPoint.Unsigned memory _inflationRate,
uint256 _rewardsExpirationTimeout,
address _votingToken,
address _finder,
address _timerAddress
) public Testable(_timerAddress) {
voteTiming.init(_phaseLength);
require(_gatPercentage.isLessThanOrEqual(1), "GAT percentage must be <= 100%");
gatPercentage = _gatPercentage;
inflationRate = _inflationRate;
votingToken = VotingToken(_votingToken);
finder = FinderInterface(_finder);
rewardsExpirationTimeout = _rewardsExpirationTimeout;
}
/***************************************
MODIFIERS
****************************************/
modifier onlyRegisteredContract() {
if (migratedAddress != address(0)) {
require(msg.sender == migratedAddress, "Caller must be migrated address");
} else {
Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry));
require(registry.isContractRegistered(msg.sender), "Called must be registered");
}
_;
}
modifier onlyIfNotMigrated() {
require(migratedAddress == address(0), "Only call this if not migrated");
_;
}
/****************************************
* PRICE REQUEST AND ACCESS FUNCTIONS *
****************************************/
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported. The length of the ancillary data
* is limited such that this method abides by the EVM transaction gas limit.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
*/
function requestPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public override onlyRegisteredContract() {
uint256 blockTime = getCurrentTime();
require(time <= blockTime, "Can only request in past");
require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier request");
require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data");
bytes32 priceRequestId = _encodePriceRequest(identifier, time, ancillaryData);
PriceRequest storage priceRequest = priceRequests[priceRequestId];
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId);
if (requestStatus == RequestStatus.NotRequested) {
// Price has never been requested.
// Price requests always go in the next round, so add 1 to the computed current round.
uint256 nextRoundId = currentRoundId.add(1);
priceRequests[priceRequestId] = PriceRequest({
identifier: identifier,
time: time,
lastVotingRound: nextRoundId,
index: pendingPriceRequests.length,
ancillaryData: ancillaryData
});
pendingPriceRequests.push(priceRequestId);
emit PriceRequestAdded(nextRoundId, identifier, time);
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function requestPrice(bytes32 identifier, uint256 time) public override {
requestPrice(identifier, time, "");
}
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp of for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return _hasPrice bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override onlyRegisteredContract() returns (bool) {
(bool _hasPrice, , ) = _getPriceOrError(identifier, time, ancillaryData);
return _hasPrice;
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) {
return hasPrice(identifier, time, "");
}
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp of for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override onlyRegisteredContract() returns (int256) {
(bool _hasPrice, int256 price, string memory message) = _getPriceOrError(identifier, time, ancillaryData);
// If the price wasn't available, revert with the provided message.
require(_hasPrice, message);
return price;
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) {
return getPrice(identifier, time, "");
}
/**
* @notice Gets the status of a list of price requests, identified by their identifier and time.
* @dev If the status for a particular request is NotRequested, the lastVotingRound will always be 0.
* @param requests array of type PendingRequest which includes an identifier and timestamp for each request.
* @return requestStates a list, in the same order as the input list, giving the status of each of the specified price requests.
*/
function getPriceRequestStatuses(PendingRequestAncillary[] memory requests)
public
view
returns (RequestState[] memory)
{
RequestState[] memory requestStates = new RequestState[](requests.length);
uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime());
for (uint256 i = 0; i < requests.length; i++) {
PriceRequest storage priceRequest =
_getPriceRequest(requests[i].identifier, requests[i].time, requests[i].ancillaryData);
RequestStatus status = _getRequestStatus(priceRequest, currentRoundId);
// If it's an active request, its true lastVotingRound is the current one, even if it hasn't been updated.
if (status == RequestStatus.Active) {
requestStates[i].lastVotingRound = currentRoundId;
} else {
requestStates[i].lastVotingRound = priceRequest.lastVotingRound;
}
requestStates[i].status = status;
}
return requestStates;
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function getPriceRequestStatuses(PendingRequest[] memory requests) public view returns (RequestState[] memory) {
PendingRequestAncillary[] memory requestsAncillary = new PendingRequestAncillary[](requests.length);
for (uint256 i = 0; i < requests.length; i++) {
requestsAncillary[i].identifier = requests[i].identifier;
requestsAncillary[i].time = requests[i].time;
requestsAncillary[i].ancillaryData = "";
}
return getPriceRequestStatuses(requestsAncillary);
}
/****************************************
* VOTING FUNCTIONS *
****************************************/
/**
* @notice Commit a vote for a price request for `identifier` at `time`.
* @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase.
* Commits can be changed.
* @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior,
* voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then
* they can determine the vote pre-reveal.
* @param identifier uniquely identifies the committed vote. EG BTC/USD price pair.
* @param time unix timestamp of the price being voted on.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash
) public override onlyIfNotMigrated() {
require(hash != bytes32(0), "Invalid provided hash");
// Current time is required for all vote timing queries.
uint256 blockTime = getCurrentTime();
require(
voteTiming.computeCurrentPhase(blockTime) == VotingAncillaryInterface.Phase.Commit,
"Cannot commit in reveal phase"
);
// At this point, the computed and last updated round ID should be equal.
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData);
require(
_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active,
"Cannot commit inactive request"
);
priceRequest.lastVotingRound = currentRoundId;
VoteInstance storage voteInstance = priceRequest.voteInstances[currentRoundId];
voteInstance.voteSubmissions[msg.sender].commit = hash;
emit VoteCommitted(msg.sender, currentRoundId, identifier, time, ancillaryData);
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function commitVote(
bytes32 identifier,
uint256 time,
bytes32 hash
) public override onlyIfNotMigrated() {
commitVote(identifier, time, "", hash);
}
/**
* @notice Snapshot the current round's token balances and lock in the inflation rate and GAT.
* @dev This function can be called multiple times, but only the first call per round into this function or `revealVote`
* will create the round snapshot. Any later calls will be a no-op. Will revert unless called during reveal period.
* @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the
* snapshot.
*/
function snapshotCurrentRound(bytes calldata signature)
external
override(VotingInterface, VotingAncillaryInterface)
onlyIfNotMigrated()
{
uint256 blockTime = getCurrentTime();
require(voteTiming.computeCurrentPhase(blockTime) == Phase.Reveal, "Only snapshot in reveal phase");
// Require public snapshot require signature to ensure caller is an EOA.
require(ECDSA.recover(snapshotMessageHash, signature) == msg.sender, "Signature must match sender");
uint256 roundId = voteTiming.computeCurrentRoundId(blockTime);
_freezeRoundVariables(roundId);
}
/**
* @notice Reveal a previously committed vote for `identifier` at `time`.
* @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash`
* that `commitVote()` was called with. Only the committer can reveal their vote.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price being voted on.
* @param price voted on during the commit phase.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param salt value used to hide the commitment price during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
bytes memory ancillaryData,
int256 salt
) public override onlyIfNotMigrated() {
require(voteTiming.computeCurrentPhase(getCurrentTime()) == Phase.Reveal, "Cannot reveal in commit phase");
// Note: computing the current round is required to disallow people from revealing an old commit after the round is over.
uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime());
PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData);
VoteInstance storage voteInstance = priceRequest.voteInstances[roundId];
VoteSubmission storage voteSubmission = voteInstance.voteSubmissions[msg.sender];
// Scoping to get rid of a stack too deep error.
{
// 0 hashes are disallowed in the commit phase, so they indicate a different error.
// Cannot reveal an uncommitted or previously revealed hash
require(voteSubmission.commit != bytes32(0), "Invalid hash reveal");
require(
keccak256(abi.encodePacked(price, salt, msg.sender, time, ancillaryData, roundId, identifier)) ==
voteSubmission.commit,
"Revealed data != commit hash"
);
// To protect against flash loans, we require snapshot be validated as EOA.
require(rounds[roundId].snapshotId != 0, "Round has no snapshot");
}
// Get the frozen snapshotId
uint256 snapshotId = rounds[roundId].snapshotId;
delete voteSubmission.commit;
// Get the voter's snapshotted balance. Since balances are returned pre-scaled by 10**18, we can directly
// initialize the Unsigned value with the returned uint.
FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(votingToken.balanceOfAt(msg.sender, snapshotId));
// Set the voter's submission.
voteSubmission.revealHash = keccak256(abi.encode(price));
// Add vote to the results.
voteInstance.resultComputation.addVote(price, balance);
emit VoteRevealed(msg.sender, roundId, identifier, time, price, ancillaryData, balance.rawValue);
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
int256 salt
) public override {
revealVote(identifier, time, price, "", salt);
}
/**
* @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote
* @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to
* retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience.
* @param identifier unique price pair identifier. Eg: BTC/USD price pair.
* @param time unix timestamp of for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param hash keccak256 hash of the price you want to vote for and a `int256 salt`.
* @param encryptedVote offchain encrypted blob containing the voters amount, time and salt.
*/
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash,
bytes memory encryptedVote
) public override {
commitVote(identifier, time, ancillaryData, hash);
uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime());
emit EncryptedVote(msg.sender, roundId, identifier, time, ancillaryData, encryptedVote);
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes32 hash,
bytes memory encryptedVote
) public override {
commitVote(identifier, time, "", hash);
commitAndEmitEncryptedVote(identifier, time, "", hash, encryptedVote);
}
/**
* @notice Submit a batch of commits in a single transaction.
* @dev Using `encryptedVote` is optional. If included then commitment is emitted in an event.
* Look at `project-root/common/Constants.js` for the tested maximum number of
* commitments that can fit in one transaction.
* @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(CommitmentAncillary[] memory commits) public override {
for (uint256 i = 0; i < commits.length; i++) {
if (commits[i].encryptedVote.length == 0) {
commitVote(commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash);
} else {
commitAndEmitEncryptedVote(
commits[i].identifier,
commits[i].time,
commits[i].ancillaryData,
commits[i].hash,
commits[i].encryptedVote
);
}
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function batchCommit(Commitment[] memory commits) public override {
CommitmentAncillary[] memory commitsAncillary = new CommitmentAncillary[](commits.length);
for (uint256 i = 0; i < commits.length; i++) {
commitsAncillary[i].identifier = commits[i].identifier;
commitsAncillary[i].time = commits[i].time;
commitsAncillary[i].ancillaryData = "";
commitsAncillary[i].hash = commits[i].hash;
commitsAncillary[i].encryptedVote = commits[i].encryptedVote;
}
batchCommit(commitsAncillary);
}
/**
* @notice Reveal multiple votes in a single transaction.
* Look at `project-root/common/Constants.js` for the tested maximum number of reveals.
* that can fit in one transaction.
* @dev For more info on reveals, review the comment for `revealVote`.
* @param reveals array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(RevealAncillary[] memory reveals) public override {
for (uint256 i = 0; i < reveals.length; i++) {
revealVote(
reveals[i].identifier,
reveals[i].time,
reveals[i].price,
reveals[i].ancillaryData,
reveals[i].salt
);
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function batchReveal(Reveal[] memory reveals) public override {
RevealAncillary[] memory revealsAncillary = new RevealAncillary[](reveals.length);
for (uint256 i = 0; i < reveals.length; i++) {
revealsAncillary[i].identifier = reveals[i].identifier;
revealsAncillary[i].time = reveals[i].time;
revealsAncillary[i].price = reveals[i].price;
revealsAncillary[i].ancillaryData = "";
revealsAncillary[i].salt = reveals[i].salt;
}
batchReveal(revealsAncillary);
}
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
* @dev Can only retrieve rewards if calling for a valid round and if the call is done within the timeout threshold
* (not expired). Note that a named return value is used here to avoid a stack to deep error.
* @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller.
* @param roundId the round from which voting rewards will be retrieved from.
* @param toRetrieve array of PendingRequests which rewards are retrieved from.
* @return totalRewardToIssue total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequestAncillary[] memory toRetrieve
) public override returns (FixedPoint.Unsigned memory totalRewardToIssue) {
if (migratedAddress != address(0)) {
require(msg.sender == migratedAddress, "Can only call from migrated");
}
require(roundId < voteTiming.computeCurrentRoundId(getCurrentTime()), "Invalid roundId");
Round storage round = rounds[roundId];
bool isExpired = getCurrentTime() > round.rewardsExpirationTime;
FixedPoint.Unsigned memory snapshotBalance =
FixedPoint.Unsigned(votingToken.balanceOfAt(voterAddress, round.snapshotId));
// Compute the total amount of reward that will be issued for each of the votes in the round.
FixedPoint.Unsigned memory snapshotTotalSupply =
FixedPoint.Unsigned(votingToken.totalSupplyAt(round.snapshotId));
FixedPoint.Unsigned memory totalRewardPerVote = round.inflationRate.mul(snapshotTotalSupply);
// Keep track of the voter's accumulated token reward.
totalRewardToIssue = FixedPoint.Unsigned(0);
for (uint256 i = 0; i < toRetrieve.length; i++) {
PriceRequest storage priceRequest =
_getPriceRequest(toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData);
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
// Only retrieve rewards for votes resolved in same round
require(priceRequest.lastVotingRound == roundId, "Retrieve for votes same round");
_resolvePriceRequest(priceRequest, voteInstance);
if (voteInstance.voteSubmissions[voterAddress].revealHash == 0) {
continue;
} else if (isExpired) {
// Emit a 0 token retrieval on expired rewards.
emit RewardsRetrieved(
voterAddress,
roundId,
toRetrieve[i].identifier,
toRetrieve[i].time,
toRetrieve[i].ancillaryData,
0
);
} else if (
voteInstance.resultComputation.wasVoteCorrect(voteInstance.voteSubmissions[voterAddress].revealHash)
) {
// The price was successfully resolved during the voter's last voting round, the voter revealed
// and was correct, so they are eligible for a reward.
// Compute the reward and add to the cumulative reward.
FixedPoint.Unsigned memory reward =
snapshotBalance.mul(totalRewardPerVote).div(
voteInstance.resultComputation.getTotalCorrectlyVotedTokens()
);
totalRewardToIssue = totalRewardToIssue.add(reward);
// Emit reward retrieval for this vote.
emit RewardsRetrieved(
voterAddress,
roundId,
toRetrieve[i].identifier,
toRetrieve[i].time,
toRetrieve[i].ancillaryData,
reward.rawValue
);
} else {
// Emit a 0 token retrieval on incorrect votes.
emit RewardsRetrieved(
voterAddress,
roundId,
toRetrieve[i].identifier,
toRetrieve[i].time,
toRetrieve[i].ancillaryData,
0
);
}
// Delete the submission to capture any refund and clean up storage.
delete voteInstance.voteSubmissions[voterAddress].revealHash;
}
// Issue any accumulated rewards.
if (totalRewardToIssue.isGreaterThan(0)) {
require(votingToken.mint(voterAddress, totalRewardToIssue.rawValue), "Voting token issuance failed");
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequest[] memory toRetrieve
) public override returns (FixedPoint.Unsigned memory) {
PendingRequestAncillary[] memory toRetrieveAncillary = new PendingRequestAncillary[](toRetrieve.length);
for (uint256 i = 0; i < toRetrieve.length; i++) {
toRetrieveAncillary[i].identifier = toRetrieve[i].identifier;
toRetrieveAncillary[i].time = toRetrieve[i].time;
toRetrieveAncillary[i].ancillaryData = "";
}
return retrieveRewards(voterAddress, roundId, toRetrieveAncillary);
}
/****************************************
* VOTING GETTER FUNCTIONS *
****************************************/
/**
* @notice Gets the queries that are being voted on this round.
* @return pendingRequests array containing identifiers of type `PendingRequest`.
* and timestamps for all pending requests.
*/
function getPendingRequests()
external
view
override(VotingInterface, VotingAncillaryInterface)
returns (PendingRequestAncillary[] memory)
{
uint256 blockTime = getCurrentTime();
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
// Solidity memory arrays aren't resizable (and reading storage is expensive). Hence this hackery to filter
// `pendingPriceRequests` only to those requests that have an Active RequestStatus.
PendingRequestAncillary[] memory unresolved = new PendingRequestAncillary[](pendingPriceRequests.length);
uint256 numUnresolved = 0;
for (uint256 i = 0; i < pendingPriceRequests.length; i++) {
PriceRequest storage priceRequest = priceRequests[pendingPriceRequests[i]];
if (_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active) {
unresolved[numUnresolved] = PendingRequestAncillary({
identifier: priceRequest.identifier,
time: priceRequest.time,
ancillaryData: priceRequest.ancillaryData
});
numUnresolved++;
}
}
PendingRequestAncillary[] memory pendingRequests = new PendingRequestAncillary[](numUnresolved);
for (uint256 i = 0; i < numUnresolved; i++) {
pendingRequests[i] = unresolved[i];
}
return pendingRequests;
}
/**
* @notice Returns the current voting phase, as a function of the current time.
* @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }.
*/
function getVotePhase() external view override(VotingInterface, VotingAncillaryInterface) returns (Phase) {
return voteTiming.computeCurrentPhase(getCurrentTime());
}
/**
* @notice Returns the current round ID, as a function of the current time.
* @return uint256 representing the unique round ID.
*/
function getCurrentRoundId() external view override(VotingInterface, VotingAncillaryInterface) returns (uint256) {
return voteTiming.computeCurrentRoundId(getCurrentTime());
}
/****************************************
* OWNER ADMIN FUNCTIONS *
****************************************/
/**
* @notice Disables this Voting contract in favor of the migrated one.
* @dev Can only be called by the contract owner.
* @param newVotingAddress the newly migrated contract address.
*/
function setMigrated(address newVotingAddress)
external
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
migratedAddress = newVotingAddress;
}
/**
* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newInflationRate sets the next round's inflation rate.
*/
function setInflationRate(FixedPoint.Unsigned memory newInflationRate)
public
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
inflationRate = newInflationRate;
}
/**
* @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newGatPercentage sets the next round's Gat percentage.
*/
function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage)
public
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
require(newGatPercentage.isLessThan(1), "GAT percentage must be < 100%");
gatPercentage = newGatPercentage;
}
/**
* @notice Resets the rewards expiration timeout.
* @dev This change only applies to rounds that have not yet begun.
* @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards.
*/
function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout)
public
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
rewardsExpirationTimeout = NewRewardsExpirationTimeout;
}
/****************************************
* PRIVATE AND INTERNAL FUNCTIONS *
****************************************/
// Returns the price for a given identifer. Three params are returns: bool if there was an error, int to represent
// the resolved price and a string which is filled with an error message, if there was an error or "".
function _getPriceOrError(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
)
private
view
returns (
bool,
int256,
string memory
)
{
PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData);
uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime());
RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId);
if (requestStatus == RequestStatus.Active) {
return (false, 0, "Current voting round not ended");
} else if (requestStatus == RequestStatus.Resolved) {
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
(, int256 resolvedPrice) =
voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound));
return (true, resolvedPrice, "");
} else if (requestStatus == RequestStatus.Future) {
return (false, 0, "Price is still to be voted on");
} else {
return (false, 0, "Price was never requested");
}
}
function _getPriceRequest(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) private view returns (PriceRequest storage) {
return priceRequests[_encodePriceRequest(identifier, time, ancillaryData)];
}
function _encodePriceRequest(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) private pure returns (bytes32) {
return keccak256(abi.encode(identifier, time, ancillaryData));
}
function _freezeRoundVariables(uint256 roundId) private {
Round storage round = rounds[roundId];
// Only on the first reveal should the snapshot be captured for that round.
if (round.snapshotId == 0) {
// There is no snapshot ID set, so create one.
round.snapshotId = votingToken.snapshot();
// Set the round inflation rate to the current global inflation rate.
rounds[roundId].inflationRate = inflationRate;
// Set the round gat percentage to the current global gat rate.
rounds[roundId].gatPercentage = gatPercentage;
// Set the rewards expiration time based on end of time of this round and the current global timeout.
rounds[roundId].rewardsExpirationTime = voteTiming.computeRoundEndTime(roundId).add(
rewardsExpirationTimeout
);
}
}
function _resolvePriceRequest(PriceRequest storage priceRequest, VoteInstance storage voteInstance) private {
if (priceRequest.index == UINT_MAX) {
return;
}
(bool isResolved, int256 resolvedPrice) =
voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound));
require(isResolved, "Can't resolve unresolved request");
// Delete the resolved price request from pendingPriceRequests.
uint256 lastIndex = pendingPriceRequests.length - 1;
PriceRequest storage lastPriceRequest = priceRequests[pendingPriceRequests[lastIndex]];
lastPriceRequest.index = priceRequest.index;
pendingPriceRequests[priceRequest.index] = pendingPriceRequests[lastIndex];
pendingPriceRequests.pop();
priceRequest.index = UINT_MAX;
emit PriceResolved(
priceRequest.lastVotingRound,
priceRequest.identifier,
priceRequest.time,
resolvedPrice,
priceRequest.ancillaryData
);
}
function _computeGat(uint256 roundId) private view returns (FixedPoint.Unsigned memory) {
uint256 snapshotId = rounds[roundId].snapshotId;
if (snapshotId == 0) {
// No snapshot - return max value to err on the side of caution.
return FixedPoint.Unsigned(UINT_MAX);
}
// Grab the snapshotted supply from the voting token. It's already scaled by 10**18, so we can directly
// initialize the Unsigned value with the returned uint.
FixedPoint.Unsigned memory snapshottedSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(snapshotId));
// Multiply the total supply at the snapshot by the gatPercentage to get the GAT in number of tokens.
return snapshottedSupply.mul(rounds[roundId].gatPercentage);
}
function _getRequestStatus(PriceRequest storage priceRequest, uint256 currentRoundId)
private
view
returns (RequestStatus)
{
if (priceRequest.lastVotingRound == 0) {
return RequestStatus.NotRequested;
} else if (priceRequest.lastVotingRound < currentRoundId) {
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
(bool isResolved, ) =
voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound));
return isResolved ? RequestStatus.Resolved : RequestStatus.Active;
} else if (priceRequest.lastVotingRound == currentRoundId) {
return RequestStatus.Active;
} else {
// Means than priceRequest.lastVotingRound > currentRoundId
return RequestStatus.Future;
}
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../common/implementation/ExpandedERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Snapshot.sol";
/**
* @title Ownership of this token allows a voter to respond to price requests.
* @dev Supports snapshotting and allows the Oracle to mint new tokens as rewards.
*/
contract VotingToken is ExpandedERC20, ERC20Snapshot {
/**
* @notice Constructs the VotingToken.
* stonkbase.org
* tw StonkBase
*/
constructor() public ExpandedERC20("StonkBase", "SBF", 18) {}
/**
* @notice Creates a new snapshot ID.
* @return uint256 Thew new snapshot ID.
*/
function snapshot() external returns (uint256) {
return _snapshot();
}
// _transfer, _mint and _burn are ERC20 internal methods that are overridden by ERC20Snapshot,
// therefore the compiler will complain that VotingToken must override these methods
// because the two base classes (ERC20 and ERC20Snapshot) both define the same functions
function _transfer(
address from,
address to,
uint256 value
) internal override(ERC20, ERC20Snapshot) {
super._transfer(from, to, value);
}
function _mint(address account, uint256 value) internal override(ERC20, ERC20Snapshot) {
super._mint(account, value);
}
function _burn(address account, uint256 value) internal override(ERC20, ERC20Snapshot) {
super._burn(account, value);
}
}
pragma solidity ^0.6.0;
import "../../math/SafeMath.sol";
import "../../utils/Arrays.sol";
import "../../utils/Counters.sol";
import "./ERC20.sol";
/**
* @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and
* total supply at the time are recorded for later access.
*
* This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting.
* In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different
* accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be
* used to create an efficient ERC20 forking mechanism.
*
* Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a
* snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot
* id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id
* and the account address.
*
* ==== Gas Costs
*
* Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log
* n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much
* smaller since identical balances in subsequent snapshots are stored as a single entry.
*
* There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is
* only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent
* transfers will have normal cost until the next snapshot, and so on.
*/
abstract contract ERC20Snapshot is ERC20 {
// Inspired by Jordi Baylina's MiniMeToken to record historical balances:
// https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol
using SafeMath for uint256;
using Arrays for uint256[];
using Counters for Counters.Counter;
// Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a
// Snapshot struct, but that would impede usage of functions that work on an array.
struct Snapshots {
uint256[] ids;
uint256[] values;
}
mapping (address => Snapshots) private _accountBalanceSnapshots;
Snapshots private _totalSupplySnapshots;
// Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid.
Counters.Counter private _currentSnapshotId;
/**
* @dev Emitted by {_snapshot} when a snapshot identified by `id` is created.
*/
event Snapshot(uint256 id);
/**
* @dev Creates a new snapshot and returns its snapshot id.
*
* Emits a {Snapshot} event that contains the same id.
*
* {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a
* set of accounts, for example using {AccessControl}, or it may be open to the public.
*
* [WARNING]
* ====
* While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking,
* you must consider that it can potentially be used by attackers in two ways.
*
* First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow
* logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target
* specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs
* section above.
*
* We haven't measured the actual numbers; if this is something you're interested in please reach out to us.
* ====
*/
function _snapshot() internal virtual returns (uint256) {
_currentSnapshotId.increment();
uint256 currentId = _currentSnapshotId.current();
emit Snapshot(currentId);
return currentId;
}
/**
* @dev Retrieves the balance of `account` at the time `snapshotId` was created.
*/
function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]);
return snapshotted ? value : balanceOf(account);
}
/**
* @dev Retrieves the total supply at the time `snapshotId` was created.
*/
function totalSupplyAt(uint256 snapshotId) public view returns(uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots);
return snapshotted ? value : totalSupply();
}
// _transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the
// snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value.
// The same is true for the total supply and _mint and _burn.
function _transfer(address from, address to, uint256 value) internal virtual override {
_updateAccountSnapshot(from);
_updateAccountSnapshot(to);
super._transfer(from, to, value);
}
function _mint(address account, uint256 value) internal virtual override {
_updateAccountSnapshot(account);
_updateTotalSupplySnapshot();
super._mint(account, value);
}
function _burn(address account, uint256 value) internal virtual override {
_updateAccountSnapshot(account);
_updateTotalSupplySnapshot();
super._burn(account, value);
}
function _valueAt(uint256 snapshotId, Snapshots storage snapshots)
private view returns (bool, uint256)
{
require(snapshotId > 0, "ERC20Snapshot: id is 0");
// solhint-disable-next-line max-line-length
require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id");
// When a valid snapshot is queried, there are three possibilities:
// a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never
// created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds
// to this id is the current one.
// b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the
// requested id, and its value is the one to return.
// c) More snapshots were created after the requested one, and the queried value was later modified. There will be
// no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is
// larger than the requested one.
//
// In summary, we need to find an element in an array, returning the index of the smallest value that is larger if
// it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does
// exactly this.
uint256 index = snapshots.ids.findUpperBound(snapshotId);
if (index == snapshots.ids.length) {
return (false, 0);
} else {
return (true, snapshots.values[index]);
}
}
function _updateAccountSnapshot(address account) private {
_updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account));
}
function _updateTotalSupplySnapshot() private {
_updateSnapshot(_totalSupplySnapshots, totalSupply());
}
function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private {
uint256 currentId = _currentSnapshotId.current();
if (_lastSnapshotId(snapshots.ids) < currentId) {
snapshots.ids.push(currentId);
snapshots.values.push(currentValue);
}
}
function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) {
if (ids.length == 0) {
return 0;
} else {
return ids[ids.length - 1];
}
}
}
pragma solidity ^0.6.0;
import "../math/Math.sol";
/**
* @dev Collection of functions related to array types.
*/
library Arrays {
/**
* @dev Searches a sorted `array` and returns the first index that contains
* a value greater or equal to `element`. If no such index exists (i.e. all
* values in the array are strictly less than `element`), the array length is
* returned. Time complexity O(log n).
*
* `array` is expected to be sorted in ascending order, and to contain no
* repeated elements.
*/
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
if (array.length == 0) {
return 0;
}
uint256 low = 0;
uint256 high = array.length;
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds down (it does integer division with truncation).
if (array[mid] > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && array[low - 1] == element) {
return low - 1;
} else {
return low;
}
}
}
pragma solidity ^0.6.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
pragma solidity ^0.6.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
pragma solidity ^0.6.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
revert("ECDSA: invalid signature 's' value");
}
if (v != 27 && v != 28) {
revert("ECDSA: invalid signature 'v' value");
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "./VotingToken.sol";
/**
* @title Migration contract for VotingTokens.
* @dev Handles migrating token holders from one token to the next.
*/
contract TokenMigrator {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
VotingToken public oldToken;
ExpandedIERC20 public newToken;
uint256 public snapshotId;
FixedPoint.Unsigned public rate;
mapping(address => bool) public hasMigrated;
/**
* @notice Construct the TokenMigrator contract.
* @dev This function triggers the snapshot upon which all migrations will be based.
* @param _rate the number of old tokens it takes to generate one new token.
* @param _oldToken address of the token being migrated from.
* @param _newToken address of the token being migrated to.
*/
constructor(
FixedPoint.Unsigned memory _rate,
address _oldToken,
address _newToken
) public {
// Prevents division by 0 in migrateTokens().
// Also it doesn’t make sense to have “0 old tokens equate to 1 new token”.
require(_rate.isGreaterThan(0), "Rate can't be 0");
rate = _rate;
newToken = ExpandedIERC20(_newToken);
oldToken = VotingToken(_oldToken);
snapshotId = oldToken.snapshot();
}
/**
* @notice Migrates the tokenHolder's old tokens to new tokens.
* @dev This function can only be called once per `tokenHolder`. Anyone can call this method
* on behalf of any other token holder since there is no disadvantage to receiving the tokens earlier.
* @param tokenHolder address of the token holder to migrate.
*/
function migrateTokens(address tokenHolder) external {
require(!hasMigrated[tokenHolder], "Already migrated tokens");
hasMigrated[tokenHolder] = true;
FixedPoint.Unsigned memory oldBalance = FixedPoint.Unsigned(oldToken.balanceOfAt(tokenHolder, snapshotId));
if (!oldBalance.isGreaterThan(0)) {
return;
}
FixedPoint.Unsigned memory newBalance = oldBalance.div(rate);
require(newToken.mint(tokenHolder, newBalance.rawValue), "Mint failed");
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/FinderInterface.sol";
import "../implementation/Constants.sol";
// A mock oracle used for testing.
contract MockOracle is OracleInterface, Testable {
// Represents an available price. Have to keep a separate bool to allow for price=0.
struct Price {
bool isAvailable;
int256 price;
// Time the verified price became available.
uint256 verifiedTime;
}
// The two structs below are used in an array and mapping to keep track of prices that have been requested but are
// not yet available.
struct QueryIndex {
bool isValid;
uint256 index;
}
// Represents a (identifier, time) point that has been queried.
struct QueryPoint {
bytes32 identifier;
uint256 time;
}
// Reference to the Finder.
FinderInterface private finder;
// Conceptually we want a (time, identifier) -> price map.
mapping(bytes32 => mapping(uint256 => Price)) private verifiedPrices;
// The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements.
// Can we generalize this data structure?
mapping(bytes32 => mapping(uint256 => QueryIndex)) private queryIndices;
QueryPoint[] private requestedPrices;
constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
}
// Enqueues a request (if a request isn't already present) for the given (identifier, time) pair.
function requestPrice(bytes32 identifier, uint256 time) public override {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
if (!lookup.isAvailable && !queryIndices[identifier][time].isValid) {
// New query, enqueue it for review.
queryIndices[identifier][time] = QueryIndex(true, requestedPrices.length);
requestedPrices.push(QueryPoint(identifier, time));
}
}
// Pushes the verified price for a requested query.
function pushPrice(
bytes32 identifier,
uint256 time,
int256 price
) external {
verifiedPrices[identifier][time] = Price(true, price, getCurrentTime());
QueryIndex storage queryIndex = queryIndices[identifier][time];
require(queryIndex.isValid, "Can't push prices that haven't been requested");
// Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with
// the contents of the last index (unless it is the last index).
uint256 indexToReplace = queryIndex.index;
delete queryIndices[identifier][time];
uint256 lastIndex = requestedPrices.length - 1;
if (lastIndex != indexToReplace) {
QueryPoint storage queryToCopy = requestedPrices[lastIndex];
queryIndices[queryToCopy.identifier][queryToCopy.time].index = indexToReplace;
requestedPrices[indexToReplace] = queryToCopy;
}
}
// Checks whether a price has been resolved.
function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
return lookup.isAvailable;
}
// Gets a price that has already been resolved.
function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
require(lookup.isAvailable);
return lookup.price;
}
// Gets the queries that still need verified prices.
function getPendingQueries() external view returns (QueryPoint[] memory) {
return requestedPrices;
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/FinderInterface.sol";
import "../implementation/Constants.sol";
// A mock oracle used for testing.
contract MockOracleAncillary is OracleAncillaryInterface, Testable {
// Represents an available price. Have to keep a separate bool to allow for price=0.
struct Price {
bool isAvailable;
int256 price;
// Time the verified price became available.
uint256 verifiedTime;
}
// The two structs below are used in an array and mapping to keep track of prices that have been requested but are
// not yet available.
struct QueryIndex {
bool isValid;
uint256 index;
}
// Represents a (identifier, time) point that has been queried.
struct QueryPoint {
bytes32 identifier;
uint256 time;
bytes ancillaryData;
}
// Reference to the Finder.
FinderInterface private finder;
// Conceptually we want a (time, identifier) -> price map.
mapping(bytes32 => mapping(uint256 => mapping(bytes => Price))) private verifiedPrices;
// The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements.
// Can we generalize this data structure?
mapping(bytes32 => mapping(uint256 => mapping(bytes => QueryIndex))) private queryIndices;
QueryPoint[] private requestedPrices;
constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
}
// Enqueues a request (if a request isn't already present) for the given (identifier, time) pair.
function requestPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public override {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time][ancillaryData];
if (!lookup.isAvailable && !queryIndices[identifier][time][ancillaryData].isValid) {
// New query, enqueue it for review.
queryIndices[identifier][time][ancillaryData] = QueryIndex(true, requestedPrices.length);
requestedPrices.push(QueryPoint(identifier, time, ancillaryData));
}
}
// Pushes the verified price for a requested query.
function pushPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
int256 price
) external {
verifiedPrices[identifier][time][ancillaryData] = Price(true, price, getCurrentTime());
QueryIndex storage queryIndex = queryIndices[identifier][time][ancillaryData];
require(queryIndex.isValid, "Can't push prices that haven't been requested");
// Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with
// the contents of the last index (unless it is the last index).
uint256 indexToReplace = queryIndex.index;
delete queryIndices[identifier][time][ancillaryData];
uint256 lastIndex = requestedPrices.length - 1;
if (lastIndex != indexToReplace) {
QueryPoint storage queryToCopy = requestedPrices[lastIndex];
queryIndices[queryToCopy.identifier][queryToCopy.time][queryToCopy.ancillaryData].index = indexToReplace;
requestedPrices[indexToReplace] = queryToCopy;
}
}
// Checks whether a price has been resolved.
function hasPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override returns (bool) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time][ancillaryData];
return lookup.isAvailable;
}
// Gets a price that has already been resolved.
function getPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override returns (int256) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time][ancillaryData];
require(lookup.isAvailable);
return lookup.price;
}
// Gets the queries that still need verified prices.
function getPendingQueries() external view returns (QueryPoint[] memory) {
return requestedPrices;
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/VotingAncillaryInterface.sol";
// A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain ancillary data.
abstract contract VotingAncillaryInterfaceTesting is OracleAncillaryInterface, VotingAncillaryInterface, Testable {
using FixedPoint for FixedPoint.Unsigned;
// Events, data structures and functions not exported in the base interfaces, used for testing.
event VoteCommitted(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData
);
event EncryptedVote(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
bytes encryptedVote
);
event VoteRevealed(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData,
uint256 numTokens
);
event RewardsRetrieved(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
uint256 numTokens
);
event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event PriceResolved(
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData
);
struct Round {
uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken.
FixedPoint.Unsigned inflationRate; // Inflation rate set for this round.
FixedPoint.Unsigned gatPercentage; // Gat rate set for this round.
uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until.
}
// Represents the status a price request has.
enum RequestStatus {
NotRequested, // Was never requested.
Active, // Is being voted on in the current round.
Resolved, // Was resolved in a previous round.
Future // Is scheduled to be voted on in a future round.
}
// Only used as a return value in view methods -- never stored in the contract.
struct RequestState {
RequestStatus status;
uint256 lastVotingRound;
}
function rounds(uint256 roundId) public view virtual returns (Round memory);
function getPriceRequestStatuses(VotingAncillaryInterface.PendingRequestAncillary[] memory requests)
public
view
virtual
returns (RequestState[] memory);
function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleInterface.sol";
import "../interfaces/VotingInterface.sol";
// A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain no ancillary data.
abstract contract VotingInterfaceTesting is OracleInterface, VotingInterface, Testable {
using FixedPoint for FixedPoint.Unsigned;
// Events, data structures and functions not exported in the base interfaces, used for testing.
event VoteCommitted(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData
);
event EncryptedVote(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
bytes encryptedVote
);
event VoteRevealed(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData,
uint256 numTokens
);
event RewardsRetrieved(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
uint256 numTokens
);
event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event PriceResolved(
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData
);
struct Round {
uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken.
FixedPoint.Unsigned inflationRate; // Inflation rate set for this round.
FixedPoint.Unsigned gatPercentage; // Gat rate set for this round.
uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until.
}
// Represents the status a price request has.
enum RequestStatus {
NotRequested, // Was never requested.
Active, // Is being voted on in the current round.
Resolved, // Was resolved in a previous round.
Future // Is scheduled to be voted on in a future round.
}
// Only used as a return value in view methods -- never stored in the contract.
struct RequestState {
RequestStatus status;
uint256 lastVotingRound;
}
function rounds(uint256 roundId) public view virtual returns (Round memory);
function getPriceRequestStatuses(VotingInterface.PendingRequest[] memory requests)
public
view
virtual
returns (RequestState[] memory);
function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../oracle/implementation/Finder.sol";
import "../oracle/implementation/Constants.sol";
import "../oracle/implementation/Voting.sol";
/**
* @title A contract to track a whitelist of addresses.
*/
contract Umip15Upgrader {
// Existing governor is the only one who can initiate the upgrade.
address public governor;
// Existing Voting contract needs to be informed of the address of the new Voting contract.
Voting public existingVoting;
// New governor will be the new owner of the finder.
// Finder contract to push upgrades to.
Finder public finder;
// Addresses to upgrade.
address public newVoting;
constructor(
address _governor,
address _existingVoting,
address _newVoting,
address _finder
) public {
governor = _governor;
existingVoting = Voting(_existingVoting);
newVoting = _newVoting;
finder = Finder(_finder);
}
function upgrade() external {
require(msg.sender == governor, "Upgrade can only be initiated by the existing governor.");
// Change the addresses in the Finder.
finder.changeImplementationAddress(OracleInterfaces.Oracle, newVoting);
// Set current Voting contract to migrated.
existingVoting.setMigrated(newVoting);
// Transfer back ownership of old voting contract and the finder to the governor.
existingVoting.transferOwnership(governor);
finder.transferOwnership(governor);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../oracle/implementation/Finder.sol";
import "../oracle/implementation/Constants.sol";
import "../oracle/implementation/Voting.sol";
/**
* @title A contract to track a whitelist of addresses.
*/
contract Umip3Upgrader {
// Existing governor is the only one who can initiate the upgrade.
address public existingGovernor;
// Existing Voting contract needs to be informed of the address of the new Voting contract.
Voting public existingVoting;
// New governor will be the new owner of the finder.
address public newGovernor;
// Finder contract to push upgrades to.
Finder public finder;
// Addresses to upgrade.
address public voting;
address public identifierWhitelist;
address public store;
address public financialContractsAdmin;
address public registry;
constructor(
address _existingGovernor,
address _existingVoting,
address _finder,
address _voting,
address _identifierWhitelist,
address _store,
address _financialContractsAdmin,
address _registry,
address _newGovernor
) public {
existingGovernor = _existingGovernor;
existingVoting = Voting(_existingVoting);
finder = Finder(_finder);
voting = _voting;
identifierWhitelist = _identifierWhitelist;
store = _store;
financialContractsAdmin = _financialContractsAdmin;
registry = _registry;
newGovernor = _newGovernor;
}
function upgrade() external {
require(msg.sender == existingGovernor, "Upgrade can only be initiated by the existing governor.");
// Change the addresses in the Finder.
finder.changeImplementationAddress(OracleInterfaces.Oracle, voting);
finder.changeImplementationAddress(OracleInterfaces.IdentifierWhitelist, identifierWhitelist);
finder.changeImplementationAddress(OracleInterfaces.Store, store);
finder.changeImplementationAddress(OracleInterfaces.FinancialContractsAdmin, financialContractsAdmin);
finder.changeImplementationAddress(OracleInterfaces.Registry, registry);
// Transfer the ownership of the Finder to the new Governor now that all the addresses have been updated.
finder.transferOwnership(newGovernor);
// Inform the existing Voting contract of the address of the new Voting contract and transfer its
// ownership to the new governor to allow for any future changes to the migrated contract.
existingVoting.setMigrated(voting);
existingVoting.transferOwnership(newGovernor);
}
} | * @notice Forwards a commit to Voting. @param identifier uniquely identifies the feed for this vote. EG BTC/USD price pair. @param time specifies the unix timestamp of the price being voted on. @param hash the keccak256 hash of the price you want to vote for and a random integer salt value./ | function commitVote(
bytes32 identifier,
uint256 time,
bytes32 hash
) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().commitVote(identifier, time, hash);
}
| 591,493 | [
1,
1290,
6397,
279,
3294,
358,
776,
17128,
18,
225,
2756,
30059,
25283,
326,
4746,
364,
333,
12501,
18,
512,
43,
605,
15988,
19,
3378,
40,
6205,
3082,
18,
225,
813,
11470,
326,
9753,
2858,
434,
326,
6205,
3832,
331,
16474,
603,
18,
225,
1651,
326,
417,
24410,
581,
5034,
1651,
434,
326,
6205,
1846,
2545,
358,
12501,
364,
471,
279,
2744,
3571,
4286,
460,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
3294,
19338,
12,
203,
3639,
1731,
1578,
2756,
16,
203,
3639,
2254,
5034,
813,
16,
203,
3639,
1731,
1578,
1651,
203,
565,
262,
3903,
1338,
2996,
6064,
12,
11890,
5034,
12,
6898,
18,
58,
20005,
3719,
288,
203,
3639,
389,
588,
58,
17128,
1887,
7675,
7371,
19338,
12,
5644,
16,
813,
16,
1651,
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
] |
./full_match/80001/0xF8a9362bA0f4F61D7a32D1e2e32113228Cf938cB/sources/StakingContract.sol | remainingBalance = (remainingBalance * 90) / 100;address payable uown = payable(msg.sender); | splitter.transfer(remainingBalance);
| 835,870 | [
1,
17956,
13937,
273,
261,
17956,
13937,
225,
8566,
13,
342,
2130,
31,
2867,
8843,
429,
582,
995,
273,
8843,
429,
12,
3576,
18,
15330,
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,
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,
3639,
21553,
18,
13866,
12,
17956,
13937,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.8.0;
import "./AccessControlEnumerable.sol";
interface PuppyToken {
function transfer(address _to, uint _amount) external returns(bool);
function transferFrom(address _from, address _to, uint _amount) external returns(bool);
function balanceOf(address _user) external returns(uint);
}
contract PuppyVesting is AccessControlEnumerable {
struct Member {
address memberAddress;
uint lastClaimed;
uint totalClaimed;
uint vested;
}
uint public totalVested;
Member[] public team;
Member[] public treasury;
Member[] public marketing;
uint public end;
uint public start;
uint public vestingPeriod;
uint public teamTotalVested;
uint public treasuryTotalVested;
uint public marketingTotalVested;
uint public teamStart;
uint public teamEnd;
PuppyToken public token;
event TeamVestingClaimed(address to, uint amount);
event TreasuryVestingClaimed(address to, uint amount);
event MarketingVestingClaimed(address to, uint amount);
event Rescue(address to, uint amount);
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
bytes32 public constant TEAM_ROLE = keccak256("TEAM_ROLE");
bytes32 public constant TREASURY_ROLE = keccak256("TREASURY_ROLE");
bytes32 public constant MARKETING_ROLE = keccak256("MARKETING_ROLE");
constructor(address _token, address _admin) {
require(_token != address(0) && _admin != address(0), "0 address not allowed");
_setupRole(ADMIN_ROLE, _admin);
end = block.timestamp + 730 days; //2 years
start = block.timestamp;
teamStart = block.timestamp + 30 days; //1 month lockup
teamEnd = block.timestamp + 30 days + 730 days; //2 years + 1 month for lockup
vestingPeriod = end - start;
token = PuppyToken(_token);
}
function addTeam(address[] memory _team) external {
require(hasRole(ADMIN_ROLE, _msgSender()), "Not allowed");
for (uint i; i < _team.length; i++) {
team.push(Member(_team[i], teamStart , 0, teamTotalVested/_team.length));
_setupRole(TEAM_ROLE, _team[i]);
}
}
function addTreasury(address[] memory _treasury) external {
require(hasRole(ADMIN_ROLE, _msgSender()), "Not allowed");
for (uint i; i < _treasury.length; i++) {
treasury.push(Member(_treasury[i], start, 0, treasuryTotalVested/_treasury.length));
_setupRole(TREASURY_ROLE, _treasury[i]);
}
}
function addMarketing(address[] memory _marketing) external {
require(hasRole(ADMIN_ROLE, _msgSender()), "Not allowed");
for (uint i; i < _marketing.length; i++) {
marketing.push(Member(_marketing[i], start, 0, marketingTotalVested/_marketing.length));
_setupRole(MARKETING_ROLE, _marketing[i]);
}
}
function claimTeamVesting() external {
require(hasRole(TEAM_ROLE, _msgSender()), "Not allowed");
require(block.timestamp >= teamStart, "Can't claim yet");
Member[] storage _team = team;
for (uint i; i <= _team.length; i++) {
if (_team[i].memberAddress == _msgSender() && _team[i].vested - _team[i].totalClaimed > 0) {
uint _reward;
if (block.timestamp < teamEnd) {
_reward = _team[i].vested * (block.timestamp - _team[i].lastClaimed) / vestingPeriod;
} else {
_reward = _team[i].vested * (teamEnd - _team[i].lastClaimed) / vestingPeriod;
}
if (_reward > _team[i].vested - _team[i].totalClaimed) {
_reward = _team[i].vested - _team[i].totalClaimed;
}
token.transfer(_team[i].memberAddress, _reward);
_team[i].totalClaimed += _reward;
_team[i].lastClaimed = block.timestamp;
emit TeamVestingClaimed(_team[i].memberAddress, _reward);
return;
}
}
}
function claimTreasuryVesting() external {
require(hasRole(TREASURY_ROLE, _msgSender()), "Not allowed");
Member[] storage _treasury = treasury;
for (uint i; i <= _treasury.length; i++) {
if (_treasury[i].memberAddress == _msgSender() && _treasury[i].vested - _treasury[i].totalClaimed > 0) {
uint _reward;
if (block.timestamp < end) {
_reward = _treasury[i].vested * (block.timestamp - _treasury[i].lastClaimed) / vestingPeriod;
} else {
_reward = _treasury[i].vested * (end - _treasury[i].lastClaimed) / vestingPeriod;
}
if (_reward > _treasury[i].vested - _treasury[i].totalClaimed) {
_reward = _treasury[i].vested - _treasury[i].totalClaimed;
}
token.transfer(_treasury[i].memberAddress, _reward);
_treasury[i].totalClaimed += _reward;
_treasury[i].lastClaimed = block.timestamp;
emit TreasuryVestingClaimed(_treasury[i].memberAddress, _reward);
return;
}
}
}
function claimMarketingVesting() external {
require(hasRole(MARKETING_ROLE, _msgSender()), "Not allowed");
Member[] storage _marketing = marketing;
for (uint i; i <= _marketing.length; i++) {
if (_marketing[i].memberAddress == _msgSender() && _marketing[i].vested - _marketing[i].totalClaimed > 0) {
uint _reward;
if (block.timestamp < end) {
_reward = _marketing[i].vested * (block.timestamp - _marketing[i].lastClaimed) / vestingPeriod;
} else {
_reward = _marketing[i].vested * (end - _marketing[i].lastClaimed) / vestingPeriod;
}
if (_reward > _marketing[i].vested - _marketing[i].totalClaimed) {
_reward = _marketing[i].vested - _marketing[i].totalClaimed;
}
token.transfer(_marketing[i].memberAddress, _reward);
_marketing[i].totalClaimed += _reward;
_marketing[i].lastClaimed = block.timestamp;
emit MarketingVestingClaimed(_marketing[i].memberAddress, _reward);
return;
}
}
}
function initVesting(uint _amount) external {
require(hasRole(ADMIN_ROLE, _msgSender()));
token.transferFrom(_msgSender(), address(this), _amount);
totalVested = _amount;
teamTotalVested = _amount * 4 / 10; //40%
treasuryTotalVested = _amount * 3 / 10; // 30%
marketingTotalVested = _amount * 3 / 10; // 30%
}
function rescue(address _to) external {
require(hasRole(ADMIN_ROLE, _msgSender()));
uint _balance = token.balanceOf(address(this));
token.transfer(_to, _balance);
emit Rescue(_to, _balance);
}
} | 2 years + 1 month for lockup
| teamEnd = block.timestamp + 30 days + 730 days; | 335,140 | [
1,
22,
11387,
397,
404,
3138,
364,
2176,
416,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5927,
1638,
273,
1203,
18,
5508,
397,
5196,
4681,
397,
2371,
5082,
4681,
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
] |
pragma solidity ^0.5.0;
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "openzeppelin-solidity/contracts/lifecycle/Pausable.sol";
import "./CryptoArcadeGame.sol";
import "./RewardSplitter.sol";
/**
* @title CryptoArcade
* @dev This contract is as a game factory and acts as a proxy between players and games.
* Operations related to the game will be delegated to the appropriate game instance.
*
* There is a circuit breaker implemented that can only be operated by the owner account, in case a serious issue is detected.
*/
contract CryptoArcade is Ownable, Pausable {
event LogGameRegistered(
address indexed creator,
string gameName,
uint256 price
);
event LogMatchPurchased(address indexed player, uint256 gameId);
event LogMatchStarted(
address indexed player,
uint256 indexed gameId,
uint256 indexed matchId
);
event LogMatchFinished(
address indexed player,
uint256 indexed gameId,
uint256 indexed matchId
);
event LogNewRecord(
address indexed player,
uint256 indexed gameId,
uint256 score
);
event LogRewardReleased(address indexed player, uint256 amount);
// The list of games registered to the arcade
mapping(uint256 => CryptoArcadeGame) private games;
// The unique game ID generator
uint256 private numRegisteredGames;
// Modifiyer that returns any ether paid in excess by the player
modifier refundExcess(uint256 gameId) {
_;
uint256 paidInExcess = msg.value - games[gameId].gameMatchPrice();
if (paidInExcess > 0) {
msg.sender.transfer(paidInExcess);
}
}
function() external payable {}
/**
* @dev Public constructor that registers a game at creation.
* The game is represented by the account of the game creator, a name and the cost of playing a match.
*
* A registration event is emitted if the creation is successful.
* @param _name The name of the game
* @param _creator The address of the creator
* @param _price The cost of one match
*/
constructor(string memory _name, address _creator, uint256 _price) public {
uint256 gameId = numRegisteredGames++;
games[gameId] = new CryptoArcadeGame(_name, _creator, _price);
emit LogGameRegistered(_creator, _name, _price);
}
/**
* @dev Method to register a new game to the platform.
*
* Emits a game registration event if sucessful.
* @param _name The name of the game
* @param _creator The address of the creator
* @param _price The cost of one match
* @return The new game ID
*/
function registerGame(string memory _name, address _creator, uint256 _price)
public
onlyOwner()
whenNotPaused()
returns (uint256)
{
uint256 gameId = numRegisteredGames++;
games[gameId] = new CryptoArcadeGame(_name, _creator, _price);
emit LogGameRegistered(_creator, _name, _price);
}
/**
* @dev This methods enables all operations for a given game.
* Games can be deactivated without being removed, in case an issue is detected.
*
* @param _gameId The id of the game to activate
*/
function activateGame(uint256 _gameId)
external
onlyOwner()
whenNotPaused()
{
games[_gameId].activateGame();
}
/**
* @dev This methods disables most of the operations for a given game.
* Games can be deactivated without being removed, in case an issue is detected.
* Deactivation keeps all related data safe while it reduces the operations available to authorised accounts.
*
* @param _gameId The id of the game to deactivate
*/
function deactivateGame(uint256 _gameId)
external
onlyOwner()
whenNotPaused()
{
games[_gameId].deactivateGame();
}
/**
* @dev Locates the price of a given game.
*
* @param _gameId The id of the game
* @return The game's price per match
*/
function matchPrice(uint256 _gameId) public view returns (uint256) {
return games[_gameId].gameMatchPrice();
}
/**
* @dev This method enables the purchase of game matches.
* The cost of the game is the price that the game owner defined at creation.
* The operation is relayed to the game contract for completion.
*
* If the purchase is successful a game purchased event is emitted.
* @param _gameId The id of the game to deactivate
* @return The ID of the match purchased
*/
function purchaseMatch(uint256 _gameId)
public
payable
refundExcess(_gameId)
whenNotPaused()
returns (uint256 matchId)
{
matchId = games[_gameId].purchaseMatch.value(msg.value)(msg.sender);
emit LogMatchPurchased(msg.sender, _gameId);
}
/**
* @dev This method looks up caller's available matches (those that are not in played status) and returns the total number.
*
* @param _gameId The id of the game
* @return The total number of matches for the caller that are not in played status
*/
function getNumberOfAvailableMatches(uint256 _gameId)
public
view
returns (uint256)
{
return games[_gameId].getNumberOfAvailableMatches(msg.sender);
}
/**
* @dev This method looks up caller's available matches (those that are not in played status) and returns the total number.
*
* @param _gameId The id of the game
* @return The total number of matches for the caller that are not in played status
*/
function getGameMatchScore(uint256 _gameId) public view returns (uint256) {
return games[_gameId].getNumberOfAvailableMatches(msg.sender);
}
/**
* @dev This method flags a match as played, which consumes it.
* The status of the match becomes Played so its score can be associated to it.
*
* @param _gameId The id of the game
* @return The ID of the match started
*/
function playMatch(uint256 _gameId) public returns (uint256 matchId) {
matchId = games[_gameId].playMatch(msg.sender);
emit LogMatchStarted(msg.sender, _gameId, matchId);
}
/**
* @dev This method is a proxy to the game method that stores the score of a match played,
* calculates whether it falls in the top 10 in which case it also calculates and awards
* a number of shares to the player. How many depends on the position achieved.
*
* The method emits a match finished event and a new record one in case the score deserves it.
* @param _gameId The id of the game
* @param _score The score attained
* @return The number of shares produced by the score (zero if the score doesn't make it to the top 10)
*/
function matchPlayed(uint256 _gameId, uint256 _score)
public
returns (uint256 shares)
{
shares = games[_gameId].matchPlayed(msg.sender, _score);
if (shares > 0) {
emit LogNewRecord(msg.sender, _gameId, _score);
}
emit LogMatchFinished(msg.sender, _gameId, _score);
}
/**
* @dev Method that retrieves the top 10 ranking one piece of data at a time,
* to avoid complex operations on-chain.
*
* @return The address of the entry in the top 10 'pos' position
*/
function getRecordEntryAddress(uint256 _gameId, uint256 _pos)
public
view
returns (address)
{
require(_pos < 10 && _pos >= 0, "The position must be between 0 and 9");
return games[_gameId].getRecordEntryAddress(_pos);
}
/**
* @dev Method that retrieves the top 10 ranking one piece of data at a time,
* to avoid complex operations on-chain.
*
* @return The score of the entry in the top 10 'pos' position
*/
function getRecordEntryScore(uint256 _gameId, uint256 _pos)
public
view
returns (uint256)
{
require(_pos < 10 && _pos >= 0, "The position must be between 0 and 9");
return games[_gameId].getRecordEntryScore(_pos);
}
/**
* @dev This method is a proxy to the game method that retrieves caller's number of shares in the common game pot.
*
* @param _gameId The id of the game
* @return Caller's total number of shares
*/
function playerBalance(uint256 _gameId) external view returns (uint256) {
return games[_gameId].playerBalance(msg.sender);
}
/**
* @dev This method is a proxy to the game pull method that retrieves the balance for a player.
*
* The method emits a reward released event.
* @param _gameId The id of the game
* @param _player The player
* @return True if player's balance is released successfully
*/
function releaseReward(uint256 _gameId, address payable _player)
public
returns (bool)
{
uint256 amount = games[_gameId].releaseReward(_player);
emit LogRewardReleased(_player, amount);
return true;
}
}
| * @dev This methods enables all operations for a given game. Games can be deactivated without being removed, in case an issue is detected. @param _gameId The id of the game to activate/ | function activateGame(uint256 _gameId)
external
onlyOwner()
whenNotPaused()
{
games[_gameId].activateGame();
}
| 14,113,116 | [
1,
2503,
2590,
19808,
777,
5295,
364,
279,
864,
7920,
18,
611,
753,
848,
506,
443,
18836,
2887,
3832,
3723,
16,
316,
648,
392,
5672,
353,
8316,
18,
225,
389,
13957,
548,
1021,
612,
434,
326,
7920,
358,
10235,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
10235,
12496,
12,
11890,
5034,
389,
13957,
548,
13,
203,
3639,
3903,
203,
3639,
1338,
5541,
1435,
203,
3639,
1347,
1248,
28590,
1435,
203,
565,
288,
203,
3639,
28422,
63,
67,
13957,
548,
8009,
10014,
12496,
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
] |
./full_match/1/0xf832b7cCa1BA656C48a789Ca474f62876b0AEbC6/sources/contracts/Governance.sol | @notice Validate token id (must be less than or equal to total tokens amount) @param _tokenId Token id @return bool flag that indicates if token id is less than or equal to total tokens amount | function isValidTokenId(uint16 _tokenId) external view returns (bool) {
return _tokenId <= totalTokens;
}
| 3,151,045 | [
1,
4270,
1147,
612,
261,
11926,
506,
5242,
2353,
578,
3959,
358,
2078,
2430,
3844,
13,
225,
389,
2316,
548,
3155,
612,
327,
1426,
2982,
716,
8527,
309,
1147,
612,
353,
5242,
2353,
578,
3959,
358,
2078,
2430,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4908,
1345,
548,
12,
11890,
2313,
389,
2316,
548,
13,
3903,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
389,
2316,
548,
1648,
2078,
5157,
31,
203,
565,
289,
203,
202,
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
] |
./full_match/80001/0x75AfbEf84bF6FF8Cafe08872Db2CB77cabebF53f/sources/phopox.sol | Update burnPercent by the previous dev. | function getBurnPercent() external view returns (uint256){
return burnPercent;
}
| 840,420 | [
1,
1891,
18305,
8410,
635,
326,
2416,
4461,
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,
2882,
321,
8410,
1435,
3903,
1476,
1135,
261,
11890,
5034,
15329,
203,
3639,
327,
18305,
8410,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/10/0xf9cFB8a62f50e10AdDE5Aa888B44cF01C5957055/sources/contracts/VeloPositionManager.sol | @notice Callback functions called by the vault to pay protocol fee. The caller to this function must be the vault contract | function payFeeToTreasuryCallback(
uint256 vaultId,
address asset,
uint256 amount,
uint256 feeType
) external {
address vaultAddress = IVaultFactory(vaultFactory).vaults(vaultId);
require(vaultAddress != address(0), Errors.VL_ADDRESS_CANNOT_ZERO);
require(
vaultAddress == _msgSender(),
Errors.VT_VAULT_CALLBACK_INVALID_SENDER
);
address treasury = IAddressRegistry(addressProvider).getAddress(
AddressId.ADDRESS_ID_TREASURY
);
require(treasury != address(0), "zero-address treasury");
SafeERC20.safeTransferFrom(
IERC20(asset),
vaultAddress,
treasury,
amount
);
emit FeePaid(vaultId, asset, feeType, amount);
}
| 3,780,645 | [
1,
2428,
4186,
2566,
635,
326,
9229,
358,
8843,
1771,
14036,
18,
1021,
4894,
358,
333,
445,
1297,
506,
326,
9229,
6835,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
8843,
14667,
774,
56,
266,
345,
22498,
2428,
12,
203,
3639,
2254,
5034,
9229,
548,
16,
203,
3639,
1758,
3310,
16,
203,
3639,
2254,
5034,
3844,
16,
203,
3639,
2254,
5034,
14036,
559,
203,
565,
262,
3903,
288,
203,
3639,
1758,
9229,
1887,
273,
467,
12003,
1733,
12,
26983,
1733,
2934,
26983,
87,
12,
26983,
548,
1769,
203,
3639,
2583,
12,
26983,
1887,
480,
1758,
12,
20,
3631,
9372,
18,
58,
48,
67,
15140,
67,
39,
16791,
67,
24968,
1769,
203,
3639,
2583,
12,
203,
5411,
9229,
1887,
422,
389,
3576,
12021,
9334,
203,
5411,
9372,
18,
58,
56,
67,
27722,
2274,
67,
30312,
67,
9347,
67,
1090,
18556,
203,
3639,
11272,
203,
203,
3639,
1758,
9787,
345,
22498,
273,
467,
1887,
4243,
12,
2867,
2249,
2934,
588,
1887,
12,
203,
5411,
5267,
548,
18,
15140,
67,
734,
67,
56,
862,
3033,
1099,
61,
203,
3639,
11272,
203,
3639,
2583,
12,
27427,
345,
22498,
480,
1758,
12,
20,
3631,
315,
7124,
17,
2867,
9787,
345,
22498,
8863,
203,
203,
3639,
14060,
654,
39,
3462,
18,
4626,
5912,
1265,
12,
203,
5411,
467,
654,
39,
3462,
12,
9406,
3631,
203,
5411,
9229,
1887,
16,
203,
5411,
9787,
345,
22498,
16,
203,
5411,
3844,
203,
3639,
11272,
203,
203,
3639,
3626,
30174,
16507,
350,
12,
26983,
548,
16,
3310,
16,
14036,
559,
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
] |
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 OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/*
* ERC20 interface
* see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
uint public totalSupply;
function balanceOf(address who) constant returns (uint);
function allowance(address owner, address spender) constant returns (uint);
function transfer(address to, uint value) returns (bool ok);
function transferFrom(address from, address to, uint value) returns (bool ok);
function approve(address spender, uint value) returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract ERC223 is ERC20 {
function transfer(address to, uint value, bytes data) returns (bool ok);
function transferFrom(address from, address to, uint value, bytes data) returns (bool ok);
}
/*
Base class contracts willing to accept ERC223 token transfers must conform to.
Sender: msg.sender to the token contract, the address originating the token transfer.
- For user originated transfers sender will be equal to tx.origin
- For contract originated transfers, tx.origin will be the user that made the tx that produced the transfer.
Origin: the origin address from whose balance the tokens are sent
- For transfer(), origin = msg.sender
- For transferFrom() origin = _from to token contract
Value is the amount of tokens sent
Data is arbitrary data sent with the token transfer. Simulates ether tx.data
From, origin and value shouldn't be trusted unless the token contract is trusted.
If sender == tx.origin, it is safe to trust it regardless of the token.
*/
contract ERC223Receiver {
function tokenFallback(address _sender, address _origin, uint _value, bytes _data) returns (bool ok);
}
/**
* Math operations with safety checks
*/
contract SafeMath {
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint a, uint b) internal returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
/*function assert(bool assertion) internal {
if (!assertion) {
throw;
}
}*/
}
/**
* Standard ERC20 token
*
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, SafeMath {
mapping(address => uint) balances;
mapping (address => mapping (address => uint)) allowed;
function transfer(address _to, uint _value) returns (bool success) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint _value) returns (bool success) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because safeSub(_allowance, _value) will already throw if this condition is not met
// if (_value > _allowance) throw;
balances[_to] = safeAdd(balances[_to], _value);
balances[_from] = safeSub(balances[_from], _value);
allowed[_from][msg.sender] = safeSub(_allowance, _value);
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
function approve(address _spender, uint _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
contract KinguinKrowns is ERC223, StandardToken {
address public owner; // token owner adddres
string public constant name = "PINGUINS";
string public constant symbol = "PGS";
uint8 public constant decimals = 18;
// uint256 public totalSupply; // defined in ERC20 contract
function KinguinKrowns() {
owner = msg.sender;
totalSupply = 100000000 * (10**18); // 100 mln
balances[msg.sender] = totalSupply;
}
/*
//only do if call is from owner modifier
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}*/
//function that is called when a user or another contract wants to transfer funds
function transfer(address _to, uint _value, bytes _data) returns (bool success) {
//filtering if the target is a contract with bytecode inside it
if (!super.transfer(_to, _value)) throw; // do a normal token transfer
if (isContract(_to)) return contractFallback(msg.sender, _to, _value, _data);
return true;
}
function transferFrom(address _from, address _to, uint _value, bytes _data) returns (bool success) {
if (!super.transferFrom(_from, _to, _value)) throw; // do a normal token transfer
if (isContract(_to)) return contractFallback(_from, _to, _value, _data);
return true;
}
function transfer(address _to, uint _value) returns (bool success) {
return transfer(_to, _value, new bytes(0));
}
function transferFrom(address _from, address _to, uint _value) returns (bool success) {
return transferFrom(_from, _to, _value, new bytes(0));
}
//function that is called when transaction target is a contract
function contractFallback(address _origin, address _to, uint _value, bytes _data) private returns (bool success) {
ERC223Receiver receiver = ERC223Receiver(_to);
return receiver.tokenFallback(msg.sender, _origin, _value, _data);
}
//assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) private returns (bool is_contract) {
// retrieve the size of the code on target address, this needs assembly
uint length;
assembly { length := extcodesize(_addr) }
return length > 0;
}
// returns krown balance of given address
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
}
contract KinguinIco is SafeMath, ERC223Receiver {
address constant public superOwner = 0xcEbb7454429830C92606836350569A17207dA857;
address public owner; // contract owner address
address public api; // address of api manager
KinguinKrowns public krs; // handler to KRS token contract
// rounds data storage:
struct IcoRoundData {
uint rMinEthPayment; // set minimum ETH payment
uint rKrsUsdFixed; // set KRS/USD fixed ratio for calculation of krown amount to be sent,
uint rKycTreshold; // KYC treshold in EUR (needed for check whether incoming payment requires KYC/AML verified address)
uint rMinKrsCap; // minimum amount of KRS to be sent during a round
uint rMaxKrsCap; // maximum amount of KRS to be sent during a round
uint rStartBlock; // number of blockchain start block for a round
uint rEndBlock; // number of blockchain end block for a round
uint rEthPaymentsAmount; // sum of ETH tokens received from participants during a round
uint rEthPaymentsCount; // counter of ETH payments during a round
uint rSentKrownsAmount; // sum of ETH tokens received from participants during a round
uint rSentKrownsCount; // counter of KRS transactions during a round
bool roundCompleted; // flag whether a round has finished
}
mapping(uint => IcoRoundData) public icoRounds; // table of rounds data: ico number, ico record
mapping(address => bool) public allowedAdresses; // list of KYC/AML approved wallets: participant address, allowed/not allowed
struct RoundPayments { // structure for storing sum of payments
uint round;
uint amount;
}
// amount of payments from the same address during each round
// (to catch multiple payments to check KYC/AML approvance): participant address, payments record
mapping(address => RoundPayments) public paymentsFromAddress;
uint public ethEur; // current EUR/ETH exchange rate (for AML check)
uint public ethUsd; // current ETH/USD exchange rate (sending KRS for ETH calc)
uint public krsUsd; // current KRS/USD exchange rate (sending KRS for ETH calc)
uint public rNo; // counter for rounds
bool public icoInProgress; // ico status flag
bool public apiAccessDisabled; // api access security flag
event LogReceivedEth(address from, uint value, uint block); // publish an event about incoming ETH
event LogSentKrs(address to, uint value, uint block); // publish an event about sent KRS
// execution allowed only for contract superowner
modifier onlySuperOwner() {
require(msg.sender == superOwner);
_;
}
// execution allowed only for contract owner
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
// execution allowed only for contract owner or api address
modifier onlyOwnerOrApi() {
require(msg.sender == owner || msg.sender == api);
if (msg.sender == api && api != owner) {
require(!apiAccessDisabled);
}
_;
}
function KinguinIco() {
owner = msg.sender; // this contract owner
api = msg.sender; // initially api address is the contract owner's address
krs = KinguinKrowns(0xdfb410994b66778bd6cc2c82e8ffe4f7b2870006); // KRS token
}
// receiving ETH and sending KRS
function () payable {
if(msg.sender != owner) { // if ETH comes from other than the contract owner address
if(block.number >= icoRounds[rNo].rStartBlock && block.number <= icoRounds[rNo].rEndBlock && !icoInProgress) {
icoInProgress = true;
}
require(block.number >= icoRounds[rNo].rStartBlock && block.number <= icoRounds[rNo].rEndBlock && !icoRounds[rNo].roundCompleted); // allow payments only during the ico round
require(msg.value >= icoRounds[rNo].rMinEthPayment); // minimum eth payment
require(ethEur > 0); // ETH/EUR rate for AML must be set earlier
require(ethUsd > 0); // ETH/USD rate for conversion to KRS
uint krowns4eth;
if(icoRounds[rNo].rKrsUsdFixed > 0) { // KRS has fixed ratio to USD
krowns4eth = safeDiv(safeMul(safeMul(msg.value, ethUsd), uint(100)), icoRounds[rNo].rKrsUsdFixed);
} else { // KRS/USD is traded on exchanges
require(krsUsd > 0); // KRS/USD rate for conversion to KRS
krowns4eth = safeDiv(safeMul(safeMul(msg.value, ethUsd), uint(100)), krsUsd);
}
require(safeAdd(icoRounds[rNo].rSentKrownsAmount, krowns4eth) <= icoRounds[rNo].rMaxKrsCap); // krs cap per round
if(paymentsFromAddress[msg.sender].round != rNo) { // on mappings all keys are possible, so there is no checking for its existence
paymentsFromAddress[msg.sender].round = rNo; // on new round set to current round
paymentsFromAddress[msg.sender].amount = 0; // zeroing amount on new round
}
if(safeMul(ethEur, safeDiv(msg.value, 10**18)) >= icoRounds[rNo].rKycTreshold || // if payment from this sender requires to be from KYC/AML approved address
// if sum of payments from this sender address requires to be from KYC/AML approved address
safeMul(ethEur, safeDiv(safeAdd(paymentsFromAddress[msg.sender].amount, msg.value), 10**18)) >= icoRounds[rNo].rKycTreshold) {
require(allowedAdresses[msg.sender]); // only KYC/AML allowed address
}
icoRounds[rNo].rEthPaymentsAmount = safeAdd(icoRounds[rNo].rEthPaymentsAmount, msg.value);
icoRounds[rNo].rEthPaymentsCount += 1;
paymentsFromAddress[msg.sender].amount = safeAdd(paymentsFromAddress[msg.sender].amount, msg.value);
LogReceivedEth(msg.sender, msg.value, block.number);
icoRounds[rNo].rSentKrownsAmount = safeAdd(icoRounds[rNo].rSentKrownsAmount, krowns4eth);
icoRounds[rNo].rSentKrownsCount += 1;
krs.transfer(msg.sender, krowns4eth);
LogSentKrs(msg.sender, krowns4eth, block.number);
} else { // owner can always pay-in (and trigger round start/stop)
if(block.number >= icoRounds[rNo].rStartBlock && block.number <= icoRounds[rNo].rEndBlock && !icoInProgress) {
icoInProgress = true;
}
if(block.number > icoRounds[rNo].rEndBlock && icoInProgress) {
endIcoRound();
}
}
}
// receiving tokens other than ETH
// ERC223 receiver implementation - https://github.com/aragon/ERC23/blob/master/contracts/implementation/Standard223Receiver.sol
Tkn tkn;
struct Tkn {
address addr;
address sender;
address origin;
uint256 value;
bytes data;
bytes4 sig;
}
function tokenFallback(address _sender, address _origin, uint _value, bytes _data) returns (bool ok) {
if (!supportsToken(msg.sender)) return false;
return true;
}
function getSig(bytes _data) private returns (bytes4 sig) {
uint l = _data.length < 4 ? _data.length : 4;
for (uint i = 0; i < l; i++) {
sig = bytes4(uint(sig) + uint(_data[i]) * (2 ** (8 * (l - 1 - i))));
}
}
bool __isTokenFallback;
modifier tokenPayable {
if (!__isTokenFallback) throw;
_;
}
function supportsToken(address token) returns (bool) {
if (token == address(krs)) {
return true;
} else {
revert();
}
}
// end of ERC223 receiver implementation ------------------------------------
// set up a new ico round
function newIcoRound(uint _rMinEthPayment, uint _rKrsUsdFixed, uint _rKycTreshold,
uint _rMinKrsCap, uint _rMaxKrsCap, uint _rStartBlock, uint _rEndBlock) public onlyOwner {
require(!icoInProgress); // new round can be set up only after finished/cancelled the active one
require(rNo < 25); // limit of 25 rounds (with pre-ico)
rNo += 1; // increment round number, pre-ico has number 1
icoRounds[rNo] = IcoRoundData(_rMinEthPayment, _rKrsUsdFixed, _rKycTreshold, _rMinKrsCap, _rMaxKrsCap,
_rStartBlock, _rEndBlock, 0, 0, 0, 0, false); // rEthPaymentsAmount, rEthPaymentsCount, rSentKrownsAmount, rSentKrownsCount);
}
// remove current round, params only - it does not refund any ETH!
function removeCurrentIcoRound() public onlyOwner {
require(icoRounds[rNo].rEthPaymentsAmount == 0); // only if there was no payment already
require(!icoRounds[rNo].roundCompleted); // only current round can be removed
icoInProgress = false;
icoRounds[rNo].rMinEthPayment = 0;
icoRounds[rNo].rKrsUsdFixed = 0;
icoRounds[rNo].rKycTreshold = 0;
icoRounds[rNo].rMinKrsCap = 0;
icoRounds[rNo].rMaxKrsCap = 0;
icoRounds[rNo].rStartBlock = 0;
icoRounds[rNo].rEndBlock = 0;
icoRounds[rNo].rEthPaymentsAmount = 0;
icoRounds[rNo].rEthPaymentsCount = 0;
icoRounds[rNo].rSentKrownsAmount = 0;
icoRounds[rNo].rSentKrownsCount = 0;
if(rNo > 0) rNo -= 1;
}
function changeIcoRoundEnding(uint _rEndBlock) public onlyOwner {
require(icoRounds[rNo].rStartBlock > 0); // round must be set up earlier
icoRounds[rNo].rEndBlock = _rEndBlock;
}
// closes round automatically
function endIcoRound() private {
icoInProgress = false;
icoRounds[rNo].rEndBlock = block.number;
icoRounds[rNo].roundCompleted = true;
}
// close round manually - if needed
function endIcoRoundManually() public onlyOwner {
endIcoRound();
}
// add a verified KYC/AML address
function addAllowedAddress(address _address) public onlyOwnerOrApi {
allowedAdresses[_address] = true;
}
function removeAllowedAddress(address _address) public onlyOwnerOrApi {
delete allowedAdresses[_address];
}
// set exchange rate for ETH/EUR - needed for check whether incoming payment
// is more than xxxx EUR (thus requires KYC/AML verified address)
function setEthEurRate(uint _ethEur) public onlyOwnerOrApi {
ethEur = _ethEur;
}
// set exchange rate for ETH/USD
function setEthUsdRate(uint _ethUsd) public onlyOwnerOrApi {
ethUsd = _ethUsd;
}
// set exchange rate for KRS/USD
function setKrsUsdRate(uint _krsUsd) public onlyOwnerOrApi {
krsUsd = _krsUsd;
}
// set all three exchange rates: ETH/EUR, ETH/USD, KRS/USD
function setAllRates(uint _ethEur, uint _ethUsd, uint _krsUsd) public onlyOwnerOrApi {
ethEur = _ethEur;
ethUsd = _ethUsd;
krsUsd = _krsUsd;
}
// send KRS from the contract to a given address (for BTC and FIAT payments)
function sendKrs(address _receiver, uint _amount) public onlyOwnerOrApi {
krs.transfer(_receiver, _amount);
}
// transfer KRS from other holder, up to amount allowed through krs.approve() function
function getKrsFromApproved(address _from, uint _amount) public onlyOwnerOrApi {
krs.transferFrom(_from, address(this), _amount);
}
// send ETH from the contract to a given address
function sendEth(address _receiver, uint _amount) public onlyOwner {
_receiver.transfer(_amount);
}
// disable/enable access from API - for security reasons
function disableApiAccess(bool _disabled) public onlyOwner {
apiAccessDisabled = _disabled;
}
// change API wallet address - for security reasons
function changeApi(address _address) public onlyOwner {
api = _address;
}
// change owner address
function changeOwner(address _address) public onlySuperOwner {
owner = _address;
}
}
library MicroWalletLib {
//change to production token address
KinguinKrowns constant token = KinguinKrowns(0xdfb410994b66778bd6cc2c82e8ffe4f7b2870006);
struct MicroWalletStorage {
uint krsAmount ;
address owner;
}
function toBytes(address a) private pure returns (bytes b){
assembly {
let m := mload(0x40)
mstore(add(m, 20), xor(0x140000000000000000000000000000000000000000, a))
mstore(0x40, add(m, 52))
b := m
}
}
function processPayment(MicroWalletStorage storage self, address _sender) public {
require(msg.sender == address(token));
if (self.owner == _sender) { //closing MicroWallet
self.krsAmount = 0;
return;
}
require(self.krsAmount > 0);
uint256 currentBalance = token.balanceOf(address(this));
require(currentBalance >= self.krsAmount);
if(currentBalance > self.krsAmount) {
//return rest of the token
require(token.transfer(_sender, currentBalance - self.krsAmount));
}
require(token.transfer(self.owner, self.krsAmount, toBytes(_sender)));
self.krsAmount = 0;
}
}
contract KinguinVault is Ownable, ERC223Receiver {
mapping(uint=>address) public microWalletPayments;
mapping(uint=>address) public microWalletsAddrs;
mapping(address=>uint) public microWalletsIDs;
mapping(uint=>uint) public microWalletPaymentBlockNr;
KinguinKrowns public token;
uint public uncleSafeNr = 5;
address public withdrawAddress;
modifier onlyWithdraw() {
require(withdrawAddress == msg.sender);
_;
}
constructor(KinguinKrowns _token) public {
token = _token;
withdrawAddress = owner;
}
function createMicroWallet(uint productOrderID, uint krsAmount) onlyOwner public {
require(productOrderID != 0 && microWalletsAddrs[productOrderID] == address(0x0));
microWalletsAddrs[productOrderID] = new MicroWallet(krsAmount);
microWalletsIDs[microWalletsAddrs[productOrderID]] = productOrderID;
}
function getMicroWalletAddress(uint productOrderID) public view returns(address) {
return microWalletsAddrs[productOrderID];
}
function closeMicroWallet(uint productOrderID) onlyOwner public {
token.transfer(microWalletsAddrs[productOrderID], 0);
}
function checkIfOnUncle(uint currentBlockNr, uint transBlockNr) private view returns (bool) {
if((currentBlockNr - transBlockNr) < uncleSafeNr) {
return true;
}
return false;
}
function setUncleSafeNr(uint newUncleSafeNr) onlyOwner public {
uncleSafeNr = newUncleSafeNr;
}
function getProductOrderPayer(uint productOrderID) public view returns (address) {
if (checkIfOnUncle(block.number, microWalletPaymentBlockNr[productOrderID])) {
return 0;
}
return microWalletPayments[productOrderID];
}
function tokenFallback(address _sender, address _origin, uint _value, bytes _data) public returns (bool) {
require(msg.sender == address(token));
if(microWalletsIDs[_sender] > 0) {
microWalletPayments[microWalletsIDs[_sender]] = bytesToAddr(_data);
microWalletPaymentBlockNr[microWalletsIDs[_sender]] = block.number;
}
return true;
}
function setWithdrawAccount(address _addr) onlyWithdraw public {
withdrawAddress = _addr;
}
function withdrawKrowns(address wallet, uint amount) onlyWithdraw public {
require(wallet != address(0x0));
token.transfer(wallet, amount);
}
function bytesToAddr (bytes b) private pure returns (address) {
uint result = 0;
for (uint i = b.length-1; i+1 > 0; i--) {
uint c = uint(b[i]);
uint to_inc = c * ( 16 ** ((b.length - i-1) * 2));
result += to_inc;
}
return address(result);
}
}
contract MicroWallet is ERC223Receiver {
MicroWalletLib.MicroWalletStorage private mwStorage;
constructor(uint _krsAmount) public {
mwStorage.krsAmount = _krsAmount;
mwStorage.owner = msg.sender;
}
function tokenFallback(address _sender, address _origin, uint _value, bytes _data) public returns (bool) {
MicroWalletLib.processPayment(mwStorage, _sender);
return true;
}
} | receiving ETH and sending KRS | function () payable {
if(block.number >= icoRounds[rNo].rStartBlock && block.number <= icoRounds[rNo].rEndBlock && !icoInProgress) {
icoInProgress = true;
}
uint krowns4eth;
krowns4eth = safeDiv(safeMul(safeMul(msg.value, ethUsd), uint(100)), icoRounds[rNo].rKrsUsdFixed);
krowns4eth = safeDiv(safeMul(safeMul(msg.value, ethUsd), uint(100)), krsUsd);
}
| 6,979,732 | [
1,
8606,
9288,
512,
2455,
471,
5431,
1475,
13225,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
1832,
8843,
429,
288,
203,
1377,
309,
12,
2629,
18,
2696,
1545,
277,
2894,
54,
9284,
63,
86,
2279,
8009,
86,
1685,
1768,
597,
1203,
18,
2696,
1648,
277,
2894,
54,
9284,
63,
86,
2279,
8009,
86,
1638,
1768,
597,
401,
10764,
13434,
13,
288,
203,
3639,
277,
2894,
13434,
273,
638,
31,
203,
1377,
289,
21281,
202,
225,
2254,
417,
492,
2387,
24,
546,
31,
203,
3639,
417,
492,
2387,
24,
546,
273,
4183,
7244,
12,
4626,
27860,
12,
4626,
27860,
12,
3576,
18,
1132,
16,
13750,
3477,
72,
3631,
2254,
12,
6625,
13,
3631,
277,
2894,
54,
9284,
63,
86,
2279,
8009,
86,
47,
5453,
3477,
72,
7505,
1769,
203,
3639,
417,
492,
2387,
24,
546,
273,
4183,
7244,
12,
4626,
27860,
12,
4626,
27860,
12,
3576,
18,
1132,
16,
13750,
3477,
72,
3631,
2254,
12,
6625,
13,
3631,
417,
5453,
3477,
72,
1769,
203,
21114,
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
] |
pragma solidity ^0.4.24;
contract EthGods {
// imported contracts
EthGodsName private eth_gods_name;
function set_eth_gods_name_contract_address(address eth_gods_name_contract_address) public returns (bool) {
require(msg.sender == admin);
eth_gods_name = EthGodsName(eth_gods_name_contract_address);
return true;
}
EthGodsDice private eth_gods_dice;
function set_eth_gods_dice_contract_address(address eth_gods_dice_contract_address) public returns (bool) {
require(msg.sender == admin);
eth_gods_dice = EthGodsDice(eth_gods_dice_contract_address);
return true;
}
// end of imported contracts
// start of database
//contract information & administration
bool private contract_created; // in case constructor logic change in the future
address private contract_address; //shown at the top of the home page
string private contact_email = "[email protected]";
string private official_url = "swarm-gateways.net/bzz:/ethgods.eth";
address private admin; // public when testing
address private controller1 = 0xcA5A9Db0EF9a0Bf5C38Fc86fdE6CB897d9d86adD; // controller can change admin at once;
address private controller2 = 0x8396D94046a099113E5fe5CBad7eC95e96c2B796; // controller can change admin at once;
address private v_god = 0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359;
uint private block_hash_duration = 255; // can't get block hash, after 256 blocks, adjustable
// god
struct god {
uint god_id;
uint level;
uint exp;
uint pet_type;// 12 animals or zodiacs
uint pet_level;
uint listed; // 0 not a god, 1 - ... rank_score in god list
uint invite_price;
uint blessing_player_id;
bool hosted_pray; // auto waitlist, when enlisted. others can invite, once hosted pray
uint bid_eth; // bid to host pray
uint credit; // gained from the amulet invitation spending of invited fellows
uint count_amulets_generated;
uint first_amulet_generated;
uint count_amulets_at_hand;
uint count_amulets_selling;
uint amulets_start_id;
uint amulets_end_id;
uint count_token_orders;
uint first_active_token_order;
uint allowed_block; // allow another account to use my egst
uint block_number; // for pray
bytes32 gene;
bool gene_created;
bytes32 pray_hash; //hash created for each pray
uint inviter_id; // who invited this fellow to this world
uint count_gods_invited; // gods invited to this game by this god.
}
uint private count_gods = 0; // Used when generating id for a new player,
mapping(address => god) private gods; // everyone is a god
mapping(uint => address) private gods_address; // gods' address => god_id
uint [] private listed_gods; // id of listed gods
uint private max_listed_gods = 10000; // adjustable
uint private initial_invite_price = 0.02 ether; // grows with each invitation for this god
uint private invite_price_increase = 0.02 ether; // grows by this amount with each invitation
uint private max_invite_price = 1000 ether; // adjustable
uint private max_extra_eth = 0.001 ether; // adjustable
uint private list_level = 10; // start from level 10
uint private max_gas_price = 100000000000; // 100 gwei for invite and pray, adjustable
// amulet
struct amulet {
uint god_id;
address owner;
uint level;
uint bound_start_block;// can't sell, if just got
// bool selling;
uint start_selling_block; // can't bind & use in pk, if selling
uint price; // set to 0, when withdraw from selling or bought
// uint order_id; // should be 0, if not selling
}
uint private count_amulets = 0;
mapping(uint => amulet) private amulets; // public when testing
uint private bound_duration = 9000; // once bought, wait a while before sell it again, adjustable
uint private order_duration = 20000; // valid for about 3 days, then not to show to public in selling amulets/token orders, but still show in my_selling amulets/token orders. adjustable
// pray
address private pray_host_god; // public when testing
bool private pray_reward_top100; // if hosted by new god, reward top 100 gods egst
uint private pray_start_block; // public when testing
bool private rewarded_pray_winners = false;
uint private count_hosted_gods; // gods hosted pray (event started). If less than bidding gods, there are new gods waiting to host pray,
mapping (uint => address) private bidding_gods; // every listed god and bid to host pray
uint private initializer_reward = 36; // reward the god who burned gas to send pray rewards to community, adjustable
mapping(uint => uint) private max_winners; // max winners for each prize
uint private min_pray_interval = 2000; // 2000, 36 in CBT, 2 in dev, adjustable
uint private min_pray_duration = 6000; // 6000, 600 in CBT, 60 in dev, adjustable
uint private max_pray_duration = 9000; // 9000, 900 in CBT, 90 in dev, adjustable
uint private count_waiting_prayers;
mapping (uint => address) private waiting_prayers; // uint is waiting sequence
uint private waiting_prayer_index = 1; // waiting sequence of the prayer ready to draw lot
mapping(uint => uint) private pk_positions; // public when testing
mapping(uint => uint) private count_listed_winners; // count for 5 prizes, public in testing
mapping (uint => mapping(uint => address)) private listed_winners; // winners for 5 prizes
bool private reEntrancyMutex = false; // for sendnig eth to msg.sender
uint private pray_egses = 0; // 10% from reward pool to top 3 winners in each round of pray events
uint private pray_egst = 0; // 10% from reward pool to 3rd & 4th prize winners in each round of pray events
mapping(address => uint) egses_balances;
// eth_gods_token (EGST)
string public name = "EthGodsToken";
string public symbol = "EGST";
uint8 public decimals = 18; //same as ethereum
uint private _totalSupply;
mapping(address => uint) balances; // bought or gained from pray or revenue share
mapping(address => mapping(address => uint)) allowed;
uint private allowed_use_CD = 20; // if used allowed amount, have to wait a while before approve new allowed amount again, prevent cheating, adjustable
struct token_order {
uint id;
uint start_selling_block;
address seller;
uint unit_price;
uint egst_amount;
}
uint private count_token_orders = 0;
mapping (uint => token_order) token_orders;
uint private first_active_token_order = 0;
uint private min_unit_price = 20; // 1 egst min value is 0.0002 ether, adjustable
uint private max_unit_price = 200; // 1 egst max value is 0.002 ether, adjustable
uint private max_egst_amount = 1000000 ether; // for create_token_order, adjustable
uint private min_egst_amount = 0.00001 ether; // for create_token_order, adjustable
//logs
uint private count_rounds = 0;
struct winner_log { // win a prize and if pk
uint god_block_number;
bytes32 block_hash;
address prayer;
address previous_winner;
uint prize;
bool pk_result;
}
mapping (uint => uint) private count_rounds_winner_logs;
mapping(uint => mapping(uint => winner_log)) private winner_logs;
struct change_log {
uint block_number;
uint asset_type; // 1 egst, 2 eth_surplus
// egses change reasons:
// 1 pray_reward, 2 god_reward for being invited, 3 inviter_reward,
// 4 admin_deposit to reward_pool, 5 withdraw egses
// 6 sell amulet, 7 sell egst, 8 withdraw bid
// egst_change reasons:
// 1 pray_reward, 2 top_gods_reward,
// 3 create_token_order, 4 withdraw token_order, 5 buy token,
// 6 upgrade pet, 7 upgrade amulet, 8 admin_reward
uint reason; // > 10 is buy token unit_price
uint change_amount;
uint after_amount;
address _from;
address _to;
}
mapping (uint => uint) private count_rounds_change_logs;
mapping(uint => mapping(uint => change_log)) private change_logs;
// end of database
// start of constructor
constructor () public {
require (contract_created == false);
contract_created = true;
contract_address = address(this);
admin = msg.sender;
create_god(admin, 0);
create_god(v_god, 0);
gods[v_god].level = 10;
enlist_god(v_god);
max_winners[1] = 1; // 1
max_winners[2] = 2; // 2
max_winners[3] = 8; // 8
max_winners[4] = 16; // 16
max_winners[5] = 100; // 100
_totalSupply = 6000000 ether;
pray_egst = 1000 ether;
balances[admin] = sub(_totalSupply, pray_egst);
initialize_pray();
}
// destruct for testing contracts. can't destruct since round 3
function finalize() public {
require(msg.sender == admin && count_rounds <= 3);
selfdestruct(admin);
}
function () public payable {
revert ();
}
// end of constructor
//start of contract information & administration
function get_controller () public view returns (address, address){
require (msg.sender == admin || msg.sender == controller1 || msg.sender == controller2);
return (controller1, controller2);
}
function set_controller (uint controller_index, address new_controller_address) public returns (bool){
if (controller_index == 1){
require(msg.sender == controller2);
controller1 = new_controller_address;
} else {
require(msg.sender == controller1);
controller2 = new_controller_address;
}
return true;
}
function set_admin (address new_admin_address) public returns (bool) {
require (msg.sender == controller1 || msg.sender == controller2);
// admin don't have game attributes, such as level'
// no need to transfer egses and egst to new_admin_address
delete gods[admin];
admin = new_admin_address;
gods_address[0] = admin;
gods[admin].god_id = 0;
return true;
}
// update system parameters
function set_parameters (uint parameter_type, uint new_parameter) public returns (bool){
require (msg.sender == admin);
if (parameter_type == 1) {
max_pray_duration = new_parameter;
} else if (parameter_type == 2) {
min_pray_duration = new_parameter;
} else if (parameter_type == 3) {
block_hash_duration = new_parameter;
} else if (parameter_type == 4) {
min_pray_interval = new_parameter;
} else if (parameter_type == 5) {
order_duration = new_parameter;
} else if (parameter_type == 6) {
bound_duration = new_parameter;
} else if (parameter_type == 7) {
initializer_reward = new_parameter;
} else if (parameter_type == 8) {
allowed_use_CD = new_parameter;
} else if (parameter_type == 9) {
min_unit_price = new_parameter;
} else if (parameter_type == 10) {
max_unit_price = new_parameter;
} else if (parameter_type == 11) {
max_listed_gods = new_parameter;
} else if (parameter_type == 12) {
max_gas_price = new_parameter;
} else if (parameter_type == 13) {
max_invite_price = new_parameter;
} else if (parameter_type == 14) {
min_egst_amount = new_parameter;
} else if (parameter_type == 15) {
max_egst_amount = new_parameter;
} else if (parameter_type == 16) {
max_extra_eth = new_parameter;
}
return true;
}
function set_strings (uint string_type, string new_string) public returns (bool){
require (msg.sender == admin);
if (string_type == 1){
official_url = new_string;
} else if (string_type == 2){
name = new_string; // egst name
} else if (string_type == 3){
symbol = new_string; // egst symbol
}
return true;
}
// for basic information to show to players, and to update parameter in sub-contracts
function query_contract () public view returns(uint, uint, address, uint, string, uint, uint){
return (count_gods,
listed_gods.length,
admin,
block_hash_duration,
official_url,
bound_duration,
min_pray_interval
);
}
function query_uints () public view returns (uint[7] uints){
uints[0] = max_invite_price;
uints[1] = list_level;
uints[2] = max_pray_duration;
uints[3] = min_pray_duration;
uints[4] = initializer_reward;
uints[5] = min_unit_price;
uints[6] = max_unit_price;
return uints;
}
function query_uints2 () public view returns (uint[6] uints){
uints[0] = allowed_use_CD;
uints[1] = max_listed_gods;
uints[2] = max_gas_price;
uints[3] = min_egst_amount;
uints[4] = max_egst_amount;
uints[5] = max_extra_eth;
return uints;
}
//end of contract information & administration
// god related functions: register, create_god, upgrade_pet, add_exp, burn_gas, invite, enlist
// if a new player comes when a round just completed, the new player may not want to initialize the next round
function register_god (uint inviter_id) public returns (uint) {
return create_god(msg.sender, inviter_id);
}
function create_god (address god_address, uint inviter_id) private returns(uint god_id){ // created by the contract // public when testing
// check if the god is already created
if (gods[god_address].credit == 0) { // create admin as god[0]
gods[god_address].credit = 1; // give 1 credit, so we know this address has a god
god_id = count_gods; // 1st god's id is admin 0
count_gods = add(count_gods, 1) ;
gods_address[god_id] = god_address;
gods[god_address].god_id = god_id;
if (god_id > 0){ // not admin
add_exp(god_address, 100);
set_inviter(inviter_id);
}
return god_id;
}
}
function set_inviter (uint inviter_id) public returns (bool){
if (inviter_id > 0 && gods_address[inviter_id] != address(0)
&& gods[msg.sender].inviter_id == 0
&& gods[gods_address[inviter_id]].inviter_id != gods[msg.sender].god_id){
gods[msg.sender].inviter_id = inviter_id;
address inviter_address = gods_address[inviter_id];
gods[inviter_address].count_gods_invited = add(gods[inviter_address].count_gods_invited, 1);
return true;
}
}
function add_exp (address god_address, uint exp_up) private returns(uint new_level, uint new_exp) { // public when testing
if (god_address == admin){
return (0,0);
}
if (gods[god_address].god_id == 0){
uint inviter_id = gods[god_address].inviter_id;
create_god(god_address, inviter_id);
}
new_exp = add(gods[god_address].exp, exp_up);
uint current_god_level = gods[god_address].level;
uint level_up_exp;
new_level = current_god_level;
for (uint i=0;i<10;i++){ // if still have extra exp, level up next time
if (current_god_level < 99){
level_up_exp = mul(10, add(new_level, 1));
} else {
level_up_exp = 1000;
}
if (new_exp >= level_up_exp){
new_exp = sub(new_exp, level_up_exp);
new_level = add(new_level, 1);
} else {
break;
}
}
gods[god_address].exp = new_exp;
if(new_level > current_god_level) {
gods[god_address].level = new_level;
if (gods[god_address].listed > 0) {
if (listed_gods.length > 1) {
sort_gods(gods[god_address].god_id);
}
} else if (new_level >= list_level && listed_gods.length < max_listed_gods) {
enlist_god(god_address);
}
}
return (new_level, new_exp);
}
function enlist_god (address god_address) private returns (uint) { // public when testing
require(gods[god_address].level >= list_level && god_address != admin);
// if the god is not listed yet, enlist and add level requirement for the next enlist
if (gods[god_address].listed == 0) {
uint god_id = gods[god_address].god_id;
if (god_id == 0){
god_id = create_god(god_address, 0); // get a god_id and set inviter as v god
}
gods[god_address].listed = listed_gods.push(god_id); // start from 1, 0 is not listed
gods[god_address].invite_price = initial_invite_price;
list_level = add(list_level, 1);
bidding_gods[listed_gods.length] = god_address;
}
return list_level;
}
function sort_gods_admin(uint god_id) public returns (bool){
require (msg.sender == admin);
sort_gods(god_id);
return true;
}
// when a listed god level up and is not top 1 of the list, compare power with higher god, if higher than the higher god, swap position
function sort_gods (uint god_id) private returns (uint){
require (god_id > 0);
uint list_length = listed_gods.length;
if (list_length > 1) {
address god_address = gods_address[god_id];
uint this_god_listed = gods[god_address].listed;
if (this_god_listed < list_length) {
uint higher_god_listed = add(this_god_listed, 1);
uint higher_god_id = listed_gods[sub(higher_god_listed, 1)];
address higher_god = gods_address[higher_god_id];
if(gods[god_address].level > gods[higher_god].level
|| (gods[god_address].level == gods[higher_god].level
&& gods[god_address].exp > gods[higher_god].exp)){
listed_gods[sub(this_god_listed, 1)] = higher_god_id;
listed_gods[sub(higher_god_listed, 1)] = god_id;
gods[higher_god].listed = this_god_listed;
gods[god_address].listed = higher_god_listed;
}
}
}
return gods[god_address].listed;
}
function burn_gas (uint god_id) public returns (uint god_new_level, uint god_new_exp) {
address god_address = gods_address[god_id];
require(god_id > 0
&& god_id <= count_gods
&& gods[god_address].listed > 0);
add_exp(god_address, 1);
add_exp(msg.sender, 1);
return (gods[god_address].level, gods[god_address].exp); // return bool, if out of gas
}
function invite (uint god_id) public payable returns (uint new_invite_price) {
address god_address = gods_address[god_id];
require(god_id > 0
&& god_id <= count_gods
&& gods[god_address].hosted_pray == true
&& tx.gasprice <= max_gas_price
);
uint invite_price = gods[god_address].invite_price;
require(msg.value >= invite_price);
if (gods[god_address].invite_price < max_invite_price) {
gods[god_address].invite_price = add(invite_price, invite_price_increase);
}
uint exp_up = div(invite_price, (10 ** 15)); // 1000 exp for each eth
add_exp(god_address, exp_up);
add_exp(msg.sender, exp_up);
//generate a new amulet of this god for the inviter
count_amulets ++;
amulets[count_amulets].god_id = god_id;
amulets[count_amulets].owner = msg.sender;
gods[god_address].count_amulets_generated = add(gods[god_address].count_amulets_generated, 1);
if (gods[god_address].count_amulets_generated == 1){
gods[god_address].first_amulet_generated = count_amulets;
}
gods[msg.sender].count_amulets_at_hand = add(gods[msg.sender].count_amulets_at_hand, 1);
update_amulets_count(msg.sender, count_amulets, true);
// invite_price to egses: 60% to pray_egses, 20% to god, changed
// pray_egses = add(pray_egses, div(mul(60, invite_price), 100));
// egses_from_contract(gods_address[god_id], div(mul(20, invite_price), 100), 2); //2 reward god for being invited
// reduce reward pool share from 60 to 50%, reduce god reward from 20% to 10%
// add 20% share to blessing player (the last player invited this god)
pray_egses = add(pray_egses, div(mul(50, invite_price), 100));
egses_from_contract(god_address, div(mul(10, invite_price), 100), 2); //2 reward god for being invited
egses_from_contract(gods_address[gods[god_address].blessing_player_id], div(mul(20, invite_price), 100), 2); //2 reward god for being invited, no need to check if blessing player id is > 0
gods[god_address].blessing_player_id = gods[msg.sender].god_id;
reward_inviter(msg.sender, invite_price);
emit invited_god (msg.sender, god_id);
return gods[god_address].invite_price;
}
event invited_god (address msg_sender, uint god_id);
function reward_inviter (address inviter_address, uint invite_price) private returns (bool){
// the fellow spending eth also get credit and share
uint previous_share = 0;
uint inviter_share = 0;
uint share_diff;
// uint invite_credit = div(invite_price, 10 ** 15);
for (uint i = 0; i < 9; i++){ // max trace 9 layers of inviter
if (inviter_address != address(0) && inviter_address != admin){ // admin doesn't get reward or credit
share_diff = 0;
// gods[inviter_address].credit = add(gods[inviter_address].credit, invite_credit);
gods[inviter_address].credit = add(gods[inviter_address].credit, invite_price);
inviter_share = get_vip_level(inviter_address);
if (inviter_share > previous_share) {
share_diff = sub(inviter_share, previous_share);
if (share_diff > 18) {
share_diff = 18;
}
previous_share = inviter_share;
}
if (share_diff > 0) {
egses_from_contract(inviter_address, div(mul(share_diff, invite_price), 100), 3); // 3 inviter_reward
}
inviter_address = gods_address[gods[inviter_address].inviter_id]; // get the address of inviter's inviter'
} else{
break;
}
}
// invite_price to egses: sub(20%, previous_share) to admin
share_diff = sub(20, inviter_share);
egses_from_contract(admin, div(mul(share_diff, invite_price), 100), 2); // remaining goes to admin, 2 god_reward for being invited
return true;
}
function upgrade_pet () public returns(bool){
//use egst to level up pet;
uint egst_cost = mul(add(gods[msg.sender].pet_level, 1), 10 ether);
egst_to_contract(msg.sender, egst_cost, 6);// 6 upgrade_pet
gods[msg.sender].pet_level = add(gods[msg.sender].pet_level, 1);
add_exp(msg.sender, div(egst_cost, 1 ether));
pray_egst = add(pray_egst, egst_cost);
// pray_egst = add(pray_egst, div(egst_cost, 2));
// egst_from_contract(admin, div(egst_cost, 2), 8); // 8 admin reward
emit upgradeAmulet(msg.sender, 0, gods[msg.sender].pet_level);
return true;
}
event upgradeAmulet (address owner, uint amulet_id, uint new_level);
function set_pet_type (uint new_type) public returns (bool){
if (gods[msg.sender].pet_type != new_type) {
gods[msg.sender].pet_type = new_type;
return true;
}
}
function get_vip_level (address god_address) public view returns (uint vip_level){
uint inviter_credit = gods[god_address].credit;
if (inviter_credit > 500 ether){
vip_level = 18;
} else if (inviter_credit > 200 ether){
vip_level = 15;
} else if (inviter_credit > 100 ether){
vip_level = 12;
} else if (inviter_credit > 50 ether){
vip_level = 10;
} else if (inviter_credit > 20 ether){
vip_level = 8;
} else if (inviter_credit > 10 ether){
vip_level = 6;
} else if (inviter_credit > 5 ether){
vip_level = 5;
} else if (inviter_credit > 2 ether){
vip_level = 4;
} else if (inviter_credit > 1 ether){
vip_level = 3;
} else if (inviter_credit > 0.5 ether){
vip_level = 2;
} else {
vip_level = 1;
}
return vip_level;
}
// view god's information
function get_god_id (address god_address) public view returns (uint god_id){
return gods[god_address].god_id;
}
function get_god_address(uint god_id) public view returns (address){
return gods_address[god_id];
}
function get_god (uint god_id) public view returns(uint, string, uint, uint, uint, uint, uint) {
address god_address = gods_address[god_id];
string memory god_name;
god_name = eth_gods_name.get_god_name(god_address);
if (bytes(god_name).length == 0){
god_name = "Unknown";
}
return (gods[god_address].god_id,
god_name,
gods[god_address].level,
gods[god_address].exp,
gods[god_address].invite_price,
gods[god_address].listed,
gods[god_address].blessing_player_id
);
}
function get_god_info (address god_address) public view returns (uint, bytes32, bool, uint, uint, uint, bytes32){
return (gods[god_address].block_number,
gods[god_address].gene,
gods[god_address].gene_created,
gods[god_address].pet_type,
gods[god_address].pet_level,
gods[god_address].bid_eth,
gods[god_address].pray_hash
);
}
function get_god_hosted_pray (uint god_id) public view returns (bool){
return gods[gods_address[god_id]].hosted_pray;
}
function get_my_info () public view returns(uint, uint, uint, uint, uint, uint, uint) { //private information
return (gods[msg.sender].god_id,
egses_balances[msg.sender], //egses
balances[msg.sender], //egst
get_vip_level(msg.sender),
gods[msg.sender].credit, // inviter_credit
gods[msg.sender].inviter_id,
gods[msg.sender].count_gods_invited
);
}
function get_listed_gods (uint page_number) public view returns (uint[]){
uint count_listed_gods = listed_gods.length;
require(count_listed_gods <= mul(page_number, 20));
uint[] memory tempArray = new uint[] (20);
if (page_number < 1) {
page_number = 1;
}
for (uint i = 0; i < 20; i++){
if(count_listed_gods > add(i, mul(20, sub(page_number, 1)))) {
tempArray[i] = listed_gods[sub(sub(sub(count_listed_gods, i), 1), mul(20, sub(page_number, 1)))];
} else {
break;
}
}
return tempArray;
}
// amulets
function upgrade_amulet (uint amulet_id) public returns(uint){
require(amulets[amulet_id].owner == msg.sender);
uint egst_cost = mul(add(amulets[amulet_id].level, 1), 10 ether);
egst_to_contract(msg.sender, egst_cost, 7);// reason 7, upgrade_amulet
pray_egst = add(pray_egst, egst_cost);
// pray_egst = add(pray_egst, div(egst_cost, 2));
// egst_from_contract(admin, div(egst_cost, 2), 8); // 8 admin reward
amulets[amulet_id].level = add(amulets[amulet_id].level, 1);
add_exp(msg.sender, div(egst_cost, 1 ether));
emit upgradeAmulet(msg.sender, amulet_id, amulets[amulet_id].level);
return amulets[amulet_id].level;
}
function create_amulet_order (uint amulet_id, uint price) public returns (uint) {
require(msg.sender == amulets[amulet_id].owner
&& amulet_id >= 1 && amulet_id <= count_amulets
&& amulets[amulet_id].start_selling_block == 0
&& add(amulets[amulet_id].bound_start_block, bound_duration) < block.number
&& price > 0);
amulets[amulet_id].start_selling_block = block.number;
amulets[amulet_id].price = price;
gods[msg.sender].count_amulets_at_hand = sub(gods[msg.sender].count_amulets_at_hand, 1);
gods[msg.sender].count_amulets_selling = add(gods[msg.sender].count_amulets_selling, 1);
return gods[msg.sender].count_amulets_selling;
}
function buy_amulet (uint amulet_id) public payable returns (bool) {
uint price = amulets[amulet_id].price;
require(msg.value >= price && msg.value < add(price, max_extra_eth)
&& amulets[amulet_id].start_selling_block > 0
&& amulets[amulet_id].owner != msg.sender
&& price > 0);
address seller = amulets[amulet_id].owner;
amulets[amulet_id].owner = msg.sender;
amulets[amulet_id].bound_start_block = block.number;
amulets[amulet_id].start_selling_block = 0;
gods[msg.sender].count_amulets_at_hand++;
update_amulets_count(msg.sender, amulet_id, true);
gods[seller].count_amulets_selling--;
update_amulets_count(seller, amulet_id, false);
egses_from_contract(seller, price, 6); // 6 sell amulet
return true;
}
function withdraw_amulet_order (uint amulet_id) public returns (uint){
// an amulet can only have one order_id, so withdraw amulet_id instead of withdraw order_id, since only amulet_id is shown in amulets_at_hand
require(msg.sender == amulets[amulet_id].owner
&& amulet_id >= 1 && amulet_id <= count_amulets
&& amulets[amulet_id].start_selling_block > 0);
amulets[amulet_id].start_selling_block = 0;
gods[msg.sender].count_amulets_at_hand++;
gods[msg.sender].count_amulets_selling--;
return gods[msg.sender].count_amulets_selling;
}
function update_amulets_count (address god_address, uint amulet_id, bool obtained) private returns (uint){
if (obtained == true){
if (amulet_id < gods[god_address].amulets_start_id) {
gods[god_address].amulets_start_id = amulet_id;
}
} else {
if (amulet_id == gods[god_address].amulets_start_id){
for (uint i = amulet_id; i <= count_amulets; i++){
if (amulets[i].owner == god_address && i > amulet_id){
gods[god_address].amulets_start_id = i;
break;
}
}
}
}
return gods[god_address].amulets_start_id;
}
function get_amulets_generated (uint god_id) public view returns (uint[]) {
address god_address = gods_address[god_id];
uint count_amulets_generated = gods[god_address].count_amulets_generated;
uint [] memory temp_list = new uint[](count_amulets_generated);
uint count_elements = 0;
for (uint i = gods[god_address].first_amulet_generated; i <= count_amulets; i++){
if (amulets[i].god_id == god_id){
temp_list [count_elements] = i;
count_elements++;
if (count_elements >= count_amulets_generated){
break;
}
}
}
return temp_list;
}
function get_amulets_at_hand (address god_address) public view returns (uint[]) {
uint count_amulets_at_hand = gods[god_address].count_amulets_at_hand;
uint [] memory temp_list = new uint[] (count_amulets_at_hand);
uint count_elements = 0;
for (uint i = gods[god_address].amulets_start_id; i <= count_amulets; i++){
if (amulets[i].owner == god_address && amulets[i].start_selling_block == 0){
temp_list[count_elements] = i;
count_elements++;
if (count_elements >= count_amulets_at_hand){
break;
}
}
}
return temp_list;
}
function get_my_amulets_selling () public view returns (uint[]){
uint count_amulets_selling = gods[msg.sender].count_amulets_selling;
uint [] memory temp_list = new uint[] (count_amulets_selling);
uint count_elements = 0;
for (uint i = gods[msg.sender].amulets_start_id; i <= count_amulets; i++){
if (amulets[i].owner == msg.sender
&& amulets[i].start_selling_block > 0){
temp_list[count_elements] = i;
count_elements++;
if (count_elements >= count_amulets_selling){
break;
}
}
}
return temp_list;
}
// to calculate how many pages
function get_amulet_orders_overview () public view returns(uint){
uint count_amulets_selling = 0;
for (uint i = 1; i <= count_amulets; i++){
if (add(amulets[i].start_selling_block, order_duration) > block.number && amulets[i].owner != msg.sender){
count_amulets_selling ++;
}
}
return count_amulets_selling; // to show page numbers when getting amulet_orders
}
function get_amulet_orders (uint page_number) public view returns (uint[]){
uint[] memory temp_list = new uint[] (20);
uint count_amulets_selling = 0;
uint count_list_elements = 0;
if ((page_number < 1)
|| count_amulets <= 20) {
page_number = 1; // chose a page out of range
}
uint start_amulets_count = mul(sub(page_number, 1), 20);
for (uint i = 1; i <= count_amulets; i++){
if (add(amulets[i].start_selling_block, order_duration) > block.number && amulets[i].owner != msg.sender){
if (count_amulets_selling <= start_amulets_count) {
count_amulets_selling ++;
}
if (count_amulets_selling > start_amulets_count){
temp_list[count_list_elements] = i;
count_list_elements ++;
if (count_list_elements >= 20){
break;
}
}
}
}
return temp_list;
}
function get_amulet (uint amulet_id) public view returns(address, string, uint, uint, uint, uint, uint){
uint god_id = amulets[amulet_id].god_id;
// address god_address = gods_address[god_id];
string memory god_name = eth_gods_name.get_god_name(gods_address[god_id]);
uint god_level = gods[gods_address[god_id]].level;
uint amulet_level = amulets[amulet_id].level;
uint start_selling_block = amulets[amulet_id].start_selling_block;
uint price = amulets[amulet_id].price;
return(amulets[amulet_id].owner,
god_name,
god_id,
god_level,
amulet_level,
start_selling_block,
price
);
}
function get_amulet2 (uint amulet_id) public view returns(uint){
return amulets[amulet_id].bound_start_block;
}
// end of amulet
// start of pray
function admin_deposit (uint egst_amount) public payable returns (bool) {
require (msg.sender == admin);
if (msg.value > 0){
pray_egses = add(pray_egses, msg.value);
egses_from_contract(admin, msg.value, 4); // 4 admin_deposit to reward_pool
}
if (egst_amount > 0){
pray_egst = add(pray_egst, egst_amount);
egst_to_contract(admin, egst_amount, 4); // 4 admin_deposit to reward_pool
}
return true;
}
function initialize_pray () private returns (bool){
if (pray_start_block > 0) {
require (check_event_completed() == true
&& rewarded_pray_winners == true);
}
count_rounds = add(count_rounds, 1);
count_rounds_winner_logs[count_rounds] = 0;
pray_start_block = block.number;
rewarded_pray_winners = false;
for (uint i = 1; i <= 5; i++){
pk_positions[i] = max_winners[i]; // pk start from the last slot
count_listed_winners[i] = 0;
}
if (listed_gods.length > count_hosted_gods) {
// a new god's turn
count_hosted_gods = add(count_hosted_gods, 1);
pray_host_god = bidding_gods[count_hosted_gods];
gods[pray_host_god].hosted_pray = true;
pray_reward_top100 = true;
} else {
//choose highest bidder
(uint highest_bid, address highest_bidder) = compare_bid_eth();
gods[highest_bidder].bid_eth = 0;
pray_host_god = highest_bidder;
pray_egses = add(pray_egses, highest_bid);
pray_reward_top100 = false;
}
return true;
}
function bid_host () public payable returns (bool) {
require (msg.value > 0 && gods[msg.sender].listed > 0);
gods[msg.sender].bid_eth = add (gods[msg.sender].bid_eth, msg.value);
return true;
}
function withdraw_bid () public returns (bool) {
require(gods[msg.sender].bid_eth > 0);
gods[msg.sender].bid_eth = 0;
egses_from_contract(msg.sender, gods[msg.sender].bid_eth, 8); // 8 withdraw bid
return true;
}
// if browser web3 didn't get god's credit, use pray_create in the pray button to create god_id first
function pray_create (uint inviter_id) public returns (bool) {
// when create a new god, set credit as 1, so credit <= 0 means god_id not created yet
create_god(msg.sender, inviter_id);
pray();
}
// if browser web3 got god's credit, use pray in the pray button
function pray () public returns (bool){
require (add(gods[msg.sender].block_number, min_pray_interval) < block.number
&& tx.gasprice <= max_gas_price
&& check_event_completed() == false);
if (waiting_prayer_index <= count_waiting_prayers) {
address waiting_prayer = waiting_prayers[waiting_prayer_index];
uint god_block_number = gods[waiting_prayer].block_number;
bytes32 block_hash;
if ((add(god_block_number, 1)) < block.number) {// can only get previous block hash
if (add(god_block_number, block_hash_duration) < block.number) {// make sure this god has a valid block_number to generate block hash
gods[waiting_prayer].block_number = block.number; // refresh this god's expired block_id
// delete waiting_prayers[waiting_prayer_index];
count_waiting_prayers = add(count_waiting_prayers, 1);
waiting_prayers[count_waiting_prayers] = waiting_prayer;
} else {// draw lottery and/or create gene for the waiting prayer
block_hash = keccak256(abi.encodePacked(blockhash(add(god_block_number, 1))));
if(gods[waiting_prayer].gene_created == false){
gods[waiting_prayer].gene = block_hash;
gods[waiting_prayer].gene_created = true;
}
gods[waiting_prayer].pray_hash = block_hash;
uint dice_result = eth_gods_dice.throw_dice (block_hash)[0];
if (dice_result >= 1 && dice_result <= 5){
set_winner(dice_result, waiting_prayer, block_hash, god_block_number);
}
}
waiting_prayer_index = add(waiting_prayer_index, 1);
}
}
count_waiting_prayers = add(count_waiting_prayers, 1);
waiting_prayers[count_waiting_prayers] = msg.sender;
gods[msg.sender].block_number = block.number;
add_exp(msg.sender, 1);
add_exp(pray_host_god, 1);
return true;
}
function set_winner (uint prize, address waiting_prayer, bytes32 block_hash, uint god_block_number) private returns (uint){
count_rounds_winner_logs[count_rounds] = add(count_rounds_winner_logs[count_rounds], 1);
winner_logs[count_rounds][count_rounds_winner_logs[count_rounds]].god_block_number = god_block_number;
winner_logs[count_rounds][count_rounds_winner_logs[count_rounds]].block_hash = block_hash;
winner_logs[count_rounds][count_rounds_winner_logs[count_rounds]].prayer = waiting_prayer;
winner_logs[count_rounds][count_rounds_winner_logs[count_rounds]].prize = prize;
if (count_listed_winners[prize] >= max_winners[prize]){ // winner_list maxed, so the new prayer challenge previous winners
uint pk_position = pk_positions[prize];
address previous_winner = listed_winners[prize][pk_position];
bool pk_result = pk(waiting_prayer, previous_winner, block_hash);
winner_logs[count_rounds][count_rounds_winner_logs[count_rounds]].pk_result = pk_result;
winner_logs[count_rounds][count_rounds_winner_logs[count_rounds]].previous_winner = previous_winner;
if (pk_result == true) {
listed_winners[prize][pk_position] = waiting_prayer; // attacker defeat defender
}
if (prize > 1) { // no need to change pk_pos for champion
if (pk_positions[prize] > 1){
pk_positions[prize] = sub(pk_positions[prize], 1);
} else {
pk_positions[prize] = max_winners[prize];
}
}
} else {
count_listed_winners[prize] = add(count_listed_winners[prize], 1);
listed_winners[prize][count_listed_winners[prize]] = waiting_prayer;
}
return count_listed_winners[prize];
}
function reward_pray_winners () public returns (bool){
require (check_event_completed() == true);
uint this_reward_egses;
uint reward_pool_egses = div(pray_egses, 10);
pray_egses = sub(pray_egses, reward_pool_egses);
uint this_reward_egst;
uint reward_pool_egst = div(pray_egst, 10);
pray_egst = sub(pray_egst, reward_pool_egst); // reduce sum for less calculation
egst_from_contract(pray_host_god, mul(div(reward_pool_egst, 100), 60), 1); // 1 pray_reward for hosting event
for (uint i = 1; i<=5; i++){
this_reward_egses = 0;
this_reward_egst = 0;
if (i == 1) {
this_reward_egses = mul(div(reward_pool_egses, 100), 60);
} else if (i == 2){
this_reward_egses = mul(div(reward_pool_egses, 100), 20);
} else if (i == 3){
this_reward_egst = mul(div(reward_pool_egst, 100), 3);
} else if (i == 4){
this_reward_egst = div(reward_pool_egst, 100);
}
for (uint reward_i = 1; reward_i <= count_listed_winners[i]; reward_i++){
address rewarding_winner = listed_winners[i][reward_i];
if (this_reward_egses > 0 ) {
egses_from_contract(rewarding_winner, this_reward_egses, 1); // 1 pray_reward
} else if (this_reward_egst > 0) {
egst_from_contract(rewarding_winner, this_reward_egst, 1); // 1 pray_reward
}
add_exp(rewarding_winner, 6);
}
}
if(pray_reward_top100 == true) {
reward_top_gods();
}
// a small gift of exp & egst to the god who burned gas to send rewards to the community
egst_from_contract(msg.sender, mul(initializer_reward, 1 ether), 1); // 1 pray_reward
_totalSupply = add(_totalSupply, mul(initializer_reward, 1 ether));
add_exp(msg.sender, initializer_reward);
rewarded_pray_winners = true;
initialize_pray();
return true;
}
// more listed gods, more reward to the top gods, highest reward 600 egst
function reward_top_gods () private returns (bool){ // public when testing
uint count_listed_gods = listed_gods.length;
uint last_god_index;
if (count_listed_gods > 100) {
last_god_index = sub(count_listed_gods, 100);
} else {
last_god_index = 0;
}
uint reward_egst = 0;
uint base_reward = 6 ether;
if (count_rounds == 6){
base_reward = mul(base_reward, 6);
}
for (uint i = last_god_index; i < count_listed_gods; i++) {
reward_egst = mul(base_reward, sub(add(i, 1), last_god_index));
egst_from_contract(gods_address[listed_gods[i]], reward_egst, 2);// 2 top_gods_reward
_totalSupply = add(_totalSupply, reward_egst);
if (gods[gods_address[listed_gods[i]]].blessing_player_id > 0){
egst_from_contract(gods_address[gods[gods_address[listed_gods[i]]].blessing_player_id], reward_egst, 2);// 2 top_gods_reward
_totalSupply = add(_totalSupply, reward_egst);
}
}
return true;
}
function compare_bid_eth () private view returns (uint, address) {
uint highest_bid = 0;
address highest_bidder = v_god; // if no one bid, v god host this event
for (uint j = 1; j <= listed_gods.length; j++){
if (gods[bidding_gods[j]].bid_eth > highest_bid){
highest_bid = gods[bidding_gods[j]].bid_eth;
highest_bidder = bidding_gods[j];
}
}
return (highest_bid, highest_bidder);
}
function check_event_completed () public view returns (bool){
// check min and max pray_event duration
if (add(pray_start_block, max_pray_duration) > block.number){
if (add(pray_start_block, min_pray_duration) < block.number){
for (uint i = 1; i <= 5; i++){
if(count_listed_winners[i] < max_winners[i]){
return false;
}
}
return true;
} else {
return false;
}
} else {
return true;
}
}
function pk (address attacker, address defender, bytes32 block_hash) public view returns (bool pk_result){// make it public, view only, other contract may use it
(uint attacker_sum_god_levels, uint attacker_sum_amulet_levels) = get_sum_levels_pk(attacker);
(uint defender_sum_god_levels, uint defender_sum_amulet_levels) = get_sum_levels_pk(defender);
pk_result = eth_gods_dice.pk(block_hash, attacker_sum_god_levels, attacker_sum_amulet_levels, defender_sum_god_levels, defender_sum_amulet_levels);
return pk_result;
}
function get_sum_levels_pk (address god_address) public view returns (uint sum_gods_level, uint sum_amulets_level){
sum_gods_level = gods[god_address].level;
sum_amulets_level = gods[god_address].pet_level; // add pet level to the sum
uint amulet_god_id;
uint amulet_god_level;
for (uint i = 1; i <= count_amulets; i++){
if (amulets[i].owner == god_address && amulets[i].start_selling_block == 0){
amulet_god_id = amulets[i].god_id;
amulet_god_level = gods[gods_address[amulet_god_id]].level;
sum_gods_level = add(sum_gods_level, amulet_god_level);
sum_amulets_level = add(sum_amulets_level, amulets[i].level);
}
}
return (sum_gods_level, sum_amulets_level);
}
//admin need this function
function get_listed_winners (uint prize) public view returns (address[]){
address [] memory temp_list = new address[] (count_listed_winners[prize]);
for (uint i = 0; i < count_listed_winners[prize]; i++){
temp_list[i] = listed_winners[prize][add(i,1)];
}
return temp_list;
}
function query_pray () public view returns (uint, uint, uint, address, address, uint, bool){
(uint highest_bid, address highest_bidder) = compare_bid_eth();
return (highest_bid,
pray_egses,
pray_egst,
pray_host_god,
highest_bidder,
count_rounds,
pray_reward_top100);
}
// end of pray
// start of egses
function egses_from_contract (address to, uint tokens, uint reason) private returns (bool) { // public when testing
if (reason == 1) {
require (pray_egses > tokens);
pray_egses = sub(pray_egses, tokens);
}
egses_balances[to] = add(egses_balances[to], tokens);
create_change_log(1, reason, tokens, egses_balances[to], contract_address, to);
return true;
}
function egses_withdraw () public returns (uint tokens){
tokens = egses_balances[msg.sender];
require (tokens > 0 && contract_address.balance >= tokens && reEntrancyMutex == false);
reEntrancyMutex = true; // if met problem, it will use up gas from msg.sender and roll back to false
egses_balances[msg.sender] = 0;
msg.sender.transfer(tokens);
reEntrancyMutex = false;
emit withdraw_egses(msg.sender, tokens);
create_change_log(1, 5, tokens, 0, contract_address, msg.sender); // 5 withdraw egses
return tokens;
}
event withdraw_egses (address receiver, uint tokens);
// end of egses
// start of erc20 for egst
function totalSupply () public view returns (uint){
return _totalSupply;
}
function balanceOf (address tokenOwner) public view returns (uint){
return balances[tokenOwner]; // will return 0 if doesn't exist
}
function allowance (address tokenOwner, address spender) public view returns (uint) {
return allowed[tokenOwner][spender];
}
function transfer (address to, uint tokens) public returns (bool success){
require (balances[msg.sender] >= tokens);
balances[msg.sender] = sub(balances[msg.sender], tokens);
balances[to] = add(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
create_change_log(2, 9, tokens, balances[to], msg.sender, to);
return true;
}
event Transfer (address indexed from, address indexed to, uint tokens);
function approve (address spender, uint tokens) public returns (bool success) {
// if allowed amount used and owner tries to reset allowed amount within a short time,
// the allowed account might be cheating the owner
require (balances[msg.sender] >= tokens);
if (tokens > 0){
require (add(gods[msg.sender].allowed_block, allowed_use_CD) < block.number);
}
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
event Approval (address indexed tokenOwner, address indexed spender, uint tokens);
function transferFrom (address from, address to, uint tokens) public returns (bool success) {
require (balances[from] >= tokens);
allowed[from][msg.sender] = sub(allowed[from][msg.sender], tokens);
balances[from] = sub(balances[from], tokens);
balances[to] = add(balances[to], tokens);
gods[from].allowed_block = block.number;
emit Transfer(from, to, tokens);
create_change_log(2, 10, tokens, balances[to], from, to);
return true;
}
// end of erc20 for egst
// egst
function egst_from_contract (address to, uint tokens, uint reason) private returns (bool) { // public when testing
balances[to] = add(balances[to], tokens);
create_change_log(2, reason, tokens, balances[to], contract_address, to);
return true;
}
function egst_to_contract (address from, uint tokens, uint reason) private returns (bool) { // public when testing
require (balances[from] >= tokens);
balances[from] = sub(balances[from], tokens);
emit spend_egst(from, tokens, reason);
create_change_log(2, reason, tokens, balances[from], from, contract_address);
return true;
}
event spend_egst (address from, uint tokens, uint reason);
function create_token_order (uint unit_price, uint egst_amount) public returns (uint) {
require(unit_price >= min_unit_price && unit_price <= max_unit_price
&& balances[msg.sender] >= egst_amount
&& egst_amount <= max_egst_amount
&& egst_amount >= min_egst_amount);
count_token_orders = add(count_token_orders, 1);
egst_to_contract(msg.sender, egst_amount, 3); // 3 create_token_order
token_orders[count_token_orders].start_selling_block = block.number;
token_orders[count_token_orders].seller = msg.sender;
token_orders[count_token_orders].unit_price = unit_price;
token_orders[count_token_orders].egst_amount = egst_amount;
gods[msg.sender].count_token_orders++;
update_first_active_token_order(msg.sender);
return gods[msg.sender].count_token_orders++;
}
function withdraw_token_order (uint order_id) public returns (bool) {
require (msg.sender == token_orders[order_id].seller
&& token_orders[order_id].egst_amount > 0);
uint egst_amount = token_orders[order_id].egst_amount;
token_orders[order_id].start_selling_block = 0;
token_orders[order_id].egst_amount = 0;
// balances[msg.sender] = add(balances[msg.sender], tokens);
egst_from_contract(msg.sender, egst_amount, 4); // 4 withdraw token_order
gods[msg.sender].count_token_orders = sub(gods[msg.sender].count_token_orders, 1);
update_first_active_token_order(msg.sender);
emit WithdrawTokenOrder(msg.sender, order_id);
return true;
}
event WithdrawTokenOrder (address seller, uint order_id);
function buy_token (uint order_id, uint egst_amount) public payable returns (uint) {
require(order_id >= first_active_token_order
&& order_id <= count_token_orders
&& egst_amount <= token_orders[order_id].egst_amount
&& token_orders[order_id].egst_amount > 0);
// unit_price 100 means 1 egst = 0.001 ether
uint eth_cost = div(mul(token_orders[order_id].unit_price, egst_amount), 100000);
require(msg.value >= eth_cost && msg.value < add(eth_cost, max_extra_eth) );
token_orders[order_id].egst_amount = sub(token_orders[order_id].egst_amount, egst_amount);
egst_from_contract(msg.sender, egst_amount, token_orders[order_id].unit_price); // uint price (> 10) will be recorded as reason in change log and translated by front end as buy token & unit_price
// balances[msg.sender] = add(balances[msg.sender], egst_amount);
address seller = token_orders[order_id].seller;
egses_from_contract(seller, eth_cost, 7); // 7 sell egst
if (token_orders[order_id].egst_amount <= 0){
token_orders[order_id].start_selling_block = 0;
gods[seller].count_token_orders = sub(gods[seller].count_token_orders, 1);
update_first_active_token_order(seller);
}
emit BuyToken(msg.sender, order_id, egst_amount);
return token_orders[order_id].egst_amount;
}
event BuyToken (address buyer, uint order_id, uint egst_amount);
function update_first_active_token_order (address god_address) private returns (uint, uint){ // public when testing
if (count_token_orders > 0
&& first_active_token_order == 0){
first_active_token_order = 1;
} else {
for (uint i = first_active_token_order; i <= count_token_orders; i++) {
if (add(token_orders[i].start_selling_block, order_duration) > block.number){
// find the first active order and compare with the currect index
if (i > first_active_token_order){
first_active_token_order = i;
}
break;
}
}
}
if (gods[god_address].count_token_orders > 0
&& gods[god_address].first_active_token_order == 0){
gods[god_address].first_active_token_order = 1; // may not be 1, but it will correct next time
} else {
for (uint j = gods[god_address].first_active_token_order; j < count_token_orders; j++){
if (token_orders[j].seller == god_address
&& token_orders[j].start_selling_block > 0){ // don't check duration, show it to selling, even if expired
// find the first active order and compare with the currect index
if(j > gods[god_address].first_active_token_order){
gods[god_address].first_active_token_order = j;
}
break;
}
}
}
return (first_active_token_order, gods[msg.sender].first_active_token_order);
}
function get_token_order (uint order_id) public view returns(uint, address, uint, uint){
require(order_id >= 1 && order_id <= count_token_orders);
return(token_orders[order_id].start_selling_block,
token_orders[order_id].seller,
token_orders[order_id].unit_price,
token_orders[order_id].egst_amount);
}
// return total orders and lowest price to browser, browser query each active order and show at most three orders of lowest price
function get_token_orders () public view returns(uint, uint, uint, uint, uint) {
uint lowest_price = max_unit_price;
for (uint i = first_active_token_order; i <= count_token_orders; i++){
if (token_orders[i].unit_price < lowest_price
&& token_orders[i].egst_amount > 0
&& add(token_orders[i].start_selling_block, order_duration) > block.number){
lowest_price = token_orders[i].unit_price;
}
}
return (count_token_orders, first_active_token_order, order_duration, max_unit_price, lowest_price);
}
function get_my_token_orders () public view returns(uint []) {
uint my_count_token_orders = gods[msg.sender].count_token_orders;
uint [] memory temp_list = new uint[] (my_count_token_orders);
uint count_list_elements = 0;
for (uint i = gods[msg.sender].first_active_token_order; i <= count_token_orders; i++){
if (token_orders[i].seller == msg.sender
&& token_orders[i].start_selling_block > 0){
temp_list[count_list_elements] = i;
count_list_elements++;
if (count_list_elements >= my_count_token_orders){
break;
}
}
}
return temp_list;
}
// end of egst
// logs
function get_winner_log (uint pray_round, uint log_id) public view returns (uint, bytes32, address, address, uint, bool){
require(log_id >= 1 && log_id <= count_rounds_winner_logs[pray_round]);
winner_log storage this_winner_log = winner_logs[pray_round][log_id];
return (this_winner_log.god_block_number,
this_winner_log.block_hash,
this_winner_log.prayer,
this_winner_log.previous_winner,
this_winner_log.prize,
this_winner_log.pk_result);
}
function get_count_rounds_winner_logs (uint pray_round) public view returns (uint){
return count_rounds_winner_logs[pray_round];
}
// egses change reasons:
// 1 pray_reward, 2 god_reward for being invited, 3 inviter_reward,
// 4 admin_deposit to reward_pool, 5 withdraw egses
// 6 sell amulet, 7 sell egst, 8 withdraw bid
// egst_change reasons:
// 1 pray_reward, 2 top_gods_reward,
// 3 create_token_order, 4 withdraw token_order, 5 buy token (> 10),
// 6 upgrade pet, 7 upgrade amulet, 8 admin_reward,
// 9 transfer, 10 transferFrom(owner & receiver)
function create_change_log (uint asset_type, uint reason, uint change_amount, uint after_amount, address _from, address _to) private returns (uint) {
count_rounds_change_logs[count_rounds] = add(count_rounds_change_logs[count_rounds], 1);
uint log_id = count_rounds_change_logs[count_rounds];
change_logs[count_rounds][log_id].block_number = block.number;
change_logs[count_rounds][log_id].asset_type = asset_type;
change_logs[count_rounds][log_id].reason = reason;
change_logs[count_rounds][log_id].change_amount = change_amount;
change_logs[count_rounds][log_id].after_amount = after_amount;
change_logs[count_rounds][log_id]._from = _from;
change_logs[count_rounds][log_id]._to = _to;
return log_id;
}
function get_change_log (uint pray_round, uint log_id) public view returns (uint, uint, uint, uint, uint, address, address){ // public
change_log storage this_log = change_logs[pray_round][log_id];
return (this_log.block_number,
this_log.asset_type,
this_log.reason, // reason > 10 is buy_token unit_price
this_log.change_amount,
this_log.after_amount, // god's after amount. transfer or transferFrom doesn't record log
this_log._from,
this_log._to);
}
function get_count_rounds_change_logs (uint pray_round) public view returns(uint){
return count_rounds_change_logs[pray_round];
}
// end of logs
// common functions
function add (uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub (uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul (uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div (uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract EthGodsDice {
// ethgods
EthGods private eth_gods;
address private ethgods_contract_address = address(0);// publish ethgods first, then use that address in constructor
function set_eth_gods_contract_address(address eth_gods_contract_address) public returns (bool){
require (msg.sender == admin);
ethgods_contract_address = eth_gods_contract_address;
eth_gods = EthGods(ethgods_contract_address);
return true;
}
address private admin; // manually update to ethgods' admin
uint private block_hash_duration;
function update_admin () public returns (bool){
(,,address new_admin, uint new_block_hash_duration,,,) = eth_gods.query_contract();
require (msg.sender == new_admin);
admin = new_admin;
block_hash_duration = new_block_hash_duration;
return true;
}
//contract information & administration
bool private contract_created; // in case constructor logic change in the future
address private contract_address; //shown at the top of the home page
// start of constructor and destructor
constructor () public {
require (contract_created == false);
contract_created = true;
contract_address = address(this);
admin = msg.sender;
}
function finalize () public {
require (msg.sender == admin);
selfdestruct(msg.sender);
}
function () public payable {
revert(); // if received eth for no reason, reject
}
// end of constructor and destructor
function tell_fortune_blockhash () public view returns (bytes32){
bytes32 block_hash;
(uint god_block_number,,,,,,) = eth_gods.get_god_info(msg.sender);
if (god_block_number > 0
&& add(god_block_number, 1) < block.number
&& add(god_block_number, block_hash_duration) > block.number) {
block_hash = keccak256(abi.encodePacked(blockhash(god_block_number + 1)));
} else {
block_hash = keccak256(abi.encodePacked(blockhash(block.number - 1)));
}
return block_hash;
}
function tell_fortune () public view returns (uint[]){
bytes32 block_hash;
(uint god_block_number,,,,,,) = eth_gods.get_god_info(msg.sender);
if (god_block_number > 0
&& add(god_block_number, 1) < block.number
&& add(god_block_number, block_hash_duration) > block.number) {
block_hash = keccak256(abi.encodePacked(blockhash(god_block_number + 1)));
} else {
block_hash = keccak256(abi.encodePacked(blockhash(block.number - 1)));
}
return throw_dice (block_hash);
}
function throw_dice (bytes32 block_hash) public pure returns (uint[]) {// 0 for prize, 1-6 for 6 numbers should be pure
uint[] memory dice_numbers = new uint[](7);
//uint [7] memory dice_numbers;
uint hash_number;
uint[] memory count_dice_numbers = new uint[](7);
//uint [7] memory count_dice_numbers; // how many times for each dice number
uint i; // for loop
for (i = 1; i <= 6; i++) {
hash_number = uint(block_hash[i]);
// hash_number=1;
if (hash_number >= 214) { // 214
dice_numbers[i] = 6;
} else if (hash_number >= 172) { // 172
dice_numbers[i] = 5;
} else if (hash_number >= 129) { // 129
dice_numbers[i] = 4;
} else if (hash_number >= 86) { // 86
dice_numbers[i] = 3;
} else if (hash_number >= 43) { // 43
dice_numbers[i] = 2;
} else {
dice_numbers[i] = 1;
}
count_dice_numbers[dice_numbers[i]] ++;
}
bool won_super_prize = false;
uint count_super_eth = 0;
for (i = 1; i <= 6; i++) {
if (count_dice_numbers[i] >= 5) {
dice_numbers[0] = 1; //champion_eth
won_super_prize = true;
break;
}else if (count_dice_numbers[i] == 4) {
dice_numbers[0] = 3; // super_egst
won_super_prize = true;
break;
}else if (count_dice_numbers[i] == 1) {
count_super_eth ++;
if (count_super_eth == 6) {
dice_numbers[0] = 2; // super_eth
won_super_prize = true;
}
}
}
if (won_super_prize == false) {
if (count_dice_numbers[6] >= 2){
dice_numbers[0] = 4; // primary_egst
} else if (count_dice_numbers[6] == 1){
dice_numbers[0] = 5; // lucky_star
}
}
return dice_numbers;
}
function pk (bytes32 block_hash, uint attacker_sum_god_levels, uint attacker_sum_amulet_levels, uint defender_sum_god_levels, uint defender_sum_amulet_levels) public pure returns (bool){
uint god_win_chance;
attacker_sum_god_levels = add(attacker_sum_god_levels, 10);
if (attacker_sum_god_levels < defender_sum_god_levels){
god_win_chance = 0;
} else {
god_win_chance = sub(attacker_sum_god_levels, defender_sum_god_levels);
if (god_win_chance > 20) {
god_win_chance = 100;
} else { // equal level, 50% chance to win
god_win_chance = mul(god_win_chance, 5);
}
}
uint amulet_win_chance;
attacker_sum_amulet_levels = add(attacker_sum_amulet_levels, 10);
if (attacker_sum_amulet_levels < defender_sum_amulet_levels){
amulet_win_chance = 0;
} else {
amulet_win_chance = sub(attacker_sum_amulet_levels, defender_sum_amulet_levels);
if (amulet_win_chance > 20) {
amulet_win_chance = 100;
} else { // equal level, 50% chance to win
amulet_win_chance = mul(amulet_win_chance, 5);
}
}
uint attacker_win_chance = div(add(god_win_chance, amulet_win_chance), 2);
if (attacker_win_chance >= div(mul(uint(block_hash[3]),2),5)){
return true;
} else {
return false;
}
}
// common functions
function add (uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub (uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul (uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div (uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract EthGodsName {
// EthGods
EthGods private eth_gods;
address private ethgods_contract_address;
function set_eth_gods_contract_address (address eth_gods_contract_address) public returns (bool){
require (msg.sender == admin);
ethgods_contract_address = eth_gods_contract_address;
eth_gods = EthGods(ethgods_contract_address);
return true;
}
address private admin; // manually update to ethgods' admin
function update_admin () public returns (bool){
(,,address new_admin,,,,) = eth_gods.query_contract();
require (msg.sender == new_admin);
admin = new_admin;
return true;
}
//contract information & administration
bool private contract_created; // in case constructor logic change in the future
address private contract_address; //shown at the top of the home page
string private invalid_chars = "\\\"";
bytes private invalid_bytes = bytes(invalid_chars);
function set_invalid_chars (string new_invalid_chars) public returns (bool) {
require(msg.sender == admin);
invalid_chars = new_invalid_chars;
invalid_bytes = bytes(invalid_chars);
return true;
}
uint private valid_length = 16;
function set_valid_length (uint new_valid_length) public returns (bool) {
require(msg.sender == admin);
valid_length = new_valid_length;
return true;
}
struct god_name {
string god_name;
uint block_number;
uint block_duration;
}
mapping (address => god_name) private gods_name;
// start of constructor and destructor
constructor () public {
require (contract_created == false);
contract_created = true;
contract_address = address(this);
admin = msg.sender;
address v_god = 0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359;
gods_name[v_god].god_name = "V";
}
function () public payable {
revert(); // if received eth for no reason, reject
}
function finalize() public {
require (msg.sender == admin);
selfdestruct(msg.sender);
}
// end of constructor and destructor
function set_god_name (string new_name) public returns (bool){
address god_address = msg.sender;
require (add(gods_name[god_address].block_number, gods_name[god_address].block_duration) < block.number );
bytes memory bs = bytes(new_name);
require (bs.length <= valid_length);
for (uint i = 0; i < bs.length; i++){
for (uint j = 0; j < invalid_bytes.length; j++) {
if (bs[i] == invalid_bytes[j]){
return false;
}
}
}
gods_name[god_address].god_name = new_name;
emit set_name(god_address, new_name);
return true;
}
event set_name (address indexed god_address, string new_name);
function get_god_name (address god_address) public view returns (string) {
return gods_name[god_address].god_name;
}
function block_god_name (address god_address, uint block_duration) public {
require (msg.sender == admin);
gods_name[god_address].god_name = "Unkown";
gods_name[god_address].block_number = block.number;
gods_name[god_address].block_duration = block_duration;
}
function add (uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
} | to calculate how many pages | function get_amulet_orders_overview () public view returns(uint){
uint count_amulets_selling = 0;
for (uint i = 1; i <= count_amulets; i++){
if (add(amulets[i].start_selling_block, order_duration) > block.number && amulets[i].owner != msg.sender){
count_amulets_selling ++;
}
}
for (uint i = 1; i <= count_amulets; i++){
if (add(amulets[i].start_selling_block, order_duration) > block.number && amulets[i].owner != msg.sender){
count_amulets_selling ++;
}
}
}
| 997,255 | [
1,
869,
4604,
3661,
4906,
4689,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
336,
67,
301,
332,
278,
67,
9972,
67,
26081,
1832,
1071,
1476,
1135,
12,
11890,
15329,
203,
3639,
2254,
1056,
67,
301,
332,
2413,
67,
87,
1165,
310,
273,
374,
31,
203,
3639,
364,
261,
11890,
277,
273,
404,
31,
277,
1648,
1056,
67,
301,
332,
2413,
31,
277,
27245,
95,
203,
5411,
309,
261,
1289,
12,
301,
332,
2413,
63,
77,
8009,
1937,
67,
87,
1165,
310,
67,
2629,
16,
1353,
67,
8760,
13,
405,
1203,
18,
2696,
597,
2125,
332,
2413,
63,
77,
8009,
8443,
480,
1234,
18,
15330,
15329,
203,
7734,
1056,
67,
301,
332,
2413,
67,
87,
1165,
310,
965,
31,
203,
5411,
289,
203,
3639,
289,
540,
203,
540,
203,
3639,
364,
261,
11890,
277,
273,
404,
31,
277,
1648,
1056,
67,
301,
332,
2413,
31,
277,
27245,
95,
203,
5411,
309,
261,
1289,
12,
301,
332,
2413,
63,
77,
8009,
1937,
67,
87,
1165,
310,
67,
2629,
16,
1353,
67,
8760,
13,
405,
1203,
18,
2696,
597,
2125,
332,
2413,
63,
77,
8009,
8443,
480,
1234,
18,
15330,
15329,
203,
7734,
1056,
67,
301,
332,
2413,
67,
87,
1165,
310,
965,
31,
203,
5411,
289,
203,
3639,
289,
540,
203,
540,
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
] |
./partial_match/1/0x5F49E1b5Ee9A34A9aD553Ac2CcA1f908C62c776a/sources/Anima.sol | set as marketing wallet
| marketingWallet = address(0xBdf1a531983c815956FB9756dABe9Dcd03C89A4D); | 15,703,021 | [
1,
542,
487,
13667,
310,
9230,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
13667,
310,
16936,
273,
1758,
12,
20,
20029,
2180,
21,
69,
8643,
3657,
10261,
71,
28,
24872,
4313,
22201,
10580,
4313,
72,
37,
1919,
29,
40,
4315,
4630,
39,
6675,
37,
24,
40,
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
] |
//Address: 0x6e34d8d84764d40f6d7b39cd569fd017bf53177d
//Contract name: Skraps
//Balance: 0 Ether
//Verification Date: 1/8/2018
//Transacion Count: 6
// CODE STARTS HERE
pragma solidity 0.4.19;
contract Owned {
address public owner;
address public candidate;
function Owned() internal {
owner = msg.sender;
}
// A functions uses the modifier can be invoked only by the owner of the contract
modifier onlyOwner {
require(owner == msg.sender);
_;
}
// To change the owner of the contract, putting the candidate
function changeOwner(address _owner) onlyOwner public {
candidate = _owner;
}
// The candidate must call this function to accept the proposal for the transfer of the rights of contract ownership
function acceptOwner() public {
require(candidate != address(0));
require(candidate == msg.sender);
owner = candidate;
delete candidate;
}
}
// Functions for safe operation with input values (subtraction and addition)
library SafeMath {
function sub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
}
// ERC20 interface https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
contract ERC20 {
uint public totalSupply;
function balanceOf(address who) public constant returns (uint balance);
function allowance(address owner, address spender) public constant returns (uint remaining);
function transfer(address to, uint value) public returns (bool success);
function transferFrom(address from, address to, uint value) public returns (bool success);
function approve(address spender, uint value) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract Skraps is ERC20, Owned {
using SafeMath for uint;
string public name = "Skraps";
string public symbol = "SKRP";
uint8 public decimals = 18;
uint public totalSupply;
uint private endOfFreeze = 1518912000; // Sun, 18 Feb 2018 00:00:00 GMT
mapping (address => uint) private balances;
mapping (address => mapping (address => uint)) private allowed;
function balanceOf(address _who) public constant returns (uint) {
return balances[_who];
}
function allowance(address _owner, address _spender) public constant returns (uint remaining) {
return allowed[_owner][_spender];
}
function Skraps() public {
totalSupply = 110000000 * 1 ether;
balances[msg.sender] = totalSupply;
Transfer(0, msg.sender, totalSupply);
}
function transfer(address _to, uint _value) public returns (bool success) {
require(_to != address(0));
require(now >= endOfFreeze || msg.sender == owner);
require(balances[msg.sender] >= _value);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint _value) public returns (bool success) {
require(_to != address(0));
require(now >= endOfFreeze || msg.sender == owner);
require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public returns (bool success) {
require(_spender != address(0));
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
// Withdraws tokens from the contract if they accidentally or on purpose was it placed there
function withdrawTokens(uint _value) public onlyOwner {
require(balances[this] > 0 && balances[this] >= _value);
balances[this] = balances[this].sub(_value);
balances[msg.sender] = balances[msg.sender].add(_value);
Transfer(this, msg.sender, _value);
}
}
| Functions for safe operation with input values (subtraction and addition) | library SafeMath {
function sub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
}
| 5,377,768 | [
1,
7503,
364,
4183,
1674,
598,
810,
924,
261,
1717,
25693,
471,
2719,
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,
12083,
14060,
10477,
288,
203,
565,
445,
720,
12,
11890,
279,
16,
2254,
324,
13,
2713,
16618,
1135,
261,
11890,
13,
288,
203,
3639,
1815,
12,
70,
1648,
279,
1769,
203,
3639,
327,
279,
300,
324,
31,
203,
565,
289,
203,
203,
565,
445,
527,
12,
11890,
279,
16,
2254,
324,
13,
2713,
16618,
1135,
261,
11890,
13,
288,
203,
3639,
2254,
276,
273,
279,
397,
324,
31,
203,
3639,
1815,
12,
71,
1545,
279,
1769,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
/*
* MIT License
* ===========
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../libraries/ExpiryUtilsLib.sol";
import "../libraries/FactoryLib.sol";
import "../interfaces/IAaveV2LendingPool.sol";
import "../interfaces/IPendleBaseToken.sol";
import "../interfaces/IPendleData.sol";
import "../interfaces/IPendleAaveForge.sol";
import "../interfaces/IPendleForge.sol";
import "../tokens/PendleFutureYieldToken.sol";
import "../tokens/PendleOwnershipToken.sol";
import "../periphery/Permissions.sol";
import "./abstract/PendleForgeBase.sol";
import {WadRayMath} from "../libraries/WadRayMath.sol";
/**
* @dev READ ME: In AaveV2, there are 2 types of balances: scaled balance & displayed balance
scaled balance (SBAL) is the balance received when scaledBalanceOf() is called. It is the
balance value that is actually stored in the contract
displayed balance (DBAL) is the balance received when balanceOf() is called. It is calculated
by SBAL * incomeIndex
Due to fixed point precision error, two different DBAL can have the exact same SBAL.
For example: 2 DBALs of 10^10 and 10^10-3, at the moment where the incomeIndex =
5877566951907055216799556412, has the exact same SBAL. => In the future, the two DBAL will
be equal again if the incomeIndex is appropriate
This led to the issue where user A transfer 10^10 to user B, then user A's DBAL decreased by
10^10, but user B's DBAL increased by only 10^10-3. Note that AaveV2's transfer actually
transfer by SBAL and not DBAL. As a result, the amount of SBAL user B receives will be
equal to the amount of SBAL that user A transfer.
Ironically, even if the amounts of SBAL are equal, user B cannot immediately transfer back
10^10 to user A since AaveV2 requires both the SBAL & DBAL to be >= the amount of SBAL
& DBAL that B wants to transfer, and it's clear that user B, despite having enough SBAL
, only have 10^10-3 in DBAL and therefore cannot transfer back
* @dev The smooth function used in this contract aims to resolve the above issue. It finds the
smallest res that rayDiv(dividen,incomeIndex) = rayDiv(res,incomeIndex). So if multiple
DBAL correspond to the same value of SBAL, the smallest DBAL will be returned.
One very important thing to note is that the smooth function, for example smooth(X,Y)=Z,
doesn't change the amount of SBAL since X/Y = Z/Y, so the amount of SBAL transfered is
unchanged IF AND ONLY IF the transfer happens immediately (in the same transaction).
So for the 10^10 transfer above, user B will only acknowledge that he has received
smooth(10^10,incomeIndex) = 10^10-3, and when the time to pay back comes, user B will only
pay smooth(10^10-3,incomeIndex2) back. In both transactions, the amount of SBAL that B & A
will receive are not affected by smooth.
*/
contract PendleAaveV2Forge is PendleForgeBase, IPendleAaveForge {
using ExpiryUtils for string;
using WadRayMath for uint256;
IAaveV2LendingPool public immutable aaveLendingPool;
mapping(address => mapping(uint256 => uint256)) public lastNormalisedIncomeBeforeExpiry;
mapping(address => mapping(uint256 => mapping(address => uint256)))
public lastNormalisedIncome; //lastNormalisedIncome[underlyingAsset][expiry][account]
mapping(address => address) private reserveATokenAddress;
constructor(
address _governance,
IPendleRouter _router,
IAaveV2LendingPool _aaveLendingPool,
bytes32 _forgeId
) PendleForgeBase(_governance, _router, _forgeId) {
require(address(_aaveLendingPool) != address(0), "ZERO_ADDRESS");
aaveLendingPool = _aaveLendingPool;
}
function _getYieldBearingToken(address _underlyingAsset) internal override returns (address) {
if (reserveATokenAddress[_underlyingAsset] == address(0)) {
reserveATokenAddress[_underlyingAsset] = aaveLendingPool
.getReserveData(_underlyingAsset)
.aTokenAddress;
}
return reserveATokenAddress[_underlyingAsset];
}
function getReserveNormalizedIncome(address _underlyingAsset, uint256 _expiry)
public
view
override
returns (uint256)
{
if (block.timestamp > _expiry) {
return lastNormalisedIncomeBeforeExpiry[_underlyingAsset][_expiry];
}
return aaveLendingPool.getReserveNormalizedIncome(_underlyingAsset);
}
function _calcDueInterests(
uint256 principal,
address _underlyingAsset,
uint256 _expiry,
address _account
) internal override returns (uint256 dueInterests) {
uint256 ix = lastNormalisedIncome[_underlyingAsset][_expiry][_account];
uint256 normalizedIncome;
if (block.timestamp >= _expiry) {
normalizedIncome = lastNormalisedIncomeBeforeExpiry[_underlyingAsset][_expiry];
} else {
normalizedIncome = aaveLendingPool.getReserveNormalizedIncome(_underlyingAsset);
lastNormalisedIncomeBeforeExpiry[_underlyingAsset][_expiry] = normalizedIncome;
}
// first time getting XYT
if (ix == 0) {
lastNormalisedIncome[_underlyingAsset][_expiry][_account] = normalizedIncome;
return 0;
}
lastNormalisedIncome[_underlyingAsset][_expiry][_account] = normalizedIncome;
uint256 principalWithDueInterests = principal.rayDiv(ix).rayMul(normalizedIncome);
principalWithDueInterests = WadRayMath.smooth(principalWithDueInterests, normalizedIncome);
// theoratically the principal should be smooth too. But due to precision error, it was
// decided not to do so in order to leave a tiny bit of balance left in the contract
// in case future transactions from this user needs it (for example, redeem all the OT
// that he is holding)
dueInterests = (
principalWithDueInterests > principal ? principalWithDueInterests - principal : 0
);
dueInterests = WadRayMath.smooth(dueInterests, normalizedIncome);
}
//calculate the (principal + interest) from the last action before expiry to now.
function _calcTotalAfterExpiry(
address,
address _underlyingAsset,
uint256 _expiry,
uint256 redeemedAmount
) internal view override returns (uint256 totalAfterExpiry) {
uint256 currentNormalizedIncome =
aaveLendingPool.getReserveNormalizedIncome(_underlyingAsset);
totalAfterExpiry = redeemedAmount
.rayDiv(lastNormalisedIncomeBeforeExpiry[_underlyingAsset][_expiry])
.rayMul(currentNormalizedIncome);
totalAfterExpiry = WadRayMath.smooth(totalAfterExpiry, currentNormalizedIncome);
}
function _calcUnderlyingToRedeem(address _underlyingAsset, uint256 _amountToRedeem)
internal
view
override
returns (uint256 underlyingToRedeem)
{
underlyingToRedeem = WadRayMath.smooth(
_amountToRedeem,
aaveLendingPool.getReserveNormalizedIncome(_underlyingAsset)
);
}
function _calcAmountToMint(address _underlyingAsset, uint256 _amountToTokenize)
internal
view
override
returns (uint256 amountToMint)
{
amountToMint = WadRayMath.smooth(
_amountToTokenize,
aaveLendingPool.getReserveNormalizedIncome(_underlyingAsset)
);
}
}
| first time getting XYT | function _calcDueInterests(
uint256 principal,
address _underlyingAsset,
uint256 _expiry,
address _account
) internal override returns (uint256 dueInterests) {
uint256 ix = lastNormalisedIncome[_underlyingAsset][_expiry][_account];
uint256 normalizedIncome;
if (block.timestamp >= _expiry) {
normalizedIncome = lastNormalisedIncomeBeforeExpiry[_underlyingAsset][_expiry];
normalizedIncome = aaveLendingPool.getReserveNormalizedIncome(_underlyingAsset);
lastNormalisedIncomeBeforeExpiry[_underlyingAsset][_expiry] = normalizedIncome;
}
if (ix == 0) {
lastNormalisedIncome[_underlyingAsset][_expiry][_account] = normalizedIncome;
return 0;
}
lastNormalisedIncome[_underlyingAsset][_expiry][_account] = normalizedIncome;
uint256 principalWithDueInterests = principal.rayDiv(ix).rayMul(normalizedIncome);
principalWithDueInterests = WadRayMath.smooth(principalWithDueInterests, normalizedIncome);
principalWithDueInterests > principal ? principalWithDueInterests - principal : 0
);
dueInterests = WadRayMath.smooth(dueInterests, normalizedIncome);
}
| 12,860,194 | [
1,
3645,
813,
8742,
18774,
56,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
389,
12448,
30023,
2465,
25563,
12,
203,
3639,
2254,
5034,
8897,
16,
203,
3639,
1758,
389,
9341,
6291,
6672,
16,
203,
3639,
2254,
5034,
389,
22409,
16,
203,
3639,
1758,
389,
4631,
203,
565,
262,
2713,
3849,
1135,
261,
11890,
5034,
6541,
2465,
25563,
13,
288,
203,
3639,
2254,
5034,
8288,
273,
1142,
5506,
5918,
382,
5624,
63,
67,
9341,
6291,
6672,
6362,
67,
22409,
6362,
67,
4631,
15533,
203,
3639,
2254,
5034,
5640,
382,
5624,
31,
203,
203,
3639,
309,
261,
2629,
18,
5508,
1545,
389,
22409,
13,
288,
203,
5411,
5640,
382,
5624,
273,
1142,
5506,
5918,
382,
5624,
4649,
14633,
63,
67,
9341,
6291,
6672,
6362,
67,
22409,
15533,
203,
5411,
5640,
382,
5624,
273,
279,
836,
48,
2846,
2864,
18,
588,
607,
6527,
15577,
382,
5624,
24899,
9341,
6291,
6672,
1769,
203,
5411,
1142,
5506,
5918,
382,
5624,
4649,
14633,
63,
67,
9341,
6291,
6672,
6362,
67,
22409,
65,
273,
5640,
382,
5624,
31,
203,
3639,
289,
203,
203,
3639,
309,
261,
697,
422,
374,
13,
288,
203,
5411,
1142,
5506,
5918,
382,
5624,
63,
67,
9341,
6291,
6672,
6362,
67,
22409,
6362,
67,
4631,
65,
273,
5640,
382,
5624,
31,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
3639,
1142,
5506,
5918,
382,
5624,
63,
67,
9341,
6291,
6672,
6362,
67,
22409,
6362,
67,
4631,
65,
273,
5640,
382,
5624,
31,
203,
203,
3639,
2254,
5034,
8897,
1190,
30023,
2465,
25563,
273,
8897,
18,
435,
7244,
12,
697,
2934,
435,
27860,
12,
17762,
382,
5624,
1769,
2
] |
./full_match/1/0x77337dEEA78720542f0A1325394Def165918D562/sources/src/SplitSwapRouter.sol | @notice Identical to swapExactTokensForETH, but succeeds for tokens that take a fee on transfer. @dev Require has been replaced with revert for gas optimization. Attempt to back-run swaps. @param amountIn Amount of input tokens to send. @param amountOutMin Minimum amount of ETH that must be received @param path Array of token addresses. path.length must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity @param to Address of receiver @param deadline Unix timestamp in seconds after which the transaction will revert | function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external virtual {
ensure(deadline);
address weth = WETH09;
if (path[_dec(path.length)] != weth) revert InvalidPath();
SplitSwapLibrary.Swap[] memory swaps = SplitSwapLibrary.getSwapsOut(
SUSHI_FACTORY,
BACKUP_FACTORY,
amountIn,
SUSHI_FACTORY_HASH,
BACKUP_FACTORY_HASH,
path
);
for (uint256 i; i < 2; i = _inc(i)) {
if (_isNonZero(swaps[0].pools[i].amountIn))
ERC20(path[0]).safeTransferFrom(msg.sender, swaps[0].pools[i].pair, swaps[0].pools[i].amountIn);
}
for (uint256 i = 2; i < 5; i = _inc(i)) {
if (_isNonZero(swaps[0].pools[i].amountIn))
ERC20(path[0]).safeTransferFrom(msg.sender, address(this), swaps[0].pools[i].amountIn);
}
uint256[] memory amounts = _swapSupportingFeeOnTransferTokens(address(this), swaps);
uint256 amountOut = amounts[_dec(path.length)];
if (amountOutMin > amountOut) revert InsufficientOutputAmount();
IWETH(weth).withdraw(amountOut);
SafeTransferLib.safeTransferETH(to, amountOut);
}
| 16,513,968 | [
1,
6106,
1706,
358,
7720,
14332,
5157,
1290,
1584,
44,
16,
1496,
21933,
364,
2430,
716,
4862,
279,
14036,
603,
7412,
18,
225,
12981,
711,
2118,
8089,
598,
15226,
364,
16189,
14850,
18,
12864,
358,
1473,
17,
2681,
1352,
6679,
18,
225,
3844,
382,
16811,
434,
810,
2430,
358,
1366,
18,
225,
3844,
1182,
2930,
23456,
3844,
434,
512,
2455,
716,
1297,
506,
5079,
225,
589,
1510,
434,
1147,
6138,
18,
589,
18,
2469,
1297,
506,
1545,
576,
18,
453,
8192,
364,
1517,
18221,
3082,
434,
6138,
1297,
1005,
471,
1240,
4501,
372,
24237,
225,
358,
5267,
434,
5971,
225,
14096,
9480,
2858,
316,
3974,
1839,
1492,
326,
2492,
903,
15226,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
14332,
5157,
1290,
1584,
44,
6289,
310,
14667,
1398,
5912,
5157,
12,
203,
3639,
2254,
5034,
3844,
382,
16,
203,
3639,
2254,
5034,
3844,
1182,
2930,
16,
203,
3639,
1758,
8526,
745,
892,
589,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
14096,
203,
565,
262,
3903,
5024,
288,
203,
3639,
3387,
12,
22097,
1369,
1769,
203,
3639,
1758,
341,
546,
273,
678,
1584,
44,
5908,
31,
203,
3639,
309,
261,
803,
63,
67,
4924,
12,
803,
18,
2469,
25887,
480,
341,
546,
13,
15226,
1962,
743,
5621,
203,
3639,
5385,
12521,
9313,
18,
12521,
8526,
3778,
1352,
6679,
273,
5385,
12521,
9313,
18,
588,
6050,
6679,
1182,
12,
203,
5411,
11726,
2664,
45,
67,
16193,
16,
203,
5411,
15842,
3079,
67,
16193,
16,
203,
5411,
3844,
382,
16,
203,
5411,
11726,
2664,
45,
67,
16193,
67,
15920,
16,
203,
5411,
15842,
3079,
67,
16193,
67,
15920,
16,
203,
5411,
589,
203,
3639,
11272,
203,
3639,
364,
261,
11890,
5034,
277,
31,
277,
411,
576,
31,
277,
273,
389,
9523,
12,
77,
3719,
288,
203,
5411,
309,
261,
67,
291,
3989,
7170,
12,
5328,
6679,
63,
20,
8009,
27663,
63,
77,
8009,
8949,
382,
3719,
203,
7734,
4232,
39,
3462,
12,
803,
63,
20,
65,
2934,
4626,
5912,
1265,
12,
3576,
18,
15330,
16,
1352,
6679,
63,
20,
8009,
27663,
63,
77,
8009,
6017,
16,
1352,
6679,
63,
20,
8009,
27663,
63,
77,
8009,
8949,
382,
1769,
203,
3639,
289,
203,
3639,
364,
261,
11890,
5034,
277,
273,
576,
2
] |
./full_match/1/0x73217eE72fDedf763BACd83Acf60b4218f6ff8Af/sources/Users/ivannikov/work/snake-jungle/cosmo-farming/contracts/FarmUniswap.sol | * @notice updates pool information to be up to date to the current block/ | function updatePool() public {
if (block.number <= farmInfo.lastRewardBlock) {
return;
}
uint256 lpSupply = farmInfo.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
farmInfo.lastRewardBlock = block.number < farmInfo.endBlock
? block.number
: farmInfo.endBlock;
return;
}
uint256 multiplier =
getMultiplier(farmInfo.lastRewardBlock, block.number);
uint256 tokenReward = multiplier.mul(farmInfo.blockReward);
farmInfo.accRewardPerShare = farmInfo.accRewardPerShare.add(
tokenReward.mul(1e12).div(lpSupply)
);
farmInfo.lastRewardBlock = block.number < farmInfo.endBlock
? block.number
: farmInfo.endBlock;
}
| 4,880,082 | [
1,
14703,
2845,
1779,
358,
506,
731,
358,
1509,
358,
326,
783,
1203,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1089,
2864,
1435,
1071,
288,
203,
3639,
309,
261,
2629,
18,
2696,
1648,
284,
4610,
966,
18,
2722,
17631,
1060,
1768,
13,
288,
203,
5411,
327,
31,
203,
3639,
289,
203,
3639,
2254,
5034,
12423,
3088,
1283,
273,
284,
4610,
966,
18,
9953,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
309,
261,
9953,
3088,
1283,
422,
374,
13,
288,
203,
5411,
284,
4610,
966,
18,
2722,
17631,
1060,
1768,
273,
1203,
18,
2696,
411,
284,
4610,
966,
18,
409,
1768,
203,
7734,
692,
1203,
18,
2696,
203,
7734,
294,
284,
4610,
966,
18,
409,
1768,
31,
203,
5411,
327,
31,
203,
3639,
289,
203,
3639,
2254,
5034,
15027,
273,
203,
5411,
31863,
5742,
12,
74,
4610,
966,
18,
2722,
17631,
1060,
1768,
16,
1203,
18,
2696,
1769,
203,
3639,
2254,
5034,
1147,
17631,
1060,
273,
15027,
18,
16411,
12,
74,
4610,
966,
18,
2629,
17631,
1060,
1769,
203,
3639,
284,
4610,
966,
18,
8981,
17631,
1060,
2173,
9535,
273,
284,
4610,
966,
18,
8981,
17631,
1060,
2173,
9535,
18,
1289,
12,
203,
5411,
1147,
17631,
1060,
18,
16411,
12,
21,
73,
2138,
2934,
2892,
12,
9953,
3088,
1283,
13,
203,
3639,
11272,
203,
3639,
284,
4610,
966,
18,
2722,
17631,
1060,
1768,
273,
1203,
18,
2696,
411,
284,
4610,
966,
18,
409,
1768,
203,
5411,
692,
1203,
18,
2696,
203,
5411,
294,
284,
4610,
966,
18,
409,
1768,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.21;
contract Owned {
/// 'owner' is the only address that can call a function with
/// this modifier
address public owner;
address internal newOwner;
///@notice The constructor assigns the message sender to be 'owner'
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
event updateOwner(address _oldOwner, address _newOwner);
///change the owner
function changeOwner(address _newOwner) public onlyOwner returns(bool) {
require(owner != _newOwner);
newOwner = _newOwner;
return true;
}
/// accept the ownership
function acceptNewOwner() public returns(bool) {
require(msg.sender == newOwner);
emit updateOwner(owner, newOwner);
owner = newOwner;
return true;
}
}
contract SafeMath {
function safeMul(uint a, uint b) pure internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeSub(uint a, uint b) pure internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) pure internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
}
contract ERC20Token {
/* This is a slight change to the ERC20 base standard.
function totalSupply() constant returns (uint256 supply);
is replaced with:
uint256 public totalSupply;
This automatically creates a getter function for the totalSupply.
This is moved to the base contract since public getter functions are not
currently recognised as an implementation of the matching abstract
function by the compiler.
*/
/// total amount of tokens
uint256 public totalSupply;
/// user tokens
mapping (address => uint256) public balances;
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant public returns (uint256 balance);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) public returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) public returns (bool success);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant public returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract PUST is ERC20Token {
string public name = "UST Put Option";
string public symbol = "PUST";
uint public decimals = 0;
uint256 public totalSupply = 0;
uint256 public topTotalSupply = 0;
function transfer(address _to, uint256 _value) public returns (bool success) {
//Default assumes totalSupply can't be over max (2^256 - 1).
//If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.
//Replace the if with this one instead.
if (balances[msg.sender] >= _value && balances[_to] + _value >= balances[_to]) {
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
//same as above. Replace this line with the following if you want to protect against wrapping uints.
if (balances[_from] >= _value && allowances[_from][msg.sender] >= _value && balances[_to] + _value >= balances[_to]) {
balances[_to] += _value;
balances[_from] -= _value;
allowances[_from][msg.sender] -= _value;
emit Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant public returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowances[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowances[_owner][_spender];
}
mapping(address => uint256) public balances;
mapping (address => mapping (address => uint256)) allowances;
}
contract ExchangeUST is SafeMath, Owned, PUST {
// Exercise End Time 1/1/2019 0:0:0
uint public ExerciseEndTime = 1546272000;
uint public exchangeRate = 100000; //percentage times (1 ether)
//mapping (address => uint) ustValue; //mapping of token addresses to mapping of account balances (token=0 means Ether)
// UST address
address public ustAddress = address(0xFa55951f84Bfbe2E6F95aA74B58cc7047f9F0644);
// our hardWallet address
//address public ustHolderAddress = address(0xe88a5b4b01c683FcE5D6cb4494c8E5705c993145);
// offical Address
address public officialAddress = address(0x472fc5B96afDbD1ebC5Ae22Ea10bafe45225Bdc6);
event Cancel(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s);
event Deposit(address token, address user, uint amount, uint balance);
event Withdraw(address token, address user, uint amount, uint balance);
event exchange(address contractAddr, address reciverAddr, uint _pustBalance);
event changeFeeAt(uint _exchangeRate);
function chgExchangeRate(uint _exchangeRate) public onlyOwner {
require (_exchangeRate != exchangeRate);
require (_exchangeRate != 0);
exchangeRate = _exchangeRate;
}
function exerciseOption(uint _pustBalance) public returns (bool) {
require (now < ExerciseEndTime);
require (_pustBalance <= balances[msg.sender]);
uint _ether = _pustBalance * 10 ** 18;
require (address(this).balance >= _ether);
uint _amount = _pustBalance * exchangeRate * 10**18;
require (PUST(ustAddress).transferFrom(msg.sender, officialAddress, _amount) == true);
balances[msg.sender] = safeSub(balances[msg.sender], _pustBalance);
totalSupply = safeSub(totalSupply, _pustBalance);
msg.sender.transfer(_ether); // convert units from ether to wei
emit exchange(address(this), msg.sender, _pustBalance);
}
}
contract USTputOption is ExchangeUST {
// constant
uint public initBlockEpoch = 40;
uint public eachUserWeight = 10;
uint public initEachPUST = 5*10**17 wei;
uint public lastEpochBlock = block.number + initBlockEpoch;
uint public price1=4*9995*10**17/10000;
uint public price2=99993 * 10**17/100000;
uint public eachPUSTprice = initEachPUST;
uint public lastEpochTX = 0;
uint public epochLast = 0;
address public lastCallAddress;
uint public lastCallPUST;
event buyPUST (address caller, uint PUST);
function () payable public {
require (now < ExerciseEndTime);
require (topTotalSupply > totalSupply);
bool firstCallReward = false;
uint epochNow = whichEpoch(block.number);
if(epochNow != epochLast) {
lastEpochBlock = safeAdd(lastEpochBlock, ((block.number - lastEpochBlock)/initBlockEpoch + 1)* initBlockEpoch);
doReward();
eachPUSTprice = calcpustprice(epochNow, epochLast);
epochLast = epochNow;
//reward _first
firstCallReward = true;
lastEpochTX = 0;
}
uint _value = msg.value;
uint _PUST = _value / eachPUSTprice;
require(_PUST > 0);
if (safeAdd(totalSupply, _PUST) > topTotalSupply) {
_PUST = safeSub(topTotalSupply, totalSupply);
}
uint _refound = _value - _PUST * eachPUSTprice;
if(_refound > 0) {
msg.sender.transfer(_refound);
}
balances[msg.sender] = safeAdd(balances[msg.sender], _PUST);
totalSupply = safeAdd(totalSupply, _PUST);
emit buyPUST(msg.sender, _PUST);
// alloc first reward in a new or init epoch
if(lastCallAddress == address(0) && epochLast == 0) {
firstCallReward = true;
}
if (firstCallReward) {
uint _firstReward = 0;
_firstReward = (_PUST - 1) * 2 / 10 + 1;
if (safeAdd(totalSupply, _firstReward) > topTotalSupply) {
_firstReward = safeSub(topTotalSupply,totalSupply);
}
balances[msg.sender] = safeAdd(balances[msg.sender], _firstReward);
totalSupply = safeAdd(totalSupply, _firstReward);
}
lastEpochTX += 1;
// last call address info
lastCallAddress = msg.sender;
lastCallPUST = _PUST;
// calc last epoch
lastEpochBlock = safeAdd(lastEpochBlock, eachUserWeight);
}
//
function whichEpoch(uint _blocknumber) internal view returns (uint _epochNow) {
if (lastEpochBlock >= _blocknumber ) {
_epochNow = epochLast;
}
else {
//lastEpochBlock = safeAdd(lastEpochBlock, thisEpochBlockCount);
//thisEpochBlockCount = initBlockEpoch;
_epochNow = epochLast + (_blocknumber - lastEpochBlock) / initBlockEpoch + 1;
}
}
function calcpustprice(uint _epochNow, uint _epochLast) public returns (uint _eachPUSTprice) {
require (_epochNow - _epochLast > 0);
uint dif = _epochNow - _epochLast;
uint dif100 = dif/100;
dif = dif - dif100*100;
for(uint i=0;i<dif100;i++)
{
price1 = price1-price1*5/100;
price2 = price2-price2*7/1000;
}
price1 = price1 - price1*5*dif/10000;
price2 = price2 - price2*7*dif/100000;
_eachPUSTprice = price1+price2;
}
function doReward() internal returns (bool) {
if (lastEpochTX == 1) return false;
uint _lastReward = 0;
if(lastCallPUST != 0) {
_lastReward = (lastCallPUST-1) * 2 / 10 + 1;
}
if (safeAdd(totalSupply, _lastReward) > topTotalSupply) {
_lastReward = safeSub(topTotalSupply,totalSupply);
}
balances[lastCallAddress] = safeAdd(balances[lastCallAddress], _lastReward);
totalSupply = safeAdd(totalSupply, _lastReward);
}
// only owner can deposit ether into put option contract
function DepositETH() payable public {
// deposit ether
require (msg.sender == officialAddress);
topTotalSupply += msg.value / 10**18;
}
// only end time, onwer can transfer contract's ether out.
function WithdrawETH() payable public onlyOwner {
require (now >= ExerciseEndTime);
officialAddress.transfer(address(this).balance);
}
// if this epoch is the last, then the reward called by the owner
function allocLastTxRewardByHand() public onlyOwner returns (bool success) {
lastEpochBlock = safeAdd(block.number, initBlockEpoch);
doReward();
success = true;
}
} | convert units from ether to wei
| msg.sender.transfer(_ether); | 10,745,311 | [
1,
6283,
4971,
628,
225,
2437,
358,
732,
77,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1234,
18,
15330,
18,
13866,
24899,
2437,
1769,
565,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x8C6AdC849Ffc03C96FA16F3d58220A6BD30D3602/sources/MasterChefLP.sol | View function to see pending LPs on frontend. | function pendingLP(address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo;
UserInfo storage user = userInfo[_user];
uint256 accLPPerShare = pool.accLPPerShare;
uint256 lpSupply = totalLPStaked;
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 rewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalLPStaked.sub(totalLPUsedForPurchase));
uint256 _totalReward = rewardBalance.sub(pool.lastLPRewardBalance);
accLPPerShare = accLPPerShare.add(_totalReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accLPPerShare).div(1e12).sub(user.rewardLPDebt);
}
| 9,220,898 | [
1,
1767,
445,
358,
2621,
4634,
511,
18124,
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,
14461,
12,
2867,
389,
1355,
13,
3903,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
8828,
966,
2502,
2845,
273,
2845,
966,
31,
203,
3639,
25003,
2502,
729,
273,
16753,
63,
67,
1355,
15533,
203,
3639,
2254,
5034,
4078,
14461,
2173,
9535,
273,
2845,
18,
8981,
14461,
2173,
9535,
31,
203,
3639,
2254,
5034,
12423,
3088,
1283,
273,
2078,
14461,
510,
9477,
31,
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,
19890,
13937,
273,
2845,
18,
9953,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
13,
2934,
1717,
12,
4963,
14461,
510,
9477,
18,
1717,
12,
4963,
14461,
6668,
1290,
23164,
10019,
203,
5411,
2254,
5034,
389,
4963,
17631,
1060,
273,
19890,
13937,
18,
1717,
12,
6011,
18,
2722,
48,
8025,
359,
1060,
13937,
1769,
203,
5411,
4078,
14461,
2173,
9535,
273,
4078,
14461,
2173,
9535,
18,
1289,
24899,
4963,
17631,
1060,
18,
16411,
12,
21,
73,
2138,
2934,
2892,
12,
9953,
3088,
1283,
10019,
203,
3639,
289,
203,
3639,
327,
729,
18,
8949,
18,
16411,
12,
8981,
14461,
2173,
9535,
2934,
2892,
12,
21,
73,
2138,
2934,
1717,
12,
1355,
18,
266,
2913,
14461,
758,
23602,
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
] |
pragma solidity ^0.4.11;
/*******************************************************************************
* ERC Token Standard #20 Interface
* https://github.com/ethereum/EIPs/issues/20
*******************************************************************************/
contract ERC20Interface {
// Get the total token supply
function totalSupply() constant returns (uint256 totalSupply);
// Get the account balance of another account with address _owner
function balanceOf(address _owner) constant returns (uint256 balance);
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value) returns (bool success);
// Send _value amount of tokens from address _from to address _to
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
// If this function is called again it overwrites the current allowance with _value.
// this function is required for some DEX functionality.
function approve(address _spender, uint256 _value) returns (bool success);
// Returns the amount which _spender is still allowed to withdraw from _owner
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
// Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
// Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
/*******************************************************************************
* AICoin - Smart Contract with token and ballot handling
*******************************************************************************/
contract AICoin is ERC20Interface {
/* ******************************
* COIN data / functions
* ******************************/
/* Token constants */
string public constant name = 'AICoin';
string public constant symbol = 'XAI';
uint8 public constant decimals = 8;
string public constant smallestUnit = 'Hofstadter';
/* Token internal data */
address m_administrator;
uint256 m_totalSupply;
/* Current balances for each account */
mapping(address => uint256) balances;
/* Account holder approves the transfer of an amount to another account */
mapping(address => mapping (address => uint256)) allowed;
/* One-time create function: initialize the supply and set the admin address */
function AICoin (uint256 _initialSupply) {
m_administrator = msg.sender;
m_totalSupply = _initialSupply;
balances[msg.sender] = _initialSupply;
}
/* Get the admin address */
function administrator() constant returns (address adminAddress) {
return m_administrator;
}
/* Get the total coin supply */
function totalSupply() constant returns (uint256 totalSupply) {
return m_totalSupply;
}
/* Get the balance of a specific account by its address */
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
/* Transfer an amount from the owner's account to an indicated account */
function transfer(address _to, uint256 _amount) returns (bool success) {
if (balances[msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]
&& (! accountHasCurrentVote(msg.sender))) {
balances[msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
/* Send _value amount of tokens from address _from to address _to
* The transferFrom method is used for a withdraw workflow, allowing contracts to send
* tokens on your behalf, for example to "deposit" to a contract address and/or to charge
* fees in sub-currencies; the command should fail unless the _from account has
* deliberately authorized the sender of the message via some mechanism; we propose
* these standardized APIs for approval:
*/
function transferFrom(address _from, address _to, uint256 _amount) returns (bool success) {
if (balances[_from] >= _amount
&& allowed[_from][msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]
&& (! accountHasCurrentVote(_from))) {
balances[_from] -= _amount;
allowed[_from][msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
}
/* Pre-authorize an address to withdraw from your account, up to the _value amount.
* Doing so (using transferFrom) reduces the remaining authorized amount,
* as well as the actual account balance)
* Subsequent calls to this function overwrite any existing authorized amount.
* Therefore, to cancel an authorization, simply write a zero amount.
*/
function approve(address _spender, uint256 _amount) returns (bool success) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
/* Get the currently authorized that can be withdrawn by account _spender from account _owner */
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/* ******************************
* BALLOT data / functions
* ******************************/
/* Dev Note: creating a struct that contained a string, uint values and
* an array of option structs, etc, would consistently fail.
* So the ballot details are held in separate mappings with a common integer
* key for each ballot. The IDs are 1-indexed, sequential and contiguous.
*/
/* Basic ballot details: time frame and number of options */
struct BallotDetails {
uint256 start;
uint256 end;
uint32 numOptions; // 1-indexed for readability
bool sealed;
}
uint32 public numBallots = 0; // 1-indexed for readability
mapping (uint32 => string) public ballotNames;
mapping (uint32 => BallotDetails) public ballotDetails;
mapping (uint32 => mapping (uint32 => string) ) public ballotOptions;
/* Create a new ballot and set the basic details (proposal description, dates)
* The ballot still need to have options added and then to be sealed
*/
function adminAddBallot(string _proposal, uint256 _start, uint256 _end) {
/* Admin functions must be called by the contract creator. */
require(msg.sender == m_administrator);
/* Create and store the new ballot objects */
numBallots++;
uint32 ballotId = numBallots;
ballotNames[ballotId] = _proposal;
ballotDetails[ballotId] = BallotDetails(_start, _end, 0, false);
}
/* Create a new ballot and set the basic details (proposal description, dates)
* The ballot still need to have options added and then to be sealed
*/
function adminAmendBallot(uint32 _ballotId, string _proposal, uint256 _start, uint256 _end) {
/* Admin functions must be called by the contract creator. */
require(msg.sender == m_administrator);
/* verify that the ballot exists */
require(_ballotId > 0 && _ballotId <= numBallots);
/* update the ballot object */
ballotNames[_ballotId] = _proposal;
ballotDetails[_ballotId].start = _start;
ballotDetails[_ballotId].end = _end;
}
/* Add an option to an existing Ballot
*/
function adminAddBallotOption(uint32 _ballotId, string _option) {
/* Admin functions must be called by the contract creator. */
require(msg.sender == m_administrator);
/* verify that the ballot exists */
require(_ballotId > 0 && _ballotId <= numBallots);
/* cannot change a ballot once it is sealed */
if(isBallotSealed(_ballotId)) {
revert();
}
/* store the new ballot option */
ballotDetails[_ballotId].numOptions += 1;
uint32 optionId = ballotDetails[_ballotId].numOptions;
ballotOptions[_ballotId][optionId] = _option;
}
/* Amend and option in an existing Ballot
*/
function adminEditBallotOption(uint32 _ballotId, uint32 _optionId, string _option) {
/* Admin functions must be called by the contract creator. */
require(msg.sender == m_administrator);
/* verify that the ballot exists */
require(_ballotId > 0 && _ballotId <= numBallots);
/* cannot change a ballot once it is sealed */
if(isBallotSealed(_ballotId)) {
revert();
}
/* validate the ballot option */
require(_optionId > 0 && _optionId <= ballotDetails[_ballotId].numOptions);
/* update the ballot option */
ballotOptions[_ballotId][_optionId] = _option;
}
/* Seal a ballot - after this the ballot is official and no changes can be made.
*/
function adminSealBallot(uint32 _ballotId) {
/* Admin functions must be called by the contract creator. */
require(msg.sender == m_administrator);
/* verify that the ballot exists */
require(_ballotId > 0 && _ballotId <= numBallots);
/* cannot change a ballot once it is sealed */
if(isBallotSealed(_ballotId)) {
revert();
}
/* set the ballot seal flag */
ballotDetails[_ballotId].sealed = true;
}
/* Function to determine if a ballot is currently in progress, based on its
* start and end dates, and that it has been sealed.
*/
function isBallotInProgress(uint32 _ballotId) private constant returns (bool) {
return (isBallotSealed(_ballotId)
&& ballotDetails[_ballotId].start <= now
&& ballotDetails[_ballotId].end >= now);
}
/* Function to determine if a ballot has ended, based on its end date */
function hasBallotEnded(uint32 _ballotId) private constant returns (bool) {
return (ballotDetails[_ballotId].end < now);
}
/* Function to determine if a ballot has been sealed, which means it has been
* authorized by the administrator and can no longer be changed.
*/
function isBallotSealed(uint32 _ballotId) private returns (bool) {
return ballotDetails[_ballotId].sealed;
}
/* ******************************
* VOTING data / functions
* ******************************/
mapping (uint32 => mapping (address => uint256) ) public ballotVoters;
mapping (uint32 => mapping (uint32 => uint256) ) public ballotVoteCount;
/* function to allow a coin holder add to the vote count of an option in an
* active ballot. The votes added equals the balance of the account. Once this is called successfully
* the coins cannot be transferred out of the account until the end of the ballot.
*
* NB: The timing of the start and end of the voting period is determined by
* the timestamp of the block in which the transaction is included. As given by
* the current Ethereum standard this is *NOT* guaranteed to be accurate to any
* given external time source. Therefore, votes should be placed well in advance
* of the UTC end time of the Ballot.
*/
function vote(uint32 _ballotId, uint32 _selectedOptionId) {
/* verify that the ballot exists */
require(_ballotId > 0 && _ballotId <= numBallots);
/* Ballot must be in progress in order to vote */
require(isBallotInProgress(_ballotId));
/* Calculate the balance which which the coin holder has not yet voted, which is the difference between
* the current balance for the senders address and the amount they already voted in this ballot.
* If the difference is zero, this attempt to vote will fail.
*/
uint256 votableBalance = balanceOf(msg.sender) - ballotVoters[_ballotId][msg.sender];
require(votableBalance > 0);
/* validate the ballot option */
require(_selectedOptionId > 0 && _selectedOptionId <= ballotDetails[_ballotId].numOptions);
/* update the vote count and record the voter */
ballotVoteCount[_ballotId][_selectedOptionId] += votableBalance;
ballotVoters[_ballotId][msg.sender] += votableBalance;
}
/* function to determine if an address has already voted in a given ballot */
function hasAddressVotedInBallot(uint32 _ballotId, address _voter) constant returns (bool hasVoted) {
return ballotVoters[_ballotId][_voter] > 0;
}
/* function to determine if an account has voted in any current ballot */
function accountHasCurrentVote(address _voter) constant returns (bool) {
for(uint32 id = 1; id <= numBallots; id++) {
if (isBallotInProgress(id) && hasAddressVotedInBallot(id, _voter)) {
return true;
}
}
return false;
}
}
| Transfer an amount from the owner's account to an indicated account */ | function transfer(address _to, uint256 _amount) returns (bool success) {
if (balances[msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]
&& (! accountHasCurrentVote(msg.sender))) {
balances[msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(msg.sender, _to, _amount);
return true;
return false;
}
}
| 5,511,732 | [
1,
5912,
392,
3844,
628,
326,
3410,
1807,
2236,
358,
392,
17710,
2236,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
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,
7412,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
1135,
261,
6430,
2216,
13,
288,
203,
565,
309,
261,
70,
26488,
63,
3576,
18,
15330,
65,
1545,
389,
8949,
203,
3639,
597,
389,
8949,
405,
374,
203,
3639,
597,
324,
26488,
63,
67,
869,
65,
397,
389,
8949,
405,
324,
26488,
63,
67,
869,
65,
203,
3639,
597,
16051,
2236,
5582,
3935,
19338,
12,
3576,
18,
15330,
20349,
288,
203,
1377,
324,
26488,
63,
3576,
18,
15330,
65,
3947,
389,
8949,
31,
203,
1377,
324,
26488,
63,
67,
869,
65,
1011,
389,
8949,
31,
203,
1377,
12279,
12,
3576,
18,
15330,
16,
389,
869,
16,
389,
8949,
1769,
203,
1377,
327,
638,
31,
203,
1377,
327,
629,
31,
203,
565,
289,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: BUSL-1.1 AND Unlicense AND MIT AND GPL-2.0-or-later
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Provides functions for deriving a pool address from the factory, tokens, and the fee
library PoolAddress {
bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;
/// @notice The identifying key of the pool
struct PoolKey {
address token0;
address token1;
uint24 fee;
}
/// @notice Returns PoolKey: the ordered tokens with the matched fee levels
/// @param tokenA The first token of a pool, unsorted
/// @param tokenB The second token of a pool, unsorted
/// @param fee The fee level of the pool
/// @return Poolkey The pool details with ordered token0 and token1 assignments
function getPoolKey(
address tokenA,
address tokenB,
uint24 fee
) internal pure returns (PoolKey memory) {
if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
return PoolKey({token0: tokenA, token1: tokenB, fee: fee});
}
/// @notice Deterministically computes the pool address given the factory and PoolKey
/// @param factory The Uniswap V3 factory contract address
/// @param key The PoolKey
/// @return pool The contract address of the V3 pool
function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
require(key.token0 < key.token1);
pool = address(
uint256(
keccak256(
abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encode(key.token0, key.token1, key.fee)),
POOL_INIT_CODE_HASH
)
)
)
);
}
}
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later
pragma solidity >=0.7.0;
/// @title Optimized overflow and underflow safe math operations
/// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost
library LowGasSafeMath {
/// @notice Returns x + y, reverts if sum overflows uint256
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
/// @notice Returns x - y, reverts if underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
/// @notice Returns x * y, reverts if overflows
/// @param x The multiplicand
/// @param y The multiplier
/// @return z The product of x and y
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(x == 0 || (z = x * y) / x == y);
}
/// @notice Returns x + y, reverts if overflows or underflows
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x + y) >= x == (y >= 0));
}
/// @notice Returns x - y, reverts if overflows or underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x - y) <= x == (y >= 0));
}
}
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later
pragma solidity >=0.5.0;
////import './pool/IUniswapV3PoolImmutables.sol';
////import './pool/IUniswapV3PoolState.sol';
////import './pool/IUniswapV3PoolDerivedState.sol';
////import './pool/IUniswapV3PoolActions.sol';
////import './pool/IUniswapV3PoolOwnerActions.sol';
////import './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(MAX_TICK), 'T');
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R');
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity >=0.4.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = -denominator & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later
pragma solidity >=0.5.0 <0.8.0;
////import '@uniswap/v3-core/contracts/libraries/FullMath.sol';
////import '@uniswap/v3-core/contracts/libraries/TickMath.sol';
////import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';
////import '@uniswap/v3-core/contracts/libraries/LowGasSafeMath.sol';
////import '../libraries/PoolAddress.sol';
/// @title Oracle library
/// @notice Provides functions to integrate with V3 pool oracle
library OracleLibrary {
/// @notice Fetches time-weighted average tick using Uniswap V3 oracle
/// @param pool Address of Uniswap V3 pool that we want to observe
/// @param period Number of seconds in the past to start calculating time-weighted average
/// @return timeWeightedAverageTick The time-weighted average tick from (block.timestamp - period) to block.timestamp
function consult(address pool, uint32 period) internal view returns (int24 timeWeightedAverageTick) {
require(period != 0, 'BP');
uint32[] memory secondAgos = new uint32[](2);
secondAgos[0] = period;
secondAgos[1] = 0;
(int56[] memory tickCumulatives, ) = IUniswapV3Pool(pool).observe(secondAgos);
int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];
timeWeightedAverageTick = int24(tickCumulativesDelta / period);
// Always round to negative infinity
if (tickCumulativesDelta < 0 && (tickCumulativesDelta % period != 0)) timeWeightedAverageTick--;
}
/// @notice Given a tick and a token amount, calculates the amount of token received in exchange
/// @param tick Tick value used to calculate the quote
/// @param baseAmount Amount of token to be converted
/// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination
/// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination
/// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken
function getQuoteAtTick(
int24 tick,
uint128 baseAmount,
address baseToken,
address quoteToken
) internal pure returns (uint256 quoteAmount) {
uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);
// Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself
if (sqrtRatioX96 <= type(uint128).max) {
uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96;
quoteAmount = baseToken < quoteToken
? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192)
: FullMath.mulDiv(1 << 192, baseAmount, ratioX192);
} else {
uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64);
quoteAmount = baseToken < quoteToken
? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128)
: FullMath.mulDiv(1 << 128, baseAmount, ratioX128);
}
}
}
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later
pragma solidity >=0.5.0;
////import '@uniswap/v3-core/contracts/libraries/FullMath.sol';
////import '@uniswap/v3-core/contracts/libraries/FixedPoint96.sol';
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
/// @notice Downcasts uint256 to uint128
/// @param x The uint258 to be downcasted
/// @return y The passed value, downcasted to uint128
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x);
}
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range
/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount0 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount0(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount1 The amount1 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount1(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount of token0 being sent in
/// @param amount1 The amount of token1 being sent in
/// @return liquidity The maximum amount of liquidity received
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
function getAmount0ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
) / sqrtRatioAX96;
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount1 The amount of token1
function getAmount1ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
}
/// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
}
}
}
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity ^0.7.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [////IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* ////IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, 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-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* ////IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: BUSL-1.1
pragma solidity 0.7.6;
interface IICHIVaultFactory {
event FeeRecipient(
address indexed sender,
address feeRecipient);
event BaseFee(
address indexed sender,
uint256 baseFee);
event BaseFeeSplit(
address indexed sender,
uint256 baseFeeSplit);
event DeployICHIVaultFactory(
address indexed sender,
address uniswapV3Factory);
event ICHIVaultCreated(
address indexed sender,
address ichiVault,
address tokenA,
bool allowTokenA,
address tokenB,
bool allowTokenB,
uint24 fee,
uint256 count);
function uniswapV3Factory() external view returns(address);
function feeRecipient() external view returns(address);
function baseFee() external view returns(uint256);
function baseFeeSplit() external view returns(uint256);
function setFeeRecipient(address _feeRecipient) external;
function setBaseFee(uint256 _baseFee) external;
function setBaseFeeSplit(uint256 _baseFeeSplit) external;
function createICHIVault(
address tokenA,
bool allowTokenA,
address tokenB,
bool allowTokenB,
uint24 fee
) external returns (address ichiVault);
function genKey(
address deployer,
address token0,
address token1,
uint24 fee,
bool allowToken0,
bool allowToken1) external pure returns(bytes32 key);
}
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: Unlicense
pragma solidity 0.7.6;
interface IICHIVault{
function ichiVaultFactory() external view returns(address);
function pool() external view returns(address);
function token0() external view returns(address);
function allowToken0() external view returns(bool);
function token1() external view returns(address);
function allowToken1() external view returns(bool);
function fee() external view returns(uint24);
function tickSpacing() external view returns(int24);
function affiliate() external view returns(address);
function baseLower() external view returns(int24);
function baseUpper() external view returns(int24);
function limitLower() external view returns(int24);
function limitUpper() external view returns(int24);
function deposit0Max() external view returns(uint256);
function deposit1Max() external view returns(uint256);
function maxTotalSupply() external view returns(uint256);
function hysteresis() external view returns(uint256);
function getTotalAmounts() external view returns (uint256, uint256);
function deposit(
uint256,
uint256,
address
) external returns (uint256);
function withdraw(
uint256,
address
) external returns (uint256, uint256);
function rebalance(
int24 _baseLower,
int24 _baseUpper,
int24 _limitLower,
int24 _limitUpper,
int256 swapQuantity
) external;
function setDepositMax(
uint256 _deposit0Max,
uint256 _deposit1Max) external;
function setAffiliate(
address _affiliate) external;
event DeployICHIVault(
address indexed sender,
address indexed pool,
bool allowToken0,
bool allowToken1,
address owner,
uint256 twapPeriod);
event SetTwapPeriod(
address sender,
uint32 newTwapPeriod
);
event Deposit(
address indexed sender,
address indexed to,
uint256 shares,
uint256 amount0,
uint256 amount1
);
event Withdraw(
address indexed sender,
address indexed to,
uint256 shares,
uint256 amount0,
uint256 amount1
);
event Rebalance(
int24 tick,
uint256 totalAmount0,
uint256 totalAmount1,
uint256 feeAmount0,
uint256 feeAmount1,
uint256 totalSupply
);
event MaxTotalSupply(
address indexed sender,
uint256 maxTotalSupply);
event Hysteresis(
address indexed sender,
uint256 hysteresis);
event DepositMax(
address indexed sender,
uint256 deposit0Max,
uint256 deposit1Max);
event Affiliate(
address indexed sender,
address affiliate);
}
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#mint
/// @notice Any contract that calls IUniswapV3PoolActions#mint must implement this interface
interface IUniswapV3MintCallback {
/// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint.
/// @dev In the implementation you must pay the pool tokens owed for the minted liquidity.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// @param amount0Owed The amount of token0 due to the pool for the minted liquidity
/// @param amount1Owed The amount of token1 due to the pool for the minted liquidity
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call
function uniswapV3MintCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata data
) external;
}
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity ^0.7.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-FLATTEN-SUPPRESS-WARNING: BUSL-1.1
pragma solidity 0.7.6;
////import {TickMath} from "@uniswap/v3-core/contracts/libraries/TickMath.sol";
////import {LiquidityAmounts} from "@uniswap/v3-periphery/contracts/libraries/LiquidityAmounts.sol";
////import {OracleLibrary} from "@uniswap/v3-periphery/contracts/libraries/OracleLibrary.sol";
library UV3Math {
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/*******************
* Tick Math
*******************/
function getSqrtRatioAtTick(
int24 currentTick
) public pure returns(uint160 sqrtPriceX96) {
sqrtPriceX96 = TickMath.getSqrtRatioAtTick(currentTick);
}
/*******************
* LiquidityAmounts
*******************/
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) public pure returns (uint256 amount0, uint256 amount1) {
(amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity(
sqrtRatioX96,
sqrtRatioAX96,
sqrtRatioBX96,
liquidity);
}
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) public pure returns (uint128 liquidity) {
liquidity = LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
sqrtRatioAX96,
sqrtRatioBX96,
amount0,
amount1);
}
/*******************
* OracleLibrary
*******************/
function consult(
address _pool,
uint32 _twapPeriod
) public view returns(int24 timeWeightedAverageTick) {
timeWeightedAverageTick = OracleLibrary.consult(_pool, _twapPeriod);
}
function getQuoteAtTick(
int24 tick,
uint128 baseAmount,
address baseToken,
address quoteToken
) public pure returns (uint256 quoteAmount) {
quoteAmount = OracleLibrary.getQuoteAtTick(tick, baseAmount, baseToken, quoteToken);
}
/*******************
* SafeUnit128
*******************/
/// @notice Cast a uint256 to a uint128, revert on overflow
/// @param y The uint256 to be downcasted
/// @return z The downcasted integer, now type uint128
function toUint128(uint256 y) public pure returns (uint128 z) {
require((z = uint128(y)) == y, "SafeUint128: overflow");
}
}
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity ^0.7.0;
////import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity ^0.7.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-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity ^0.7.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_) {
_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-FLATTEN-SUPPRESS-WARNING: BUSL-1.1
pragma solidity 0.7.6;
////import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
////import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
////import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
////import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
////import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
////import {UV3Math} from "./lib/UV3Math.sol";
////import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
////import {IUniswapV3MintCallback} from "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3MintCallback.sol";
////import {IUniswapV3SwapCallback} from "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol";
////import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
////import {IICHIVault} from "../interfaces/IICHIVault.sol";
////import {IICHIVaultFactory} from "../interfaces/IICHIVaultFactory.sol";
/**
@notice A Uniswap V2-like interface with fungible liquidity to Uniswap V3
which allows for either one-sided or two-sided liquidity provision.
ICHIVaults should be deployed by the ICHIVaultFactory.
ICHIVaults should not be used with tokens that charge transaction fees.
*/
contract ICHIVault is
IICHIVault,
IUniswapV3MintCallback,
IUniswapV3SwapCallback,
ERC20,
ReentrancyGuard,
Ownable
{
using SafeERC20 for IERC20;
using SafeMath for uint256;
address public immutable override ichiVaultFactory;
address public immutable override pool;
address public immutable override token0;
address public immutable override token1;
bool public immutable override allowToken0;
bool public immutable override allowToken1;
uint24 public immutable override fee;
int24 public immutable override tickSpacing;
address public override affiliate;
int24 public override baseLower;
int24 public override baseUpper;
int24 public override limitLower;
int24 public override limitUpper;
// The following three variables serve the very ////important purpose of
// limiting inventory risk and the arbitrage opportunities made possible by
// instant deposit & withdrawal.
// If, in the ETHUSDT pool at an ETH price of 2500 USDT, I deposit 100k
// USDT in a pool with 40 WETH, and then directly afterwards withdraw 50k
// USDT and 20 WETH (this is of equivalent dollar value), I drastically
// change the pool composition and additionally decreases deployed capital
// by 50%. Keeping a maxTotalSupply just above our current total supply
// means that large amounts of funds can't be deposited all at once to
// create a large imbalance of funds or to sideline many funds.
// Additionally, deposit maximums prevent users from using the pool as
// a counterparty to trade assets against while avoiding uniswap fees
// & slippage--if someone were to try to do this with a large amount of
// capital they would be overwhelmed by the gas fees necessary to call
// deposit & withdrawal many times.
uint256 public override deposit0Max;
uint256 public override deposit1Max;
uint256 public override maxTotalSupply;
uint256 public override hysteresis;
uint256 public constant PRECISION = 10**18;
uint256 constant PERCENT = 100;
address constant NULL_ADDRESS = address(0);
uint32 public twapPeriod;
/**
@notice creates an instance of ICHIVault based on the pool. allowToken parameters control whether the ICHIVault allows one-sided or two-sided liquidity provision
@param _pool Uniswap V3 pool for which liquidity is managed
@param _allowToken0 flag that indicates whether token0 is accepted during deposit
@param _allowToken1 flag that indicates whether token1 is accepted during deposit
@param __owner Owner of the ICHIVault
*/
constructor(
address _pool,
bool _allowToken0,
bool _allowToken1,
address __owner,
uint32 _twapPeriod
) ERC20("ICHI Vault Liquidity", "ICHI_Vault_LP") {
require(_pool != NULL_ADDRESS, "IV.constructor: zero address");
require(_allowToken0 || _allowToken1, 'IV.constructor: no allowed tokens');
ichiVaultFactory = msg.sender;
pool = _pool;
token0 = IUniswapV3Pool(_pool).token0();
token1 = IUniswapV3Pool(_pool).token1();
fee = IUniswapV3Pool(_pool).fee();
allowToken0 = _allowToken0;
allowToken1 = _allowToken1;
twapPeriod = _twapPeriod;
tickSpacing = IUniswapV3Pool(_pool).tickSpacing();
transferOwnership(__owner);
maxTotalSupply = 0; // no cap
hysteresis = PRECISION.div(PERCENT); // 1% threshold
deposit0Max = uint256(-1); // max uint256
deposit1Max = uint256(-1); // max uint256
affiliate = NULL_ADDRESS; // by default there is no affiliate address
emit DeployICHIVault(
msg.sender,
_pool,
_allowToken0,
_allowToken1,
__owner,
_twapPeriod
);
}
function setTwapPeriod(uint32 newTwapPeriod) external onlyOwner {
require(newTwapPeriod > 0, "IV.setTwapPeriod: missing period");
twapPeriod = newTwapPeriod;
emit SetTwapPeriod(msg.sender, newTwapPeriod);
}
/**
@notice Distributes shares to depositor equal to the token1 value of his deposit multiplied by the ratio of total liquidity shares issued divided by the pool's AUM measured in token1 value.
@param deposit0 Amount of token0 transfered from sender to ICHIVault
@param deposit1 Amount of token0 transfered from sender to ICHIVault
@param to Address to which liquidity tokens are minted
@param shares Quantity of liquidity tokens minted as a result of deposit
*/
function deposit(
uint256 deposit0,
uint256 deposit1,
address to
) external override nonReentrant returns (uint256 shares) {
require(allowToken0 || deposit0 == 0, "IV.deposit: token0 not allowed");
require(allowToken1 || deposit1 == 0, "IV.deposit: token1 not allowed");
require(
deposit0 > 0 || deposit1 > 0,
"IV.deposit: deposits must be > 0"
);
require(
deposit0 < deposit0Max && deposit1 < deposit1Max,
"IV.deposit: deposits too large"
);
require(to != NULL_ADDRESS && to != address(this), "IV.deposit: to");
// update fees for inclusion in total pool amounts
(uint128 baseLiquidity, , ) = _position(baseLower, baseUpper);
if (baseLiquidity > 0) {
(uint burn0, uint burn1) = IUniswapV3Pool(pool).burn(baseLower, baseUpper, 0);
require(burn0 == 0 && burn1 == 0, "IV.deposit: unexpected burn (1)");
}
(uint128 limitLiquidity, , ) = _position(limitLower, limitUpper);
if (limitLiquidity > 0) {
(uint burn0, uint burn1) = IUniswapV3Pool(pool).burn(limitLower, limitUpper, 0);
require(burn0 == 0 && burn1 == 0, "IV.deposit: unexpected burn (2)");
}
// Spot
uint256 price = _fetchSpot(
token0,
token1,
currentTick(),
PRECISION
);
// TWAP
uint256 twap = _fetchTwap(
pool,
token0,
token1,
twapPeriod,
PRECISION);
// if difference between spot and twap is too big, check if the price may have been manipulated in this block
uint256 delta = (price > twap) ? price.sub(twap).mul(PRECISION).div(price) : twap.sub(price).mul(PRECISION).div(twap);
if (delta > hysteresis) require(checkHysteresis(), "IV.deposit: try later");
(uint256 pool0, uint256 pool1) = getTotalAmounts();
// aggregated deposit
uint256 deposit0PricedInToken1 = deposit0.mul((price < twap) ? price : twap).div(PRECISION);
if (deposit0 > 0) {
IERC20(token0).safeTransferFrom(
msg.sender,
address(this),
deposit0
);
}
if (deposit1 > 0) {
IERC20(token1).safeTransferFrom(
msg.sender,
address(this),
deposit1
);
}
shares = deposit1.add(deposit0PricedInToken1);
if (totalSupply() != 0) {
uint256 pool0PricedInToken1 = pool0.mul((price > twap) ? price : twap).div(PRECISION);
shares = shares.mul(totalSupply()).div(
pool0PricedInToken1.add(pool1)
);
}
_mint(to, shares);
emit Deposit(msg.sender, to, shares, deposit0, deposit1);
// Check total supply cap not exceeded. A value of 0 means no limit.
require(
maxTotalSupply == 0 || totalSupply() <= maxTotalSupply,
"IV.deposit: maxTotalSupply"
);
}
/**
@notice Redeems shares by sending out a percentage of the ICHIVault's AUM - this percentage is equal to the percentage of total issued shares represented by the redeeemed shares.
@param shares Number of liquidity tokens to redeem as pool assets
@param to Address to which redeemed pool assets are sent
@param amount0 Amount of token0 redeemed by the submitted liquidity tokens
@param amount1 Amount of token1 redeemed by the submitted liquidity tokens
*/
function withdraw(uint256 shares, address to)
external
override
nonReentrant
returns (uint256 amount0, uint256 amount1)
{
require(shares > 0, "IV.withdraw: shares");
require(to != NULL_ADDRESS, "IV.withdraw: to");
// Withdraw liquidity from Uniswap pool
(uint256 base0, uint256 base1) = _burnLiquidity(
baseLower,
baseUpper,
_liquidityForShares(baseLower, baseUpper, shares),
to,
false
);
(uint256 limit0, uint256 limit1) = _burnLiquidity(
limitLower,
limitUpper,
_liquidityForShares(limitLower, limitUpper, shares),
to,
false
);
// Push tokens proportional to unused balances
uint256 _totalSupply = totalSupply();
uint256 unusedAmount0 = IERC20(token0)
.balanceOf(address(this))
.mul(shares)
.div(_totalSupply);
uint256 unusedAmount1 = IERC20(token1)
.balanceOf(address(this))
.mul(shares)
.div(_totalSupply);
if (unusedAmount0 > 0) IERC20(token0).safeTransfer(to, unusedAmount0);
if (unusedAmount1 > 0) IERC20(token1).safeTransfer(to, unusedAmount1);
amount0 = base0.add(limit0).add(unusedAmount0);
amount1 = base1.add(limit1).add(unusedAmount1);
_burn(msg.sender, shares);
emit Withdraw(msg.sender, to, shares, amount0, amount1);
}
/**
@notice Updates ICHIVault's LP positions.
@dev The base position is placed first with as much liquidity as possible and is typically symmetric around the current price. This order should use up all of one token, leaving some unused quantity of the other. This unused amount is then placed as a single-sided order.
@param _baseLower The lower tick of the base position
@param _baseUpper The upper tick of the base position
@param _limitLower The lower tick of the limit position
@param _limitUpper The upper tick of the limit position
@param swapQuantity Quantity of tokens to swap; if quantity is positive, `swapQuantity` token0 are swaped for token1, if negative, `swapQuantity` token1 is swaped for token0
*/
function rebalance(
int24 _baseLower,
int24 _baseUpper,
int24 _limitLower,
int24 _limitUpper,
int256 swapQuantity
) external override nonReentrant onlyOwner {
require(
_baseLower < _baseUpper &&
_baseLower % tickSpacing == 0 &&
_baseUpper % tickSpacing == 0,
"IV.rebalance: base position invalid"
);
require(
_limitLower < _limitUpper &&
_limitLower % tickSpacing == 0 &&
_limitUpper % tickSpacing == 0,
"IV.rebalance: limit position invalid"
);
// update fees
(uint128 baseLiquidity, , ) = _position(baseLower, baseUpper);
if (baseLiquidity > 0) {
IUniswapV3Pool(pool).burn(baseLower, baseUpper, 0);
}
(uint128 limitLiquidity, , ) = _position(limitLower, limitUpper);
if (limitLiquidity > 0) {
IUniswapV3Pool(pool).burn(limitLower, limitUpper, 0);
}
// Withdraw all liquidity and collect all fees from Uniswap pool
(, uint256 feesBase0, uint256 feesBase1) = _position(
baseLower,
baseUpper
);
(, uint256 feesLimit0, uint256 feesLimit1) = _position(
limitLower,
limitUpper
);
uint256 fees0 = feesBase0.add(feesLimit0);
uint256 fees1 = feesBase1.add(feesLimit1);
_burnLiquidity(
baseLower,
baseUpper,
baseLiquidity,
address(this),
true
);
_burnLiquidity(
limitLower,
limitUpper,
limitLiquidity,
address(this),
true
);
_distributeFees(fees0, fees1);
emit Rebalance(
currentTick(),
IERC20(token0).balanceOf(address(this)),
IERC20(token1).balanceOf(address(this)),
fees0,
fees1,
totalSupply()
);
// swap tokens if required
if (swapQuantity != 0) {
IUniswapV3Pool(pool).swap(
address(this),
swapQuantity > 0,
swapQuantity > 0 ? swapQuantity : -swapQuantity,
swapQuantity > 0
? UV3Math.MIN_SQRT_RATIO + 1
: UV3Math.MAX_SQRT_RATIO - 1,
abi.encode(address(this))
);
}
baseLower = _baseLower;
baseUpper = _baseUpper;
baseLiquidity = _liquidityForAmounts(
baseLower,
baseUpper,
IERC20(token0).balanceOf(address(this)),
IERC20(token1).balanceOf(address(this))
);
_mintLiquidity(baseLower, baseUpper, baseLiquidity);
limitLower = _limitLower;
limitUpper = _limitUpper;
limitLiquidity = _liquidityForAmounts(
limitLower,
limitUpper,
IERC20(token0).balanceOf(address(this)),
IERC20(token1).balanceOf(address(this))
);
_mintLiquidity(limitLower, limitUpper, limitLiquidity);
}
/**
@notice Sends portion of swap fees to feeRecipient and affiliate.
@param fees0 fees for token0
@param fees1 fees for token1
*/
function _distributeFees(uint256 fees0, uint256 fees1) internal {
uint256 baseFee = IICHIVaultFactory(ichiVaultFactory).baseFee();
// if there is no affiliate 100% of the baseFee should go to feeRecipient
uint256 baseFeeSplit = (affiliate == NULL_ADDRESS)
? PRECISION
: IICHIVaultFactory(ichiVaultFactory).baseFeeSplit();
address feeRecipient = IICHIVaultFactory(ichiVaultFactory).feeRecipient();
require(baseFee <= PRECISION, "IV.rebalance: fee must be <= 10**18");
require(baseFeeSplit <= PRECISION, "IV.rebalance: split must be <= 10**18");
require(feeRecipient != NULL_ADDRESS, "IV.rebalance: zero address");
if (baseFee > 0) {
if (fees0 > 0) {
uint256 totalFee = fees0.mul(baseFee).div(PRECISION);
uint256 toRecipient = totalFee.mul(baseFeeSplit).div(PRECISION);
uint256 toAffiliate = totalFee.sub(toRecipient);
IERC20(token0).safeTransfer(feeRecipient, toRecipient);
if (toAffiliate > 0) {
IERC20(token0).safeTransfer(affiliate, toAffiliate);
}
}
if (fees1 > 0) {
uint256 totalFee = fees1.mul(baseFee).div(PRECISION);
uint256 toRecipient = totalFee.mul(baseFeeSplit).div(PRECISION);
uint256 toAffiliate = totalFee.sub(toRecipient);
IERC20(token1).safeTransfer(feeRecipient, toRecipient);
if (toAffiliate > 0) {
IERC20(token1).safeTransfer(affiliate, toAffiliate);
}
}
}
}
/**
@notice Mint liquidity in Uniswap V3 pool.
@param tickLower The lower tick of the liquidity position
@param tickUpper The upper tick of the liquidity position
@param liquidity Amount of liquidity to mint
@param amount0 Used amount of token0
@param amount1 Used amount of token1
*/
function _mintLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity
) internal returns (uint256 amount0, uint256 amount1) {
if (liquidity > 0) {
(amount0, amount1) = IUniswapV3Pool(pool).mint(
address(this),
tickLower,
tickUpper,
liquidity,
abi.encode(address(this))
);
}
}
/**
@notice Burn liquidity in Uniswap V3 pool.
@param tickLower The lower tick of the liquidity position
@param tickUpper The upper tick of the liquidity position
@param liquidity amount of liquidity to burn
@param to The account to receive token0 and token1 amounts
@param collectAll Flag that indicates whether all token0 and token1 tokens should be collected or only the ones released during this burn
@param amount0 released amount of token0
@param amount1 released amount of token1
*/
function _burnLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
address to,
bool collectAll
) internal returns (uint256 amount0, uint256 amount1) {
if (liquidity > 0) {
// Burn liquidity
(uint256 owed0, uint256 owed1) = IUniswapV3Pool(pool).burn(
tickLower,
tickUpper,
liquidity
);
// Collect amount owed
uint128 collect0 = collectAll
? type(uint128).max
: _uint128Safe(owed0);
uint128 collect1 = collectAll
? type(uint128).max
: _uint128Safe(owed1);
if (collect0 > 0 || collect1 > 0) {
(amount0, amount1) = IUniswapV3Pool(pool).collect(
to,
tickLower,
tickUpper,
collect0,
collect1
);
}
}
}
/**
@notice Calculates liquidity amount for the given shares.
@param tickLower The lower tick of the liquidity position
@param tickUpper The upper tick of the liquidity position
@param shares number of shares
*/
function _liquidityForShares(
int24 tickLower,
int24 tickUpper,
uint256 shares
) internal view returns (uint128) {
(uint128 position, , ) = _position(tickLower, tickUpper);
return _uint128Safe(uint256(position).mul(shares).div(totalSupply()));
}
/**
@notice Returns information about the liquidity position.
@param tickLower The lower tick of the liquidity position
@param tickUpper The upper tick of the liquidity position
@param liquidity liquidity amount
@param tokensOwed0 amount of token0 owed to the owner of the position
@param tokensOwed1 amount of token1 owed to the owner of the position
*/
function _position(int24 tickLower, int24 tickUpper)
internal
view
returns (
uint128 liquidity,
uint128 tokensOwed0,
uint128 tokensOwed1
)
{
bytes32 positionKey = keccak256(
abi.encodePacked(address(this), tickLower, tickUpper)
);
(liquidity, , , tokensOwed0, tokensOwed1) = IUniswapV3Pool(pool)
.positions(positionKey);
}
/**
@notice Callback function for mint
@dev this is where the payer transfers required token0 and token1 amounts
@param amount0 required amount of token0
@param amount1 required amount of token1
@param data encoded payer's address
*/
function uniswapV3MintCallback(
uint256 amount0,
uint256 amount1,
bytes calldata data
) external override {
require(msg.sender == address(pool), "cb1");
address payer = abi.decode(data, (address));
if (payer == address(this)) {
if (amount0 > 0) IERC20(token0).safeTransfer(msg.sender, amount0);
if (amount1 > 0) IERC20(token1).safeTransfer(msg.sender, amount1);
} else {
if (amount0 > 0)
IERC20(token0).safeTransferFrom(payer, msg.sender, amount0);
if (amount1 > 0)
IERC20(token1).safeTransferFrom(payer, msg.sender, amount1);
}
}
/**
@notice Callback function for swap
@dev this is where the payer transfers required token0 and token1 amounts
@param amount0Delta required amount of token0
@param amount1Delta required amount of token1
@param data encoded payer's address
*/
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external override {
require(msg.sender == address(pool), "cb2");
address payer = abi.decode(data, (address));
if (amount0Delta > 0) {
if (payer == address(this)) {
IERC20(token0).safeTransfer(msg.sender, uint256(amount0Delta));
} else {
IERC20(token0).safeTransferFrom(
payer,
msg.sender,
uint256(amount0Delta)
);
}
} else if (amount1Delta > 0) {
if (payer == address(this)) {
IERC20(token1).safeTransfer(msg.sender, uint256(amount1Delta));
} else {
IERC20(token1).safeTransferFrom(
payer,
msg.sender,
uint256(amount1Delta)
);
}
}
}
/**
@notice Checks if the last price change happened in the current block
*/
function checkHysteresis() private view returns(bool) {
(, , uint16 observationIndex, , , , ) = IUniswapV3Pool(pool).slot0();
(uint32 blockTimestamp, , ,) = IUniswapV3Pool(pool).observations(observationIndex);
return( block.timestamp != blockTimestamp );
}
/**
@notice Sets the maximum liquidity token supply the contract allows
@dev onlyOwner
@param _maxTotalSupply The maximum liquidity token supply the contract allows
*/
function setMaxTotalSupply(uint256 _maxTotalSupply) external onlyOwner {
maxTotalSupply = _maxTotalSupply;
emit MaxTotalSupply(msg.sender, _maxTotalSupply);
}
/**
@notice Sets the hysteresis threshold (in percentage points, 10**16 = 1%). When difference between spot price and TWAP exceeds the threshold, a check for a flashloan attack is executed
@dev onlyOwner
@param _hysteresis hysteresis threshold
*/
function setHysteresis(uint256 _hysteresis) external onlyOwner {
hysteresis = _hysteresis;
emit Hysteresis(msg.sender, _hysteresis);
}
/**
@notice Sets the affiliate account address where portion of the collected swap fees will be distributed
@dev onlyOwner
@param _affiliate The affiliate account address
*/
function setAffiliate(address _affiliate) external override onlyOwner {
affiliate = _affiliate;
emit Affiliate(msg.sender, _affiliate);
}
/**
@notice Sets the maximum token0 and token1 amounts the contract allows in a deposit
@dev onlyOwner
@param _deposit0Max The maximum amount of token0 allowed in a deposit
@param _deposit1Max The maximum amount of token1 allowed in a deposit
*/
function setDepositMax(uint256 _deposit0Max, uint256 _deposit1Max)
external
override
onlyOwner
{
deposit0Max = _deposit0Max;
deposit1Max = _deposit1Max;
emit DepositMax(msg.sender, _deposit0Max, _deposit1Max);
}
/**
@notice Calculates token0 and token1 amounts for liquidity in a position
@param tickLower The lower tick of the liquidity position
@param tickUpper The upper tick of the liquidity position
@param liquidity Amount of liquidity in the position
*/
function _amountsForLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity
) internal view returns (uint256, uint256) {
(uint160 sqrtRatioX96, , , , , , ) = IUniswapV3Pool(pool).slot0();
return
UV3Math.getAmountsForLiquidity(
sqrtRatioX96,
UV3Math.getSqrtRatioAtTick(tickLower),
UV3Math.getSqrtRatioAtTick(tickUpper),
liquidity
);
}
/**
@notice Calculates amount of liquidity in a position for given token0 and token1 amounts
@param tickLower The lower tick of the liquidity position
@param tickUpper The upper tick of the liquidity position
@param amount0 token0 amount
@param amount1 token1 amount
*/
function _liquidityForAmounts(
int24 tickLower,
int24 tickUpper,
uint256 amount0,
uint256 amount1
) internal view returns (uint128) {
(uint160 sqrtRatioX96, , , , , , ) = IUniswapV3Pool(pool).slot0();
return
UV3Math.getLiquidityForAmounts(
sqrtRatioX96,
UV3Math.getSqrtRatioAtTick(tickLower),
UV3Math.getSqrtRatioAtTick(tickUpper),
amount0,
amount1
);
}
/**
@notice uint128Safe function
@param x input value
*/
function _uint128Safe(uint256 x) internal pure returns (uint128) {
require(x <= type(uint128).max, "IV.128_OF");
return uint128(x);
}
/**
@notice Calculates total quantity of token0 and token1 in both positions (and unused in the ICHIVault)
@param total0 Quantity of token0 in both positions (and unused in the ICHIVault)
@param total1 Quantity of token1 in both positions (and unused in the ICHIVault)
*/
function getTotalAmounts()
public
view
override
returns (uint256 total0, uint256 total1)
{
(, uint256 base0, uint256 base1) = getBasePosition();
(, uint256 limit0, uint256 limit1) = getLimitPosition();
total0 = IERC20(token0).balanceOf(address(this)).add(base0).add(limit0);
total1 = IERC20(token1).balanceOf(address(this)).add(base1).add(limit1);
}
/**
@notice Calculates amount of total liquidity in the base position
@param liquidity Amount of total liquidity in the base position
@param amount0 Estimated amount of token0 that could be collected by burning the base position
@param amount1 Estimated amount of token1 that could be collected by burning the base position
*/
function getBasePosition()
public
view
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
)
{
(
uint128 positionLiquidity,
uint128 tokensOwed0,
uint128 tokensOwed1
) = _position(baseLower, baseUpper);
(amount0, amount1) = _amountsForLiquidity(
baseLower,
baseUpper,
positionLiquidity
);
liquidity = positionLiquidity;
amount0 = amount0.add(uint256(tokensOwed0));
amount1 = amount1.add(uint256(tokensOwed1));
}
/**
@notice Calculates amount of total liquidity in the limit position
@param liquidity Amount of total liquidity in the base position
@param amount0 Estimated amount of token0 that could be collected by burning the limit position
@param amount1 Estimated amount of token1 that could be collected by burning the limit position
*/
function getLimitPosition()
public
view
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
)
{
(
uint128 positionLiquidity,
uint128 tokensOwed0,
uint128 tokensOwed1
) = _position(limitLower, limitUpper);
(amount0, amount1) = _amountsForLiquidity(
limitLower,
limitUpper,
positionLiquidity
);
liquidity = positionLiquidity;
amount0 = amount0.add(uint256(tokensOwed0));
amount1 = amount1.add(uint256(tokensOwed1));
}
/**
@notice Returns current price tick
@param tick Uniswap pool's current price tick
*/
function currentTick() public view returns (int24 tick) {
(, int24 tick_, , , , , bool unlocked_) = IUniswapV3Pool(pool).slot0();
require(unlocked_, "IV.currentTick: the pool is locked");
tick = tick_;
}
/**
@notice returns equivalent _tokenOut for _amountIn, _tokenIn using spot price
@param _tokenIn token the input amount is in
@param _tokenOut token for the output amount
@param _tick tick for the spot price
@param _amountIn amount in _tokenIn
@param amountOut equivalent anount in _tokenOut
*/
function _fetchSpot(
address _tokenIn,
address _tokenOut,
int24 _tick,
uint256 _amountIn
) internal pure returns (uint256 amountOut) {
return
UV3Math.getQuoteAtTick(
_tick,
UV3Math.toUint128(_amountIn),
_tokenIn,
_tokenOut
);
}
/**
@notice returns equivalent _tokenOut for _amountIn, _tokenIn using TWAP price
@param _pool Uniswap V3 pool address to be used for price checking
@param _tokenIn token the input amount is in
@param _tokenOut token for the output amount
@param _twapPeriod the averaging time period
@param _amountIn amount in _tokenIn
@param amountOut equivalent anount in _tokenOut
*/
function _fetchTwap(
address _pool,
address _tokenIn,
address _tokenOut,
uint32 _twapPeriod,
uint256 _amountIn
) internal view returns (uint256 amountOut) {
// Leave twapTick as a int256 to avoid solidity casting
int256 twapTick = UV3Math.consult(_pool, _twapPeriod);
return
UV3Math.getQuoteAtTick(
int24(twapTick), // can assume safe being result from consult()
UV3Math.toUint128(_amountIn),
_tokenIn,
_tokenOut
);
}
} | / Burn liquidity Collect amount owed | function _burnLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
address to,
bool collectAll
) internal returns (uint256 amount0, uint256 amount1) {
if (liquidity > 0) {
(uint256 owed0, uint256 owed1) = IUniswapV3Pool(pool).burn(
tickLower,
tickUpper,
liquidity
);
uint128 collect0 = collectAll
? type(uint128).max
: _uint128Safe(owed0);
uint128 collect1 = collectAll
? type(uint128).max
: _uint128Safe(owed1);
if (collect0 > 0 || collect1 > 0) {
(amount0, amount1) = IUniswapV3Pool(pool).collect(
to,
tickLower,
tickUpper,
collect0,
collect1
);
}
}
}
@param tickLower The lower tick of the liquidity position
@param tickUpper The upper tick of the liquidity position
@param shares number of shares
| 1,119,772 | [
1,
19,
605,
321,
4501,
372,
24237,
9302,
3844,
2523,
329,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
389,
70,
321,
48,
18988,
24237,
12,
203,
3639,
509,
3247,
4024,
4070,
16,
203,
3639,
509,
3247,
4024,
5988,
16,
203,
3639,
2254,
10392,
4501,
372,
24237,
16,
203,
3639,
1758,
358,
16,
203,
3639,
1426,
3274,
1595,
203,
565,
262,
2713,
1135,
261,
11890,
5034,
3844,
20,
16,
2254,
5034,
3844,
21,
13,
288,
203,
3639,
309,
261,
549,
372,
24237,
405,
374,
13,
288,
203,
5411,
261,
11890,
5034,
2523,
329,
20,
16,
2254,
5034,
2523,
329,
21,
13,
273,
467,
984,
291,
91,
438,
58,
23,
2864,
12,
6011,
2934,
70,
321,
12,
203,
7734,
4024,
4070,
16,
203,
7734,
4024,
5988,
16,
203,
7734,
4501,
372,
24237,
203,
5411,
11272,
203,
203,
5411,
2254,
10392,
3274,
20,
273,
3274,
1595,
203,
7734,
692,
618,
12,
11890,
10392,
2934,
1896,
203,
7734,
294,
389,
11890,
10392,
9890,
12,
543,
329,
20,
1769,
203,
5411,
2254,
10392,
3274,
21,
273,
3274,
1595,
203,
7734,
692,
618,
12,
11890,
10392,
2934,
1896,
203,
7734,
294,
389,
11890,
10392,
9890,
12,
543,
329,
21,
1769,
203,
5411,
309,
261,
14676,
20,
405,
374,
747,
3274,
21,
405,
374,
13,
288,
203,
7734,
261,
8949,
20,
16,
3844,
21,
13,
273,
467,
984,
291,
91,
438,
58,
23,
2864,
12,
6011,
2934,
14676,
12,
203,
10792,
358,
16,
203,
10792,
4024,
4070,
16,
203,
10792,
4024,
5988,
16,
203,
10792,
3274,
20,
16,
203,
10792,
3274,
21,
203,
7734,
11272,
203,
5411,
289,
203,
3639,
289,
203,
565,
289,
203,
203,
377,
2
] |
./full_match/1/0x39Ac1AC1B7c45b3E78f1290a542D428E7aB8E59C/sources/browser/XTrinity_flat.sol | 3-pool DAI/USDC/USDT
| address constant CURVE_ADDRESS = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; | 4,980,394 | [
1,
23,
17,
6011,
463,
18194,
19,
3378,
5528,
19,
3378,
9081,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1758,
5381,
4706,
3412,
67,
15140,
273,
374,
6114,
41,
13459,
6334,
8285,
22,
39,
27,
72,
38,
20,
69,
21,
37,
4848,
15237,
26,
3030,
10580,
72,
20,
70,
8875,
5082,
1578,
2246,
21,
39,
27,
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
] |
./full_match/1/0xed0941e5dC9141A2b029C65862044A4Cac9e56E9/sources/src/Vault.sol | @dev do not touch debt outside of _lend(), _collect() and _report() | function _report(Strategy _strategy, uint256 _harvested) internal {
uint256 assets = _strategy.totalAssets();
uint256 debt = strategies[_strategy].debt;
uint256 gain;
uint256 loss;
uint256 lockedProfitBefore = lockedProfit();
if (assets > debt) {
unchecked {
gain = assets - debt;
}
totalDebt += gain;
_lockedProfit = lockedProfitBefore + gain + _harvested;
unchecked {
loss = debt - assets;
totalDebt -= loss;
_lockedProfit = lockedProfitBefore + _harvested > loss ? lockedProfitBefore + _harvested - loss : 0;
}
}
uint256 possibleDebt =
totalDebtRatio == 0 ? 0 : totalAssets().mulDivDown(strategies[_strategy].debtRatio, totalDebtRatio);
if (possibleDebt > assets) _lend(_strategy, possibleDebt - assets);
else if (assets > possibleDebt) _collect(_strategy, assets - possibleDebt, address(this));
emit Report(_strategy, _harvested, gain, loss);
}
| 3,219,485 | [
1,
2896,
486,
6920,
18202,
88,
8220,
434,
389,
80,
409,
9334,
389,
14676,
1435,
471,
389,
6006,
1435,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
6006,
12,
4525,
389,
14914,
16,
2254,
5034,
389,
30250,
90,
3149,
13,
2713,
288,
203,
3639,
2254,
5034,
7176,
273,
389,
14914,
18,
4963,
10726,
5621,
203,
3639,
2254,
5034,
18202,
88,
273,
20417,
63,
67,
14914,
8009,
323,
23602,
31,
203,
203,
203,
3639,
2254,
5034,
17527,
31,
203,
3639,
2254,
5034,
8324,
31,
203,
203,
3639,
2254,
5034,
8586,
626,
7216,
4649,
273,
8586,
626,
7216,
5621,
203,
203,
3639,
309,
261,
9971,
405,
18202,
88,
13,
288,
203,
5411,
22893,
288,
203,
7734,
17527,
273,
7176,
300,
18202,
88,
31,
203,
5411,
289,
203,
5411,
2078,
758,
23602,
1011,
17527,
31,
203,
203,
5411,
389,
15091,
626,
7216,
273,
8586,
626,
7216,
4649,
397,
17527,
397,
389,
30250,
90,
3149,
31,
203,
5411,
22893,
288,
203,
7734,
8324,
273,
18202,
88,
300,
7176,
31,
203,
7734,
2078,
758,
23602,
3947,
8324,
31,
203,
203,
7734,
389,
15091,
626,
7216,
273,
8586,
626,
7216,
4649,
397,
389,
30250,
90,
3149,
405,
8324,
692,
8586,
626,
7216,
4649,
397,
389,
30250,
90,
3149,
300,
8324,
294,
374,
31,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
3323,
758,
23602,
273,
203,
5411,
2078,
758,
23602,
8541,
422,
374,
692,
374,
294,
2078,
10726,
7675,
16411,
7244,
4164,
12,
701,
15127,
63,
67,
14914,
8009,
323,
23602,
8541,
16,
2078,
758,
23602,
8541,
1769,
203,
203,
3639,
309,
261,
12708,
758,
23602,
405,
7176,
13,
389,
80,
409,
24899,
14914,
16,
3323,
758,
23602,
300,
7176,
1769,
2
] |
// File: @openzeppelin/contracts/access/IAccessControl.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
// 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: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/access/AccessControl.sol
// OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol)
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721URIStorage.sol)
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// File: @openzeppelin/contracts/utils/cryptography/ECDSA.sol
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// File: @openzeppelin/contracts/utils/cryptography/draft-EIP712.sol
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol)
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
address private immutable _CACHED_THIS;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_CACHED_THIS = address(this);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: contracts/@rarible/contracts/LibPart.sol
library LibPart {
bytes32 public constant TYPE_HASH = keccak256("Part(address account,uint96 value)");
struct Part {
address payable account;
uint96 value;
}
function hash(Part memory part) internal pure returns (bytes32) {
return keccak256(abi.encode(TYPE_HASH, part.account, part.value));
}
}
// File: contracts/@rarible/contracts/impl/AbstractRoyalties.sol
abstract contract AbstractRoyalties {
mapping (uint256 => LibPart.Part[]) internal royalties;
function _saveRoyalties(uint256 id, LibPart.Part[] memory _royalties) internal {
uint256 totalValue;
for (uint i = 0; i < _royalties.length; i++) {
require(_royalties[i].account != address(0x0), "Recipient should be present");
require(_royalties[i].value != 0, "Royalty value should be positive");
totalValue += _royalties[i].value;
royalties[id].push(_royalties[i]);
}
require(totalValue < 10000, "Royalty total value should be < 10000");
_onRoyaltiesSet(id, _royalties);
}
function _updateAccount(uint256 _id, address _from, address _to) internal {
uint length = royalties[_id].length;
for(uint i = 0; i < length; i++) {
if (royalties[_id][i].account == _from) {
royalties[_id][i].account = payable(address(uint160(_to)));
}
}
}
function _onRoyaltiesSet(uint256 id, LibPart.Part[] memory _royalties) virtual internal;
}
// File: contracts/@rarible/contracts/RoyaltiesV2.sol
interface RoyaltiesV2 {
event RoyaltiesSet(uint256 tokenId, LibPart.Part[] royalties);
function getRaribleV2Royalties(uint256 id) external view returns (LibPart.Part[] memory);
}
// File: contracts/@rarible/contracts/impl/RoyaltiesV2Impl.sol
contract RoyaltiesV2Impl is AbstractRoyalties, RoyaltiesV2 {
function getRaribleV2Royalties(uint256 id) override external view returns (LibPart.Part[] memory) {
return royalties[id];
}
function _onRoyaltiesSet(uint256 id, LibPart.Part[] memory _royalties) override internal {
emit RoyaltiesSet(id, _royalties);
}
}
// File: contracts/@rarible/contracts/LibRoyaltiesV2.sol
library LibRoyaltiesV2 {
/*
* bytes4(keccak256('getRaribleV2Royalties(uint256)')) == 0xcad96cca
*/
bytes4 constant _INTERFACE_ID_ROYALTIES = 0xcad96cca;
}
// File: contracts/MooNFT.sol
contract MooNFT is ERC721URIStorage, EIP712, Ownable, RoyaltiesV2Impl, AccessControl {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
string private constant SIGNING_DOMAIN = "LazyNFT-Voucher";
string private constant SIGNATURE_VERSION = "1";
bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a;
event LogTokenMinted(address receiver, uint256 tokenId, uint256 cost);
event LogPaymentReceived(address from, uint amount);
event LogPaymentReleased(address to, uint amount);
uint16 _totalSupply;
constructor()
ERC721("To The Moo", "MOONSCAN")
EIP712(SIGNING_DOMAIN, SIGNATURE_VERSION) {
_setupRole(AccessControl.DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(MINTER_ROLE, msg.sender);
}
/// @notice Represents an un-minted NFT, which has not yet been recorded into the blockchain. A signed voucher can be redeemed for a real NFT using the redeem function.
struct NFTVoucher {
/// @notice The id of the token to be redeemed. Must be unique - if another token with this ID already exists, the redeem function will revert.
uint256 tokenId;
/// @notice The minimum price (in wei) that the NFT creator is willing to accept for the initial sale of this NFT.
uint256 minPrice;
/// @notice The metadata URI to associate with this token.
string uri;
/// @notice when does this voucher expire?
uint256 expires;
/// @notice the EIP-712 signature of all other fields in the NFTVoucher struct. For a voucher to be valid, it must be signed by an account with the MINTER_ROLE.
bytes signature;
}
/// @notice Redeems an NFTVoucher for an actual NFT, creating it in the process.
/// @param redeemer The address of the account which will receive the NFT upon success.
/// @param voucher A signed NFTVoucher that describes the NFT to be redeemed.
function redeem(address redeemer, NFTVoucher calldata voucher) public payable returns (uint256) {
// make sure signature is valid and get the address of the signer
address signer = _verify(voucher);
// make sure that the signer is authorized to mint NFTs
require(hasRole(MINTER_ROLE, signer), "Signature invalid or unauthorized");
// make sure that the redeemer is paying enough to cover the buyer's cost
require(msg.value >= voucher.minPrice, "Insufficient funds to redeem");
// make sure that the voucher is still valid
require(block.timestamp <= voucher.expires, "Voucher expired");
// first assign the token to the signer, to establish provenance on-chain
_mint(signer, voucher.tokenId);
_setTokenURI(voucher.tokenId, voucher.uri);
// transfer the token to the redeemer
_transfer(signer, redeemer, voucher.tokenId);
emit LogTokenMinted(redeemer, voucher.tokenId, msg.value);
_totalSupply += 1;
// initially set the royalty fee to 10% for the owner
LibPart.Part[] memory _royalties = new LibPart.Part[](1);
_royalties[0].value = 1000;
_royalties[0].account = payable(owner());
_saveRoyalties(voucher.tokenId, _royalties);
return voucher.tokenId;
}
receive() external payable {
emit LogPaymentReceived(msg.sender, msg.value);
}
/// @notice Transfers all
function withdraw() public onlyOwner {
// IMPORTANT: casting msg.sender to a payable address is only safe if ALL members of the minter role are payable addresses.
address payable receiver = payable(msg.sender);
uint256 balance = address(this).balance;
require(balance > 0, "Balance must be higher than zero");
receiver.transfer(balance);
}
/// @notice Returns a hash of the given NFTVoucher, prepared using EIP712 typed data hashing rules.
/// @param voucher An NFTVoucher to hash.
function _hash(NFTVoucher calldata voucher) internal view returns (bytes32) {
return _hashTypedDataV4(keccak256(abi.encode(
keccak256("NFTVoucher(uint256 tokenId,uint256 minPrice,string uri,uint256 expires)"),
voucher.tokenId,
voucher.minPrice,
keccak256(bytes(voucher.uri)),
voucher.expires
)));
}
/// @notice Returns the chain id of the current blockchain.
/// @dev This is used to workaround an issue with ganache returning different values from the on-chain chainid() function and
/// the eth_chainId RPC method. See https://github.com/protocol/nft-website/issues/121 for context.
function getChainID() external view returns (uint256) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
/// @notice Verifies the signature for a given NFTVoucher, returning the address of the signer.
/// @dev Will revert if the signature is invalid. Does not verify that the signer is authorized to mint NFTs.
/// @param voucher An NFTVoucher describing an unminted NFT.
function _verify(NFTVoucher calldata voucher) internal view returns (address) {
bytes32 digest = _hash(voucher);
return ECDSA.recover(digest, voucher.signature);
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function setRoyalties(uint _tokenId, address payable _royaltiesRecipientAddress, uint96 _percentageBasisPoints) public onlyOwner {
// retrieve share splitter address
LibPart.Part[] memory _royalties = new LibPart.Part[](1);
_royalties[0].value = _percentageBasisPoints;
_royalties[0].account = _royaltiesRecipientAddress;
_saveRoyalties(_tokenId, _royalties);
}
function supportsInterface(bytes4 interfaceId) public view virtual override (AccessControl, ERC721) returns (bool) {
if (interfaceId == LibRoyaltiesV2._INTERFACE_ID_ROYALTIES) {
return true;
}
if (interfaceId == _INTERFACE_ID_ERC2981) {
return true;
}
return ERC721.supportsInterface(interfaceId) || AccessControl.supportsInterface(interfaceId);
}
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) {
LibPart.Part[] memory _royalties = royalties[_tokenId];
if (_royalties.length > 0) {
return (_royalties[0].account, (_salePrice * _royalties[0].value) / 1000);
}
return (address(0), 0);
}
function _baseURI() internal view virtual override returns (string memory) {
return "https://ipfs.io/ipfs/";
}
} | File: @openzeppelin/contracts/token/ERC721/ERC721.sol OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)* the Metadata extension, but not including the Enumerable extension, which is available separately as {ERC721Enumerable}./ Token name Token symbol Mapping from token ID to owner address Mapping owner address to token count Mapping from token ID to approved address Mapping from owner to operator approvals | contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
string private _name;
string private _symbol;
mapping(uint256 => address) private _owners;
mapping(address => uint256) private _balances;
mapping(uint256 => address) private _tokenApprovals;
mapping(address => mapping(address => bool)) private _operatorApprovals;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
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;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
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())) : "";
}
function _baseURI() internal view virtual returns (string memory) {
return "";
}
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);
}
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
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);
}
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
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);
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
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;
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
assembly {
revert(add(32, reason), mload(reason))
}
}
}
return true;
}
}
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;
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
assembly {
revert(add(32, reason), mload(reason))
}
}
}
return true;
}
}
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;
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
assembly {
revert(add(32, reason), mload(reason))
}
}
}
return true;
}
}
} catch (bytes memory reason) {
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;
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
assembly {
revert(add(32, reason), mload(reason))
}
}
}
return true;
}
}
} else {
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;
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
assembly {
revert(add(32, reason), mload(reason))
}
}
}
return true;
}
}
} else {
) internal virtual {}
}
| 12,104,736 | [
1,
812,
30,
632,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
2316,
19,
654,
39,
27,
5340,
19,
654,
39,
27,
5340,
18,
18281,
3502,
62,
881,
84,
292,
267,
30131,
331,
24,
18,
24,
18,
21,
261,
2316,
19,
654,
39,
27,
5340,
19,
654,
39,
27,
5340,
18,
18281,
13,
326,
6912,
2710,
16,
1496,
486,
6508,
326,
6057,
25121,
2710,
16,
1492,
353,
2319,
18190,
487,
288,
654,
39,
27,
5340,
3572,
25121,
5496,
19,
3155,
508,
3155,
3273,
9408,
628,
1147,
1599,
358,
3410,
1758,
9408,
3410,
1758,
358,
1147,
1056,
9408,
628,
1147,
1599,
358,
20412,
1758,
9408,
628,
3410,
358,
3726,
6617,
4524,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
4232,
39,
27,
5340,
353,
1772,
16,
4232,
39,
28275,
16,
467,
654,
39,
27,
5340,
16,
467,
654,
39,
27,
5340,
2277,
288,
203,
565,
1450,
5267,
364,
1758,
31,
203,
565,
1450,
8139,
364,
2254,
5034,
31,
203,
565,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
565,
2874,
12,
11890,
5034,
516,
1758,
13,
3238,
389,
995,
414,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
565,
2874,
12,
11890,
5034,
516,
1758,
13,
3238,
389,
2316,
12053,
4524,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
1426,
3719,
3238,
389,
9497,
12053,
4524,
31,
203,
565,
3885,
12,
1080,
3778,
508,
67,
16,
533,
3778,
3273,
67,
13,
288,
203,
3639,
389,
529,
273,
508,
67,
31,
203,
3639,
389,
7175,
273,
3273,
67,
31,
203,
565,
289,
203,
565,
445,
6146,
1358,
12,
3890,
24,
1560,
548,
13,
1071,
1476,
5024,
3849,
12,
654,
39,
28275,
16,
467,
654,
39,
28275,
13,
1135,
261,
6430,
13,
288,
203,
3639,
327,
203,
5411,
1560,
548,
422,
618,
12,
45,
654,
39,
27,
5340,
2934,
5831,
548,
747,
203,
5411,
1560,
548,
422,
618,
12,
45,
654,
39,
27,
5340,
2277,
2934,
5831,
548,
747,
203,
5411,
2240,
18,
28064,
1358,
12,
5831,
548,
1769,
203,
565,
289,
203,
565,
445,
11013,
951,
12,
2867,
3410,
13,
1071,
1476,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
12,
8443,
480,
1758,
2
] |
pragma solidity ^0.5.0;
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice 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 Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract EthMadness is Ownable {
// Represents the submission to the contest.
struct Entrant {
// The user who submitted this entry
address submitter;
// The "index" of this entry. Used to break ties incase two submissions are the same. (earlier submission wins)
uint48 entryIndex;
}
// Represents a current top score in the contest
struct TopScore {
// The index of this entry (used for tie-breakas a de-dups)
uint48 entryIndex;
// This bracket's score
uint32 score;
// The total point differential for this bracket
uint64 difference;
// The account which submitted this bracket
address submitter;
}
// Represents the results of the contest.
struct Result {
// The encoded results of the tournament
bytes16 winners;
// Team A's score in the final
uint8 scoreA;
// Team B's score in the final
uint8 scoreB;
// Whether or not this is the final Results (used to tell if a vote is real or not)
bool isFinal;
}
// Represents the various states that the contest will go through.
enum ContestState {
// The contest is open for people to submit entries. Oracles can also be added during this period.
OPEN_FOR_ENTRIES,
// The tournament is in progress, no more entries can be received and no oracles can vote
TOURNAMENT_IN_PROGRESS,
// The tournament is over and we're waiting for all the oracles to submit the results
WAITING_FOR_ORACLES,
// The oracels have submitted the results and we're waiting for winners to claim their prize
WAITING_FOR_WINNING_CLAIMS,
// The contest has completed and the winners have been paid out
COMPLETED
}
// Maximum number of entries that will be allowed
uint constant MAX_ENTRIES = 2**48;
// The number of entries which have been received.
uint48 entryCount = 0;
// Map of the encoded entry to the user who crreated it.
mapping (uint256 => Entrant) public entries;
// The times where we're allowed to transition the contract's state
mapping (uint => uint) public transitionTimes;
// The current state of the contest
ContestState public currentState;
// The recorded votes of our oracles
mapping (address => Result) public oracleVotes;
// The oracles who will submit the results of the tournament
address[] public oracles;
// The maximum number of oracles we'll allow vote in our contest
uint constant MAX_ORACLES = 10;
// The final result of the tournament that the oracles agreed on
Result public finalResult;
// Keeps the current top 3 best scores and who submitted them. When the contest ends, they'll be paid out
TopScore[3] public topThree;
// The address of the ERC20 token that defines our prize
address public prizeERC20TokenAddress;
// The amount of the prize to reward
uint public prizeAmount;
// Event emitted when a new entry gets submitted to the contest
event EntrySubmitted(
// The account who submitted this bracket
address indexed submitter,
// A compressed representation of the entry combining the picks and final game scores
uint256 indexed entryCompressed,
// The order this entry was received. Used for tiebreaks
uint48 indexed entryIndex,
// Optional bracket name provided by the submitter
string bracketName
);
// Constructs a new instance of the EthMadness contract with the given transition times
constructor(uint[] memory times, address erc20Token, uint erc20Amount) public {
// Initialize the oracles array with the sender's address
oracles = [msg.sender];
// Set up our prize info
prizeERC20TokenAddress = erc20Token;
prizeAmount = erc20Amount;
// Set up our transition times
require(times.length == 4);
transitionTimes[uint(ContestState.TOURNAMENT_IN_PROGRESS)] = times[0];
transitionTimes[uint(ContestState.WAITING_FOR_ORACLES)] = times[1];
transitionTimes[uint(ContestState.WAITING_FOR_WINNING_CLAIMS)] = times[2];
transitionTimes[uint(ContestState.COMPLETED)] = times[3];
// The initial state should be allowing people to make entries
currentState = ContestState.OPEN_FOR_ENTRIES;
}
// Gets the total number of entries we've received
function getEntryCount() public view returns (uint256) {
return entryCount;
}
// Gets the number of Oracles we have registered
function getOracleCount() public view returns(uint256) {
return oracles.length;
}
// Returns the transition times for our contest
function getTransitionTimes() public view returns (uint256, uint256, uint256, uint256) {
return (
transitionTimes[uint(ContestState.TOURNAMENT_IN_PROGRESS)],
transitionTimes[uint(ContestState.WAITING_FOR_ORACLES)],
transitionTimes[uint(ContestState.WAITING_FOR_WINNING_CLAIMS)],
transitionTimes[uint(ContestState.COMPLETED)]
);
}
// Internal function for advancing the state of the bracket
function advanceState(ContestState nextState) private {
require(uint(nextState) == uint(currentState) + 1, "Can only advance state by 1");
require(now > transitionTimes[uint(nextState)], "Transition time hasn't happened yet");
currentState = nextState;
}
// Helper to make sure the picks submitted are legal
function arePicksOrResultsValid(bytes16 picksOrResults) public pure returns (bool) {
// Go through and make sure that this entry has 1 pick for each game
for (uint8 gameId = 0; gameId < 63; gameId++) {
uint128 currentPick = extractResult(picksOrResults, gameId);
if (currentPick != 2 && currentPick != 1) {
return false;
}
}
return true;
}
// Submits a new entry to the tournament
function submitEntry(bytes16 picks, uint64 scoreA, uint64 scoreB, string memory bracketName) public {
require(currentState == ContestState.OPEN_FOR_ENTRIES, "Must be in the open for entries state");
require(arePicksOrResultsValid(picks), "The supplied picks are not valid");
// Do some work to encode the picks and scores into a single uint256 which becomes a key
uint256 scoreAShifted = uint256(scoreA) * (2 ** (24 * 8));
uint256 scoreBShifted = uint256(scoreB) * (2 ** (16 * 8));
uint256 picksAsNumber = uint128(picks);
uint256 entryCompressed = scoreAShifted | scoreBShifted | picksAsNumber;
require(entries[entryCompressed].submitter == address(0), "This exact bracket & score has already been submitted");
// Emit the event that this entry was received and save the entry
emit EntrySubmitted(msg.sender, entryCompressed, entryCount, bracketName);
Entrant memory entrant = Entrant(msg.sender, entryCount);
entries[entryCompressed] = entrant;
entryCount++;
}
// Adds an allowerd oracle who will vote on the results of the contest. Only the contract owner can do this
// and it can only be done while the tournament is still open for entries
function addOracle(address oracle) public onlyOwner {
require(currentState == ContestState.OPEN_FOR_ENTRIES, "Must be accepting entries");
require(oracles.length < MAX_ORACLES - 1, "Must be less than max number of oracles");
oracles.push(oracle);
}
// In case something goes wrong, allow the owner to eject from the contract
// but only while picks are still being made or after the contest completes
function refundRemaining(uint256 amount) public onlyOwner {
require(currentState == ContestState.OPEN_FOR_ENTRIES || currentState == ContestState.COMPLETED, "Must be accepting entries");
IERC20 erc20 = IERC20(prizeERC20TokenAddress);
erc20.transfer(msg.sender, amount);
}
// Submits a new oracle's vote describing the results of the tournament
function submitOracleVote(uint oracleIndex, bytes16 winners, uint8 scoreA, uint8 scoreB) public {
require(currentState == ContestState.WAITING_FOR_ORACLES, "Must be in waiting for oracles state");
require(oracles[oracleIndex] == msg.sender, "Wrong oracle index");
require(arePicksOrResultsValid(winners), "Results are not valid");
oracleVotes[msg.sender] = Result(winners, scoreA, scoreB, true);
}
// Close the voting and set the final result. Pass in what should be the consensus agreed by the
// 70% of the oracles
function closeOracleVoting(bytes16 winners, uint8 scoreA, uint8 scoreB) public {
require(currentState == ContestState.WAITING_FOR_ORACLES);
// Count up how many oracles agree with this result
uint confirmingOracles = 0;
for (uint i = 0; i < oracles.length; i++) {
Result memory oracleVote = oracleVotes[oracles[i]];
if (oracleVote.isFinal &&
oracleVote.winners == winners &&
oracleVote.scoreA == scoreA &&
oracleVote.scoreB == scoreB) {
confirmingOracles++;
}
}
// Require 70%+ of Oracles to have voted and agree on the result
uint percentAggreement = (confirmingOracles * 100) / oracles.length;
require(percentAggreement > 70, "To close oracle voting, > 70% of oracles must agree");
// Change the state and set our final result which will be used to compute scores
advanceState(ContestState.WAITING_FOR_WINNING_CLAIMS);
finalResult = Result(winners, scoreA, scoreB, true);
}
// Closes the entry period and marks that the actual tournament is in progress
function markTournamentInProgress() public {
advanceState(ContestState.TOURNAMENT_IN_PROGRESS);
require(oracles.length > 0, "Must have at least 1 oracle registered");
// Require that we have the amount of funds locked in the contract we expect
IERC20 erc20 = IERC20(prizeERC20TokenAddress);
require(erc20.balanceOf(address(this)) >= prizeAmount, "Must have a balance in this contract");
}
// Mark that the tournament has completed and oracles can start submitting results
function markTournamentFinished() public {
advanceState(ContestState.WAITING_FOR_ORACLES);
}
// After the oracles have voted and winners have claimed their prizes, this closes the contest and
// pays out the winnings to the 3 winners
function closeContestAndPayWinners() public {
advanceState(ContestState.COMPLETED);
require(topThree[0].submitter != address(0), "Not enough claims");
require(topThree[1].submitter != address(0), "Not enough claims");
require(topThree[2].submitter != address(0), "Not enough claims");
uint firstPrize = (prizeAmount * 70) / 100;
uint secondPrize = (prizeAmount * 20) / 100;
uint thirdPrize = (prizeAmount * 10) / 100;
IERC20 erc20 = IERC20(prizeERC20TokenAddress);
erc20.transfer(topThree[0].submitter, firstPrize);
erc20.transfer(topThree[1].submitter, secondPrize);
erc20.transfer(topThree[2].submitter, thirdPrize);
}
// Scores an entry and places it in the right sort order
function scoreAndSortEntry(uint256 entryCompressed, bytes16 results, uint64 scoreAActual, uint64 scoreBActual) private returns (uint32) {
require(currentState == ContestState.WAITING_FOR_WINNING_CLAIMS, "Must be in the waiting for claims state");
require(entries[entryCompressed].submitter != address(0), "The entry must have actually been submitted");
// Pull out the pick information from the compressed entry
bytes16 picks = bytes16(uint128((entryCompressed & uint256((2 ** 128) - 1))));
uint256 shifted = entryCompressed / (2 ** 128); // shift over 128 bits
uint64 scoreA = uint64((shifted & uint256((2 ** 64) - 1)));
shifted = entryCompressed / (2 ** 192);
uint64 scoreB = uint64((shifted & uint256((2 ** 64) - 1)));
// Compute the score and the total difference
uint32 score = scoreEntry(picks, results);
uint64 difference = computeFinalGameDifference(scoreA, scoreB, scoreAActual, scoreBActual);
// Make a score and place it in the right sort order
TopScore memory scoreResult = TopScore(entries[entryCompressed].entryIndex, score, difference, entries[entryCompressed].submitter);
if (isScoreBetter(scoreResult, topThree[0])) {
topThree[2] = topThree[1];
topThree[1] = topThree[0];
topThree[0] = scoreResult;
} else if (isScoreBetter(scoreResult, topThree[1])) {
topThree[2] = topThree[1];
topThree[1] = scoreResult;
} else if (isScoreBetter(scoreResult, topThree[2])) {
topThree[2] = scoreResult;
}
return score;
}
function claimTopEntry(uint256 entryCompressed) public {
require(currentState == ContestState.WAITING_FOR_WINNING_CLAIMS, "Must be in the waiting for winners state");
require(finalResult.isFinal, "The final result must be marked as final");
scoreAndSortEntry(entryCompressed, finalResult.winners, finalResult.scoreA, finalResult.scoreB);
}
function computeFinalGameDifference(
uint64 scoreAGuess, uint64 scoreBGuess, uint64 scoreAActual, uint64 scoreBActual) private pure returns (uint64) {
// Don't worry about overflow here, not much you can really do with it
uint64 difference = 0;
difference += ((scoreAActual > scoreAGuess) ? (scoreAActual - scoreAGuess) : (scoreAGuess - scoreAActual));
difference += ((scoreBActual > scoreBGuess) ? (scoreBActual - scoreBGuess) : (scoreBGuess - scoreBActual));
return difference;
}
// Gets the bit at index n in a
function getBit16(bytes16 a, uint16 n) private pure returns (bool) {
uint128 mask = uint128(2) ** n;
return uint128(a) & mask != 0;
}
// Sets the bit at index n to 1 in a
function setBit16(bytes16 a, uint16 n) private pure returns (bytes16) {
uint128 mask = uint128(2) ** n;
return a | bytes16(mask);
}
// Sets the bit at index n to 0 in a
function clearBit16(bytes16 a, uint16 n) private pure returns (bytes16) {
uint128 mask = uint128(2) ** n;
mask = mask ^ uint128(-1);
return a & bytes16(mask);
}
// Returns either 0 if there is no possible winner, 1 if team B is chosen, or 2 if team A is chosen
function extractResult(bytes16 a, uint8 n) private pure returns (uint128) {
uint128 mask = uint128(0x00000000000000000000000000000003) * uint128(2) ** (n * 2);
uint128 masked = uint128(a) & mask;
// Shift back to get either 0, 1 or 2
return (masked / (uint128(2) ** (n * 2)));
}
// Gets which round a game belongs to based on its id
function getRoundForGame(uint8 gameId) private pure returns (uint8) {
if (gameId < 32) {
return 0;
} else if (gameId < 48) {
return 1;
} else if (gameId < 56) {
return 2;
} else if (gameId < 60) {
return 3;
} else if (gameId < 62) {
return 4;
} else {
return 5;
}
}
// Gets the first game in a round given the round number
function getFirstGameIdOfRound(uint8 round) private pure returns (uint8) {
if (round == 0) {
return 0;
} else if (round == 1) {
return 32;
} else if (round == 2) {
return 48;
} else if (round == 3) {
return 56;
} else if (round == 4) {
return 60;
} else {
return 62;
}
}
// Looks at two scores and decided whether newScore is a better score than old score
function isScoreBetter(TopScore memory newScore, TopScore memory oldScore) private pure returns (bool) {
if (newScore.score > oldScore.score) {
return true;
}
if (newScore.score < oldScore.score) {
return false;
}
// Case where we have a tie
if (newScore.difference < oldScore.difference) {
return true;
}
if (newScore.difference < oldScore.difference) {
return false;
}
require(newScore.entryIndex != oldScore.entryIndex, "This entry has already claimed a prize");
// Crazy case where we have the same score and same diference. Return the earlier entry as the winnner
return newScore.entryIndex < oldScore.entryIndex;
}
// Scores an entry given the picks and the results
function scoreEntry(bytes16 picks, bytes16 results) private pure returns (uint32) {
uint32 score = 0;
uint8 round = 0;
bytes16 currentPicks = picks;
for (uint8 gameId = 0; gameId < 63; gameId++) {
// Update which round we're in when on the transitions
round = getRoundForGame(gameId);
uint128 currentPick = extractResult(currentPicks, gameId);
if (currentPick == extractResult(results, gameId)) {
score += (uint32(2) ** round);
} else if (currentPick != 0) { // If we actually had a pick, propagate forward
// Mark all the future currentPicks which required this team winning as null
uint16 currentPickId = (gameId * 2) + (currentPick == 2 ? 1 : 0);
for (uint8 futureRound = round + 1; futureRound < 6; futureRound++) {
uint16 currentPickOffset = currentPickId - (getFirstGameIdOfRound(futureRound - 1) * 2);
currentPickId = (getFirstGameIdOfRound(futureRound) * 2) + (currentPickOffset / 2);
bool pickedLoser = getBit16(currentPicks, currentPickId);
if (pickedLoser) {
currentPicks = clearBit16(currentPicks, currentPickId);
} else {
break;
}
}
}
}
return score;
}
} | Sets the bit at index n to 0 in a | function clearBit16(bytes16 a, uint16 n) private pure returns (bytes16) {
uint128 mask = uint128(2) ** n;
mask = mask ^ uint128(-1);
return a & bytes16(mask);
}
| 5,431,630 | [
1,
2785,
326,
2831,
622,
770,
290,
358,
374,
316,
279,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2424,
5775,
2313,
12,
3890,
2313,
279,
16,
2254,
2313,
290,
13,
3238,
16618,
1135,
261,
3890,
2313,
13,
288,
203,
3639,
2254,
10392,
3066,
273,
2254,
10392,
12,
22,
13,
2826,
290,
31,
203,
3639,
3066,
273,
3066,
3602,
2254,
10392,
19236,
21,
1769,
203,
3639,
327,
279,
473,
1731,
2313,
12,
4455,
1769,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
function decimals() external view returns (uint8);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _governance;
event GovernanceTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_governance = msgSender;
emit GovernanceTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function governance() public view returns (address) {
return _governance;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyGovernance() {
require(_governance == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferGovernance(address newOwner) internal virtual onlyGovernance {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit GovernanceTransferred(_governance, newOwner);
_governance = newOwner;
}
}
// File: contracts/strategies/StabilizeStrategyTSBTCArbV1.sol
pragma solidity =0.6.6;
// This is a strategy that takes advantage of arb opportunities for tbtc and sbtc
// Strat will constantly trade between synthetic tokens using Curve
interface StabilizeStakingPool {
function notifyRewardAmount(uint256) external;
}
interface UniswapRouter {
function swapExactETHForTokens(uint, address[] calldata, address, uint) external payable returns (uint[] memory);
function swapExactTokensForTokens(uint, uint, address[] calldata, address, uint) external returns (uint[] memory);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(uint, uint, address[] calldata, address, uint) external;
function getAmountsOut(uint, address[] calldata) external view returns (uint[] memory); // For a value in, it calculates value out
}
interface CurvePool {
function get_dy_underlying(int128, int128, uint256) external view returns (uint256); // Get quantity estimate
function exchange_underlying(int128, int128, uint256, uint256) external; // Exchange tokens
function get_dy(int128, int128, uint256) external view returns (uint256); // Get quantity estimate
function exchange(int128, int128, uint256, uint256) external; // Exchange tokens
}
interface AggregatorV3Interface {
function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}
contract StabilizeStrategyTSBTCArbV1 is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
address public treasuryAddress; // Address of the treasury
address public stakingAddress; // Address to the STBZ staking pool
address public zsTokenAddress; // The address of the controlling zs-Token
uint256 constant DIVISION_FACTOR = 100000;
uint256 public lastTradeTime = 0;
uint256 public lastActionBalance = 0; // Balance before last deposit or withdraw
uint256 public percentTradeTrigger = 1000; // 1% change in value will trigger a trade
uint256 public maxPercentSell = 80000; // Up to 80% of the tokens are sold to the cheapest token
uint256 public maxAmountSell = 100e18; // The maximum amount of tokens that can be sold at once
uint256 public minTradeSplit = 1e14; // If the balance is less than or equal to this, it trades the entire balance
uint256 public gasStipend = 1500000; // This is the gas units that are covered by executing a trade taken from the WETH profit
uint256 public minGain = 1e13; // Minimum amount of gain (normalized) needed before paying executors
uint256 public maxPercentStipend = 30000; // The maximum amount of WETH profit that can be allocated to the executor for gas in percent
uint256 public percentDepositor = 50000; // 1000 = 1%, depositors earn 50% of all gains
uint256 public percentExecutor = 10000; // 10000 = 10% of WETH goes to executor, 5% of total profit. This is on top of gas stipend
uint256 public percentStakers = 50000; // 50% of non-depositors WETH goes to stakers, can be changed
uint256 private lastTradeID = 0;
// Token information
// This strategy accepts tbtc and sbtc
struct TokenInfo {
IERC20 token; // Reference of token
uint256 decimals; // Decimals of token
int128 curveID; // ID in curve pool
}
TokenInfo[] private tokenList; // An array of tokens accepted as deposits
// Strategy specific variables
address constant UNISWAP_ROUTER_ADDRESS = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //Address of Uniswap
address constant THREE_BTC_ADDRESS = address(0x7fC77b5c7614E1533320Ea6DDc2Eb61fa00A9714);
address constant TBTC_CURVE_ADDRESS = address(0xC25099792E9349C7DD09759744ea681C7de2cb66);
address constant WETH_ADDRESS = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
address constant WBTC_ADDRESS = address(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599);
address constant GAS_ORACLE_ADDRESS = address(0x169E633A2D1E6c10dD91238Ba11c4A708dfEF37C); // Chainlink address for fast gas oracle
uint256 constant WETH_ID = 2;
constructor(
address _treasury,
address _staking,
address _zsToken
) public {
treasuryAddress = _treasury;
stakingAddress = _staking;
zsTokenAddress = _zsToken;
setupWithdrawTokens();
}
// Initialization functions
function setupWithdrawTokens() internal {
// Start with tBTC
IERC20 _token = IERC20(address(0x8dAEBADE922dF735c38C80C7eBD708Af50815fAa));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals(),
curveID: 0
})
);
// sBTC from Synthetix
_token = IERC20(address(0xfE18be6b3Bd88A2D2A7f928d00292E7a9963CfC6));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals(),
curveID: 3
})
);
}
// Modifier
modifier onlyZSToken() {
require(zsTokenAddress == _msgSender(), "Call not sent from the zs-Token");
_;
}
// Read functions
function rewardTokensCount() external view returns (uint256) {
return tokenList.length;
}
function rewardTokenAddress(uint256 _pos) external view returns (address) {
require(_pos < tokenList.length,"No token at that position");
return address(tokenList[_pos].token);
}
function balance() public view returns (uint256) {
return getNormalizedTotalBalance(address(this));
}
function getNormalizedTotalBalance(address _address) public view returns (uint256) {
// Get the balance of the atokens+tokens at this address
uint256 _balance = 0;
uint256 _length = tokenList.length;
for(uint256 i = 0; i < _length; i++){
uint256 _bal = tokenList[i].token.balanceOf(_address);
_bal = _bal.mul(1e18).div(10**tokenList[i].decimals);
_balance = _balance.add(_bal); // This has been normalized to 1e18 decimals
}
return _balance;
}
function withdrawTokenReserves() public view returns (address, uint256) {
(uint256 targetID, uint256 _bal) = withdrawTokenReservesID();
if(_bal == 0){
return (address(0), _bal);
}else{
return (address(tokenList[targetID].token), _bal);
}
}
function withdrawTokenReservesID() internal view returns (uint256, uint256) {
// This function will return the address and amount of the token with the highest balance
uint256 length = tokenList.length;
uint256 targetID = 0;
uint256 targetNormBalance = 0;
for(uint256 i = 0; i < length; i++){
uint256 _normBal = tokenList[i].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i].decimals);
if(_normBal > 0){
if(targetNormBalance == 0 || _normBal >= targetNormBalance){
targetNormBalance = _normBal;
targetID = i;
}
}
}
if(targetNormBalance > 0){
return (targetID, tokenList[targetID].token.balanceOf(address(this)));
}else{
return (0, 0); // No balance
}
}
// Write functions
function enter() external onlyZSToken {
deposit(false);
}
function exit() external onlyZSToken {
// The ZS token vault is removing all tokens from this strategy
withdraw(_msgSender(),1,1, false);
}
function deposit(bool nonContract) public onlyZSToken {
// Only the ZS token can call the function
// No trading is performed on deposit
if(nonContract == true){ }
lastActionBalance = balance();
}
function simulateExchange(uint256 _inID, uint256 _outID, uint256 _amount) internal view returns (uint256) {
if(_outID == WETH_ID){
// Sending for weth, calculate route
if(_inID == 0){
// tBTC -> WETH via Uniswap
UniswapRouter router = UniswapRouter(UNISWAP_ROUTER_ADDRESS);
address[] memory path = new address[](2);
path[0] = address(tokenList[0].token);
path[1] = WETH_ADDRESS;
uint256[] memory estimates = router.getAmountsOut(_amount, path);
_amount = estimates[estimates.length - 1];
return _amount;
}else{
// sBTC -> wBTC -> WETH
CurvePool pool = CurvePool(THREE_BTC_ADDRESS);
_amount = pool.get_dy(2, 1, _amount); // returns wBTC amount
UniswapRouter router = UniswapRouter(UNISWAP_ROUTER_ADDRESS);
address[] memory path = new address[](2);
path[0] = WBTC_ADDRESS;
path[1] = WETH_ADDRESS;
uint256[] memory estimates = router.getAmountsOut(_amount, path);
_amount = estimates[estimates.length - 1];
return _amount;
}
}else{
// Easy swap
CurvePool pool = CurvePool(TBTC_CURVE_ADDRESS);
_amount = pool.get_dy_underlying(tokenList[_inID].curveID, tokenList[_outID].curveID, _amount);
return _amount;
}
}
function exchange(uint256 _inID, uint256 _outID, uint256 _amount) internal {
if(_outID == WETH_ID){
// Sending for weth, calculate route
if(_inID == 0){
// tBTC -> WETH via Uniswap
UniswapRouter router = UniswapRouter(UNISWAP_ROUTER_ADDRESS);
address[] memory path = new address[](2);
path[0] = address(tokenList[0].token);
path[1] = WETH_ADDRESS;
tokenList[0].token.safeApprove(UNISWAP_ROUTER_ADDRESS, 0);
tokenList[0].token.safeApprove(UNISWAP_ROUTER_ADDRESS, _amount);
router.swapExactTokensForTokens(_amount, 1, path, address(this), now.add(60)); // Get WETH from token
return;
}else{
// sBTC -> wBTC -> WETH
CurvePool pool = CurvePool(THREE_BTC_ADDRESS);
tokenList[1].token.safeApprove(THREE_BTC_ADDRESS, 0);
tokenList[1].token.safeApprove(THREE_BTC_ADDRESS, _amount);
uint256 _before = IERC20(WBTC_ADDRESS).balanceOf(address(this));
pool.exchange(2, 1, _amount, 1);
_amount = IERC20(WBTC_ADDRESS).balanceOf(address(this)).sub(_before); // Get wbtc amount
UniswapRouter router = UniswapRouter(UNISWAP_ROUTER_ADDRESS);
address[] memory path = new address[](2);
path[0] = WBTC_ADDRESS;
path[1] = WETH_ADDRESS;
IERC20(WBTC_ADDRESS).safeApprove(UNISWAP_ROUTER_ADDRESS, 0);
IERC20(WBTC_ADDRESS).safeApprove(UNISWAP_ROUTER_ADDRESS, _amount);
router.swapExactTokensForTokens(_amount, 1, path, address(this), now.add(60)); // Get WETH from token
return;
}
}else{
// Easy swap
CurvePool pool = CurvePool(TBTC_CURVE_ADDRESS);
tokenList[_inID].token.safeApprove(TBTC_CURVE_ADDRESS, 0);
tokenList[_inID].token.safeApprove(TBTC_CURVE_ADDRESS, _amount);
pool.exchange_underlying(tokenList[_inID].curveID, tokenList[_outID].curveID, _amount, 1);
return;
}
}
function getCheaperToken() internal view returns (uint256) {
// This will give us the ID of the cheapest token on Curve
// We will estimate the return for trading 0.001
// The higher the return, the lower the price of the other token
uint256 targetID = 0;
uint256 mainAmount = minTradeSplit.mul(10**tokenList[0].decimals).div(1e18);
// Estimate sell tBTC for sBTC
uint256 estimate = 0;
estimate = simulateExchange(0,1,mainAmount);
estimate = estimate.mul(10**tokenList[0].decimals).div(10**tokenList[1].decimals); // Convert to main decimals
if(estimate > mainAmount){
// This token is worth less than the other token
targetID = 1;
}
return targetID;
}
function estimateSellAtMaximumProfit(uint256 originID, uint256 targetID, uint256 _tokenBalance) internal view returns (uint256) {
// This will estimate the amount that can be sold for the maximum profit possible
// We discover the price then compare it to the actual return
// The return must be positive to return a positive amount
uint256 originDecimals = tokenList[originID].decimals;
uint256 targetDecimals = tokenList[targetID].decimals;
// Discover the price with near 0 slip
uint256 _minAmount = _tokenBalance.mul(maxPercentSell.div(1000)).div(DIVISION_FACTOR);
if(_minAmount == 0){ return 0; } // Nothing to sell, can't calculate
uint256 _minReturn = _minAmount.mul(10**targetDecimals).div(10**originDecimals); // Convert decimals
uint256 _return = simulateExchange(originID, targetID, _minAmount);
if(_return <= _minReturn){
return 0; // We are not going to gain from this trade
}
_return = _return.mul(10**originDecimals).div(10**targetDecimals); // Convert to origin decimals
uint256 _startPrice = _return.mul(1e18).div(_minAmount);
// Now get the price at a higher amount, expected to be lower due to slippage
uint256 _bigAmount = _tokenBalance.mul(maxPercentSell).div(DIVISION_FACTOR);
_return = simulateExchange(originID, targetID, _bigAmount);
_return = _return.mul(10**originDecimals).div(10**targetDecimals); // Convert to origin decimals
uint256 _endPrice = _return.mul(1e18).div(_bigAmount);
if(_endPrice >= _startPrice){
// Really good liquidity
return _bigAmount;
}
// Else calculate amount at max profit
uint256 scaleFactor = uint256(1).mul(10**originDecimals);
uint256 _targetAmount = _startPrice.sub(1e18).mul(scaleFactor).div(_startPrice.sub(_endPrice).mul(scaleFactor).div(_bigAmount.sub(_minAmount))).div(2);
if(_targetAmount > _bigAmount){
// Cannot create an estimate larger than what we want to sell
return _bigAmount;
}
return _targetAmount;
}
function getFastGasPrice() internal view returns (uint256) {
AggregatorV3Interface gasOracle = AggregatorV3Interface(GAS_ORACLE_ADDRESS);
( , int intGasPrice, , , ) = gasOracle.latestRoundData(); // We only want the answer
return uint256(intGasPrice);
}
function checkAndSwapTokens(address _executor, uint256 targetID) internal {
lastTradeTime = now;
uint256 gain = 0;
uint256 length = tokenList.length;
// Now sell all the other tokens into this token
uint256 _totalBalance = balance(); // Get the token balance at this contract, should increase
bool _expectIncrease = false;
for(uint256 i = 0; i < length; i++){
if(i != targetID){
uint256 sellBalance = 0;
uint256 _bal = tokenList[i].token.balanceOf(address(this));
uint256 _minTradeTarget = minTradeSplit.mul(10**tokenList[i].decimals).div(1e18);
uint256 _maxTradeTarget = maxAmountSell.mul(10**tokenList[i].decimals).div(1e18); // Determine the maximum amount of tokens to sell at once
if(_bal <= _minTradeTarget){
// If balance is too small,sell all tokens at once
sellBalance = _bal;
}else{
sellBalance = estimateSellAtMaximumProfit(i, targetID, _bal);
}
if(sellBalance > _maxTradeTarget){
// If greater than the maximum trade allowed, match it
sellBalance = _maxTradeTarget;
}
if(sellBalance > 0){
uint256 minReceiveBalance = sellBalance.mul(10**tokenList[targetID].decimals).div(10**tokenList[i].decimals); // Change to match decimals of destination
uint256 estimate = simulateExchange(i, targetID, sellBalance);
if(estimate > minReceiveBalance){
_expectIncrease = true;
lastTradeID = targetID;
exchange(i, targetID, sellBalance);
}
}
}
}
uint256 _newBalance = balance();
if(_expectIncrease == true){
// There may be rare scenarios where we don't gain any by calling this function
require(_newBalance > _totalBalance, "Failed to gain in balance from selling tokens");
}
gain = _newBalance.sub(_totalBalance);
IERC20 weth = IERC20(WETH_ADDRESS);
uint256 _wethBalance = weth.balanceOf(address(this));
if(gain >= minGain){
// Buy WETH from Uniswap with tokens
uint256 sellBalance = gain.mul(10**tokenList[targetID].decimals).div(1e18); // Convert to target decimals
sellBalance = sellBalance.mul(DIVISION_FACTOR.sub(percentDepositor)).div(DIVISION_FACTOR);
if(sellBalance <= tokenList[targetID].token.balanceOf(address(this))){
// Sell some of our gained token for WETH
exchange(targetID, WETH_ID, sellBalance);
_wethBalance = weth.balanceOf(address(this));
}
}
if(_wethBalance > 0){
// Split the rest between the stakers and such
// This is pure profit, figure out allocation
// Split the amount sent to the treasury, stakers and executor if one exists
if(_executor != address(0)){
// Executors will get a gas reimbursement in WETH and a percent of the remaining
uint256 maxGasFee = getFastGasPrice().mul(gasStipend); // This is gas stipend in wei
uint256 gasFee = tx.gasprice.mul(gasStipend); // This is gas fee requested
if(gasFee > maxGasFee){
gasFee = maxGasFee; // Gas fee cannot be greater than the maximum
}
uint256 executorAmount = gasFee;
if(gasFee >= _wethBalance.mul(maxPercentStipend).div(DIVISION_FACTOR)){
executorAmount = _wethBalance.mul(maxPercentStipend).div(DIVISION_FACTOR); // The executor will get the entire amount up to point
}else{
// Add the executor percent on top of gas fee
executorAmount = _wethBalance.sub(gasFee).mul(percentExecutor).div(DIVISION_FACTOR).add(gasFee);
}
if(executorAmount > 0){
weth.safeTransfer(_executor, executorAmount);
_wethBalance = weth.balanceOf(address(this)); // Recalculate WETH in contract
}
}
if(_wethBalance > 0){
uint256 stakersAmount = _wethBalance.mul(percentStakers).div(DIVISION_FACTOR);
uint256 treasuryAmount = _wethBalance.sub(stakersAmount);
if(treasuryAmount > 0){
weth.safeTransfer(treasuryAddress, treasuryAmount);
}
if(stakersAmount > 0){
if(stakingAddress != address(0)){
weth.safeTransfer(stakingAddress, stakersAmount);
StabilizeStakingPool(stakingAddress).notifyRewardAmount(stakersAmount);
}else{
// No staking pool selected, just send to the treasury
weth.safeTransfer(treasuryAddress, stakersAmount);
}
}
}
}
}
function expectedProfit(bool inWETHForExecutor) external view returns (uint256, uint256) {
// This view will return the amount of gain a forced swap or loan will make on next call
// Now find our target token to sell into
uint256 targetID = 0;
uint256 _normalizedGain = 0;
targetID = getCheaperToken();
uint256 length = tokenList.length;
for(uint256 i = 0; i < length; i++){
if(i != targetID){
uint256 sellBalance = 0;
uint256 _bal = tokenList[i].token.balanceOf(address(this));
uint256 _minTradeTarget = minTradeSplit.mul(10**tokenList[i].decimals).div(1e18);
uint256 _maxTradeTarget = maxAmountSell.mul(10**tokenList[i].decimals).div(1e18); // Determine the maximum amount of tokens to sell at once
if(_bal <= _minTradeTarget){
// If balance is too small,sell all tokens at once
sellBalance = _bal;
}else{
sellBalance = estimateSellAtMaximumProfit(i, targetID, _bal);
}
if(sellBalance > _maxTradeTarget){
// If greater than the maximum trade allowed, match it
sellBalance = _maxTradeTarget;
}
if(sellBalance > 0){
uint256 minReceiveBalance = sellBalance.mul(10**tokenList[targetID].decimals).div(10**tokenList[i].decimals); // Change to match decimals of destination
uint256 estimate = simulateExchange(i, targetID, sellBalance);
if(estimate > minReceiveBalance){
uint256 _gain = estimate.sub(minReceiveBalance).mul(1e18).div(10**tokenList[targetID].decimals); // Normalized gain
_normalizedGain = _normalizedGain.add(_gain);
}
}
}
}
if(inWETHForExecutor == false){
return (_normalizedGain, 0); // This will be in stablecoins regardless of whether flash loan or not
}else{
if(_normalizedGain == 0){
return (0, 0);
}
// Calculate how much WETH the executor would make as profit
uint256 estimate = 0;
if(_normalizedGain > 0){
uint256 sellBalance = _normalizedGain.mul(10**tokenList[targetID].decimals).div(1e18); // Convert to target decimals
sellBalance = sellBalance.mul(DIVISION_FACTOR.sub(percentDepositor)).div(DIVISION_FACTOR);
// Estimate output
estimate = simulateExchange(targetID, WETH_ID, sellBalance);
}
// Now calculate the amount going to the executor
uint256 gasFee = getFastGasPrice().mul(gasStipend); // This is gas stipend in wei
if(gasFee >= estimate.mul(maxPercentStipend).div(DIVISION_FACTOR)){ // Max percent of total
return (estimate.mul(maxPercentStipend).div(DIVISION_FACTOR), targetID); // The executor will get max percent of total
}else{
estimate = estimate.sub(gasFee); // Subtract fee from remaining balance
return (estimate.mul(percentExecutor).div(DIVISION_FACTOR).add(gasFee), targetID); // Executor amount with fee added
}
}
}
function withdraw(address _depositor, uint256 _share, uint256 _total, bool nonContract) public onlyZSToken returns (uint256) {
require(balance() > 0, "There are no tokens in this strategy");
if(nonContract == true){
if(_share > _total.mul(percentTradeTrigger).div(DIVISION_FACTOR)){
checkAndSwapTokens(address(0), lastTradeID);
}
}
uint256 withdrawAmount = 0;
uint256 _balance = balance();
if(_share < _total){
uint256 _myBalance = _balance.mul(_share).div(_total);
withdrawPerBalance(_depositor, _myBalance, false); // This will withdraw based on token balance
withdrawAmount = _myBalance;
}else{
// We are all shares, transfer all
withdrawPerBalance(_depositor, _balance, true);
withdrawAmount = _balance;
}
lastActionBalance = balance();
return withdrawAmount;
}
// This will withdraw the tokens from the contract based on their balance, from highest balance to lowest
function withdrawPerBalance(address _receiver, uint256 _withdrawAmount, bool _takeAll) internal {
uint256 length = tokenList.length;
if(_takeAll == true){
// Send the entire balance
for(uint256 i = 0; i < length; i++){
uint256 _bal = tokenList[i].token.balanceOf(address(this));
if(_bal > 0){
tokenList[i].token.safeTransfer(_receiver, _bal);
}
}
return;
}
bool[] memory done = new bool[](length);
uint256 targetID = 0;
uint256 targetNormBalance = 0;
for(uint256 i = 0; i < length; i++){
targetNormBalance = 0; // Reset the target balance
// Find the highest balanced token to withdraw
for(uint256 i2 = 0; i2 < length; i2++){
if(done[i2] == false){
uint256 _normBal = tokenList[i2].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i2].decimals);
if(targetNormBalance == 0 || _normBal >= targetNormBalance){
targetNormBalance = _normBal;
targetID = i2;
}
}
}
done[targetID] = true;
// Determine the balance left
uint256 _normalizedBalance = tokenList[targetID].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[targetID].decimals);
if(_normalizedBalance <= _withdrawAmount){
// Withdraw the entire balance of this token
if(_normalizedBalance > 0){
_withdrawAmount = _withdrawAmount.sub(_normalizedBalance);
tokenList[targetID].token.safeTransfer(_receiver, tokenList[targetID].token.balanceOf(address(this)));
}
}else{
// Withdraw a partial amount of this token
if(_withdrawAmount > 0){
// Convert the withdraw amount to the token's decimal amount
uint256 _balance = _withdrawAmount.mul(10**tokenList[targetID].decimals).div(1e18);
_withdrawAmount = 0;
tokenList[targetID].token.safeTransfer(_receiver, _balance);
}
break; // Nothing more to withdraw
}
}
}
function executorSwapTokens(address _executor, uint256 _minSecSinceLastTrade, uint256 _buyID) external {
// Function designed to promote trading with incentive. Users get 20% of WETH from profitable trades
require(now.sub(lastTradeTime) > _minSecSinceLastTrade, "The last trade was too recent");
require(_msgSender() == tx.origin, "Contracts cannot interact with this function");
checkAndSwapTokens(_executor, _buyID);
}
// Governance functions
function governanceSwapTokens(uint256 _buyID) external onlyGovernance {
// This is function that force trade tokens at anytime. It can only be called by governance
checkAndSwapTokens(governance(), _buyID);
}
// Change the trading conditions used by the strategy without timelock
// --------------------
function changeTradingConditions(uint256 _pTradeTrigger,
uint256 _minSplit,
uint256 _pSellPercent,
uint256 _maxSell,
uint256 _pStipend,
uint256 _maxStipend,
uint256 _minGain) external onlyGovernance {
// Changes a lot of trading parameters in one call
require(_pTradeTrigger <= 100000 && _pSellPercent <= 100000 && _pStipend <= 100000,"Percent cannot be greater than 100%");
percentTradeTrigger = _pTradeTrigger;
minTradeSplit = _minSplit;
maxPercentSell = _pSellPercent;
maxAmountSell = _maxSell;
maxPercentStipend = _pStipend;
gasStipend = _maxStipend;
minGain = _minGain;
}
// --------------------
// Timelock variables
uint256 private _timelockStart; // The start of the timelock to change governance variables
uint256 private _timelockType; // The function that needs to be changed
uint256 constant TIMELOCK_DURATION = 86400; // Timelock is 24 hours
// Reusable timelock variables
address private _timelock_address;
uint256[3] private _timelock_data;
modifier timelockConditionsMet(uint256 _type) {
require(_timelockType == _type, "Timelock not acquired for this function");
_timelockType = 0; // Reset the type once the timelock is used
if(balance() > 0){ // Timelock only applies when balance exists
require(now >= _timelockStart + TIMELOCK_DURATION, "Timelock time not met");
}
_;
}
// Change the owner of the token contract
// --------------------
function startGovernanceChange(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 1;
_timelock_address = _address;
}
function finishGovernanceChange() external onlyGovernance timelockConditionsMet(1) {
transferGovernance(_timelock_address);
}
// --------------------
// Change the treasury address
// --------------------
function startChangeTreasury(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 2;
_timelock_address = _address;
}
function finishChangeTreasury() external onlyGovernance timelockConditionsMet(2) {
treasuryAddress = _timelock_address;
}
// --------------------
// Change the staking address
// --------------------
function startChangeStakingPool(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 3;
_timelock_address = _address;
}
function finishChangeStakingPool() external onlyGovernance timelockConditionsMet(3) {
stakingAddress = _timelock_address;
}
// --------------------
// Change the zsToken address
// --------------------
function startChangeZSToken(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 4;
_timelock_address = _address;
}
function finishChangeZSToken() external onlyGovernance timelockConditionsMet(4) {
zsTokenAddress = _timelock_address;
}
// --------------------
// Change the strategy allocations between the parties
// --------------------
function startChangeStrategyAllocations(uint256 _pDepositors,
uint256 _pExecutor, uint256 _pStakers) external onlyGovernance {
// Changes strategy allocations in one call
require(_pDepositors <= 100000 && _pExecutor <= 100000 && _pStakers <= 100000,"Percent cannot be greater than 100%");
_timelockStart = now;
_timelockType = 5;
_timelock_data[0] = _pDepositors;
_timelock_data[1] = _pExecutor;
_timelock_data[2] = _pStakers;
}
function finishChangeStrategyAllocations() external onlyGovernance timelockConditionsMet(5) {
percentDepositor = _timelock_data[0];
percentExecutor = _timelock_data[1];
percentStakers = _timelock_data[2];
}
// --------------------
} | -------------------- Change the staking address -------------------- | function startChangeStakingPool(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 3;
_timelock_address = _address;
}
| 5,721,397 | [
1,
1271,
553,
7576,
326,
384,
6159,
1758,
12146,
6062,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
787,
3043,
510,
6159,
2864,
12,
2867,
389,
2867,
13,
3903,
1338,
43,
1643,
82,
1359,
288,
203,
3639,
389,
8584,
292,
975,
1685,
273,
2037,
31,
203,
3639,
389,
8584,
292,
975,
559,
273,
890,
31,
203,
3639,
389,
8584,
292,
975,
67,
2867,
273,
389,
2867,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract 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];
}
}
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,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @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;
}
}
contract CouponTokenConfig {
string public constant name = "Coupon Chain Token";
string public constant symbol = "CCT";
uint8 public constant decimals = 18;
uint256 internal constant DECIMALS_FACTOR = 10 ** uint(decimals);
uint256 internal constant TOTAL_COUPON_SUPPLY = 1000000000 * DECIMALS_FACTOR;
uint8 constant USER_NONE = 0;
uint8 constant USER_FOUNDER = 1;
uint8 constant USER_BUYER = 2;
uint8 constant USER_BONUS = 3;
}
//contract CouponToken is MintableToken {
contract CouponToken is StandardToken, Ownable, CouponTokenConfig {
using SafeMath for uint256;
// Start time of the Sale-lot 4
uint256 public startTimeOfSaleLot4;
// End time of Sale
uint256 public endSaleTime;
// Address of CouponTokenSale contract
address public couponTokenSaleAddr;
// Address of CouponTokenBounty contract
address public couponTokenBountyAddr;
// Address of CouponTokenCampaign contract
address public couponTokenCampaignAddr;
// List of User for Vesting Period
mapping(address => uint8) vestingUsers;
/*
*
* E v e n t s
*
*/
event Mint(address indexed to, uint256 tokens);
/*
*
* M o d i f i e r s
*
*/
modifier canMint() {
require(
couponTokenSaleAddr == msg.sender ||
couponTokenBountyAddr == msg.sender ||
couponTokenCampaignAddr == msg.sender);
_;
}
modifier onlyCallFromCouponTokenSale() {
require(msg.sender == couponTokenSaleAddr);
_;
}
modifier onlyIfValidTransfer(address sender) {
require(isTransferAllowed(sender) == true);
_;
}
modifier onlyCallFromTokenSaleOrBountyOrCampaign() {
require(
msg.sender == couponTokenSaleAddr ||
msg.sender == couponTokenBountyAddr ||
msg.sender == couponTokenCampaignAddr);
_;
}
/*
*
* C o n s t r u c t o r
*
*/
constructor() public {
balances[msg.sender] = 0;
}
/*
*
* F u n c t i o n s
*
*/
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) canMint public {
require(totalSupply_.add(_amount) <= TOTAL_COUPON_SUPPLY);
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
}
/*
* Transfer token from message sender to another
*
* @param to: Destination address
* @param value: Amount of Coupon token to transfer
*/
function transfer(address to, uint256 value)
public
onlyIfValidTransfer(msg.sender)
returns (bool) {
return super.transfer(to, value);
}
/*
* Transfer token from 'from' address to 'to' addreess
*
* @param from: Origin address
* @param to: Destination address
* @param value: Amount of Coupon Token to transfer
*/
function transferFrom(address from, address to, uint256 value)
public
onlyIfValidTransfer(from)
returns (bool){
return super.transferFrom(from, to, value);
}
function setContractAddresses(
address _couponTokenSaleAddr,
address _couponTokenBountyAddr,
address _couponTokenCampaignAddr)
external
onlyOwner
{
couponTokenSaleAddr = _couponTokenSaleAddr;
couponTokenBountyAddr = _couponTokenBountyAddr;
couponTokenCampaignAddr = _couponTokenCampaignAddr;
}
function setSalesEndTime(uint256 _endSaleTime)
external
onlyCallFromCouponTokenSale {
endSaleTime = _endSaleTime;
}
function setSaleLot4StartTime(uint256 _startTime)
external
onlyCallFromCouponTokenSale {
startTimeOfSaleLot4 = _startTime;
}
function setFounderUser(address _user)
public
onlyCallFromCouponTokenSale {
// Add vesting user as Founder
vestingUsers[_user] = USER_FOUNDER;
}
function setSalesUser(address _user)
public
onlyCallFromCouponTokenSale {
// Add vesting user under sales purchase
vestingUsers[_user] = USER_BUYER;
}
function setBonusUser(address _user)
public
onlyCallFromTokenSaleOrBountyOrCampaign {
// Set this user as who got bonus
vestingUsers[_user] = USER_BONUS;
}
function isTransferAllowed(address _user)
internal view
returns (bool) {
bool retVal = true;
if(vestingUsers[_user] == USER_FOUNDER) {
if(endSaleTime == 0 || // See whether sale is over?
(now < (endSaleTime + 730 days))) // 2 years
retVal = false;
}
else if(vestingUsers[_user] == USER_BUYER || vestingUsers[_user] == USER_BONUS) {
if(startTimeOfSaleLot4 == 0 || // See if the SaleLot4 started?
(now < (startTimeOfSaleLot4 + 90 days)))
retVal = false;
}
return retVal;
}
} | F u n c t i o n s/* @dev Function to mint tokens @param _to The address that will receive the minted tokens. @param _amount The amount of tokens to mint. @return A boolean that indicates if the operation was successful./ | function mint(address _to, uint256 _amount) canMint public {
require(totalSupply_.add(_amount) <= TOTAL_COUPON_SUPPLY);
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
}
| 1,612,941 | [
1,
42,
582,
290,
276,
268,
277,
320,
290,
272,
19,
225,
4284,
358,
312,
474,
2430,
225,
389,
869,
1021,
1758,
716,
903,
6798,
326,
312,
474,
329,
2430,
18,
225,
389,
8949,
1021,
3844,
434,
2430,
358,
312,
474,
18,
327,
432,
1250,
716,
8527,
309,
326,
1674,
1703,
6873,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
312,
474,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
848,
49,
474,
1071,
288,
203,
540,
203,
3639,
2583,
12,
4963,
3088,
1283,
27799,
1289,
24899,
8949,
13,
1648,
399,
19851,
67,
3865,
3079,
673,
67,
13272,
23893,
1769,
203,
203,
3639,
2078,
3088,
1283,
67,
273,
2078,
3088,
1283,
27799,
1289,
24899,
8949,
1769,
203,
3639,
324,
26488,
63,
67,
869,
65,
273,
324,
26488,
63,
67,
869,
8009,
1289,
24899,
8949,
1769,
203,
3639,
3626,
490,
474,
24899,
869,
16,
389,
8949,
1769,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
389,
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
] |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "./helpers/timeHelper.sol";
import "./oraclesign.sol";
/**
* @dev EmiDelivery contract recevs signed user's requests and allows to claim requested tokens after XX time passed
* admin set: lock time period, can reject requesdt, deposite and withdraw tokens
*/
contract emidelivery is ReentrancyGuardUpgradeable, OwnableUpgradeable, OracleSign, timeHelper {
using SafeERC20Upgradeable for IERC20Upgradeable;
IERC20Upgradeable public deliveryToken;
// settings values
address public signatureWallet;
uint256 public claimTimeout;
uint256 public claimDailyLimit;
// allow only one unclaimed request for the wallet, make new request only after fully claimed previous
bool public isOneRequest;
/**
* working day shift feature, to make YMD shifted of block.timestamp
*
* cases:
* Paris local time from block.timestamp (GMT) + 1 hour
* localShift = true
* positiveShift = 1 * 60 * 60
*
* NewYork local time from block.timestamp (GMT) - 5 hour
* localShift = false
* positiveShift = 5 * 60 * 60
*
* Tokyo local time from block.timestamp (GMT) + 9 hour
* localShift = true
* positiveShift = 9 * 60 * 60
*/
bool public positiveShift;
uint256 public localShift;
// current rest of daily limit available to claim
uint256 public currentClaimDailyLimit;
uint256 public lastYMD;
mapping(address => uint256) public walletNonce;
/*
availableForRequests = deliveryToken.balanceOf() - lockedForRequests
*/
// value locked by existing unclaimed requests values
uint256 public lockedForRequests;
/*
request record structure
"rest request payment" = requestedAmount - paidAmount
*/
struct Request {
uint256 claimfromYMD; // date for start claiming
uint256 requestedAmount;
uint256 paidAmount;
uint256 index; // index at walletRequests
bool isDeactivated; // false by default means request is actual (not deactivated by admin)
}
// raw request list
Request[] public requests;
// wallet -> request ids list, to reduce memory usage needs to move (clear from requests) finished id to finishedRequests
mapping(address => uint256[]) public walletRequests;
// request -> wallet, only added link for getting wallet by requestId
mapping(uint256 => address) public requestWallet;
// wallet -> finished request ids list
mapping(address => uint256[]) public walletFinishedRequests;
// operator - activated
mapping(address => bool) public operators;
event ClaimRequested(address indexed wallet, uint256 indexed requestId);
event Claimed(address indexed wallet, uint256 amount);
modifier onlyOperator() {
require(operators[msg.sender], "Only operator allowed");
_;
}
function initialize(
address _signatureWallet,
address _deliveryToken,
address _deliveryAdmin,
uint256 _claimTimeout,
uint256 _claimDailyLimit,
bool _isOneRequest,
uint256 _localShift,
bool _positiveShift
) public virtual initializer {
__Ownable_init();
transferOwnership(_deliveryAdmin);
signatureWallet = _signatureWallet;
claimTimeout = _claimTimeout;
claimDailyLimit = _claimDailyLimit;
deliveryToken = IERC20Upgradeable(_deliveryToken);
isOneRequest = _isOneRequest;
operators[_deliveryAdmin] = true;
localShift = _localShift;
positiveShift = _positiveShift;
}
function getWalletNonce() public view returns (uint256) {
return walletNonce[msg.sender];
}
function request(
address wallet,
uint256 amount,
uint256 nonce,
bytes memory sig
) public {
require(wallet == msg.sender, "incorrect sender");
require(amount <= availableForRequests(), "insufficient reserves");
if (isOneRequest) {
(uint256 remainder, , , ) = getRemainderOfRequests();
require(isOneRequest && remainder == 0, "unclaimed request exists");
}
// check sign
bytes32 message = _prefixed(keccak256(abi.encodePacked(wallet, amount, nonce, this)));
require(
_recoverSigner(message, sig) == signatureWallet && walletNonce[msg.sender] < nonce,
"incorrect signature"
);
walletNonce[wallet] = nonce;
// set requests
requests.push(
Request({
claimfromYMD: timestampToYMD(localTime() + claimTimeout),
requestedAmount: amount,
paidAmount: 0,
index: walletRequests[msg.sender].length, // save index
isDeactivated: false
})
);
lockedForRequests += amount;
// save request id by wallet
walletRequests[msg.sender].push(requests.length - 1); // Request.index
// link request to wallet
requestWallet[requests.length - 1] = msg.sender;
emit ClaimRequested(msg.sender, requests.length - 1);
}
function claim() public {
_updateLimits();
(uint256 available, uint256[] memory requestIds) = getAvailableToClaim();
require(available > 0, "nothing to claim");
require(available <= currentClaimDailyLimit, "Limit exceeded");
currentClaimDailyLimit -= available;
_claimRequests(available, requestIds);
lockedForRequests -= available;
deliveryToken.safeTransfer(msg.sender, available);
emit Claimed(msg.sender, available);
}
/***************************** internal ****************************/
/**
* @dev update daily limits: reset on new day
*/
function _updateLimits() internal {
// set next day limits
if (lastYMD < timestampToYMD(localTime())) {
currentClaimDailyLimit = claimDailyLimit;
lastYMD = timestampToYMD(localTime());
}
}
function _claimRequests(uint256 available, uint256[] memory requestIds) internal {
require(requestIds.length > 0, "no requests for claiming");
// go by requests and claim available amount one by one
for (uint256 i = 0; i < requestIds.length; i++) {
uint256 reqId = requestIds[i];
require(requests[reqId].claimfromYMD <= timestampToYMD(localTime()), "incorrect claim");
if (available <= 0) return;
// claim available
uint256 restOfPayment = requests[reqId].requestedAmount - requests[reqId].paidAmount;
// reduce available by rest of payment
if (available >= restOfPayment) {
requests[reqId].paidAmount += restOfPayment;
available -= restOfPayment;
} else {
requests[reqId].paidAmount += available;
available = 0;
}
// request filled -> add to finished requests and remove from wallet requests
if (requests[reqId].requestedAmount == requests[reqId].paidAmount) {
walletFinishedRequests[msg.sender].push(reqId);
uint256 shiftedReqId = walletRequests[msg.sender][walletRequests[msg.sender].length - 1];
// remove completed reuqest id
walletRequests[msg.sender][requests[reqId].index] = shiftedReqId;
// set index of shifted request to finished reqId
requests[shiftedReqId].index = requests[reqId].index;
// remove freed record
walletRequests[msg.sender].pop();
}
}
}
/****************************** admin ******************************/
function setLocalTimeShift(uint256 newLocalShift, bool newPositiveShift) public onlyOperator {
positiveShift = newPositiveShift;
localShift = newLocalShift;
}
function setOperator(address newOperator, bool isActive) public onlyOwner {
operators[newOperator] = isActive;
}
function setisOneRequest(bool newisOneRequest) public onlyOperator {
require(isOneRequest != newisOneRequest, "nothing to change");
isOneRequest = newisOneRequest;
}
/**
* @dev owner deposit amount for delivery tokens by requests
* @param amount deposited value of "deliveryToken"
*/
function deposite(uint256 amount) public onlyOwner {
require(amount > 0, "amount must be > 0");
deliveryToken.safeTransferFrom(msg.sender, address(this), amount);
}
/**
* @dev owner withdraw amount from available amount
* @param amount for withdraw of "deliveryToken"
*/
function withdraw(uint256 amount) public onlyOwner {
require(amount > 0 && amount <= availableForRequests(), "amount must be > 0 and <= available");
deliveryToken.safeTransfer(msg.sender, amount);
}
function setNewTimeOut(uint256 newClaimTimeout) public onlyOperator {
claimTimeout = newClaimTimeout;
}
/**
* @dev set new claim daily limit, changes affect next day!
*/
function setNewClaimDailyLimit(uint256 newclaimDailyLimit) public onlyOperator {
claimDailyLimit = newclaimDailyLimit;
}
function setSignatureWallet(address _signatureWallet) public onlyOperator {
require(signatureWallet != _signatureWallet, "not changed");
signatureWallet = _signatureWallet;
}
/**
* @dev Owner can transfer out any accidentally sent ERC20 tokens
* @param tokenAddress Address of ERC-20 token to transfer
* @param beneficiary Address to transfer to
* @param amount of tokens to transfer
*/
function transferAnyERC20Token(
address tokenAddress,
address beneficiary,
uint256 amount
) public nonReentrant onlyOwner returns (bool success) {
require(tokenAddress != address(0), "address 0!");
require(tokenAddress != address(deliveryToken), "not deliveryToken");
return IERC20Upgradeable(tokenAddress).transfer(beneficiary, amount);
}
/**
* @dev set request index
*/
function setRequestIndex(uint256 ReuestId, uint256 indexValue) public onlyOperator {
requests[ReuestId].index = indexValue;
}
function reduceLockedForRequests(uint256 freedAmount) public onlyOperator {
lockedForRequests -= freedAmount;
}
/**
* @dev only "operator" remove request list
* @param requestIds - list of gequests to remove
*/
function removeRequest(uint256[] memory requestIds) public onlyOperator {
uint256 freedAmount;
address wallet;
for (uint256 i = 0; i < requestIds.length; i++) {
uint256 reqId = requestIds[i];
// if request is active and not completly paid
Request storage req = requests[reqId];
if (!req.isDeactivated && (req.requestedAmount - req.paidAmount) > 0) {
// save freed amount
freedAmount += (req.requestedAmount - req.paidAmount);
// power off request
req.isDeactivated = true;
// get wallet
wallet = requestWallet[reqId];
//finish request
walletFinishedRequests[wallet].push(reqId);
uint256 shiftedReqId = walletRequests[wallet][walletRequests[wallet].length - 1];
// remove completed reuqest id
walletRequests[wallet][req.index] = shiftedReqId;
// set index of shifted request to finished reqId
requests[shiftedReqId].index = req.index;
walletRequests[wallet].pop();
}
}
// resurect limit
currentClaimDailyLimit += freedAmount;
// reduce requested amount
lockedForRequests -= freedAmount;
}
/*************************** view ************************************/
/**
* @dev get block.timestamp corrected with local settings shift
*/
function localTime() public view returns (uint256 localTimeStamp) {
return positiveShift ? block.timestamp + localShift : block.timestamp - localShift;
}
/**
* @dev get today starting timestamp and tomorrow starting timestamp
*/
function getDatesStarts() public view returns (uint256 todayStart, uint256 tomorrowStart) {
return (
YMDToTimestamp(timestampToYMD(localTime())),
YMDToTimestamp(timestampToYMD(localTime())) + 24 * 60 * 60
);
}
function getClaimDailyLimit() public view returns (uint256 limit) {
if (lastYMD < timestampToYMD(localTime())) {
limit = claimDailyLimit; // if not updated this day
} else {
limit = currentClaimDailyLimit; // if updated
}
}
function totalSupply() public view returns (uint256 supply) {
supply = deliveryToken.balanceOf(address(this));
}
function availableForRequests() public view returns (uint256 available) {
available = totalSupply() - lockedForRequests;
}
function getFinishedRequests(address wallet) public view returns (uint256[] memory requestIds) {
// fillup returning requestIds
if (walletFinishedRequests[wallet].length > 0) {
uint256[] memory _tempList = new uint256[](walletFinishedRequests[wallet].length);
for (uint256 i = 0; i < walletFinishedRequests[wallet].length; i++) {
_tempList[i] = walletFinishedRequests[wallet][i];
}
requestIds = _tempList;
}
}
/**
* @dev get remainder for actual requests
* @return remainderTotal - total reuqested amount, not respected day limits
* @return remainderPreparedForClaim - total reuqested amount, ready to claim at this day, not respected day limits
* @return requestIds - list of actual request IDs
* @return veryFirstRequestDate very first request claim-ready day from actual requests
*/
function getRemainderOfRequests()
public
view
returns (
uint256 remainderTotal,
uint256 remainderPreparedForClaim,
uint256[] memory requestIds,
uint256 veryFirstRequestDate
)
{
(remainderTotal, remainderPreparedForClaim, requestIds, veryFirstRequestDate) = getRemainderOfRequestsbyWallet(
msg.sender
);
}
/**
* @dev get remainder for actual requests by passed wallet
* @param wallet - wallet for getting data
* @return remainderTotal - total reuqested amount, not respected day limits
* @return remainderPreparedForClaim - total reuqested amount, ready to claim at this day, not respected day limits
* @return requestIds - list of actual request IDs
* @return veryFirstRequestDate very first request claim-ready day from actual requests
*/
function getRemainderOfRequestsbyWallet(address wallet)
public
view
returns (
uint256 remainderTotal,
uint256 remainderPreparedForClaim,
uint256[] memory requestIds,
uint256 veryFirstRequestDate
)
{
uint256 count;
for (uint256 i = 0; i < walletRequests[wallet].length; i++) {
Request memory _req = requests[walletRequests[wallet][i]];
// add remainderTotal amount for all requests
remainderTotal += _req.requestedAmount - _req.paidAmount;
if (veryFirstRequestDate == 0 || _req.claimfromYMD <= veryFirstRequestDate) {
veryFirstRequestDate = _req.claimfromYMD;
}
// calc amounts prepared for claim not respected day limits
if (_req.claimfromYMD <= timestampToYMD(localTime())) {
remainderPreparedForClaim += _req.requestedAmount - _req.paidAmount;
}
// count requests
count++;
}
// fillup returning requestIds
if (count > 0) {
uint256[] memory _tempList = new uint256[](count);
for (uint256 i = 0; i < walletRequests[wallet].length; i++) {
count--;
_tempList[count] = walletRequests[wallet][i];
}
requestIds = _tempList;
}
}
/**
* @dev get available tokens to claim according claim date and day limits, so once requested available will shown after claim date
* @return available - tokens amount for the sender wallet
* @return requestIds - request ids for the sender wallet
*/
function getAvailableToClaim() public view returns (uint256 available, uint256[] memory requestIds) {
(available, requestIds) = getAvailableToClaimbyWallet(msg.sender);
}
/**
* @dev get available tokens to claim according claim date and day limits by passed wallet, so once requested available will shown after claim date
* @param wallet - wallet for getting data
* @return available - tokens amount for the sender wallet
* @return requestIds - request ids for the sender wallet
*/
function getAvailableToClaimbyWallet(address wallet)
public
view
returns (uint256 available, uint256[] memory requestIds)
{
uint256 count;
uint256 restOfPayment;
uint256 dailyLimit = getClaimDailyLimit();
uint256 _localYMD = timestampToYMD(localTime());
for (uint256 i = 0; i < walletRequests[wallet].length; i++) {
Request memory _req = requests[walletRequests[wallet][i]];
restOfPayment = _req.requestedAmount - _req.paidAmount;
if (available < dailyLimit && !_req.isDeactivated && restOfPayment > 0 && _req.claimfromYMD <= _localYMD) {
if (available + restOfPayment <= dailyLimit) {
available += restOfPayment;
count++;
} else {
available = dailyLimit;
count++;
break;
}
}
}
// fillup returning requestIds
if (count > 0) {
uint256[] memory _tempList = new uint256[](count);
for (uint256 i = 0; i < walletRequests[wallet].length; i++) {
Request memory _req = requests[walletRequests[wallet][i]];
if (
available <= dailyLimit &&
!_req.isDeactivated &&
(_req.requestedAmount - _req.paidAmount) > 0 &&
_req.claimfromYMD <= _localYMD
) {
count--;
// save request id
_tempList[count] = walletRequests[wallet][i];
// only one request takes it all - quit
if (available == dailyLimit) {
break;
}
}
}
requestIds = _tempList;
}
}
function checkRequests() public view returns (uint256 lockedByActiveRequests) {
for (uint256 i = 0; i < requests.length; i++) {
// if request is active and not completly paid
Request storage req = requests[i];
if (!req.isDeactivated && (req.requestedAmount - req.paidAmount) > 0) {
lockedByActiveRequests += (req.requestedAmount - req.paidAmount);
}
}
}
}
| wallet -> finished request ids list | mapping(address => uint256[]) public walletFinishedRequests;
| 911,503 | [
1,
19177,
317,
6708,
590,
3258,
666,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
12,
2867,
516,
2254,
5034,
63,
5717,
1071,
9230,
10577,
6421,
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
] |
./full_match/1/0x06903cC35c37f90B4A9ef38B0b037262a327F83B/sources/contracts/Light.sol | code below expects that integer overflows will revert
| pragma solidity ^0.8.15; | 16,586,329 | [
1,
710,
5712,
10999,
716,
3571,
9391,
87,
903,
15226,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
3600,
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
] |
pragma solidity ^0.4.18;
interface token {
function transferFrom(address _from, address _to, uint256 _value) public;
}
contract RetailSale {
address public beneficiary;
uint public actualPrice;
uint public nextPrice;
uint public nextPriceDate = 0;
uint public periodStart;
uint public periodEnd;
uint public bonus = 0;
uint public bonusStart = 0;
uint public bonusEnd = 0;
uint public milestone = 0;
uint public milestoneBonus = 0;
bool public milestoneReached = true;
uint public minPurchase;
token public tokenReward;
event FundTransfer(address backer, uint amount, uint bonus, uint tokens);
/**
* Constrctor function
*
* Setup the owner
*/
function RetailSale(
address _beneficiary,
address addressOfTokenUsedAsReward,
uint ethPriceInWei,
uint _minPurchase,
uint start,
uint end
) public {
beneficiary = _beneficiary;
tokenReward = token(addressOfTokenUsedAsReward);
actualPrice = ethPriceInWei;
nextPrice = ethPriceInWei;
minPurchase = _minPurchase;
periodStart = start;
periodEnd = end;
}
/**
* Fallback function
*
* The function without name is the default function that is called whenever anyone sends funds to a contract
*/
function()
payable
isOpen
aboveMinValue
public {
uint price = actualPrice;
if (now >= nextPriceDate) {
price = nextPrice;
}
uint vp = (msg.value * 1 ether) / price;
uint b = 0;
uint tokens = 0;
if (now >= bonusStart && now <= bonusEnd) {
b = bonus;
}
if (this.balance >= milestone && !milestoneReached) {
b = milestoneBonus;
milestoneReached = true;
}
if (b == 0) {
tokens = vp;
} else {
tokens = (vp + ((vp * b) / 100));
}
tokenReward.transferFrom(beneficiary, msg.sender, tokens);
FundTransfer(msg.sender, msg.value, b, tokens);
}
modifier aboveMinValue() {
require(msg.value >= minPurchase);
_;
}
modifier isOwner() {
require(msg.sender == beneficiary);
_;
}
modifier isClosed() {
require(!(now >= periodStart && now <= periodEnd));
_;
}
modifier isOpen() {
require(now >= periodStart && now <= periodEnd);
_;
}
modifier validPeriod(uint start, uint end){
require(start < end);
_;
}
/**
* Set next start date
* @param _start the next start date in seconds.
* @param _start the next end date in seconds.
*/
function setNextPeriod(uint _start, uint _end)
isOwner
validPeriod(_start, _end)
public {
periodStart = _start;
periodEnd = _end;
}
/**
* Set the new min purchase value
* @param _minPurchase the new minpurchase value in wei.
*/
function setMinPurchase(uint _minPurchase)
isOwner
public {
minPurchase = _minPurchase;
}
/**
* Change the bonus percentage
* @param _bonus the new bonus percentage.
* @param _bonusStart When the bonus starts in seconds.
* @param _bonusEnd When the bonus ends in seconds.
*/
function changeBonus(uint _bonus, uint _bonusStart, uint _bonusEnd)
isOwner
public {
bonus = _bonus;
bonusStart = _bonusStart;
bonusEnd = _bonusEnd;
}
/**
* Change the next milestone
* @param _milestone The next milestone amount in wei
* @param _milestoneBonus The bonus of the next milestone
*/
function setNextMilestone(uint _milestone, uint _milestoneBonus)
isOwner
public {
milestone = _milestone;
milestoneBonus = _milestoneBonus;
milestoneReached = false;
}
/**
* Set the next price
* @param _price The next eth price in wei
* @param _priceDate The date in second when the next price start
*/
function setNextPrice(uint _price, uint _priceDate)
isOwner
public {
actualPrice = nextPrice;
nextPrice = _price;
nextPriceDate = _priceDate;
}
/**
* Withdraw the funds
*
* Checks to see if goal or time limit has been reached, and if so, and the funding goal was reached,
* sends the entire amount to the beneficiary. If goal was not reached, each contributor can withdraw
* the amount they contributed.
*/
function safeWithdrawal()
isClosed
isOwner
public {
beneficiary.transfer(this.balance);
}
function open() view public returns (bool) {
return (now >= periodStart && now <= periodEnd);
}
} | * Set the next price @param _price The next eth price in wei @param _priceDate The date in second when the next price start/ | function setNextPrice(uint _price, uint _priceDate)
isOwner
public {
actualPrice = nextPrice;
nextPrice = _price;
nextPriceDate = _priceDate;
}
| 373,622 | [
1,
694,
326,
1024,
6205,
225,
389,
8694,
1021,
1024,
13750,
6205,
316,
732,
77,
225,
389,
8694,
1626,
1021,
1509,
316,
2205,
1347,
326,
1024,
6205,
787,
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,
27674,
5147,
12,
11890,
389,
8694,
16,
2254,
389,
8694,
1626,
13,
203,
565,
353,
5541,
203,
565,
1071,
288,
203,
3639,
3214,
5147,
273,
1024,
5147,
31,
203,
3639,
1024,
5147,
273,
389,
8694,
31,
203,
3639,
1024,
5147,
1626,
273,
389,
8694,
1626,
31,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xA0d1345244C89b5574ba50bd6530d4EBd237e826/sources/DigitalaxLPStaking.sol | @dev Updates the amount of rewards owed for each user before any tokens are moved | function updateReward(
address _user
)
public
{
rewardsContract.updateRewards();
uint256 lpRewards = rewardsContract.LPRewards(lastUpdateTime,
block.timestamp);
if (stakedLPTotal > 0) {
rewardsPerTokenPoints = rewardsPerTokenPoints.add(lpRewards
.mul(1e18)
.mul(pointMultiplier)
.div(stakedLPTotal));
}
lastUpdateTime = block.timestamp;
uint256 rewards = rewardsOwing(_user);
Staker storage staker = stakers[_user];
if (_user != address(0)) {
staker.rewardsEarned = staker.rewardsEarned.add(rewards);
staker.lastRewardPoints = rewardsPerTokenPoints;
}
}
| 4,298,332 | [
1,
5121,
326,
3844,
434,
283,
6397,
2523,
329,
364,
1517,
729,
1865,
1281,
2430,
854,
10456,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1089,
17631,
1060,
12,
203,
3639,
1758,
389,
1355,
203,
565,
262,
7010,
3639,
1071,
7010,
565,
288,
203,
203,
3639,
283,
6397,
8924,
18,
2725,
17631,
14727,
5621,
203,
3639,
2254,
5034,
12423,
17631,
14727,
273,
283,
6397,
8924,
18,
48,
8025,
359,
14727,
12,
2722,
1891,
950,
16,
203,
4766,
13491,
1203,
18,
5508,
1769,
203,
203,
3639,
309,
261,
334,
9477,
48,
1856,
1568,
405,
374,
13,
288,
203,
5411,
283,
6397,
2173,
1345,
5636,
273,
283,
6397,
2173,
1345,
5636,
18,
1289,
12,
9953,
17631,
14727,
203,
4766,
13491,
263,
16411,
12,
21,
73,
2643,
13,
203,
4766,
13491,
263,
16411,
12,
1153,
23365,
13,
203,
4766,
13491,
263,
2892,
12,
334,
9477,
48,
1856,
1568,
10019,
203,
3639,
289,
203,
540,
203,
3639,
1142,
1891,
950,
273,
1203,
18,
5508,
31,
203,
3639,
2254,
5034,
283,
6397,
273,
283,
6397,
3494,
310,
24899,
1355,
1769,
203,
203,
3639,
934,
6388,
2502,
384,
6388,
273,
384,
581,
414,
63,
67,
1355,
15533,
203,
3639,
309,
261,
67,
1355,
480,
1758,
12,
20,
3719,
288,
203,
5411,
384,
6388,
18,
266,
6397,
41,
1303,
329,
273,
384,
6388,
18,
266,
6397,
41,
1303,
329,
18,
1289,
12,
266,
6397,
1769,
203,
5411,
384,
6388,
18,
2722,
17631,
1060,
5636,
273,
283,
6397,
2173,
1345,
5636,
31,
7010,
3639,
289,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0x52cbE67E81C61549Dc7115CE1A26D39Ef39f0793/sources/contracts/IMasStaking1155Upgradeable.sol | * @notice Set time unit. Set as a number of seconds. Could be specified as -- x 1 hours, x 1 days, etc. @dev Only admin/authorized-account can call it. @param _tokenId ERC1155 token Id. @param _timeUnit New time unit./ | function setTimeUnit(uint256 _tokenId, uint256 _timeUnit) external virtual {
if (!_canSetStakeConditions()) {
revert("Not authorized");
}
uint256 _nextConditionId = nextConditionId[_tokenId];
StakingCondition memory condition = _nextConditionId == 0
? defaultCondition[nextDefaultConditionId - 1]
: stakingConditions[_tokenId][_nextConditionId - 1];
require(_timeUnit != condition.timeUnit, "Time-unit unchanged.");
_setStakingCondition(_tokenId, _timeUnit, condition.iMasRewardsPerUnitTime, condition.iMasXRewardsPerUnitTime);
emit UpdatedTimeUnit(_tokenId, condition.timeUnit, _timeUnit);
}
| 7,047,538 | [
1,
694,
813,
2836,
18,
1000,
487,
279,
1300,
434,
3974,
18,
6647,
14312,
506,
1269,
487,
1493,
619,
225,
404,
7507,
16,
619,
225,
404,
4681,
16,
5527,
18,
4202,
5098,
3981,
19,
8434,
17,
4631,
848,
745,
518,
18,
282,
389,
2316,
548,
377,
4232,
39,
2499,
2539,
1147,
3124,
18,
282,
389,
957,
2802,
565,
1166,
813,
2836,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
11195,
2802,
12,
11890,
5034,
389,
2316,
548,
16,
2254,
5034,
389,
957,
2802,
13,
3903,
5024,
288,
203,
3639,
309,
16051,
67,
4169,
694,
510,
911,
8545,
10756,
288,
203,
5411,
15226,
2932,
1248,
10799,
8863,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
389,
4285,
3418,
548,
273,
1024,
3418,
548,
63,
67,
2316,
548,
15533,
203,
3639,
934,
6159,
3418,
3778,
2269,
273,
389,
4285,
3418,
548,
422,
374,
203,
5411,
692,
805,
3418,
63,
4285,
1868,
3418,
548,
300,
404,
65,
203,
5411,
294,
384,
6159,
8545,
63,
67,
2316,
548,
6362,
67,
4285,
3418,
548,
300,
404,
15533,
203,
3639,
2583,
24899,
957,
2802,
480,
2269,
18,
957,
2802,
16,
315,
950,
17,
4873,
14827,
1199,
1769,
203,
203,
3639,
389,
542,
510,
6159,
3418,
24899,
2316,
548,
16,
389,
957,
2802,
16,
2269,
18,
77,
49,
345,
17631,
14727,
2173,
2802,
950,
16,
2269,
18,
77,
49,
345,
60,
17631,
14727,
2173,
2802,
950,
1769,
203,
203,
3639,
3626,
19301,
950,
2802,
24899,
2316,
548,
16,
2269,
18,
957,
2802,
16,
389,
957,
2802,
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
] |
./full_match/4/0xf749B509E209107cee2B013FCC93046F46409EE2/sources/UUUU.sol | * @title VVVV contract @dev Extends ERC721 Non-Fungible Token Standard basic implementation/ | contract WWWW is ERC721, ERC721Enumerable, Ownable {
using Strings for uint256;
string public PROVENANCE = "";
uint public constant maxTokenPurchase = 15;
uint256 public MAX_TOKENS = 100;
bool public saleIsActive = false;
bool public revealed = false;
uint public presaleMaxMint = 7;
bool public presaleActive = false;
mapping(address => bool) private presaleList;
mapping(address => uint256) private presalePurchases;
string baseURI;
string private notRevealedUri;
string public baseExtension = ".json";
constructor(
string memory _initNotRevealedUri
pragma solidity ^0.8.0;
) ERC721("WWWW", "WWWW") {
setNotRevealedURI(_initNotRevealedUri);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) {
return super.supportsInterface(interfaceId);
}
function setPresaleMaxMint(uint256 _presaleMaxMint) external onlyOwner {
presaleMaxMint = _presaleMaxMint;
}
function flipPresaleState() external onlyOwner {
presaleActive = !presaleActive;
}
function addToPresaleList(address[] calldata addresses) external onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
if (!presaleList[addresses[i]]) {
presaleList[addresses[i]] = true;
presalePurchases[addresses[i]] = 0;
}
}
}
function addToPresaleList(address[] calldata addresses) external onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
if (!presaleList[addresses[i]]) {
presaleList[addresses[i]] = true;
presalePurchases[addresses[i]] = 0;
}
}
}
function addToPresaleList(address[] calldata addresses) external onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
if (!presaleList[addresses[i]]) {
presaleList[addresses[i]] = true;
presalePurchases[addresses[i]] = 0;
}
}
}
function isOnPresaleList(address addr) external view returns (bool) {
return presaleList[addr];
}
function presaleAmountAvailable(address addr) external view returns (uint256) {
if (presaleList[addr]) {
return presaleMaxMint - presalePurchases[addr];
}
return 0;
}
function presaleAmountAvailable(address addr) external view returns (uint256) {
if (presaleList[addr]) {
return presaleMaxMint - presalePurchases[addr];
}
return 0;
}
function mintPresale(uint256 _mintAmount) public payable {
uint256 supply = totalSupply();
require(presaleActive, "Presale must be active to mint Tokens");
require(_mintAmount > 0, "_mintAmount must be at 0");
require(_mintAmount <= presaleMaxMint, "_mintAmount must be <= presaleMaxMint");
require(supply + _mintAmount <= MAX_TOKENS, "Mint must not surpass maxSupply");
require(msg.value >= tokenPrice * _mintAmount, "Not enough money");
require(presaleList[msg.sender] == true, "Not on the list");
require(presalePurchases[msg.sender] + _mintAmount <= presaleMaxMint, "No presale mints left");
presalePurchases[msg.sender] += _mintAmount;
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, supply + i);
}
}
function mintPresale(uint256 _mintAmount) public payable {
uint256 supply = totalSupply();
require(presaleActive, "Presale must be active to mint Tokens");
require(_mintAmount > 0, "_mintAmount must be at 0");
require(_mintAmount <= presaleMaxMint, "_mintAmount must be <= presaleMaxMint");
require(supply + _mintAmount <= MAX_TOKENS, "Mint must not surpass maxSupply");
require(msg.value >= tokenPrice * _mintAmount, "Not enough money");
require(presaleList[msg.sender] == true, "Not on the list");
require(presalePurchases[msg.sender] + _mintAmount <= presaleMaxMint, "No presale mints left");
presalePurchases[msg.sender] += _mintAmount;
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, supply + i);
}
}
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if(revealed == false) {
return notRevealedUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension))
: "";
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if(revealed == false) {
return notRevealedUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension))
: "";
}
function setProvenance(string memory provenance) public onlyOwner {
PROVENANCE = provenance;
}
function reveal() public onlyOwner() {
revealed = true;
}
function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner {
notRevealedUri = _notRevealedURI;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function reserveTokens() public onlyOwner {
uint supply = totalSupply();
uint i;
for (i = 0; i < 13; i++) {
_safeMint(msg.sender, supply + i);
}
}
function reserveTokens() public onlyOwner {
uint supply = totalSupply();
uint i;
for (i = 0; i < 13; i++) {
_safeMint(msg.sender, supply + i);
}
}
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
function mint(uint numberOfTokens) public payable {
uint256 supply = totalSupply();
require(saleIsActive, "Sale must be active to mint Tokens");
require(numberOfTokens <= maxTokenPurchase, "Exceeded max token purchase");
require(totalSupply() + numberOfTokens <= MAX_TOKENS, "Purchase would exceed max supply of tokens");
require(tokenPrice * numberOfTokens <= msg.value, "Ether value sent is not correct");
presalePurchases[msg.sender] += numberOfTokens;
for (uint256 i = 1; i <= numberOfTokens; i++) {
_safeMint(msg.sender, supply + i);
}
}
function mint(uint numberOfTokens) public payable {
uint256 supply = totalSupply();
require(saleIsActive, "Sale must be active to mint Tokens");
require(numberOfTokens <= maxTokenPurchase, "Exceeded max token purchase");
require(totalSupply() + numberOfTokens <= MAX_TOKENS, "Purchase would exceed max supply of tokens");
require(tokenPrice * numberOfTokens <= msg.value, "Ether value sent is not correct");
presalePurchases[msg.sender] += numberOfTokens;
for (uint256 i = 1; i <= numberOfTokens; i++) {
_safeMint(msg.sender, supply + i);
}
}
function withdraw() public onlyOwner {
uint balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
} | 659,437 | [
1,
58,
58,
58,
58,
6835,
225,
6419,
5839,
4232,
39,
27,
5340,
3858,
17,
42,
20651,
1523,
3155,
8263,
5337,
4471,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
678,
19989,
59,
353,
4232,
39,
27,
5340,
16,
4232,
39,
27,
5340,
3572,
25121,
16,
14223,
6914,
288,
203,
565,
1450,
8139,
364,
2254,
5034,
31,
203,
377,
203,
565,
533,
1071,
4629,
58,
1157,
4722,
273,
1408,
31,
203,
203,
565,
2254,
1071,
5381,
943,
1345,
23164,
273,
4711,
31,
203,
565,
2254,
5034,
1071,
4552,
67,
8412,
55,
273,
2130,
31,
203,
203,
565,
1426,
1071,
272,
5349,
2520,
3896,
273,
629,
31,
203,
565,
1426,
1071,
283,
537,
18931,
273,
629,
31,
203,
203,
565,
2254,
1071,
4075,
5349,
2747,
49,
474,
273,
2371,
31,
203,
565,
1426,
1071,
4075,
5349,
3896,
273,
629,
31,
203,
203,
565,
2874,
12,
2867,
516,
1426,
13,
3238,
4075,
5349,
682,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
4075,
5349,
10262,
343,
3304,
31,
203,
203,
565,
533,
1026,
3098,
31,
203,
565,
533,
3238,
486,
426,
537,
18931,
3006,
31,
203,
565,
533,
1071,
1026,
3625,
273,
3552,
1977,
14432,
203,
377,
203,
203,
565,
3885,
12,
203,
3639,
533,
3778,
389,
2738,
1248,
426,
537,
18931,
3006,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
203,
3639,
262,
4232,
39,
27,
5340,
2932,
19989,
19989,
3113,
315,
19989,
19989,
7923,
288,
203,
1850,
444,
1248,
426,
537,
18931,
3098,
24899,
2738,
1248,
426,
537,
18931,
3006,
1769,
203,
565,
289,
203,
203,
565,
445,
389,
5771,
1345,
5912,
12,
2867,
628,
16,
1758,
358,
16,
2254,
5034,
1147,
548,
2
] |
./partial_match/3/0xb622C2d63b258d9515e87f8051A37b58e87f2CDB/sources/CircleSwapPair.sol | bytes32 private constant PairCodeHash = keccak256(type(InitializableProductProxy).creationCode); it will be changed when deploy because of Swarm bzzrbytes32 private constant PairCodeHash = hex'9e3d176cd7b9504eb5f6b77283eeba7ad886f58601c2a02d5adcb699159904b4';bytes32 private constant PairCodeHash = hex'493e805a012a4ce1167ced187774d903abbec5300ab15a5c67fa30aad54cbc19'; | library UniswapV2Library {
using SafeMath for uint;
bytes32 private constant PairCodeHash = hex'fedbb088ef498755e9141b5dd7d391cda1cccf1803cda25f76bfc0c3d685474a';
function pairCodeHash() internal pure returns (bytes32) {
return PairCodeHash;
}
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');
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
))));
}
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
| 5,158,891 | [
1,
3890,
1578,
3238,
5381,
8599,
1085,
2310,
273,
417,
24410,
581,
5034,
12,
723,
12,
4435,
6934,
4133,
3886,
2934,
17169,
1085,
1769,
4202,
518,
903,
506,
3550,
1347,
7286,
2724,
434,
348,
13113,
324,
6378,
86,
3890,
1578,
3238,
5381,
8599,
1085,
2310,
273,
3827,
11,
29,
73,
23,
72,
28493,
4315,
27,
70,
8778,
3028,
24008,
25,
74,
26,
70,
4700,
6030,
23,
1340,
12124,
27,
361,
28,
5292,
74,
25,
14181,
71,
22,
69,
3103,
72,
25,
361,
7358,
26,
2733,
3600,
2733,
3028,
70,
24,
13506,
3890,
1578,
3238,
5381,
8599,
1085,
2310,
273,
3827,
11,
7616,
23,
73,
3672,
25,
69,
1611,
22,
69,
24,
311,
20562,
27,
3263,
2643,
4700,
5608,
72,
29,
4630,
19364,
557,
8643,
713,
378,
3600,
69,
25,
71,
9599,
507,
5082,
69,
361,
6564,
28409,
3657,
13506,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
12083,
1351,
291,
91,
438,
58,
22,
9313,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
31,
203,
565,
1731,
1578,
3238,
5381,
8599,
1085,
2310,
273,
3827,
11,
31835,
9897,
20,
5482,
10241,
7616,
11035,
2539,
73,
29,
3461,
21,
70,
25,
449,
27,
72,
5520,
21,
71,
2414,
21,
952,
8522,
2643,
4630,
71,
2414,
2947,
74,
6669,
70,
7142,
20,
71,
23,
72,
9470,
6564,
5608,
69,
13506,
203,
377,
203,
565,
445,
3082,
1085,
2310,
1435,
2713,
16618,
1135,
261,
3890,
1578,
13,
288,
203,
3639,
327,
8599,
1085,
2310,
31,
203,
565,
289,
203,
377,
203,
565,
445,
1524,
5157,
12,
2867,
1147,
37,
16,
1758,
1147,
38,
13,
2713,
16618,
1135,
261,
2867,
1147,
20,
16,
1758,
1147,
21,
13,
288,
203,
3639,
2583,
12,
2316,
37,
480,
1147,
38,
16,
296,
984,
291,
91,
438,
58,
22,
9313,
30,
19768,
10109,
67,
8355,
7031,
1090,
55,
8284,
203,
3639,
261,
2316,
20,
16,
1147,
21,
13,
273,
1147,
37,
411,
1147,
38,
692,
261,
2316,
37,
16,
1147,
38,
13,
294,
261,
2316,
38,
16,
1147,
37,
1769,
203,
3639,
2583,
12,
2316,
20,
480,
1758,
12,
20,
3631,
296,
984,
291,
91,
438,
58,
22,
9313,
30,
18449,
67,
15140,
8284,
203,
565,
289,
203,
203,
565,
445,
3082,
1290,
12,
2867,
3272,
16,
1758,
1147,
37,
16,
1758,
1147,
38,
13,
2713,
16618,
1135,
261,
2867,
3082,
13,
288,
203,
3639,
261,
2867,
1147,
20,
16,
1758,
1147,
21,
13,
273,
1524,
5157,
12,
2316,
2
] |
pragma solidity ^0.4.24;
import "./UserEscrow.sol";
import "contracts/NuCypherToken.sol";
import "contracts/MinersEscrow.sol";
import "contracts/PolicyManager.sol";
/**
* @notice Proxy to access main contracts from the UserEscrow contract
* @dev All methods must be stateless because this code will execute by delegatecall call
* If state is needed - use getStateContract() method to access state of this contract
**/
contract UserEscrowProxy {
event DepositedAsMiner(address indexed owner, uint256 value, uint16 periods);
event WithdrawnAsMiner(address indexed owner, uint256 value);
event Locked(address indexed owner, uint256 value, uint16 periods);
event Divided(address indexed owner, uint256 index, uint256 newValue, uint16 periods);
event ActivityConfirmed(address indexed owner);
event Mined(address indexed owner);
event PolicyRewardWithdrawn(address indexed owner, uint256 value);
event MinRewardRateSet(address indexed owner, uint256 value);
NuCypherToken public token;
MinersEscrow public escrow;
PolicyManager public policyManager;
/**
* @notice Constructor sets addresses of the contracts
* @param _token Token contract
* @param _escrow Escrow contract
* @param _policyManager PolicyManager contract
**/
constructor(
NuCypherToken _token,
MinersEscrow _escrow,
PolicyManager _policyManager
)
public
{
require(address(_token) != 0x0 &&
address(_escrow) != 0x0 &&
address(_policyManager) != 0x0);
token = _token;
escrow = _escrow;
policyManager = _policyManager;
}
/**
* @notice Get contract which stores state
* @dev Assume that `this` is the UserEscrow contract
**/
function getStateContract() internal view returns (UserEscrowProxy) {
UserEscrowLibraryLinker linker = UserEscrow(address(this)).linker();
return UserEscrowProxy(linker.target());
}
/**
* @notice Deposit tokens to the miners escrow
* @param _value Amount of token to deposit
* @param _periods Amount of periods during which tokens will be locked
**/
function depositAsMiner(uint256 _value, uint16 _periods) public {
UserEscrowProxy state = getStateContract();
NuCypherToken tokenFromState = state.token();
require(tokenFromState.balanceOf(address(this)) > _value);
MinersEscrow escrowFromState = state.escrow();
tokenFromState.approve(address(escrowFromState), _value);
escrowFromState.deposit(_value, _periods);
emit DepositedAsMiner(msg.sender, _value, _periods);
}
/**
* @notice Withdraw available amount of tokens from the miners escrow to the user escrow
* @param _value Amount of token to withdraw
**/
function withdrawAsMiner(uint256 _value) public {
getStateContract().escrow().withdraw(_value);
emit WithdrawnAsMiner(msg.sender, _value);
}
/**
* @notice Lock some tokens or increase lock in the miners escrow
* @param _value Amount of tokens which should lock
* @param _periods Amount of periods during which tokens will be locked
**/
function lock(uint256 _value, uint16 _periods) public {
getStateContract().escrow().lock(_value, _periods);
emit Locked(msg.sender, _value, _periods);
}
/**
* @notice Divide stake into two parts
* @param _index Index of stake
* @param _newValue New stake value
* @param _periods Amount of periods for extending stake
**/
function divideStake(
uint256 _index,
uint256 _newValue,
uint16 _periods
)
public
{
getStateContract().escrow().divideStake(_index, _newValue, _periods);
emit Divided(msg.sender, _index, _newValue, _periods);
}
/**
* @notice Confirm activity for future period in the miners escrow
**/
function confirmActivity() external {
getStateContract().escrow().confirmActivity();
emit ActivityConfirmed(msg.sender);
}
/**
* @notice Mint tokens in the miners escrow
**/
function mint() external {
getStateContract().escrow().mint();
emit Mined(msg.sender);
}
/**
* @notice Withdraw available reward from the policy manager to the user escrow
**/
function withdrawPolicyReward() public {
uint256 value = getStateContract().policyManager().withdraw(msg.sender);
emit PolicyRewardWithdrawn(msg.sender, value);
}
/**
* @notice Set the minimum reward that the miner will take in the policy manager
**/
function setMinRewardRate(uint256 _minRewardRate) public {
getStateContract().policyManager().setMinRewardRate(_minRewardRate);
emit MinRewardRateSet(msg.sender, _minRewardRate);
}
}
| * @notice Get contract which stores state @dev Assume that `this` is the UserEscrow contract/ | function getStateContract() internal view returns (UserEscrowProxy) {
UserEscrowLibraryLinker linker = UserEscrow(address(this)).linker();
return UserEscrowProxy(linker.target());
}
| 5,474,810 | [
1,
967,
6835,
1492,
9064,
919,
225,
15983,
716,
1375,
2211,
68,
353,
326,
2177,
6412,
492,
6835,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
8997,
8924,
1435,
2713,
1476,
1135,
261,
1299,
6412,
492,
3886,
13,
288,
203,
3639,
2177,
6412,
492,
9313,
2098,
264,
28058,
273,
2177,
6412,
492,
12,
2867,
12,
2211,
13,
2934,
1232,
264,
5621,
203,
3639,
327,
2177,
6412,
492,
3886,
12,
1232,
264,
18,
3299,
10663,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: Apache-2.0
pragma solidity >=0.4.9 <0.9.0;
library HederaResponseCodes {
// response codes
int32 public constant OK = 0; // The transaction passed the precheck validations.
int32 public constant INVALID_TRANSACTION = 1; // For any error not handled by specific error codes listed below.
int32 public constant PAYER_ACCOUNT_NOT_FOUND = 2; //Payer account does not exist.
int32 public constant INVALID_NODE_ACCOUNT = 3; //Node Account provided does not match the node account of the node the transaction was submitted to.
int32 public constant TRANSACTION_EXPIRED = 4; // Pre-Check error when TransactionValidStart + transactionValidDuration is less than current consensus time.
int32 public constant INVALID_TRANSACTION_START = 5; // Transaction start time is greater than current consensus time
int32 public constant INVALID_TRANSACTION_DURATION = 6; //valid transaction duration is a positive non zero number that does not exceed 120 seconds
int32 public constant INVALID_SIGNATURE = 7; // The transaction signature is not valid
int32 public constant MEMO_TOO_LONG = 8; //Transaction memo size exceeded 100 bytes
int32 public constant INSUFFICIENT_TX_FEE = 9; // The fee provided in the transaction is insufficient for this type of transaction
int32 public constant INSUFFICIENT_PAYER_BALANCE = 10; // The payer account has insufficient cryptocurrency to pay the transaction fee
int32 public constant DUPLICATE_TRANSACTION = 11; // This transaction ID is a duplicate of one that was submitted to this node or reached consensus in the last 180 seconds (receipt period)
int32 public constant BUSY = 12; //If API is throttled out
int32 public constant NOT_SUPPORTED = 13; //The API is not currently supported
int32 public constant INVALID_FILE_ID = 14; //The file id is invalid or does not exist
int32 public constant INVALID_ACCOUNT_ID = 15; //The account id is invalid or does not exist
int32 public constant INVALID_CONTRACT_ID = 16; //The contract id is invalid or does not exist
int32 public constant INVALID_TRANSACTION_ID = 17; //Transaction id is not valid
int32 public constant RECEIPT_NOT_FOUND = 18; //Receipt for given transaction id does not exist
int32 public constant RECORD_NOT_FOUND = 19; //Record for given transaction id does not exist
int32 public constant INVALID_SOLIDITY_ID = 20; //The solidity id is invalid or entity with this solidity id does not exist
int32 public constant UNKNOWN = 21; // The responding node has submitted the transaction to the network. Its final status is still unknown.
int32 public constant SUCCESS = 22; // The transaction succeeded
int32 public constant FAIL_INVALID = 23; // There was a system error and the transaction failed because of invalid request parameters.
int32 public constant FAIL_FEE = 24; // There was a system error while performing fee calculation, reserved for future.
int32 public constant FAIL_BALANCE = 25; // There was a system error while performing balance checks, reserved for future.
int32 public constant KEY_REQUIRED = 26; //Key not provided in the transaction body
int32 public constant BAD_ENCODING = 27; //Unsupported algorithm/encoding used for keys in the transaction
int32 public constant INSUFFICIENT_ACCOUNT_BALANCE = 28; //When the account balance is not sufficient for the transfer
int32 public constant INVALID_SOLIDITY_ADDRESS = 29; //During an update transaction when the system is not able to find the Users Solidity address
int32 public constant INSUFFICIENT_GAS = 30; //Not enough gas was supplied to execute transaction
int32 public constant CONTRACT_SIZE_LIMIT_EXCEEDED = 31; //contract byte code size is over the limit
int32 public constant LOCAL_CALL_MODIFICATION_EXCEPTION = 32; //local execution (query) is requested for a function which changes state
int32 public constant CONTRACT_REVERT_EXECUTED = 33; //Contract REVERT OPCODE executed
int32 public constant CONTRACT_EXECUTION_EXCEPTION = 34; //For any contract execution related error not handled by specific error codes listed above.
int32 public constant INVALID_RECEIVING_NODE_ACCOUNT = 35; //In Query validation, account with +ve(amount) value should be Receiving node account, the receiver account should be only one account in the list
int32 public constant MISSING_QUERY_HEADER = 36; // Header is missing in Query request
int32 public constant ACCOUNT_UPDATE_FAILED = 37; // The update of the account failed
int32 public constant INVALID_KEY_ENCODING = 38; // Provided key encoding was not supported by the system
int32 public constant NULL_SOLIDITY_ADDRESS = 39; // null solidity address
int32 public constant CONTRACT_UPDATE_FAILED = 40; // update of the contract failed
int32 public constant INVALID_QUERY_HEADER = 41; // the query header is invalid
int32 public constant INVALID_FEE_SUBMITTED = 42; // Invalid fee submitted
int32 public constant INVALID_PAYER_SIGNATURE = 43; // Payer signature is invalid
int32 public constant KEY_NOT_PROVIDED = 44; // The keys were not provided in the request.
int32 public constant INVALID_EXPIRATION_TIME = 45; // Expiration time provided in the transaction was invalid.
int32 public constant NO_WACL_KEY = 46; //WriteAccess Control Keys are not provided for the file
int32 public constant FILE_CONTENT_EMPTY = 47; //The contents of file are provided as empty.
int32 public constant INVALID_ACCOUNT_AMOUNTS = 48; // The crypto transfer credit and debit do not sum equal to 0
int32 public constant EMPTY_TRANSACTION_BODY = 49; // Transaction body provided is empty
int32 public constant INVALID_TRANSACTION_BODY = 50; // Invalid transaction body provided
int32 public constant INVALID_SIGNATURE_TYPE_MISMATCHING_KEY = 51; // the type of key (base ed25519 key, KeyList, or ThresholdKey) does not match the type of signature (base ed25519 signature, SignatureList, or ThresholdKeySignature)
int32 public constant INVALID_SIGNATURE_COUNT_MISMATCHING_KEY = 52; // the number of key (KeyList, or ThresholdKey) does not match that of signature (SignatureList, or ThresholdKeySignature). e.g. if a keyList has 3 base keys, then the corresponding signatureList should also have 3 base signatures.
int32 public constant EMPTY_LIVE_HASH_BODY = 53; // the livehash body is empty
int32 public constant EMPTY_LIVE_HASH = 54; // the livehash data is missing
int32 public constant EMPTY_LIVE_HASH_KEYS = 55; // the keys for a livehash are missing
int32 public constant INVALID_LIVE_HASH_SIZE = 56; // the livehash data is not the output of a SHA-384 digest
int32 public constant EMPTY_QUERY_BODY = 57; // the query body is empty
int32 public constant EMPTY_LIVE_HASH_QUERY = 58; // the crypto livehash query is empty
int32 public constant LIVE_HASH_NOT_FOUND = 59; // the livehash is not present
int32 public constant ACCOUNT_ID_DOES_NOT_EXIST = 60; // the account id passed has not yet been created.
int32 public constant LIVE_HASH_ALREADY_EXISTS = 61; // the livehash already exists for a given account
int32 public constant INVALID_FILE_WACL = 62; // File WACL keys are invalid
int32 public constant SERIALIZATION_FAILED = 63; // Serialization failure
int32 public constant TRANSACTION_OVERSIZE = 64; // The size of the Transaction is greater than transactionMaxBytes
int32 public constant TRANSACTION_TOO_MANY_LAYERS = 65; // The Transaction has more than 50 levels
int32 public constant CONTRACT_DELETED = 66; //Contract is marked as deleted
int32 public constant PLATFORM_NOT_ACTIVE = 67; // the platform node is either disconnected or lagging behind.
int32 public constant KEY_PREFIX_MISMATCH = 68; // one public key matches more than one prefixes on the signature map
int32 public constant PLATFORM_TRANSACTION_NOT_CREATED = 69; // transaction not created by platform due to large backlog
int32 public constant INVALID_RENEWAL_PERIOD = 70; // auto renewal period is not a positive number of seconds
int32 public constant INVALID_PAYER_ACCOUNT_ID = 71; // the response code when a smart contract id is passed for a crypto API request
int32 public constant ACCOUNT_DELETED = 72; // the account has been marked as deleted
int32 public constant FILE_DELETED = 73; // the file has been marked as deleted
int32 public constant ACCOUNT_REPEATED_IN_ACCOUNT_AMOUNTS = 74; // same accounts repeated in the transfer account list
int32 public constant SETTING_NEGATIVE_ACCOUNT_BALANCE = 75; // attempting to set negative balance value for crypto account
int32 public constant OBTAINER_REQUIRED = 76; // when deleting smart contract that has crypto balance either transfer account or transfer smart contract is required
int32 public constant OBTAINER_SAME_CONTRACT_ID = 77; //when deleting smart contract that has crypto balance you can not use the same contract id as transferContractId as the one being deleted
int32 public constant OBTAINER_DOES_NOT_EXIST = 78; //transferAccountId or transferContractId specified for contract delete does not exist
int32 public constant MODIFYING_IMMUTABLE_CONTRACT = 79; //attempting to modify (update or delete a immutable smart contract, i.e. one created without a admin key)
int32 public constant FILE_SYSTEM_EXCEPTION = 80; //Unexpected exception thrown by file system functions
int32 public constant AUTORENEW_DURATION_NOT_IN_RANGE = 81; // the duration is not a subset of [MINIMUM_AUTORENEW_DURATION,MAXIMUM_AUTORENEW_DURATION]
int32 public constant ERROR_DECODING_BYTESTRING = 82; // Decoding the smart contract binary to a byte array failed. Check that the input is a valid hex string.
int32 public constant CONTRACT_FILE_EMPTY = 83; // File to create a smart contract was of length zero
int32 public constant CONTRACT_BYTECODE_EMPTY = 84; // Bytecode for smart contract is of length zero
int32 public constant INVALID_INITIAL_BALANCE = 85; // Attempt to set negative initial balance
int32 public constant INVALID_RECEIVE_RECORD_THRESHOLD = 86; // [Deprecated]. attempt to set negative receive record threshold
int32 public constant INVALID_SEND_RECORD_THRESHOLD = 87; // [Deprecated]. attempt to set negative send record threshold
int32 public constant ACCOUNT_IS_NOT_GENESIS_ACCOUNT = 88; // Special Account Operations should be performed by only Genesis account, return this code if it is not Genesis Account
int32 public constant PAYER_ACCOUNT_UNAUTHORIZED = 89; // The fee payer account doesn't have permission to submit such Transaction
int32 public constant INVALID_FREEZE_TRANSACTION_BODY = 90; // FreezeTransactionBody is invalid
int32 public constant FREEZE_TRANSACTION_BODY_NOT_FOUND = 91; // FreezeTransactionBody does not exist
int32 public constant TRANSFER_LIST_SIZE_LIMIT_EXCEEDED = 92; //Exceeded the number of accounts (both from and to) allowed for crypto transfer list
int32 public constant RESULT_SIZE_LIMIT_EXCEEDED = 93; // Smart contract result size greater than specified maxResultSize
int32 public constant NOT_SPECIAL_ACCOUNT = 94; //The payer account is not a special account(account 0.0.55)
int32 public constant CONTRACT_NEGATIVE_GAS = 95; // Negative gas was offered in smart contract call
int32 public constant CONTRACT_NEGATIVE_VALUE = 96; // Negative value / initial balance was specified in a smart contract call / create
int32 public constant INVALID_FEE_FILE = 97; // Failed to update fee file
int32 public constant INVALID_EXCHANGE_RATE_FILE = 98; // Failed to update exchange rate file
int32 public constant INSUFFICIENT_LOCAL_CALL_GAS = 99; // Payment tendered for contract local call cannot cover both the fee and the gas
int32 public constant ENTITY_NOT_ALLOWED_TO_DELETE = 100; // Entities with Entity ID below 1000 are not allowed to be deleted
int32 public constant AUTHORIZATION_FAILED = 101; // Violating one of these rules: 1) treasury account can update all entities below 0.0.1000, 2) account 0.0.50 can update all entities from 0.0.51 - 0.0.80, 3) Network Function Master Account A/c 0.0.50 - Update all Network Function accounts & perform all the Network Functions listed below, 4) Network Function Accounts: i) A/c 0.0.55 - Update Address Book files (0.0.101/102), ii) A/c 0.0.56 - Update Fee schedule (0.0.111), iii) A/c 0.0.57 - Update Exchange Rate (0.0.112).
int32 public constant FILE_UPLOADED_PROTO_INVALID = 102; // Fee Schedule Proto uploaded but not valid (append or update is required)
int32 public constant FILE_UPLOADED_PROTO_NOT_SAVED_TO_DISK = 103; // Fee Schedule Proto uploaded but not valid (append or update is required)
int32 public constant FEE_SCHEDULE_FILE_PART_UPLOADED = 104; // Fee Schedule Proto File Part uploaded
int32 public constant EXCHANGE_RATE_CHANGE_LIMIT_EXCEEDED = 105; // The change on Exchange Rate exceeds Exchange_Rate_Allowed_Percentage
int32 public constant MAX_CONTRACT_STORAGE_EXCEEDED = 106; // Contract permanent storage exceeded the currently allowable limit
int32 public constant TRANSFER_ACCOUNT_SAME_AS_DELETE_ACCOUNT = 107; // Transfer Account should not be same as Account to be deleted
int32 public constant TOTAL_LEDGER_BALANCE_INVALID = 108;
int32 public constant EXPIRATION_REDUCTION_NOT_ALLOWED = 110; // The expiration date/time on a smart contract may not be reduced
int32 public constant MAX_GAS_LIMIT_EXCEEDED = 111; //Gas exceeded currently allowable gas limit per transaction
int32 public constant MAX_FILE_SIZE_EXCEEDED = 112; // File size exceeded the currently allowable limit
int32 public constant INVALID_TOPIC_ID = 150; // The Topic ID specified is not in the system.
int32 public constant INVALID_ADMIN_KEY = 155; // A provided admin key was invalid.
int32 public constant INVALID_SUBMIT_KEY = 156; // A provided submit key was invalid.
int32 public constant UNAUTHORIZED = 157; // An attempted operation was not authorized (ie - a deleteTopic for a topic with no adminKey).
int32 public constant INVALID_TOPIC_MESSAGE = 158; // A ConsensusService message is empty.
int32 public constant INVALID_AUTORENEW_ACCOUNT = 159; // The autoRenewAccount specified is not a valid, active account.
int32 public constant AUTORENEW_ACCOUNT_NOT_ALLOWED = 160; // An adminKey was not specified on the topic, so there must not be an autoRenewAccount.
// The topic has expired, was not automatically renewed, and is in a 7 day grace period before the topic will be
// deleted unrecoverably. This error response code will not be returned until autoRenew functionality is supported
// by HAPI.
int32 public constant TOPIC_EXPIRED = 162;
int32 public constant INVALID_CHUNK_NUMBER = 163; // chunk number must be from 1 to total (chunks) inclusive.
int32 public constant INVALID_CHUNK_TRANSACTION_ID = 164; // For every chunk, the payer account that is part of initialTransactionID must match the Payer Account of this transaction. The entire initialTransactionID should match the transactionID of the first chunk, but this is not checked or enforced by Hedera except when the chunk number is 1.
int32 public constant ACCOUNT_FROZEN_FOR_TOKEN = 165; // Account is frozen and cannot transact with the token
int32 public constant TOKENS_PER_ACCOUNT_LIMIT_EXCEEDED = 166; // An involved account already has more than <tt>tokens.maxPerAccount</tt> associations with non-deleted tokens.
int32 public constant INVALID_TOKEN_ID = 167; // The token is invalid or does not exist
int32 public constant INVALID_TOKEN_DECIMALS = 168; // Invalid token decimals
int32 public constant INVALID_TOKEN_INITIAL_SUPPLY = 169; // Invalid token initial supply
int32 public constant INVALID_TREASURY_ACCOUNT_FOR_TOKEN = 170; // Treasury Account does not exist or is deleted
int32 public constant INVALID_TOKEN_SYMBOL = 171; // Token Symbol is not UTF-8 capitalized alphabetical string
int32 public constant TOKEN_HAS_NO_FREEZE_KEY = 172; // Freeze key is not set on token
int32 public constant TRANSFERS_NOT_ZERO_SUM_FOR_TOKEN = 173; // Amounts in transfer list are not net zero
int32 public constant MISSING_TOKEN_SYMBOL = 174; // A token symbol was not provided
int32 public constant TOKEN_SYMBOL_TOO_LONG = 175; // The provided token symbol was too long
int32 public constant ACCOUNT_KYC_NOT_GRANTED_FOR_TOKEN = 176; // KYC must be granted and account does not have KYC granted
int32 public constant TOKEN_HAS_NO_KYC_KEY = 177; // KYC key is not set on token
int32 public constant INSUFFICIENT_TOKEN_BALANCE = 178; // Token balance is not sufficient for the transaction
int32 public constant TOKEN_WAS_DELETED = 179; // Token transactions cannot be executed on deleted token
int32 public constant TOKEN_HAS_NO_SUPPLY_KEY = 180; // Supply key is not set on token
int32 public constant TOKEN_HAS_NO_WIPE_KEY = 181; // Wipe key is not set on token
int32 public constant INVALID_TOKEN_MINT_AMOUNT = 182; // The requested token mint amount would cause an invalid total supply
int32 public constant INVALID_TOKEN_BURN_AMOUNT = 183; // The requested token burn amount would cause an invalid total supply
int32 public constant TOKEN_NOT_ASSOCIATED_TO_ACCOUNT = 184; // A required token-account relationship is missing
int32 public constant CANNOT_WIPE_TOKEN_TREASURY_ACCOUNT = 185; // The target of a wipe operation was the token treasury account
int32 public constant INVALID_KYC_KEY = 186; // The provided KYC key was invalid.
int32 public constant INVALID_WIPE_KEY = 187; // The provided wipe key was invalid.
int32 public constant INVALID_FREEZE_KEY = 188; // The provided freeze key was invalid.
int32 public constant INVALID_SUPPLY_KEY = 189; // The provided supply key was invalid.
int32 public constant MISSING_TOKEN_NAME = 190; // Token Name is not provided
int32 public constant TOKEN_NAME_TOO_LONG = 191; // Token Name is too long
int32 public constant INVALID_WIPING_AMOUNT = 192; // The provided wipe amount must not be negative, zero or bigger than the token holder balance
int32 public constant TOKEN_IS_IMMUTABLE = 193; // Token does not have Admin key set, thus update/delete transactions cannot be performed
int32 public constant TOKEN_ALREADY_ASSOCIATED_TO_ACCOUNT = 194; // An <tt>associateToken</tt> operation specified a token already associated to the account
int32 public constant TRANSACTION_REQUIRES_ZERO_TOKEN_BALANCES = 195; // An attempted operation is invalid until all token balances for the target account are zero
int32 public constant ACCOUNT_IS_TREASURY = 196; // An attempted operation is invalid because the account is a treasury
int32 public constant TOKEN_ID_REPEATED_IN_TOKEN_LIST = 197; // Same TokenIDs present in the token list
int32 public constant TOKEN_TRANSFER_LIST_SIZE_LIMIT_EXCEEDED = 198; // Exceeded the number of token transfers (both from and to) allowed for token transfer list
int32 public constant EMPTY_TOKEN_TRANSFER_BODY = 199; // TokenTransfersTransactionBody has no TokenTransferList
int32 public constant EMPTY_TOKEN_TRANSFER_ACCOUNT_AMOUNTS = 200; // TokenTransfersTransactionBody has a TokenTransferList with no AccountAmounts
int32 public constant INVALID_SCHEDULE_ID = 201; // The Scheduled entity does not exist; or has now expired, been deleted, or been executed
int32 public constant SCHEDULE_IS_IMMUTABLE = 202; // The Scheduled entity cannot be modified. Admin key not set
int32 public constant INVALID_SCHEDULE_PAYER_ID = 203; // The provided Scheduled Payer does not exist
int32 public constant INVALID_SCHEDULE_ACCOUNT_ID = 204; // The Schedule Create Transaction TransactionID account does not exist
int32 public constant NO_NEW_VALID_SIGNATURES = 205; // The provided sig map did not contain any new valid signatures from required signers of the scheduled transaction
int32 public constant UNRESOLVABLE_REQUIRED_SIGNERS = 206; // The required signers for a scheduled transaction cannot be resolved, for example because they do not exist or have been deleted
int32 public constant SCHEDULED_TRANSACTION_NOT_IN_WHITELIST = 207; // Only whitelisted transaction types may be scheduled
int32 public constant SOME_SIGNATURES_WERE_INVALID = 208; // At least one of the signatures in the provided sig map did not represent a valid signature for any required signer
int32 public constant TRANSACTION_ID_FIELD_NOT_ALLOWED = 209; // The scheduled field in the TransactionID may not be set to true
int32 public constant IDENTICAL_SCHEDULE_ALREADY_CREATED = 210; // A schedule already exists with the same identifying fields of an attempted ScheduleCreate (that is, all fields other than scheduledPayerAccountID)
int32 public constant INVALID_ZERO_BYTE_IN_STRING = 211; // A string field in the transaction has a UTF-8 encoding with the prohibited zero byte
int32 public constant SCHEDULE_ALREADY_DELETED = 212; // A schedule being signed or deleted has already been deleted
int32 public constant SCHEDULE_ALREADY_EXECUTED = 213; // A schedule being signed or deleted has already been executed
int32 public constant MESSAGE_SIZE_TOO_LARGE = 214; // ConsensusSubmitMessage request's message size is larger than allowed.
}
| The API is not currently supported
| int32 public constant NOT_SUPPORTED = 13; | 14,068,795 | [
1,
1986,
1491,
353,
486,
4551,
3260,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
509,
1578,
1071,
5381,
4269,
67,
21134,
273,
5958,
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
] |
pragma solidity 0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
if (_a == 0) {
return 0;
}
uint256 c = _a * _b;
assert(c / _a == _b);
return c;
}
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a / _b;
}
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
assert(c >= _a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract holds owner addresses, and provides basic authorization control
* functions.
*/
contract Ownable {
/**
* @dev Allows to check if the given address has owner rights.
* @param _owner The address to check for owner rights.
* @return True if the address is owner, false if it is not.
*/
mapping(address => bool) public owners;
/**
* @dev The Ownable constructor adds the sender
* account to the owners mapping.
*/
constructor() public {
owners[msg.sender] = true;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwners() {
require(owners[msg.sender], 'Owner message sender required.');
_;
}
/**
* @dev Allows the current owners to grant or revoke
* owner-level access rights to the contract.
* @param _owner The address to grant or revoke owner rights.
* @param _isAllowed Boolean granting or revoking owner rights.
* @return True if the operation has passed or throws if failed.
*/
function setOwner(address _owner, bool _isAllowed) public onlyOwners {
require(_owner != address(0), 'Non-zero owner-address required.');
owners[_owner] = _isAllowed;
}
}
/**
* @title Destroyable
* @dev Base contract that can be destroyed by the owners. All funds in contract will be sent back.
*/
contract Destroyable is Ownable {
constructor() public payable {}
/**
* @dev Transfers The current balance to the message sender and terminates the contract.
*/
function destroy() public onlyOwners {
selfdestruct(msg.sender);
}
/**
* @dev Transfers The current balance to the specified _recipient and terminates the contract.
* @param _recipient The address to send the current balance to.
*/
function destroyAndSend(address _recipient) public onlyOwners {
require(_recipient != address(0), 'Non-zero recipient address required.');
selfdestruct(_recipient);
}
}
/**
* @title BotOperated
* @dev The BotOperated contract holds bot addresses, and provides basic authorization control
* functions.
*/
contract BotOperated is Ownable {
/**
* @dev Allows to check if the given address has bot rights.
* @param _bot The address to check for bot rights.
* @return True if the address is bot, false if it is not.
*/
mapping(address => bool) public bots;
/**
* @dev Throws if called by any account other than bot or owner.
*/
modifier onlyBotsOrOwners() {
require(bots[msg.sender] || owners[msg.sender], 'Bot or owner message sender required.');
_;
}
/**
* @dev Throws if called by any account other than the bot.
*/
modifier onlyBots() {
require(bots[msg.sender], 'Bot message sender required.');
_;
}
/**
* @dev The BotOperated constructor adds the sender
* account to the bots mapping.
*/
constructor() public {
bots[msg.sender] = true;
}
/**
* @dev Allows the current owners to grant or revoke
* bot-level access rights to the contract.
* @param _bot The address to grant or revoke bot rights.
* @param _isAllowed Boolean granting or revoking bot rights.
* @return True if the operation has passed or throws if failed.
*/
function setBot(address _bot, bool _isAllowed) public onlyOwners {
require(_bot != address(0), 'Non-zero bot-address required.');
bots[_bot] = _isAllowed;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is BotOperated {
event Pause();
event Unpause();
bool public paused = true;
/**
* @dev Modifier to allow actions only when the contract IS NOT paused.
*/
modifier whenNotPaused() {
require(!paused, 'Unpaused contract required.');
_;
}
/**
* @dev Called by the owner to pause, triggers stopped state.
* @return True if the operation has passed.
*/
function pause() public onlyBotsOrOwners {
paused = true;
emit Pause();
}
/**
* @dev Called by the owner to unpause, returns to normal state.
* @return True if the operation has passed.
*/
function unpause() public onlyBotsOrOwners {
paused = false;
emit Unpause();
}
}
interface EternalDataStorage {
function balances(address _owner) external view returns (uint256);
function setBalance(address _owner, uint256 _value) external;
function allowed(address _owner, address _spender) external view returns (uint256);
function setAllowance(address _owner, address _spender, uint256 _amount) external;
function totalSupply() external view returns (uint256);
function setTotalSupply(uint256 _value) external;
function frozenAccounts(address _target) external view returns (bool isFrozen);
function setFrozenAccount(address _target, bool _isFrozen) external;
function increaseAllowance(address _owner, address _spender, uint256 _increase) external;
function decreaseAllowance(address _owner, address _spender, uint256 _decrease) external;
}
interface Ledger {
function addTransaction(address _from, address _to, uint _tokens) external;
}
interface WhitelistData {
function kycId(address _customer) external view returns (bytes32);
}
/**
* @title ERC20Standard token
* @dev Implementation of the basic standard token.
* @notice https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
*/
contract ERC20Standard {
using SafeMath for uint256;
EternalDataStorage internal dataStorage;
Ledger internal ledger;
WhitelistData internal whitelist;
/**
* @dev Triggered when tokens are transferred.
* @notice MUST trigger when tokens are transferred, including zero value transfers.
*/
event Transfer(address indexed _from, address indexed _to, uint256 _value);
/**
* @dev Triggered whenever approve(address _spender, uint256 _value) is called.
* @notice MUST trigger on any successful call to approve(address _spender, uint256 _value).
*/
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
modifier isWhitelisted(address _customer) {
require(whitelist.kycId(_customer) != 0x0, 'Whitelisted customer required.');
_;
}
/**
* @dev Constructor function that instantiates the EternalDataStorage, Ledger and Whitelist contracts.
* @param _dataStorage Address of the Data Storage Contract.
* @param _ledger Address of the Ledger Contract.
* @param _whitelist Address of the Whitelist Data Contract.
*/
constructor(address _dataStorage, address _ledger, address _whitelist) public {
require(_dataStorage != address(0), 'Non-zero data storage address required.');
require(_ledger != address(0), 'Non-zero ledger address required.');
require(_whitelist != address(0), 'Non-zero whitelist address required.');
dataStorage = EternalDataStorage(_dataStorage);
ledger = Ledger(_ledger);
whitelist = WhitelistData(_whitelist);
}
/**
* @dev Gets the total supply of tokens.
* @return totalSupplyAmount The total amount of tokens.
*/
function totalSupply() public view returns (uint256 totalSupplyAmount) {
return dataStorage.totalSupply();
}
/**
* @dev Get the balance of the specified `_owner` address.
* @return balance The token balance of the given address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return dataStorage.balances(_owner);
}
/**
* @dev Transfer token to a specified address.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
* @return success True if the transfer was successful, or throws.
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
return _transfer(msg.sender, _to, _value);
}
/**
* @dev Transfer `_value` tokens to `_to` in behalf of `_from`.
* @param _from The address of the sender.
* @param _to The address of the recipient.
* @param _value The amount to send.
* @return success True if the transfer was successful, or throws.
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
uint256 allowed = dataStorage.allowed(_from, msg.sender);
require(allowed >= _value, 'From account has insufficient balance');
allowed = allowed.sub(_value);
dataStorage.setAllowance(_from, msg.sender, allowed);
return _transfer(_from, _to, _value);
}
/**
* @dev Allows `_spender` to withdraw from your account multiple times, up to the `_value` amount.
* approve will revert if allowance of _spender is 0. increaseApproval and decreaseApproval should
* be used instead to avoid exploit identified here: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approve
* @notice If this function is called again it overwrites the current allowance with `_value`.
* @param _spender The address authorized to spend.
* @param _value The max amount they can spend.
* @return success True if the operation was successful, or false.
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
require
(
_value == 0 || dataStorage.allowed(msg.sender, _spender) == 0,
'Approve value is required to be zero or account has already been approved.'
);
dataStorage.setAllowance(msg.sender, _spender, _value);
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* This function must be called for increasing approval from a non-zero value
* as using approve will revert. It has been added as a fix to the exploit mentioned
* here: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approve
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint256 _addedValue) public {
dataStorage.increaseAllowance(msg.sender, _spender, _addedValue);
emit Approval(msg.sender, _spender, dataStorage.allowed(msg.sender, _spender));
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* This function must be called for decreasing approval from a non-zero value
* as using approve will revert. It has been added as a fix to the exploit mentioned
* here: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approve
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint256 _subtractedValue) public {
dataStorage.decreaseAllowance(msg.sender, _spender, _subtractedValue);
emit Approval(msg.sender, _spender, dataStorage.allowed(msg.sender, _spender));
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner The address which owns the funds.
* @param _spender 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 dataStorage.allowed(_owner, _spender);
}
/**
* @dev Internal transfer, can only be called by this contract.
* @param _from The address of the sender.
* @param _to The address of the recipient.
* @param _value The amount to send.
* @return success True if the transfer was successful, or throws.
*/
function _transfer(address _from, address _to, uint256 _value) internal returns (bool success) {
require(_to != address(0), 'Non-zero to-address required.');
uint256 fromBalance = dataStorage.balances(_from);
require(fromBalance >= _value, 'From-address has insufficient balance.');
fromBalance = fromBalance.sub(_value);
uint256 toBalance = dataStorage.balances(_to);
toBalance = toBalance.add(_value);
dataStorage.setBalance(_from, fromBalance);
dataStorage.setBalance(_to, toBalance);
ledger.addTransaction(_from, _to, _value);
emit Transfer(_from, _to, _value);
return true;
}
}
/**
* @title MintableToken
* @dev ERC20Standard modified with mintable token creation.
*/
contract MintableToken is ERC20Standard, Ownable {
/**
* @dev Hardcap - maximum allowed amount of tokens to be minted
*/
uint104 public constant MINTING_HARDCAP = 1e30;
/**
* @dev Auto-generated function to check whether the minting has finished.
* @return True if the minting has finished, or false.
*/
bool public mintingFinished = false;
event Mint(address indexed _to, uint256 _amount);
event MintFinished();
modifier canMint() {
require(!mintingFinished, 'Uninished minting required.');
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
*/
function mint(address _to, uint256 _amount) public onlyOwners canMint() {
uint256 totalSupply = dataStorage.totalSupply();
totalSupply = totalSupply.add(_amount);
require(totalSupply <= MINTING_HARDCAP, 'Total supply of token in circulation must be below hardcap.');
dataStorage.setTotalSupply(totalSupply);
uint256 toBalance = dataStorage.balances(_to);
toBalance = toBalance.add(_amount);
dataStorage.setBalance(_to, toBalance);
ledger.addTransaction(address(0), _to, _amount);
emit Transfer(address(0), _to, _amount);
emit Mint(_to, _amount);
}
/**
* @dev Function to permanently stop minting new tokens.
*/
function finishMinting() public onlyOwners {
mintingFinished = true;
emit MintFinished();
}
}
/**
* @title BurnableToken
* @dev ERC20Standard token that can be irreversibly burned(destroyed).
*/
contract BurnableToken is ERC20Standard {
event Burn(address indexed _burner, uint256 _value);
/**
* @dev Remove tokens from the system irreversibly.
* @notice Destroy tokens from your account.
* @param _value The amount of tokens to burn.
*/
function burn(uint256 _value) public {
uint256 senderBalance = dataStorage.balances(msg.sender);
require(senderBalance >= _value, 'Burn value less than account balance required.');
senderBalance = senderBalance.sub(_value);
dataStorage.setBalance(msg.sender, senderBalance);
uint256 totalSupply = dataStorage.totalSupply();
totalSupply = totalSupply.sub(_value);
dataStorage.setTotalSupply(totalSupply);
emit Burn(msg.sender, _value);
emit Transfer(msg.sender, address(0), _value);
}
/**
* @dev Remove specified `_value` tokens from the system irreversibly on behalf of `_from`.
* @param _from The address from which to burn tokens.
* @param _value The amount of money to burn.
*/
function burnFrom(address _from, uint256 _value) public {
uint256 fromBalance = dataStorage.balances(_from);
require(fromBalance >= _value, 'Burn value less than from-account balance required.');
uint256 allowed = dataStorage.allowed(_from, msg.sender);
require(allowed >= _value, 'Burn value less than account allowance required.');
fromBalance = fromBalance.sub(_value);
dataStorage.setBalance(_from, fromBalance);
allowed = allowed.sub(_value);
dataStorage.setAllowance(_from, msg.sender, allowed);
uint256 totalSupply = dataStorage.totalSupply();
totalSupply = totalSupply.sub(_value);
dataStorage.setTotalSupply(totalSupply);
emit Burn(_from, _value);
emit Transfer(_from, address(0), _value);
}
}
/**
* @title PausableToken
* @dev ERC20Standard modified with pausable transfers.
**/
contract PausableToken is ERC20Standard, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool success) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool success) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool success) {
return super.approve(_spender, _value);
}
}
/**
* @title FreezableToken
* @dev ERC20Standard modified with freezing accounts ability.
*/
contract FreezableToken is ERC20Standard, Ownable {
event FrozenFunds(address indexed _target, bool _isFrozen);
/**
* @dev Allow or prevent target address from sending & receiving tokens.
* @param _target Address to be frozen or unfrozen.
* @param _isFrozen Boolean indicating freeze or unfreeze operation.
*/
function freezeAccount(address _target, bool _isFrozen) public onlyOwners {
require(_target != address(0), 'Non-zero to-be-frozen-account address required.');
dataStorage.setFrozenAccount(_target, _isFrozen);
emit FrozenFunds(_target, _isFrozen);
}
/**
* @dev Checks whether the target is frozen or not.
* @param _target Address to check.
* @return isFrozen A boolean that indicates whether the account is frozen or not.
*/
function isAccountFrozen(address _target) public view returns (bool isFrozen) {
return dataStorage.frozenAccounts(_target);
}
/**
* @dev Overrided _transfer function that uses freeze functionality
*/
function _transfer(address _from, address _to, uint256 _value) internal returns (bool success) {
assert(!dataStorage.frozenAccounts(_from));
assert(!dataStorage.frozenAccounts(_to));
return super._transfer(_from, _to, _value);
}
}
/**
* @title ERC20Extended
* @dev Standard ERC20 token with extended functionalities.
*/
contract ERC20Extended is FreezableToken, PausableToken, BurnableToken, MintableToken, Destroyable {
/**
* @dev Auto-generated function that returns the name of the token.
* @return The name of the token.
*/
string public constant name = 'ORBISE10';
/**
* @dev Auto-generated function that returns the symbol of the token.
* @return The symbol of the token.
*/
string public constant symbol = 'ORBT';
/**
* @dev Auto-generated function that returns the number of decimals of the token.
* @return The number of decimals of the token.
*/
uint8 public constant decimals = 18;
/**
* @dev Constant for the minimum allowed amount of tokens one can buy
*/
uint72 public constant MINIMUM_BUY_AMOUNT = 200e18;
/**
* @dev Auto-generated function that gets the price at which the token is sold.
* @return The sell price of the token.
*/
uint256 public sellPrice;
/**
* @dev Auto-generated function that gets the price at which the token is bought.
* @return The buy price of the token.
*/
uint256 public buyPrice;
/**
* @dev Auto-generated function that gets the address of the wallet of the contract.
* @return The address of the wallet.
*/
address public wallet;
/**
* @dev Constructor function that calculates the total supply of tokens,
* sets the initial sell and buy prices and
* passes arguments to base constructors.
* @param _dataStorage Address of the Data Storage Contract.
* @param _ledger Address of the Data Storage Contract.
* @param _whitelist Address of the Whitelist Data Contract.
*/
constructor
(
address _dataStorage,
address _ledger,
address _whitelist
)
ERC20Standard(_dataStorage, _ledger, _whitelist)
public
{
}
/**
* @dev Fallback function that allows the contract
* to receive Ether directly.
*/
function() public payable { }
/**
* @dev Function that sets both the sell and the buy price of the token.
* @param _sellPrice The price at which the token will be sold.
* @param _buyPrice The price at which the token will be bought.
*/
function setPrices(uint256 _sellPrice, uint256 _buyPrice) public onlyBotsOrOwners {
sellPrice = _sellPrice;
buyPrice = _buyPrice;
}
/**
* @dev Function that sets the current wallet address.
* @param _walletAddress The address of wallet to be set.
*/
function setWallet(address _walletAddress) public onlyOwners {
require(_walletAddress != address(0), 'Non-zero wallet address required.');
wallet = _walletAddress;
}
/**
* @dev Send Ether to buy tokens at the current token sell price.
* @notice buy function has minimum allowed amount one can buy
*/
function buy() public payable whenNotPaused isWhitelisted(msg.sender) {
uint256 amount = msg.value.mul(1e18);
amount = amount.div(sellPrice);
require(amount >= MINIMUM_BUY_AMOUNT, "Buy amount too small");
_transfer(this, msg.sender, amount);
}
/**
* @dev Sell `_amount` tokens at the current buy price.
* @param _amount The amount to sell.
*/
function sell(uint256 _amount) public whenNotPaused {
uint256 toBeTransferred = _amount.mul(buyPrice);
require(toBeTransferred >= 1e18, "Sell amount too small");
toBeTransferred = toBeTransferred.div(1e18);
require(address(this).balance >= toBeTransferred, 'Contract has insufficient balance.');
_transfer(msg.sender, this, _amount);
msg.sender.transfer(toBeTransferred);
}
/**
* @dev Get the contract balance in WEI.
*/
function getContractBalance() public view returns (uint256) {
return address(this).balance;
}
/**
* @dev Withdraw `_amount` ETH to the wallet address.
* @param _amount The amount to withdraw.
*/
function withdraw(uint256 _amount) public onlyOwners {
require(address(this).balance >= _amount, 'Unable to withdraw specified amount.');
require(wallet != address(0), 'Non-zero wallet address required.');
wallet.transfer(_amount);
}
/**
* @dev Transfer, which is used when Orbise is bought with different currency than ETH.
* @param _to The address of the recipient.
* @param _value The amount of Orbise Tokens to transfer.
* @return success True if operation is executed successfully.
*/
function nonEtherPurchaseTransfer(address _to, uint256 _value) public isWhitelisted(_to) onlyBots whenNotPaused returns (bool success) {
return _transfer(msg.sender, _to, _value);
}
} | * @dev Get the balance of the specified `_owner` address. @return balance The token balance of the given address./ | function balanceOf(address _owner) public view returns (uint256 balance) {
return dataStorage.balances(_owner);
}
| 12,954,027 | [
1,
967,
326,
11013,
434,
326,
1269,
1375,
67,
8443,
68,
1758,
18,
327,
11013,
1021,
1147,
11013,
434,
326,
864,
1758,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
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,
202,
915,
11013,
951,
12,
2867,
389,
8443,
13,
1071,
1476,
1135,
261,
11890,
5034,
11013,
13,
288,
203,
202,
202,
2463,
501,
3245,
18,
70,
26488,
24899,
8443,
1769,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0xA13E43d299dd822677f3Cc62d3E77b84DC3665c3/sources/project_/contracts/base/MetawinMinterManager.sol | * @dev Contract defining Metawin NFT minting environments Rules: Max 10 mints per transaction (editable by the admin) Price: Dutch auction The ContractStates module facilitates setting time-based state transitions. With {mint} permitted only during state "1", minting can be time-bound and divided into multiple rounds. The {mintingCap} state variable enables adjusting the supply cap for each round. Furthermore, individual rounds can have distinct durations and Dutch auction rules, as these configurations can be modified after each round when preparing the subsequent one./ | contract MetawinMinterManager is Roles, MintingEvents, ReentrancyGuard {
using Clones for address;
mapping(uint8 => MetawinMinterProxy) public minterProxy;
MetawinMinterProxy private immutable _MINTER_IMPLEMENTATION;
event NewMinter(address indexed minterAddress, uint8 indexed minterId, uint64[2] indexed idRange);
error OverlapsExistingBatch(uint8 batchId);
constructor(){
_MINTER_IMPLEMENTATION = new MetawinMinterProxy();
}
function setupMinting(
uint64[2] calldata startEndId,
uint256[] memory startEndTime,
uint256 startPrice,
uint64 priceTimestep,
uint16 priceReductionRate,
bool priceReductionIsCompound
)
external
onlyRole(METAWIN_ROLE)
returns(address proxyAddress)
{
require(startEndTime.length == 2, "Invalid start/end time");
address nftAddress = address(NFTcontract);
require(nftAddress!=address(0), "NFT contract not set");
uint8 overlappedBatch = _findOverlappedBatch(startEndId);
MetawinMinterProxy newProxy = MetawinMinterProxy(address(_MINTER_IMPLEMENTATION).clone());
proxyAddress = address(newProxy);
emit NewMinter(proxyAddress, curNumProxies, startEndId);
newProxy.initialize(
nftAddress,
startEndId,
startEndTime,
startPrice,
priceTimestep,
priceReductionRate,
priceReductionIsCompound
);
_tokenIdRange[curNumProxies] = startEndId;
minterProxy[curNumProxies] = newProxy;
++numProxies;
NFTcontract.grantRole(MINTER_ROLE, address(newProxy));
}
function setNFTaddress(
address _NFTcontract
) external onlyRole(DEFAULT_ADMIN_ROLE) {
NFTcontract = IMetawinNFT(_NFTcontract);
}
function mintTeamReserve(
uint256 amount,
address teamAddress
) external onlyRole(METAWIN_ROLE) nonReentrant {
require(numProxies == 0, "Forbidden: minting started");
uint64[2] memory mintedRange = [0, uint64(amount-1)];
_tokenIdRange[0] = mintedRange;
++numProxies;
NFTcontract.grantRole(MINTER_ROLE, address(this));
NFTcontract.mint(teamAddress, 0, amount);
emit ReservedToTeam(amount);
}
function withdraw() external onlyRole(METAWIN_ROLE) {
uint8 i;
if(minterProxy[i]==MetawinMinterProxy(address(0))) i=1;
for(; i<numProxies;){
minterProxy[i].withdraw();
}
}
function withdraw() external onlyRole(METAWIN_ROLE) {
uint8 i;
if(minterProxy[i]==MetawinMinterProxy(address(0))) i=1;
for(; i<numProxies;){
minterProxy[i].withdraw();
}
}
unchecked{++i;}
function _findOverlappedBatch(uint64[2] calldata startEndId) view private returns (uint8){
uint64[2] memory proxyRange;
uint8 numBatches=numProxies;
for(uint8 i; i<numBatches;){
proxyRange = _tokenIdRange[i];
if(startEndId[0] <= proxyRange[1]){
if(startEndId[1] >= proxyRange[0]){
return i;
}
}
}
return numBatches;
}
function _findOverlappedBatch(uint64[2] calldata startEndId) view private returns (uint8){
uint64[2] memory proxyRange;
uint8 numBatches=numProxies;
for(uint8 i; i<numBatches;){
proxyRange = _tokenIdRange[i];
if(startEndId[0] <= proxyRange[1]){
if(startEndId[1] >= proxyRange[0]){
return i;
}
}
}
return numBatches;
}
function _findOverlappedBatch(uint64[2] calldata startEndId) view private returns (uint8){
uint64[2] memory proxyRange;
uint8 numBatches=numProxies;
for(uint8 i; i<numBatches;){
proxyRange = _tokenIdRange[i];
if(startEndId[0] <= proxyRange[1]){
if(startEndId[1] >= proxyRange[0]){
return i;
}
}
}
return numBatches;
}
function _findOverlappedBatch(uint64[2] calldata startEndId) view private returns (uint8){
uint64[2] memory proxyRange;
uint8 numBatches=numProxies;
for(uint8 i; i<numBatches;){
proxyRange = _tokenIdRange[i];
if(startEndId[0] <= proxyRange[1]){
if(startEndId[1] >= proxyRange[0]){
return i;
}
}
}
return numBatches;
}
unchecked{++i;}
}
| 1,942,857 | [
1,
8924,
9364,
6565,
8082,
423,
4464,
312,
474,
310,
15900,
15718,
30,
377,
4238,
1728,
312,
28142,
1534,
2492,
261,
19653,
635,
326,
3981,
13,
377,
20137,
30,
463,
322,
343,
279,
4062,
377,
1021,
13456,
7629,
1605,
5853,
330,
305,
815,
3637,
813,
17,
12261,
919,
13136,
18,
377,
3423,
288,
81,
474,
97,
15498,
1338,
4982,
919,
315,
21,
3113,
312,
474,
310,
848,
506,
813,
17,
3653,
471,
377,
26057,
1368,
3229,
21196,
18,
1021,
288,
81,
474,
310,
4664,
97,
919,
2190,
19808,
377,
5765,
310,
326,
14467,
3523,
364,
1517,
3643,
18,
478,
295,
451,
1035,
479,
16,
7327,
21196,
848,
377,
1240,
10217,
23920,
471,
463,
322,
343,
279,
4062,
2931,
16,
487,
4259,
10459,
848,
377,
506,
4358,
1839,
1517,
3643,
1347,
675,
12583,
326,
10815,
1245,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
16351,
6565,
8082,
49,
2761,
1318,
353,
19576,
16,
490,
474,
310,
3783,
16,
868,
8230,
12514,
16709,
288,
203,
203,
565,
1450,
3905,
5322,
364,
1758,
31,
203,
203,
565,
2874,
12,
11890,
28,
516,
6565,
8082,
49,
2761,
3886,
13,
1071,
1131,
387,
3886,
31,
203,
565,
6565,
8082,
49,
2761,
3886,
3238,
11732,
389,
6236,
2560,
67,
9883,
7618,
2689,
31,
203,
203,
565,
871,
1166,
49,
2761,
12,
2867,
8808,
1131,
387,
1887,
16,
2254,
28,
8808,
1131,
387,
548,
16,
2254,
1105,
63,
22,
65,
8808,
612,
2655,
1769,
203,
565,
555,
10752,
3762,
87,
9895,
4497,
12,
11890,
28,
2581,
548,
1769,
203,
203,
203,
565,
3885,
1435,
95,
203,
3639,
389,
6236,
2560,
67,
9883,
7618,
2689,
273,
394,
6565,
8082,
49,
2761,
3886,
5621,
203,
565,
289,
203,
203,
565,
445,
3875,
49,
474,
310,
12,
203,
3639,
2254,
1105,
63,
22,
65,
745,
892,
787,
1638,
548,
16,
203,
3639,
2254,
5034,
8526,
3778,
787,
25255,
16,
203,
3639,
2254,
5034,
787,
5147,
16,
203,
3639,
2254,
1105,
6205,
10178,
395,
881,
16,
203,
3639,
2254,
2313,
6205,
3715,
4062,
4727,
16,
203,
3639,
1426,
6205,
3715,
4062,
2520,
16835,
203,
565,
262,
203,
3639,
3903,
203,
3639,
1338,
2996,
12,
19294,
24572,
67,
16256,
13,
203,
3639,
1135,
12,
2867,
2889,
1887,
13,
203,
565,
288,
203,
3639,
2583,
12,
1937,
25255,
18,
2469,
422,
576,
16,
315,
1941,
787,
19,
409,
813,
8863,
203,
3639,
1758,
290,
1222,
1887,
273,
1758,
12,
50,
2
] |
./full_match/44787/0xaBbefF52D9F1cE1d1Cd10bEfC7e0F7DE0AdEb7C7/sources/contracts/StarFarm.sol | Deposit LP tokens to MasterChef for STAR allocation.require (_pid != 0, 'withdraw STAR by unstaking');if (_pid == 0) require(userNFTs[_msgSender()].length == 0, "nft user"); | 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();
uint256 _useramount = user.amount.sub(user.nftAmount);
uint256 _amountGain = _useramount.add(_useramount.mul(_selfGain).div(100));
if (_amountGain > 0) {
uint256 pending = _amountGain.mul(pool.accStarPerShare).div(1e12).sub(user.rewardDebt).add(user.nftRewardDebt);
if(pending > 0) {
if (user.lastDeposit > block.timestamp.sub(604800)) {
pending = pending.mul(90).div(100);
starToken.safeTransfer(bonusAddr, pending.mul(10).div(100));
}
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), user.amount);
}
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(_msgSender(), address(this), _amount);
user.amount = user.amount.add(_amount);
uint256 _extraAmount = _amount.mul(_selfGain.add(_parentGain)).div(100);
pool.extraAmount = pool.extraAmount.add(_extraAmount);
_useramount = user.amount.sub(user.nftAmount);
_amountGain = _useramount.add(_useramount.mul(_selfGain).div(100));
}
user.rewardDebt = _amountGain.mul(pool.accStarPerShare).div(1e12).add(user.nftRewardDebt);
emit Deposit(_msgSender(), _pid, _amount, isNodeUser[_msgSender()]);
}
| 13,269,042 | [
1,
758,
1724,
511,
52,
2430,
358,
13453,
39,
580,
74,
364,
21807,
13481,
18,
6528,
261,
67,
6610,
480,
374,
16,
296,
1918,
9446,
21807,
635,
640,
334,
6159,
8284,
430,
261,
67,
6610,
422,
374,
13,
2583,
12,
1355,
50,
4464,
87,
63,
67,
3576,
12021,
1435,
8009,
2469,
422,
374,
16,
315,
82,
1222,
729,
8863,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
443,
1724,
12,
11890,
5034,
389,
6610,
16,
2254,
5034,
389,
8949,
13,
1071,
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,
3576,
12021,
1435,
15533,
203,
3639,
1089,
2864,
24899,
6610,
1769,
203,
203,
3639,
261,
11890,
5034,
389,
2890,
43,
530,
16,
2254,
5034,
389,
2938,
43,
530,
13,
273,
10443,
907,
18,
2159,
43,
530,
5621,
203,
3639,
2254,
5034,
389,
1355,
8949,
273,
729,
18,
8949,
18,
1717,
12,
1355,
18,
82,
1222,
6275,
1769,
203,
3639,
2254,
5034,
389,
8949,
43,
530,
273,
389,
1355,
8949,
18,
1289,
24899,
1355,
8949,
18,
16411,
24899,
2890,
43,
530,
2934,
2892,
12,
6625,
10019,
203,
203,
3639,
309,
261,
67,
8949,
43,
530,
405,
374,
13,
288,
203,
5411,
2254,
5034,
4634,
273,
389,
8949,
43,
530,
18,
16411,
12,
6011,
18,
8981,
18379,
2173,
9535,
2934,
2892,
12,
21,
73,
2138,
2934,
1717,
12,
1355,
18,
266,
2913,
758,
23602,
2934,
1289,
12,
1355,
18,
82,
1222,
17631,
1060,
758,
23602,
1769,
203,
5411,
309,
12,
9561,
405,
374,
13,
288,
203,
7734,
309,
261,
1355,
18,
2722,
758,
1724,
405,
1203,
18,
5508,
18,
1717,
12,
26,
3028,
17374,
3719,
288,
203,
10792,
4634,
273,
4634,
18,
16411,
12,
9349,
2934,
2892,
12,
6625,
1769,
203,
10792,
10443,
1345,
18,
4626,
5912,
12,
18688,
407,
3178,
16,
4634,
18,
16411,
12,
2163,
2934,
2892,
12,
6625,
10019,
203,
7734,
2
] |
pragma solidity ^0.4.25;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @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 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.
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_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,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
/**
* @title Pausable token
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, Pausable {
function transfer(
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transfer(_to, _value);
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
function approve(
address _spender,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.approve(_spender, _value);
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool success)
{
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool success)
{
return super.decreaseApproval(_spender, _subtractedValue);
}
}
/**
* @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);
}
}
contract RepublicToken is PausableToken, BurnableToken {
string public constant name = "Republic Token";
string public constant symbol = "REN";
uint8 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 1000000000 * 10**uint256(decimals);
/// @notice The RepublicToken Constructor.
constructor() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
function transferTokens(address beneficiary, uint256 amount) public onlyOwner returns (bool) {
/* solium-disable error-reason */
require(amount > 0);
balances[owner] = balances[owner].sub(amount);
balances[beneficiary] = balances[beneficiary].add(amount);
emit Transfer(owner, beneficiary, amount);
return true;
}
}
/**
* @notice LinkedList is a library for a circular double linked list.
*/
library LinkedList {
/*
* @notice A permanent NULL node (0x0) in the circular double linked list.
* NULL.next is the head, and NULL.previous is the tail.
*/
address public constant NULL = 0x0;
/**
* @notice A node points to the node before it, and the node after it. If
* node.previous = NULL, then the node is the head of the list. If
* node.next = NULL, then the node is the tail of the list.
*/
struct Node {
bool inList;
address previous;
address next;
}
/**
* @notice LinkedList uses a mapping from address to nodes. Each address
* uniquely identifies a node, and in this way they are used like pointers.
*/
struct List {
mapping (address => Node) list;
}
/**
* @notice Insert a new node before an existing node.
*
* @param self The list being used.
* @param target The existing node in the list.
* @param newNode The next node to insert before the target.
*/
function insertBefore(List storage self, address target, address newNode) internal {
require(!isInList(self, newNode), "already in list");
require(isInList(self, target) || target == NULL, "not in list");
// It is expected that this value is sometimes NULL.
address prev = self.list[target].previous;
self.list[newNode].next = target;
self.list[newNode].previous = prev;
self.list[target].previous = newNode;
self.list[prev].next = newNode;
self.list[newNode].inList = true;
}
/**
* @notice Insert a new node after an existing node.
*
* @param self The list being used.
* @param target The existing node in the list.
* @param newNode The next node to insert after the target.
*/
function insertAfter(List storage self, address target, address newNode) internal {
require(!isInList(self, newNode), "already in list");
require(isInList(self, target) || target == NULL, "not in list");
// It is expected that this value is sometimes NULL.
address n = self.list[target].next;
self.list[newNode].previous = target;
self.list[newNode].next = n;
self.list[target].next = newNode;
self.list[n].previous = newNode;
self.list[newNode].inList = true;
}
/**
* @notice Remove a node from the list, and fix the previous and next
* pointers that are pointing to the removed node. Removing anode that is not
* in the list will do nothing.
*
* @param self The list being using.
* @param node The node in the list to be removed.
*/
function remove(List storage self, address node) internal {
require(isInList(self, node), "not in list");
if (node == NULL) {
return;
}
address p = self.list[node].previous;
address n = self.list[node].next;
self.list[p].next = n;
self.list[n].previous = p;
// Deleting the node should set this value to false, but we set it here for
// explicitness.
self.list[node].inList = false;
delete self.list[node];
}
/**
* @notice Insert a node at the beginning of the list.
*
* @param self The list being used.
* @param node The node to insert at the beginning of the list.
*/
function prepend(List storage self, address node) internal {
// isInList(node) is checked in insertBefore
insertBefore(self, begin(self), node);
}
/**
* @notice Insert a node at the end of the list.
*
* @param self The list being used.
* @param node The node to insert at the end of the list.
*/
function append(List storage self, address node) internal {
// isInList(node) is checked in insertBefore
insertAfter(self, end(self), node);
}
function swap(List storage self, address left, address right) internal {
// isInList(left) and isInList(right) are checked in remove
address previousRight = self.list[right].previous;
remove(self, right);
insertAfter(self, left, right);
remove(self, left);
insertAfter(self, previousRight, left);
}
function isInList(List storage self, address node) internal view returns (bool) {
return self.list[node].inList;
}
/**
* @notice Get the node at the beginning of a double linked list.
*
* @param self The list being used.
*
* @return A address identifying the node at the beginning of the double
* linked list.
*/
function begin(List storage self) internal view returns (address) {
return self.list[NULL].next;
}
/**
* @notice Get the node at the end of a double linked list.
*
* @param self The list being used.
*
* @return A address identifying the node at the end of the double linked
* list.
*/
function end(List storage self) internal view returns (address) {
return self.list[NULL].previous;
}
function next(List storage self, address node) internal view returns (address) {
require(isInList(self, node), "not in list");
return self.list[node].next;
}
function previous(List storage self, address node) internal view returns (address) {
require(isInList(self, node), "not in list");
return self.list[node].previous;
}
}
/// @notice This contract stores data and funds for the DarknodeRegistry
/// contract. The data / fund logic and storage have been separated to improve
/// upgradability.
contract DarknodeRegistryStore is Ownable {
string public VERSION; // Passed in as a constructor parameter.
/// @notice Darknodes are stored in the darknode struct. The owner is the
/// address that registered the darknode, the bond is the amount of REN that
/// was transferred during registration, and the public key is the
/// encryption key that should be used when sending sensitive information to
/// the darknode.
struct Darknode {
// The owner of a Darknode is the address that called the register
// function. The owner is the only address that is allowed to
// deregister the Darknode, unless the Darknode is slashed for
// malicious behavior.
address owner;
// The bond is the amount of REN submitted as a bond by the Darknode.
// This amount is reduced when the Darknode is slashed for malicious
// behavior.
uint256 bond;
// The block number at which the Darknode is considered registered.
uint256 registeredAt;
// The block number at which the Darknode is considered deregistered.
uint256 deregisteredAt;
// The public key used by this Darknode for encrypting sensitive data
// off chain. It is assumed that the Darknode has access to the
// respective private key, and that there is an agreement on the format
// of the public key.
bytes publicKey;
}
/// Registry data.
mapping(address => Darknode) private darknodeRegistry;
LinkedList.List private darknodes;
// RepublicToken.
RepublicToken public ren;
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
/// @param _ren The address of the RepublicToken contract.
constructor(
string _VERSION,
RepublicToken _ren
) public {
VERSION = _VERSION;
ren = _ren;
}
/// @notice Instantiates a darknode and appends it to the darknodes
/// linked-list.
///
/// @param _darknodeID The darknode's ID.
/// @param _darknodeOwner The darknode's owner's address
/// @param _bond The darknode's bond value
/// @param _publicKey The darknode's public key
/// @param _registeredAt The time stamp when the darknode is registered.
/// @param _deregisteredAt The time stamp when the darknode is deregistered.
function appendDarknode(
address _darknodeID,
address _darknodeOwner,
uint256 _bond,
bytes _publicKey,
uint256 _registeredAt,
uint256 _deregisteredAt
) external onlyOwner {
Darknode memory darknode = Darknode({
owner: _darknodeOwner,
bond: _bond,
publicKey: _publicKey,
registeredAt: _registeredAt,
deregisteredAt: _deregisteredAt
});
darknodeRegistry[_darknodeID] = darknode;
LinkedList.append(darknodes, _darknodeID);
}
/// @notice Returns the address of the first darknode in the store
function begin() external view onlyOwner returns(address) {
return LinkedList.begin(darknodes);
}
/// @notice Returns the address of the next darknode in the store after the
/// given address.
function next(address darknodeID) external view onlyOwner returns(address) {
return LinkedList.next(darknodes, darknodeID);
}
/// @notice Removes a darknode from the store and transfers its bond to the
/// owner of this contract.
function removeDarknode(address darknodeID) external onlyOwner {
uint256 bond = darknodeRegistry[darknodeID].bond;
delete darknodeRegistry[darknodeID];
LinkedList.remove(darknodes, darknodeID);
require(ren.transfer(owner, bond), "bond transfer failed");
}
/// @notice Updates the bond of the darknode. If the bond is being
/// decreased, the difference is sent to the owner of this contract.
function updateDarknodeBond(address darknodeID, uint256 bond) external onlyOwner {
uint256 previousBond = darknodeRegistry[darknodeID].bond;
darknodeRegistry[darknodeID].bond = bond;
if (previousBond > bond) {
require(ren.transfer(owner, previousBond - bond), "cannot transfer bond");
}
}
/// @notice Updates the deregistration timestamp of a darknode.
function updateDarknodeDeregisteredAt(address darknodeID, uint256 deregisteredAt) external onlyOwner {
darknodeRegistry[darknodeID].deregisteredAt = deregisteredAt;
}
/// @notice Returns the owner of a given darknode.
function darknodeOwner(address darknodeID) external view onlyOwner returns (address) {
return darknodeRegistry[darknodeID].owner;
}
/// @notice Returns the bond of a given darknode.
function darknodeBond(address darknodeID) external view onlyOwner returns (uint256) {
return darknodeRegistry[darknodeID].bond;
}
/// @notice Returns the registration time of a given darknode.
function darknodeRegisteredAt(address darknodeID) external view onlyOwner returns (uint256) {
return darknodeRegistry[darknodeID].registeredAt;
}
/// @notice Returns the deregistration time of a given darknode.
function darknodeDeregisteredAt(address darknodeID) external view onlyOwner returns (uint256) {
return darknodeRegistry[darknodeID].deregisteredAt;
}
/// @notice Returns the encryption public key of a given darknode.
function darknodePublicKey(address darknodeID) external view onlyOwner returns (bytes) {
return darknodeRegistry[darknodeID].publicKey;
}
}
/// @notice DarknodeRegistry is responsible for the registration and
/// deregistration of Darknodes.
contract DarknodeRegistry is Ownable {
string public VERSION; // Passed in as a constructor parameter.
/// @notice Darknode pods are shuffled after a fixed number of blocks.
/// An Epoch stores an epoch hash used as an (insecure) RNG seed, and the
/// blocknumber which restricts when the next epoch can be called.
struct Epoch {
uint256 epochhash;
uint256 blocknumber;
}
uint256 public numDarknodes;
uint256 public numDarknodesNextEpoch;
uint256 public numDarknodesPreviousEpoch;
/// Variables used to parameterize behavior.
uint256 public minimumBond;
uint256 public minimumPodSize;
uint256 public minimumEpochInterval;
address public slasher;
/// When one of the above variables is modified, it is only updated when the
/// next epoch is called. These variables store the values for the next epoch.
uint256 public nextMinimumBond;
uint256 public nextMinimumPodSize;
uint256 public nextMinimumEpochInterval;
address public nextSlasher;
/// The current and previous epoch
Epoch public currentEpoch;
Epoch public previousEpoch;
/// Republic ERC20 token contract used to transfer bonds.
RepublicToken public ren;
/// Darknode Registry Store is the storage contract for darknodes.
DarknodeRegistryStore public store;
/// @notice Emitted when a darknode is registered.
/// @param _darknodeID The darknode ID that was registered.
/// @param _bond The amount of REN that was transferred as bond.
event LogDarknodeRegistered(address _darknodeID, uint256 _bond);
/// @notice Emitted when a darknode is deregistered.
/// @param _darknodeID The darknode ID that was deregistered.
event LogDarknodeDeregistered(address _darknodeID);
/// @notice Emitted when a refund has been made.
/// @param _owner The address that was refunded.
/// @param _amount The amount of REN that was refunded.
event LogDarknodeOwnerRefunded(address _owner, uint256 _amount);
/// @notice Emitted when a new epoch has begun.
event LogNewEpoch();
/// @notice Emitted when a constructor parameter has been updated.
event LogMinimumBondUpdated(uint256 previousMinimumBond, uint256 nextMinimumBond);
event LogMinimumPodSizeUpdated(uint256 previousMinimumPodSize, uint256 nextMinimumPodSize);
event LogMinimumEpochIntervalUpdated(uint256 previousMinimumEpochInterval, uint256 nextMinimumEpochInterval);
event LogSlasherUpdated(address previousSlasher, address nextSlasher);
/// @notice Only allow the owner that registered the darknode to pass.
modifier onlyDarknodeOwner(address _darknodeID) {
require(store.darknodeOwner(_darknodeID) == msg.sender, "must be darknode owner");
_;
}
/// @notice Only allow unregistered darknodes.
modifier onlyRefunded(address _darknodeID) {
require(isRefunded(_darknodeID), "must be refunded or never registered");
_;
}
/// @notice Only allow refundable darknodes.
modifier onlyRefundable(address _darknodeID) {
require(isRefundable(_darknodeID), "must be deregistered for at least one epoch");
_;
}
/// @notice Only allowed registered nodes without a pending deregistration to
/// deregister
modifier onlyDeregisterable(address _darknodeID) {
require(isDeregisterable(_darknodeID), "must be deregisterable");
_;
}
/// @notice Only allow the Slasher contract.
modifier onlySlasher() {
require(slasher == msg.sender, "must be slasher");
_;
}
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
/// @param _renAddress The address of the RepublicToken contract.
/// @param _storeAddress The address of the DarknodeRegistryStore contract.
/// @param _minimumBond The minimum bond amount that can be submitted by a
/// Darknode.
/// @param _minimumPodSize The minimum size of a Darknode pod.
/// @param _minimumEpochInterval The minimum number of blocks between
/// epochs.
constructor(
string _VERSION,
RepublicToken _renAddress,
DarknodeRegistryStore _storeAddress,
uint256 _minimumBond,
uint256 _minimumPodSize,
uint256 _minimumEpochInterval
) public {
VERSION = _VERSION;
store = _storeAddress;
ren = _renAddress;
minimumBond = _minimumBond;
nextMinimumBond = minimumBond;
minimumPodSize = _minimumPodSize;
nextMinimumPodSize = minimumPodSize;
minimumEpochInterval = _minimumEpochInterval;
nextMinimumEpochInterval = minimumEpochInterval;
currentEpoch = Epoch({
epochhash: uint256(blockhash(block.number - 1)),
blocknumber: block.number
});
numDarknodes = 0;
numDarknodesNextEpoch = 0;
numDarknodesPreviousEpoch = 0;
}
/// @notice Register a darknode and transfer the bond to this contract. The
/// caller must provide a public encryption key for the darknode as well as
/// a bond in REN. The bond must be provided as an ERC20 allowance. The dark
/// node will remain pending registration until the next epoch. Only after
/// this period can the darknode be deregistered. The caller of this method
/// will be stored as the owner of the darknode.
///
/// @param _darknodeID The darknode ID that will be registered.
/// @param _publicKey The public key of the darknode. It is stored to allow
/// other darknodes and traders to encrypt messages to the trader.
/// @param _bond The bond that will be paid. It must be greater than, or
/// equal to, the minimum bond.
function register(address _darknodeID, bytes _publicKey, uint256 _bond) external onlyRefunded(_darknodeID) {
// REN allowance
require(_bond >= minimumBond, "insufficient bond");
// require(ren.allowance(msg.sender, address(this)) >= _bond);
require(ren.transferFrom(msg.sender, address(this), _bond), "bond transfer failed");
ren.transfer(address(store), _bond);
// Flag this darknode for registration
store.appendDarknode(
_darknodeID,
msg.sender,
_bond,
_publicKey,
currentEpoch.blocknumber + minimumEpochInterval,
0
);
numDarknodesNextEpoch += 1;
// Emit an event.
emit LogDarknodeRegistered(_darknodeID, _bond);
}
/// @notice Deregister a darknode. The darknode will not be deregistered
/// until the end of the epoch. After another epoch, the bond can be
/// refunded by calling the refund method.
/// @param _darknodeID The darknode ID that will be deregistered. The caller
/// of this method store.darknodeRegisteredAt(_darknodeID) must be
// the owner of this darknode.
function deregister(address _darknodeID) external onlyDeregisterable(_darknodeID) onlyDarknodeOwner(_darknodeID) {
// Flag the darknode for deregistration
store.updateDarknodeDeregisteredAt(_darknodeID, currentEpoch.blocknumber + minimumEpochInterval);
numDarknodesNextEpoch -= 1;
// Emit an event
emit LogDarknodeDeregistered(_darknodeID);
}
/// @notice Progress the epoch if it is possible to do so. This captures
/// the current timestamp and current blockhash and overrides the current
/// epoch.
function epoch() external {
if (previousEpoch.blocknumber == 0) {
// The first epoch must be called by the owner of the contract
require(msg.sender == owner, "not authorized (first epochs)");
}
// Require that the epoch interval has passed
require(block.number >= currentEpoch.blocknumber + minimumEpochInterval, "epoch interval has not passed");
uint256 epochhash = uint256(blockhash(block.number - 1));
// Update the epoch hash and timestamp
previousEpoch = currentEpoch;
currentEpoch = Epoch({
epochhash: epochhash,
blocknumber: block.number
});
// Update the registry information
numDarknodesPreviousEpoch = numDarknodes;
numDarknodes = numDarknodesNextEpoch;
// If any update functions have been called, update the values now
if (nextMinimumBond != minimumBond) {
minimumBond = nextMinimumBond;
emit LogMinimumBondUpdated(minimumBond, nextMinimumBond);
}
if (nextMinimumPodSize != minimumPodSize) {
minimumPodSize = nextMinimumPodSize;
emit LogMinimumPodSizeUpdated(minimumPodSize, nextMinimumPodSize);
}
if (nextMinimumEpochInterval != minimumEpochInterval) {
minimumEpochInterval = nextMinimumEpochInterval;
emit LogMinimumEpochIntervalUpdated(minimumEpochInterval, nextMinimumEpochInterval);
}
if (nextSlasher != slasher) {
slasher = nextSlasher;
emit LogSlasherUpdated(slasher, nextSlasher);
}
// Emit an event
emit LogNewEpoch();
}
/// @notice Allows the contract owner to transfer ownership of the
/// DarknodeRegistryStore.
/// @param _newOwner The address to transfer the ownership to.
function transferStoreOwnership(address _newOwner) external onlyOwner {
store.transferOwnership(_newOwner);
}
/// @notice Allows the contract owner to update the minimum bond.
/// @param _nextMinimumBond The minimum bond amount that can be submitted by
/// a darknode.
function updateMinimumBond(uint256 _nextMinimumBond) external onlyOwner {
// Will be updated next epoch
nextMinimumBond = _nextMinimumBond;
}
/// @notice Allows the contract owner to update the minimum pod size.
/// @param _nextMinimumPodSize The minimum size of a pod.
function updateMinimumPodSize(uint256 _nextMinimumPodSize) external onlyOwner {
// Will be updated next epoch
nextMinimumPodSize = _nextMinimumPodSize;
}
/// @notice Allows the contract owner to update the minimum epoch interval.
/// @param _nextMinimumEpochInterval The minimum number of blocks between epochs.
function updateMinimumEpochInterval(uint256 _nextMinimumEpochInterval) external onlyOwner {
// Will be updated next epoch
nextMinimumEpochInterval = _nextMinimumEpochInterval;
}
/// @notice Allow the contract owner to update the DarknodeSlasher contract
/// address.
/// @param _slasher The new slasher address.
function updateSlasher(address _slasher) external onlyOwner {
nextSlasher = _slasher;
}
/// @notice Allow the DarknodeSlasher contract to slash half of a darknode's
/// bond and deregister it. The bond is distributed as follows:
/// 1/2 is kept by the guilty prover
/// 1/8 is rewarded to the first challenger
/// 1/8 is rewarded to the second challenger
/// 1/4 becomes unassigned
/// @param _prover The guilty prover whose bond is being slashed
/// @param _challenger1 The first of the two darknodes who submitted the challenge
/// @param _challenger2 The second of the two darknodes who submitted the challenge
function slash(address _prover, address _challenger1, address _challenger2)
external
onlySlasher
{
uint256 penalty = store.darknodeBond(_prover) / 2;
uint256 reward = penalty / 4;
// Slash the bond of the failed prover in half
store.updateDarknodeBond(_prover, penalty);
// If the darknode has not been deregistered then deregister it
if (isDeregisterable(_prover)) {
store.updateDarknodeDeregisteredAt(_prover, currentEpoch.blocknumber + minimumEpochInterval);
numDarknodesNextEpoch -= 1;
emit LogDarknodeDeregistered(_prover);
}
// Reward the challengers with less than the penalty so that it is not
// worth challenging yourself
ren.transfer(store.darknodeOwner(_challenger1), reward);
ren.transfer(store.darknodeOwner(_challenger2), reward);
}
/// @notice Refund the bond of a deregistered darknode. This will make the
/// darknode available for registration again. Anyone can call this function
/// but the bond will always be refunded to the darknode owner.
///
/// @param _darknodeID The darknode ID that will be refunded. The caller
/// of this method must be the owner of this darknode.
function refund(address _darknodeID) external onlyRefundable(_darknodeID) {
address darknodeOwner = store.darknodeOwner(_darknodeID);
// Remember the bond amount
uint256 amount = store.darknodeBond(_darknodeID);
// Erase the darknode from the registry
store.removeDarknode(_darknodeID);
// Refund the owner by transferring REN
ren.transfer(darknodeOwner, amount);
// Emit an event.
emit LogDarknodeOwnerRefunded(darknodeOwner, amount);
}
/// @notice Retrieves the address of the account that registered a darknode.
/// @param _darknodeID The ID of the darknode to retrieve the owner for.
function getDarknodeOwner(address _darknodeID) external view returns (address) {
return store.darknodeOwner(_darknodeID);
}
/// @notice Retrieves the bond amount of a darknode in 10^-18 REN.
/// @param _darknodeID The ID of the darknode to retrieve the bond for.
function getDarknodeBond(address _darknodeID) external view returns (uint256) {
return store.darknodeBond(_darknodeID);
}
/// @notice Retrieves the encryption public key of the darknode.
/// @param _darknodeID The ID of the darknode to retrieve the public key for.
function getDarknodePublicKey(address _darknodeID) external view returns (bytes) {
return store.darknodePublicKey(_darknodeID);
}
/// @notice Retrieves a list of darknodes which are registered for the
/// current epoch.
/// @param _start A darknode ID used as an offset for the list. If _start is
/// 0x0, the first dark node will be used. _start won't be
/// included it is not registered for the epoch.
/// @param _count The number of darknodes to retrieve starting from _start.
/// If _count is 0, all of the darknodes from _start are
/// retrieved. If _count is more than the remaining number of
/// registered darknodes, the rest of the list will contain
/// 0x0s.
function getDarknodes(address _start, uint256 _count) external view returns (address[]) {
uint256 count = _count;
if (count == 0) {
count = numDarknodes;
}
return getDarknodesFromEpochs(_start, count, false);
}
/// @notice Retrieves a list of darknodes which were registered for the
/// previous epoch. See `getDarknodes` for the parameter documentation.
function getPreviousDarknodes(address _start, uint256 _count) external view returns (address[]) {
uint256 count = _count;
if (count == 0) {
count = numDarknodesPreviousEpoch;
}
return getDarknodesFromEpochs(_start, count, true);
}
/// @notice Returns whether a darknode is scheduled to become registered
/// at next epoch.
/// @param _darknodeID The ID of the darknode to return
function isPendingRegistration(address _darknodeID) external view returns (bool) {
uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID);
return registeredAt != 0 && registeredAt > currentEpoch.blocknumber;
}
/// @notice Returns if a darknode is in the pending deregistered state. In
/// this state a darknode is still considered registered.
function isPendingDeregistration(address _darknodeID) external view returns (bool) {
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
return deregisteredAt != 0 && deregisteredAt > currentEpoch.blocknumber;
}
/// @notice Returns if a darknode is in the deregistered state.
function isDeregistered(address _darknodeID) public view returns (bool) {
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
return deregisteredAt != 0 && deregisteredAt <= currentEpoch.blocknumber;
}
/// @notice Returns if a darknode can be deregistered. This is true if the
/// darknodes is in the registered state and has not attempted to
/// deregister yet.
function isDeregisterable(address _darknodeID) public view returns (bool) {
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
// The Darknode is currently in the registered state and has not been
// transitioned to the pending deregistration, or deregistered, state
return isRegistered(_darknodeID) && deregisteredAt == 0;
}
/// @notice Returns if a darknode is in the refunded state. This is true
/// for darknodes that have never been registered, or darknodes that have
/// been deregistered and refunded.
function isRefunded(address _darknodeID) public view returns (bool) {
uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID);
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
return registeredAt == 0 && deregisteredAt == 0;
}
/// @notice Returns if a darknode is refundable. This is true for darknodes
/// that have been in the deregistered state for one full epoch.
function isRefundable(address _darknodeID) public view returns (bool) {
return isDeregistered(_darknodeID) && store.darknodeDeregisteredAt(_darknodeID) <= previousEpoch.blocknumber;
}
/// @notice Returns if a darknode is in the registered state.
function isRegistered(address _darknodeID) public view returns (bool) {
return isRegisteredInEpoch(_darknodeID, currentEpoch);
}
/// @notice Returns if a darknode was in the registered state last epoch.
function isRegisteredInPreviousEpoch(address _darknodeID) public view returns (bool) {
return isRegisteredInEpoch(_darknodeID, previousEpoch);
}
/// @notice Returns if a darknode was in the registered state for a given
/// epoch.
/// @param _darknodeID The ID of the darknode
/// @param _epoch One of currentEpoch, previousEpoch
function isRegisteredInEpoch(address _darknodeID, Epoch _epoch) private view returns (bool) {
uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID);
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
bool registered = registeredAt != 0 && registeredAt <= _epoch.blocknumber;
bool notDeregistered = deregisteredAt == 0 || deregisteredAt > _epoch.blocknumber;
// The Darknode has been registered and has not yet been deregistered,
// although it might be pending deregistration
return registered && notDeregistered;
}
/// @notice Returns a list of darknodes registered for either the current
/// or the previous epoch. See `getDarknodes` for documentation on the
/// parameters `_start` and `_count`.
/// @param _usePreviousEpoch If true, use the previous epoch, otherwise use
/// the current epoch.
function getDarknodesFromEpochs(address _start, uint256 _count, bool _usePreviousEpoch) private view returns (address[]) {
uint256 count = _count;
if (count == 0) {
count = numDarknodes;
}
address[] memory nodes = new address[](count);
// Begin with the first node in the list
uint256 n = 0;
address next = _start;
if (next == 0x0) {
next = store.begin();
}
// Iterate until all registered Darknodes have been collected
while (n < count) {
if (next == 0x0) {
break;
}
// Only include Darknodes that are currently registered
bool includeNext;
if (_usePreviousEpoch) {
includeNext = isRegisteredInPreviousEpoch(next);
} else {
includeNext = isRegistered(next);
}
if (!includeNext) {
next = store.next(next);
continue;
}
nodes[n] = next;
next = store.next(next);
n += 1;
}
return nodes;
}
}
/**
* @title Math
* @dev Assorted math operations
*/
library Math {
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(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;
}
}
/// @notice Implements safeTransfer, safeTransferFrom and
/// safeApprove for CompatibleERC20.
///
/// See https://github.com/ethereum/solidity/issues/4116
///
/// This library allows interacting with ERC20 tokens that implement any of
/// these interfaces:
///
/// (1) transfer returns true on success, false on failure
/// (2) transfer returns true on success, reverts on failure
/// (3) transfer returns nothing on success, reverts on failure
///
/// Additionally, safeTransferFromWithFees will return the final token
/// value received after accounting for token fees.
library CompatibleERC20Functions {
using SafeMath for uint256;
/// @notice Calls transfer on the token and reverts if the call fails.
function safeTransfer(address token, address to, uint256 amount) internal {
CompatibleERC20(token).transfer(to, amount);
require(previousReturnValue(), "transfer failed");
}
/// @notice Calls transferFrom on the token and reverts if the call fails.
function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
CompatibleERC20(token).transferFrom(from, to, amount);
require(previousReturnValue(), "transferFrom failed");
}
/// @notice Calls approve on the token and reverts if the call fails.
function safeApprove(address token, address spender, uint256 amount) internal {
CompatibleERC20(token).approve(spender, amount);
require(previousReturnValue(), "approve failed");
}
/// @notice Calls transferFrom on the token, reverts if the call fails and
/// returns the value transferred after fees.
function safeTransferFromWithFees(address token, address from, address to, uint256 amount) internal returns (uint256) {
uint256 balancesBefore = CompatibleERC20(token).balanceOf(to);
CompatibleERC20(token).transferFrom(from, to, amount);
require(previousReturnValue(), "transferFrom failed");
uint256 balancesAfter = CompatibleERC20(token).balanceOf(to);
return Math.min256(amount, balancesAfter.sub(balancesBefore));
}
/// @notice Checks the return value of the previous function. Returns true
/// if the previous function returned 32 non-zero bytes or returned zero
/// bytes.
function previousReturnValue() private pure returns (bool)
{
uint256 returnData = 0;
assembly { /* solium-disable-line security/no-inline-assembly */
// Switch on the number of bytes returned by the previous call
switch returndatasize
// 0 bytes: ERC20 of type (3), did not throw
case 0 {
returnData := 1
}
// 32 bytes: ERC20 of types (1) or (2)
case 32 {
// Copy the return data into scratch space
returndatacopy(0x0, 0x0, 32)
// Load the return data into returnData
returnData := mload(0x0)
}
// Other return size: return false
default { }
}
return returnData != 0;
}
}
/// @notice ERC20 interface which doesn't specify the return type for transfer,
/// transferFrom and approve.
interface CompatibleERC20 {
// Modified to not return boolean
function transfer(address to, uint256 value) external;
function transferFrom(address from, address to, uint256 value) external;
function approve(address spender, uint256 value) external;
// Not modifier
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/// @notice The DarknodeRewardVault contract is responsible for holding fees
/// for darknodes for settling orders. Fees can be withdrawn to the address of
/// the darknode's operator. Fees can be in ETH or in ERC20 tokens.
/// Docs: https://github.com/republicprotocol/republic-sol/blob/master/docs/02-darknode-reward-vault.md
contract DarknodeRewardVault is Ownable {
using SafeMath for uint256;
using CompatibleERC20Functions for CompatibleERC20;
string public VERSION; // Passed in as a constructor parameter.
/// @notice The special address for Ether.
address constant public ETHEREUM = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
DarknodeRegistry public darknodeRegistry;
mapping(address => mapping(address => uint256)) public darknodeBalances;
event LogDarknodeRegistryUpdated(DarknodeRegistry previousDarknodeRegistry, DarknodeRegistry nextDarknodeRegistry);
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
/// @param _darknodeRegistry The DarknodeRegistry contract that is used by
/// the vault to lookup Darknode owners.
constructor(string _VERSION, DarknodeRegistry _darknodeRegistry) public {
VERSION = _VERSION;
darknodeRegistry = _darknodeRegistry;
}
function updateDarknodeRegistry(DarknodeRegistry _newDarknodeRegistry) public onlyOwner {
emit LogDarknodeRegistryUpdated(darknodeRegistry, _newDarknodeRegistry);
darknodeRegistry = _newDarknodeRegistry;
}
/// @notice Deposit fees into the vault for a Darknode. The Darknode
/// registration is not checked (to reduce gas fees); the caller must be
/// careful not to call this function for a Darknode that is not registered
/// otherwise any fees deposited to that Darknode can be withdrawn by a
/// malicious adversary (by registering the Darknode before the honest
/// party and claiming ownership).
///
/// @param _darknode The address of the Darknode that will receive the
/// fees.
/// @param _token The address of the ERC20 token being used to pay the fee.
/// A special address is used for Ether.
/// @param _value The amount of fees in the smallest unit of the token.
function deposit(address _darknode, ERC20 _token, uint256 _value) public payable {
uint256 receivedValue = _value;
if (address(_token) == ETHEREUM) {
require(msg.value == _value, "mismatched ether value");
} else {
require(msg.value == 0, "unexpected ether value");
receivedValue = CompatibleERC20(_token).safeTransferFromWithFees(msg.sender, address(this), _value);
}
darknodeBalances[_darknode][_token] = darknodeBalances[_darknode][_token].add(receivedValue);
}
/// @notice Withdraw fees earned by a Darknode. The fees will be sent to
/// the owner of the Darknode. If a Darknode is not registered the fees
/// cannot be withdrawn.
///
/// @param _darknode The address of the Darknode whose fees are being
/// withdrawn. The owner of this Darknode will receive the fees.
/// @param _token The address of the ERC20 token to withdraw.
function withdraw(address _darknode, ERC20 _token) public {
address darknodeOwner = darknodeRegistry.getDarknodeOwner(address(_darknode));
require(darknodeOwner != 0x0, "invalid darknode owner");
uint256 value = darknodeBalances[_darknode][_token];
darknodeBalances[_darknode][_token] = 0;
if (address(_token) == ETHEREUM) {
darknodeOwner.transfer(value);
} else {
CompatibleERC20(_token).safeTransfer(darknodeOwner, value);
}
}
} | @notice Retrieves the bond amount of a darknode in 10^-18 REN. @param _darknodeID The ID of the darknode to retrieve the bond for. | function getDarknodeBond(address _darknodeID) external view returns (uint256) {
return store.darknodeBond(_darknodeID);
}
| 13,800 | [
1,
6960,
326,
8427,
3844,
434,
279,
23433,
2159,
316,
1728,
66,
17,
2643,
534,
1157,
18,
225,
389,
25045,
2159,
734,
1021,
1599,
434,
326,
23433,
2159,
358,
4614,
326,
8427,
364,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2343,
1313,
2159,
9807,
12,
2867,
389,
25045,
2159,
734,
13,
3903,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
1707,
18,
25045,
2159,
9807,
24899,
25045,
2159,
734,
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
] |
./full_match/11155111/0xe9BF8462eA32893661bA3Ab1739ED3e0e68856f8/sources/src/lending/Lender.sol | solhint-disable-line not-rely-on-time
| lastReportTimestamp = block.timestamp; | 3,794,524 | [
1,
18281,
11317,
17,
8394,
17,
1369,
486,
17,
266,
715,
17,
265,
17,
957,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1142,
4820,
4921,
273,
1203,
18,
5508,
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
] |
pragma solidity ^0.5.13;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "./interfaces/IAccounts.sol";
import "../common/Initializable.sol";
import "../common/interfaces/ICeloVersionedContract.sol";
import "../common/Signatures.sol";
import "../common/UsingRegistry.sol";
import "../common/libraries/ReentrancyGuard.sol";
contract Accounts is
IAccounts,
ICeloVersionedContract,
Ownable,
ReentrancyGuard,
Initializable,
UsingRegistry
{
using SafeMath for uint256;
struct Signers {
// The address that is authorized to vote in governance and validator elections on behalf of the
// account. The account can vote as well, whether or not a vote signing key has been specified.
address vote;
// The address that is authorized to manage a validator or validator group and sign consensus
// messages on behalf of the account. The account can manage the validator, whether or not a
// validator signing key has been specified. However, if a validator signing key has been
// specified, only that key may actually participate in consensus.
address validator;
// The address of the key with which this account wants to sign attestations on the Attestations
// contract
address attestation;
}
struct SignerAuthorization {
bool started;
bool completed;
}
struct Account {
bool exists;
// [Deprecated] Each account may authorize signing keys to use for voting,
// validating or attestation. These keys may not be keys of other accounts,
// and may not be authorized by any other account for any purpose.
Signers signers;
// The address at which the account expects to receive transfers. If it's empty/0x0, the
// account indicates that an address exchange should be initiated with the dataEncryptionKey
address walletAddress;
// An optional human readable identifier for the account
string name;
// The ECDSA public key used to encrypt and decrypt data for this account
bytes dataEncryptionKey;
// The URL under which an account adds metadata and claims
string metadataURL;
}
mapping(address => Account) internal accounts;
// Maps authorized signers to the account that provided the authorization.
mapping(address => address) public authorizedBy;
// Default signers by account (replaces the legacy Signers struct on Account)
mapping(address => mapping(bytes32 => address)) defaultSigners;
// All signers and their roles for a given account
// solhint-disable-next-line max-line-length
mapping(address => mapping(bytes32 => mapping(address => SignerAuthorization))) signerAuthorizations;
bytes32 public constant EIP712_AUTHORIZE_SIGNER_TYPEHASH = keccak256(
"AuthorizeSigner(address account,address signer,bytes32 role)"
);
bytes32 public eip712DomainSeparator;
bytes32 constant ValidatorSigner = keccak256(abi.encodePacked("celo.org/core/validator"));
bytes32 constant AttestationSigner = keccak256(abi.encodePacked("celo.org/core/attestation"));
bytes32 constant VoteSigner = keccak256(abi.encodePacked("celo.org/core/vote"));
event AttestationSignerAuthorized(address indexed account, address signer);
event VoteSignerAuthorized(address indexed account, address signer);
event ValidatorSignerAuthorized(address indexed account, address signer);
event SignerAuthorized(address indexed account, address signer, bytes32 indexed role);
event SignerAuthorizationStarted(address indexed account, address signer, bytes32 indexed role);
event SignerAuthorizationCompleted(address indexed account, address signer, bytes32 indexed role);
event AttestationSignerRemoved(address indexed account, address oldSigner);
event VoteSignerRemoved(address indexed account, address oldSigner);
event ValidatorSignerRemoved(address indexed account, address oldSigner);
event IndexedSignerSet(address indexed account, address signer, bytes32 role);
event IndexedSignerRemoved(address indexed account, address oldSigner, bytes32 role);
event DefaultSignerSet(address indexed account, address signer, bytes32 role);
event DefaultSignerRemoved(address indexed account, address oldSigner, bytes32 role);
event LegacySignerSet(address indexed account, address signer, bytes32 role);
event LegacySignerRemoved(address indexed account, address oldSigner, bytes32 role);
event SignerRemoved(address indexed account, address oldSigner, bytes32 indexed role);
event AccountDataEncryptionKeySet(address indexed account, bytes dataEncryptionKey);
event AccountNameSet(address indexed account, string name);
event AccountMetadataURLSet(address indexed account, string metadataURL);
event AccountWalletAddressSet(address indexed account, address walletAddress);
event AccountCreated(address indexed account);
/**
* @notice Sets initialized == true on implementation contracts
* @param test Set to true to skip implementation initialization
*/
constructor(bool test) public Initializable(test) {}
/**
* @notice Returns the storage, major, minor, and patch version of the contract.
* @return The storage, major, minor, and patch version of the contract.
*/
function getVersionNumber() external pure returns (uint256, uint256, uint256, uint256) {
return (1, 1, 2, 1);
}
/**
* @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.
*/
function initialize(address registryAddress) external initializer {
_transferOwnership(msg.sender);
setRegistry(registryAddress);
setEip712DomainSeparator();
}
/**
* @notice Sets the EIP712 domain separator for the Celo Accounts abstraction.
*/
function setEip712DomainSeparator() public {
uint256 chainId;
assembly {
chainId := chainid
}
eip712DomainSeparator = keccak256(
abi.encode(
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
),
keccak256(bytes("Celo Core Contracts")),
keccak256("1.0"),
chainId,
address(this)
)
);
}
/**
* @notice Convenience Setter for the dataEncryptionKey and wallet address for an account
* @param name A string to set as the name of the account
* @param dataEncryptionKey secp256k1 public key for data encryption. Preferably compressed.
* @param walletAddress The wallet address to set for the account
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @dev v, r, s constitute `signer`'s signature on `msg.sender` (unless the wallet address
* is 0x0 or msg.sender).
*/
function setAccount(
string calldata name,
bytes calldata dataEncryptionKey,
address walletAddress,
uint8 v,
bytes32 r,
bytes32 s
) external {
if (!isAccount(msg.sender)) {
createAccount();
}
setName(name);
setAccountDataEncryptionKey(dataEncryptionKey);
setWalletAddress(walletAddress, v, r, s);
}
/**
* @notice Creates an account.
* @return True if account creation succeeded.
*/
function createAccount() public returns (bool) {
require(isNotAccount(msg.sender) && isNotAuthorizedSigner(msg.sender), "Account exists");
Account storage account = accounts[msg.sender];
account.exists = true;
emit AccountCreated(msg.sender);
return true;
}
/**
* @notice Setter for the name of an account.
* @param name The name to set.
*/
function setName(string memory name) public {
require(isAccount(msg.sender), "Unknown account");
Account storage account = accounts[msg.sender];
account.name = name;
emit AccountNameSet(msg.sender, name);
}
/**
* @notice Setter for the wallet address for an account
* @param walletAddress The wallet address to set for the account
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @dev Wallet address can be zero. This means that the owner of the wallet
* does not want to be paid directly without interaction, and instead wants users to
* contact them, using the data encryption key, and arrange a payment.
* @dev v, r, s constitute `signer`'s signature on `msg.sender` (unless the wallet address
* is 0x0 or msg.sender).
*/
function setWalletAddress(address walletAddress, uint8 v, bytes32 r, bytes32 s) public {
require(isAccount(msg.sender), "Unknown account");
if (!(walletAddress == msg.sender || walletAddress == address(0x0))) {
address signer = Signatures.getSignerOfAddress(msg.sender, v, r, s);
require(signer == walletAddress, "Invalid signature");
}
Account storage account = accounts[msg.sender];
account.walletAddress = walletAddress;
emit AccountWalletAddressSet(msg.sender, walletAddress);
}
/**
* @notice Setter for the data encryption key and version.
* @param dataEncryptionKey secp256k1 public key for data encryption. Preferably compressed.
*/
function setAccountDataEncryptionKey(bytes memory dataEncryptionKey) public {
require(dataEncryptionKey.length >= 33, "data encryption key length <= 32");
Account storage account = accounts[msg.sender];
account.dataEncryptionKey = dataEncryptionKey;
emit AccountDataEncryptionKeySet(msg.sender, dataEncryptionKey);
}
/**
* @notice Setter for the metadata of an account.
* @param metadataURL The URL to access the metadata.
*/
function setMetadataURL(string calldata metadataURL) external {
require(isAccount(msg.sender), "Unknown account");
Account storage account = accounts[msg.sender];
account.metadataURL = metadataURL;
emit AccountMetadataURLSet(msg.sender, metadataURL);
}
/**
* @notice Set the indexed signer for a specific role
* @param signer the address to set as default
* @param role the role to register a default signer for
*/
function setIndexedSigner(address signer, bytes32 role) public {
require(isAccount(msg.sender), "Not an account");
require(isNotAccount(signer), "Cannot authorize account as signer");
require(
isNotAuthorizedSignerForAnotherAccount(msg.sender, signer),
"Not a signer for this account"
);
require(isSigner(msg.sender, signer, role), "Must authorize signer before setting as default");
Account storage account = accounts[msg.sender];
if (isLegacyRole(role)) {
if (role == VoteSigner) {
account.signers.vote = signer;
} else if (role == AttestationSigner) {
account.signers.attestation = signer;
} else if (role == ValidatorSigner) {
account.signers.validator = signer;
}
emit LegacySignerSet(msg.sender, signer, role);
} else {
defaultSigners[msg.sender][role] = signer;
emit DefaultSignerSet(msg.sender, signer, role);
}
emit IndexedSignerSet(msg.sender, signer, role);
}
/**
* @notice Authorizes an address to act as a signer, for `role`, on behalf of the account.
* @param signer The address of the signing key to authorize.
* @param role The role to authorize signing for.
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @dev v, r, s constitute `signer`'s EIP712 signature over `role`, `msg.sender`
* and `signer`.
*/
function authorizeSignerWithSignature(address signer, bytes32 role, uint8 v, bytes32 r, bytes32 s)
public
{
authorizeAddressWithRole(signer, role, v, r, s);
signerAuthorizations[msg.sender][role][signer] = SignerAuthorization({
started: true,
completed: true
});
emit SignerAuthorized(msg.sender, signer, role);
}
function legacyAuthorizeSignerWithSignature(
address signer,
bytes32 role,
uint8 v,
bytes32 r,
bytes32 s
) private {
authorizeAddress(signer, v, r, s);
signerAuthorizations[msg.sender][role][signer] = SignerAuthorization({
started: true,
completed: true
});
emit SignerAuthorized(msg.sender, signer, role);
}
/**
* @notice Authorizes an address to sign votes on behalf of the account.
* @param signer The address of the signing key to authorize.
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @dev v, r, s constitute `signer`'s signature on `msg.sender`.
*/
function authorizeVoteSigner(address signer, uint8 v, bytes32 r, bytes32 s)
external
nonReentrant
{
legacyAuthorizeSignerWithSignature(signer, VoteSigner, v, r, s);
setIndexedSigner(signer, VoteSigner);
emit VoteSignerAuthorized(msg.sender, signer);
}
/**
* @notice Authorizes an address to sign consensus messages on behalf of the account.
* @param signer The address of the signing key to authorize.
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @dev v, r, s constitute `signer`'s signature on `msg.sender`.
*/
function authorizeValidatorSigner(address signer, uint8 v, bytes32 r, bytes32 s)
external
nonReentrant
{
legacyAuthorizeSignerWithSignature(signer, ValidatorSigner, v, r, s);
setIndexedSigner(signer, ValidatorSigner);
require(!getValidators().isValidator(msg.sender), "Cannot authorize validator signer");
emit ValidatorSignerAuthorized(msg.sender, signer);
}
/**
* @notice Authorizes an address to sign consensus messages on behalf of the account.
* @param signer The address of the signing key to authorize.
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @param ecdsaPublicKey The ECDSA public key corresponding to `signer`.
* @dev v, r, s constitute `signer`'s signature on `msg.sender`.
*/
function authorizeValidatorSignerWithPublicKey(
address signer,
uint8 v,
bytes32 r,
bytes32 s,
bytes calldata ecdsaPublicKey
) external nonReentrant {
legacyAuthorizeSignerWithSignature(signer, ValidatorSigner, v, r, s);
setIndexedSigner(signer, ValidatorSigner);
require(
getValidators().updateEcdsaPublicKey(msg.sender, signer, ecdsaPublicKey),
"Failed to update ECDSA public key"
);
emit ValidatorSignerAuthorized(msg.sender, signer);
}
/**
* @notice Authorizes an address to sign consensus messages on behalf of the account.
* @param signer The address of the signing key to authorize.
* @param ecdsaPublicKey The ECDSA public key corresponding to `signer`.
* @param blsPublicKey The BLS public key that the validator is using for consensus, should pass
* proof of possession. 96 bytes.
* @param blsPop The BLS public key proof-of-possession, which consists of a signature on the
* account address. 48 bytes.
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @dev v, r, s constitute `signer`'s signature on `msg.sender`.
*/
function authorizeValidatorSignerWithKeys(
address signer,
uint8 v,
bytes32 r,
bytes32 s,
bytes calldata ecdsaPublicKey,
bytes calldata blsPublicKey,
bytes calldata blsPop
) external nonReentrant {
legacyAuthorizeSignerWithSignature(signer, ValidatorSigner, v, r, s);
setIndexedSigner(signer, ValidatorSigner);
require(
getValidators().updatePublicKeys(msg.sender, signer, ecdsaPublicKey, blsPublicKey, blsPop),
"Failed to update validator keys"
);
emit ValidatorSignerAuthorized(msg.sender, signer);
}
/**
* @notice Authorizes an address to sign attestations on behalf of the account.
* @param signer The address of the signing key to authorize.
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @dev v, r, s constitute `signer`'s signature on `msg.sender`.
*/
function authorizeAttestationSigner(address signer, uint8 v, bytes32 r, bytes32 s) public {
legacyAuthorizeSignerWithSignature(signer, AttestationSigner, v, r, s);
setIndexedSigner(signer, AttestationSigner);
emit AttestationSignerAuthorized(msg.sender, signer);
}
/**
* @notice Begin the process of authorizing an address to sign on behalf of the account
* @param signer The address of the signing key to authorize.
* @param role The role to authorize signing for.
*/
function authorizeSigner(address signer, bytes32 role) public {
require(isAccount(msg.sender), "Unknown account");
require(
isNotAccount(signer) && isNotAuthorizedSignerForAnotherAccount(msg.sender, signer),
"Cannot re-authorize address signer"
);
signerAuthorizations[msg.sender][role][signer] = SignerAuthorization({
started: true,
completed: false
});
emit SignerAuthorizationStarted(msg.sender, signer, role);
}
/**
* @notice Finish the process of authorizing an address to sign on behalf of the account.
* @param account The address of account that authorized signing.
* @param role The role to finish authorizing for.
*/
function completeSignerAuthorization(address account, bytes32 role) public {
require(isAccount(account), "Unknown account");
require(
isNotAccount(msg.sender) && isNotAuthorizedSignerForAnotherAccount(account, msg.sender),
"Cannot re-authorize address signer"
);
require(
signerAuthorizations[account][role][msg.sender].started == true,
"Signer authorization not started"
);
authorizedBy[msg.sender] = account;
signerAuthorizations[account][role][msg.sender].completed = true;
emit SignerAuthorizationCompleted(account, msg.sender, role);
}
/**
* @notice Whether or not the signer has been registered as the legacy signer for role
* @param _account The address of account that authorized signing.
* @param signer The address of the signer.
* @param role The role that has been authorized.
*/
function isLegacySigner(address _account, address signer, bytes32 role)
public
view
returns (bool)
{
Account storage account = accounts[_account];
if (role == ValidatorSigner && account.signers.validator == signer) {
return true;
} else if (role == AttestationSigner && account.signers.attestation == signer) {
return true;
} else if (role == VoteSigner && account.signers.vote == signer) {
return true;
} else {
return false;
}
}
/**
* @notice Whether or not the signer has been registered as the default signer for role
* @param account The address of account that authorized signing.
* @param signer The address of the signer.
* @param role The role that has been authorized.
*/
function isDefaultSigner(address account, address signer, bytes32 role)
public
view
returns (bool)
{
return defaultSigners[account][role] == signer;
}
/**
* @notice Whether or not the signer has been registered as an indexed signer for role
* @param account The address of account that authorized signing.
* @param signer The address of the signer.
* @param role The role that has been authorized.
*/
function isIndexedSigner(address account, address signer, bytes32 role)
public
view
returns (bool)
{
return
isLegacyRole(role)
? isLegacySigner(account, signer, role)
: isDefaultSigner(account, signer, role);
}
/**
* @notice Whether or not the signer has been registered as a signer for role
* @param account The address of account that authorized signing.
* @param signer The address of the signer.
* @param role The role that has been authorized.
*/
function isSigner(address account, address signer, bytes32 role) public view returns (bool) {
return
isLegacySigner(account, signer, role) ||
(signerAuthorizations[account][role][signer].completed && authorizedBy[signer] == account);
}
/**
* @notice Removes the signer for a default role.
* @param role The role that has been authorized.
*/
function removeDefaultSigner(bytes32 role) public {
address signer = defaultSigners[msg.sender][role];
defaultSigners[msg.sender][role] = address(0);
emit DefaultSignerRemoved(msg.sender, signer, role);
}
/**
* @notice Remove one of the Validator, Attestation or
* Vote signers from an account. Should only be called from
* methods that check the role is a legacy signer.
* @param role The role that has been authorized.
*/
function removeLegacySigner(bytes32 role) private {
Account storage account = accounts[msg.sender];
address signer;
if (role == ValidatorSigner) {
signer = account.signers.validator;
account.signers.validator = address(0);
} else if (role == AttestationSigner) {
signer = account.signers.attestation;
account.signers.attestation = address(0);
} else if (role == VoteSigner) {
signer = account.signers.vote;
account.signers.vote = address(0);
}
emit LegacySignerRemoved(msg.sender, signer, role);
}
/**
* @notice Removes the currently authorized and indexed signer
* for a specific role
* @param role The role of the signer.
*/
function removeIndexedSigner(bytes32 role) public {
address oldSigner = getIndexedSigner(msg.sender, role);
isLegacyRole(role) ? removeLegacySigner(role) : removeDefaultSigner(role);
emit IndexedSignerRemoved(msg.sender, oldSigner, role);
}
/**
* @notice Removes the currently authorized signer for a specific role and
* if the signer is indexed, remove that as well.
* @param signer The address of the signer.
* @param role The role that has been authorized.
*/
function removeSigner(address signer, bytes32 role) public {
if (isIndexedSigner(msg.sender, signer, role)) {
removeIndexedSigner(role);
}
delete signerAuthorizations[msg.sender][role][signer];
emit SignerRemoved(msg.sender, signer, role);
}
/**
* @notice Removes the currently authorized vote signer for the account.
* Note that the signers cannot be reauthorized after they have been removed.
*/
function removeVoteSigner() public {
address signer = getLegacySigner(msg.sender, VoteSigner);
removeSigner(signer, VoteSigner);
emit VoteSignerRemoved(msg.sender, signer);
}
/**
* @notice Removes the currently authorized validator signer for the account
* Note that the signers cannot be reauthorized after they have been removed.
*/
function removeValidatorSigner() public {
address signer = getLegacySigner(msg.sender, ValidatorSigner);
removeSigner(signer, ValidatorSigner);
emit ValidatorSignerRemoved(msg.sender, signer);
}
/**
* @notice Removes the currently authorized attestation signer for the account
* Note that the signers cannot be reauthorized after they have been removed.
*/
function removeAttestationSigner() public {
address signer = getLegacySigner(msg.sender, AttestationSigner);
removeSigner(signer, AttestationSigner);
emit AttestationSignerRemoved(msg.sender, signer);
}
function signerToAccountWithRole(address signer, bytes32 role) internal view returns (address) {
address account = authorizedBy[signer];
if (account != address(0)) {
require(isSigner(account, signer, role), "not active authorized signer for role");
return account;
}
require(isAccount(signer), "not an account");
return signer;
}
/**
* @notice Returns the account associated with `signer`.
* @param signer The address of the account or currently authorized attestation signer.
* @dev Fails if the `signer` is not an account or currently authorized attestation signer.
* @return The associated account.
*/
function attestationSignerToAccount(address signer) external view returns (address) {
return signerToAccountWithRole(signer, AttestationSigner);
}
/**
* @notice Returns the account associated with `signer`.
* @param signer The address of an account or currently authorized validator signer.
* @dev Fails if the `signer` is not an account or currently authorized validator.
* @return The associated account.
*/
function validatorSignerToAccount(address signer) public view returns (address) {
return signerToAccountWithRole(signer, ValidatorSigner);
}
/**
* @notice Returns the account associated with `signer`.
* @param signer The address of the account or currently authorized vote signer.
* @dev Fails if the `signer` is not an account or currently authorized vote signer.
* @return The associated account.
*/
function voteSignerToAccount(address signer) external view returns (address) {
return signerToAccountWithRole(signer, VoteSigner);
}
/**
* @notice Returns the account associated with `signer`.
* @param signer The address of the account or previously authorized signer.
* @dev Fails if the `signer` is not an account or previously authorized signer.
* @return The associated account.
*/
function signerToAccount(address signer) external view returns (address) {
address authorizingAccount = authorizedBy[signer];
if (authorizingAccount != address(0)) {
return authorizingAccount;
} else {
require(isAccount(signer), "Not an account");
return signer;
}
}
/**
* @notice Checks whether the role is one of Vote, Validator or Attestation
* @param role The role to check
*/
function isLegacyRole(bytes32 role) public pure returns (bool) {
return role == VoteSigner || role == ValidatorSigner || role == AttestationSigner;
}
/**
* @notice Returns the legacy signer for the specified account and
* role. If no signer has been specified it will return the account itself.
* @param _account The address of the account.
* @param role The role of the signer.
*/
function getLegacySigner(address _account, bytes32 role) public view returns (address) {
require(isLegacyRole(role), "Role is not a legacy signer");
Account storage account = accounts[_account];
address signer;
if (role == ValidatorSigner) {
signer = account.signers.validator;
} else if (role == AttestationSigner) {
signer = account.signers.attestation;
} else if (role == VoteSigner) {
signer = account.signers.vote;
}
return signer == address(0) ? _account : signer;
}
/**
* @notice Returns the default signer for the specified account and
* role. If no signer has been specified it will return the account itself.
* @param account The address of the account.
* @param role The role of the signer.
*/
function getDefaultSigner(address account, bytes32 role) public view returns (address) {
address defaultSigner = defaultSigners[account][role];
return defaultSigner == address(0) ? account : defaultSigner;
}
/**
* @notice Returns the indexed signer for the specified account and role.
* If no signer has been specified it will return the account itself.
* @param account The address of the account.
* @param role The role of the signer.
*/
function getIndexedSigner(address account, bytes32 role) public view returns (address) {
return isLegacyRole(role) ? getLegacySigner(account, role) : getDefaultSigner(account, role);
}
/**
* @notice Returns the vote signer for the specified account.
* @param account The address of the account.
* @return The address with which the account can sign votes.
*/
function getVoteSigner(address account) public view returns (address) {
return getLegacySigner(account, VoteSigner);
}
/**
* @notice Returns the validator signer for the specified account.
* @param account The address of the account.
* @return The address with which the account can register a validator or group.
*/
function getValidatorSigner(address account) public view returns (address) {
return getLegacySigner(account, ValidatorSigner);
}
/**
* @notice Returns the attestation signer for the specified account.
* @param account The address of the account.
* @return The address with which the account can sign attestations.
*/
function getAttestationSigner(address account) public view returns (address) {
return getLegacySigner(account, AttestationSigner);
}
/**
* @notice Checks whether or not the account has an indexed signer
* registered for one of the legacy roles
*/
function hasLegacySigner(address account, bytes32 role) public view returns (bool) {
return getLegacySigner(account, role) != account;
}
/**
* @notice Checks whether or not the account has an indexed signer
* registered for a role
*/
function hasDefaultSigner(address account, bytes32 role) public view returns (bool) {
return getDefaultSigner(account, role) != account;
}
/**
* @notice Checks whether or not the account has an indexed signer
* registered for the role
*/
function hasIndexedSigner(address account, bytes32 role) public view returns (bool) {
return isLegacyRole(role) ? hasLegacySigner(account, role) : hasDefaultSigner(account, role);
}
/**
* @notice Checks whether or not the account has a signer
* registered for the plaintext role.
* @dev See `hasIndexedSigner` for more gas efficient call.
*/
function hasAuthorizedSigner(address account, string calldata role) external view returns (bool) {
return hasIndexedSigner(account, keccak256(abi.encodePacked(role)));
}
/**
* @notice Returns if account has specified a dedicated vote signer.
* @param account The address of the account.
* @return Whether the account has specified a dedicated vote signer.
*/
function hasAuthorizedVoteSigner(address account) external view returns (bool) {
return hasLegacySigner(account, VoteSigner);
}
/**
* @notice Returns if account has specified a dedicated validator signer.
* @param account The address of the account.
* @return Whether the account has specified a dedicated validator signer.
*/
function hasAuthorizedValidatorSigner(address account) external view returns (bool) {
return hasLegacySigner(account, ValidatorSigner);
}
/**
* @notice Returns if account has specified a dedicated attestation signer.
* @param account The address of the account.
* @return Whether the account has specified a dedicated attestation signer.
*/
function hasAuthorizedAttestationSigner(address account) external view returns (bool) {
return hasLegacySigner(account, AttestationSigner);
}
/**
* @notice Getter for the name of an account.
* @param account The address of the account to get the name for.
* @return name The name of the account.
*/
function getName(address account) external view returns (string memory) {
return accounts[account].name;
}
/**
* @notice Getter for the metadata of an account.
* @param account The address of the account to get the metadata for.
* @return metadataURL The URL to access the metadata.
*/
function getMetadataURL(address account) external view returns (string memory) {
return accounts[account].metadataURL;
}
/**
* @notice Getter for the metadata of multiple accounts.
* @param accountsToQuery The addresses of the accounts to get the metadata for.
* @return (stringLengths[] - the length of each string in bytes
* data - all strings concatenated
* )
*/
function batchGetMetadataURL(address[] calldata accountsToQuery)
external
view
returns (uint256[] memory, bytes memory)
{
uint256 totalSize = 0;
uint256[] memory sizes = new uint256[](accountsToQuery.length);
for (uint256 i = 0; i < accountsToQuery.length; i = i.add(1)) {
sizes[i] = bytes(accounts[accountsToQuery[i]].metadataURL).length;
totalSize = totalSize.add(sizes[i]);
}
bytes memory data = new bytes(totalSize);
uint256 pointer = 0;
for (uint256 i = 0; i < accountsToQuery.length; i = i.add(1)) {
for (uint256 j = 0; j < sizes[i]; j = j.add(1)) {
data[pointer] = bytes(accounts[accountsToQuery[i]].metadataURL)[j];
pointer = pointer.add(1);
}
}
return (sizes, data);
}
/**
* @notice Getter for the data encryption key and version.
* @param account The address of the account to get the key for
* @return dataEncryptionKey secp256k1 public key for data encryption. Preferably compressed.
*/
function getDataEncryptionKey(address account) external view returns (bytes memory) {
return accounts[account].dataEncryptionKey;
}
/**
* @notice Getter for the wallet address for an account
* @param account The address of the account to get the wallet address for
* @return Wallet address
*/
function getWalletAddress(address account) external view returns (address) {
return accounts[account].walletAddress;
}
/**
* @notice Check if an account already exists.
* @param account The address of the account
* @return Returns `true` if account exists. Returns `false` otherwise.
*/
function isAccount(address account) public view returns (bool) {
return (accounts[account].exists);
}
/**
* @notice Check if an account already exists.
* @param account The address of the account
* @return Returns `false` if account exists. Returns `true` otherwise.
*/
function isNotAccount(address account) internal view returns (bool) {
return (!accounts[account].exists);
}
/**
* @notice Check if an address has been an authorized signer for an account.
* @param signer The possibly authorized address.
* @return Returns `true` if authorized. Returns `false` otherwise.
*/
function isAuthorizedSigner(address signer) external view returns (bool) {
return (authorizedBy[signer] != address(0));
}
/**
* @notice Check if an address has not been an authorized signer for an account.
* @param signer The possibly authorized address.
* @return Returns `false` if authorized. Returns `true` otherwise.
*/
function isNotAuthorizedSigner(address signer) internal view returns (bool) {
return (authorizedBy[signer] == address(0));
}
/**
* @notice Check if `signer` has not been authorized, and if it has been previously
* authorized that it was authorized by `account`.
* @param account The authorizing account address.
* @param signer The possibly authorized address.
* @return Returns `false` if authorized. Returns `true` otherwise.
*/
function isNotAuthorizedSignerForAnotherAccount(address account, address signer)
internal
view
returns (bool)
{
return (authorizedBy[signer] == address(0) || authorizedBy[signer] == account);
}
/**
* @notice Authorizes some role of `msg.sender`'s account to another address.
* @param authorized The address to authorize.
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @dev Fails if the address is already authorized to another account or is an account itself.
* @dev Note that once an address is authorized, it may never be authorized again.
* @dev v, r, s constitute `authorized`'s signature on `msg.sender`.
*/
function authorizeAddress(address authorized, uint8 v, bytes32 r, bytes32 s) private {
address signer = Signatures.getSignerOfAddress(msg.sender, v, r, s);
require(signer == authorized, "Invalid signature");
authorize(authorized);
}
/**
* @notice Returns the address that signed the provided role authorization.
* @param account The `account` property signed over in the EIP712 signature
* @param signer The `signer` property signed over in the EIP712 signature
* @param role The `role` property signed over in the EIP712 signature
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @return The address that signed the provided role authorization.
*/
function getRoleAuthorizationSigner(
address account,
address signer,
bytes32 role,
uint8 v,
bytes32 r,
bytes32 s
) public view returns (address) {
bytes32 structHash = keccak256(
abi.encode(EIP712_AUTHORIZE_SIGNER_TYPEHASH, account, signer, role)
);
return Signatures.getSignerOfTypedDataHash(eip712DomainSeparator, structHash, v, r, s);
}
/**
* @notice Authorizes a role of `msg.sender`'s account to another address (`authorized`).
* @param authorized The address to authorize.
* @param role The role to authorize.
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @dev Fails if the address is already authorized to another account or is an account itself.
* @dev Note that this signature is EIP712 compliant over the authorizing `account`
* (`msg.sender`), `signer` (`authorized`) and `role`.
*/
function authorizeAddressWithRole(address authorized, bytes32 role, uint8 v, bytes32 r, bytes32 s)
private
{
address signer = getRoleAuthorizationSigner(msg.sender, authorized, role, v, r, s);
require(signer == authorized, "Invalid signature");
authorize(authorized);
}
/**
* @notice Authorizes an address to `msg.sender`'s account
* @param authorized The address to authorize.
* @dev Fails if the address is already authorized for another account or is an account itself.
*/
function authorize(address authorized) private {
require(isAccount(msg.sender), "Unknown account");
require(
isNotAccount(authorized) && isNotAuthorizedSignerForAnotherAccount(msg.sender, authorized),
"Cannot re-authorize address or locked gold account for another account"
);
authorizedBy[authorized] = msg.sender;
}
}
| * @notice Setter for the wallet address for an account @param walletAddress The wallet address to set for the account @param v The recovery id of the incoming ECDSA signature. @param r Output value r of the ECDSA signature. @param s Output value s of the ECDSA signature. @dev Wallet address can be zero. This means that the owner of the wallet does not want to be paid directly without interaction, and instead wants users to contact them, using the data encryption key, and arrange a payment. @dev v, r, s constitute `signer`'s signature on `msg.sender` (unless the wallet address is 0x0 or msg.sender)./ | function setWalletAddress(address walletAddress, uint8 v, bytes32 r, bytes32 s) public {
require(isAccount(msg.sender), "Unknown account");
if (!(walletAddress == msg.sender || walletAddress == address(0x0))) {
address signer = Signatures.getSignerOfAddress(msg.sender, v, r, s);
require(signer == walletAddress, "Invalid signature");
}
Account storage account = accounts[msg.sender];
account.walletAddress = walletAddress;
emit AccountWalletAddressSet(msg.sender, walletAddress);
}
| 1,012,271 | [
1,
8465,
364,
326,
9230,
1758,
364,
392,
2236,
225,
9230,
1887,
1021,
9230,
1758,
358,
444,
364,
326,
2236,
225,
331,
1021,
11044,
612,
434,
326,
6935,
7773,
19748,
3372,
18,
225,
436,
3633,
460,
436,
434,
326,
7773,
19748,
3372,
18,
225,
272,
3633,
460,
272,
434,
326,
7773,
19748,
3372,
18,
225,
20126,
1758,
848,
506,
3634,
18,
1220,
4696,
716,
326,
3410,
434,
326,
9230,
225,
1552,
486,
2545,
358,
506,
30591,
5122,
2887,
13581,
16,
471,
3560,
14805,
3677,
358,
5388,
2182,
16,
1450,
326,
501,
8731,
498,
16,
471,
2454,
726,
279,
5184,
18,
225,
331,
16,
436,
16,
272,
29152,
624,
1375,
2977,
264,
11294,
87,
3372,
603,
1375,
3576,
18,
15330,
68,
261,
28502,
326,
9230,
1758,
1377,
353,
374,
92,
20,
578,
1234,
18,
15330,
2934,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
225,
445,
444,
16936,
1887,
12,
2867,
9230,
1887,
16,
2254,
28,
331,
16,
1731,
1578,
436,
16,
1731,
1578,
272,
13,
1071,
288,
203,
565,
2583,
12,
291,
3032,
12,
3576,
18,
15330,
3631,
315,
4874,
2236,
8863,
203,
565,
309,
16051,
12,
19177,
1887,
422,
1234,
18,
15330,
747,
9230,
1887,
422,
1758,
12,
20,
92,
20,
20349,
288,
203,
1377,
1758,
10363,
273,
4383,
2790,
18,
588,
15647,
951,
1887,
12,
3576,
18,
15330,
16,
331,
16,
436,
16,
272,
1769,
203,
1377,
2583,
12,
2977,
264,
422,
9230,
1887,
16,
315,
1941,
3372,
8863,
203,
565,
289,
203,
565,
6590,
2502,
2236,
273,
9484,
63,
3576,
18,
15330,
15533,
203,
565,
2236,
18,
19177,
1887,
273,
9230,
1887,
31,
203,
565,
3626,
6590,
16936,
1887,
694,
12,
3576,
18,
15330,
16,
9230,
1887,
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
] |
pragma solidity 0.4.21;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev revert()s if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/**
* Math operations with safety checks
*/
library SafeMath {
function mul256(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div256(uint256 a, uint256 b) internal returns (uint256) {
require(b > 0); // Solidity automatically revert()s when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub256(uint256 a, uint256 b) internal returns (uint256) {
require(b <= a);
return a - b;
}
function add256(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant public returns (uint256);
function transfer(address to, uint256 value) public;
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev ERC20 interface with allowances.
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant public returns (uint256);
function transferFrom(address from, address to, uint256 value) public;
function approve(address spender, uint256 value) public;
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev Fix for the ERC20 short address attack.
*/
modifier onlyPayloadSize(uint size) {
require(msg.data.length >= size + 4);
_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public {
balances[msg.sender] = balances[msg.sender].sub256(_value);
balances[_to] = balances[_to].add256(_value);
Transfer(msg.sender, _to, _value);
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant public returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
* @dev Implemantation of the basic standart token.
*/
contract StandardToken is BasicToken, ERC20 {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) public {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already revert() if this condition is not met
// if (_value > _allowance) revert();
balances[_to] = balances[_to].add256(_value);
balances[_from] = balances[_from].sub256(_value);
allowed[_from][msg.sender] = _allowance.sub256(_value);
Transfer(_from, _to, _value);
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public {
// To change the approve amount you first have to reduce the addresses
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) revert();
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
/**
* @dev Function to check the amount of tokens than an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title TeuToken
* @dev The main TEU token contract
*
*/
contract TeuToken is StandardToken, Ownable{
string public name = "20-footEqvUnit";
string public symbol = "TEU";
uint public decimals = 18;
event TokenBurned(uint256 value);
function TeuToken() public {
totalSupply = (10 ** 8) * (10 ** decimals);
balances[msg.sender] = totalSupply;
}
/**
* @dev Allows the owner to burn the token
* @param _value number of tokens to be burned.
*/
function burn(uint _value) onlyOwner public {
require(balances[msg.sender] >= _value);
balances[msg.sender] = balances[msg.sender].sub256(_value);
totalSupply = totalSupply.sub256(_value);
TokenBurned(_value);
}
}
/**
* @title teuInitialTokenSale
* @dev The TEU token ICO contract
*
*/
contract teuInitialTokenSale is Ownable {
using SafeMath for uint256;
event LogContribution(address indexed _contributor, uint256 _etherAmount, uint256 _basicTokenAmount, uint256 _timeBonusTokenAmount, uint256 _volumeBonusTokenAmount);
event LogContributionBitcoin(address indexed _contributor, uint256 _bitcoinAmount, uint256 _etherAmount, uint256 _basicTokenAmount, uint256 _timeBonusTokenAmount, uint256 _volumeBonusTokenAmount, uint _contributionDatetime);
event LogOffChainContribution(address indexed _contributor, uint256 _etherAmount, uint256 _tokenAmount);
event LogReferralAward(address indexed _refereeWallet, address indexed _referrerWallet, uint256 _referralBonusAmount);
event LogTokenCollected(address indexed _contributor, uint256 _collectedTokenAmount);
event LogClientIdentRejectListChange(address indexed _contributor, uint8 _newValue);
TeuToken constant private token = TeuToken(0xeEAc3F8da16bb0485a4A11c5128b0518DaC81448); // hard coded due to token already deployed
address constant private etherHolderWallet = 0x00222EaD2D0F83A71F645d3d9634599EC8222830; // hard coded due to deployment for once only
uint256 constant private minContribution = 100 finney;
uint public saleStart = 1523498400;
uint public saleEnd = 1526090400;
uint constant private etherToTokenConversionRate = 400;
uint constant private referralAwardPercent = 20;
uint256 constant private maxCollectableToken = 20 * 10 ** 6 * 10 ** 18;
mapping (address => uint256) private referralContribution; // record the referral contribution amount in ether for claiming of referral bonus
mapping (address => uint) private lastContribitionDate; // record the last contribution date/time for valid the referral bonus claiming period
mapping (address => uint256) private collectableToken; // record the token amount to be collected of each contributor
mapping (address => uint8) private clientIdentRejectList; // record a list of contributors who do not pass the client identification process
bool public isCollectTokenStart = false; // flag to indicate if token collection is started
bool public isAllowContribution = true; // flag to enable/disable contribution.
uint256 public totalCollectableToken; // the total amount of token will be colleceted after considering all the contribution and bonus
// ***** private helper functions ***************
/**
* @dev get the current datetime
*/
function getCurrentDatetime() private constant returns (uint) {
return now;
}
/**
* @dev get the current sale day
*/
function getCurrentSaleDay() private saleIsOn returns (uint) {
return getCurrentDatetime().sub256(saleStart).div256(86400).add256(1);
}
/**
* @dev to get the time bonus Percentage based on the no. of sale day(s)
* @param _days no of sale day to calculate the time bonus
*/
function getTimeBonusPercent(uint _days) private pure returns (uint) {
if (_days <= 20)
return 50;
return 0;
}
/**
* @dev to get the volumne bonus percentage based on the ether amount contributed
* @param _etherAmount ether amount contributed.
*/
function getVolumeBonusPercent(uint256 _etherAmount) private pure returns (uint) {
if (_etherAmount < 1 ether)
return 0;
if (_etherAmount < 2 ether)
return 35;
if (_etherAmount < 3 ether)
return 40;
if (_etherAmount < 4 ether)
return 45;
if (_etherAmount < 5 ether)
return 50;
if (_etherAmount < 10 ether)
return 55;
if (_etherAmount < 20 ether)
return 60;
if (_etherAmount < 30 ether)
return 65;
if (_etherAmount < 40 ether)
return 70;
if (_etherAmount < 50 ether)
return 75;
if (_etherAmount < 100 ether)
return 80;
if (_etherAmount < 200 ether)
return 90;
if (_etherAmount >= 200 ether)
return 100;
return 0;
}
/**
* @dev to get the time bonus amount given the token amount to be collected from contribution
* @param _tokenAmount token amount to be collected from contribution
*/
function getTimeBonusAmount(uint256 _tokenAmount) private returns (uint256) {
return _tokenAmount.mul256(getTimeBonusPercent(getCurrentSaleDay())).div256(100);
}
/**
* @dev to get the volume bonus amount given the token amount to be collected from contribution and the ether amount contributed
* @param _tokenAmount token amount to be collected from contribution
* @param _etherAmount ether amount contributed
*/
function getVolumeBonusAmount(uint256 _tokenAmount, uint256 _etherAmount) private returns (uint256) {
return _tokenAmount.mul256(getVolumeBonusPercent(_etherAmount)).div256(100);
}
/**
* @dev to get the referral bonus amount given the ether amount contributed
* @param _etherAmount ether amount contributed
*/
function getReferralBonusAmount(uint256 _etherAmount) private returns (uint256) {
return _etherAmount.mul256(etherToTokenConversionRate).mul256(referralAwardPercent).div256(100);
}
/**
* @dev to get the basic amount of token to be collected given the ether amount contributed
* @param _etherAmount ether amount contributed
*/
function getBasicTokenAmount(uint256 _etherAmount) private returns (uint256) {
return _etherAmount.mul256(etherToTokenConversionRate);
}
// ****** modifiers ************
/**
* @dev modifier to allow contribution only when the sale is ON
*/
modifier saleIsOn() {
require(getCurrentDatetime() >= saleStart && getCurrentDatetime() < saleEnd);
_;
}
/**
* @dev modifier to check if the sale is ended
*/
modifier saleIsEnd() {
require(getCurrentDatetime() >= saleEnd);
_;
}
/**
* @dev modifier to check if token is collectable
*/
modifier tokenIsCollectable() {
require(isCollectTokenStart);
_;
}
/**
* @dev modifier to check if contribution is over the min. contribution amount
*/
modifier overMinContribution(uint256 _etherAmount) {
require(_etherAmount >= minContribution);
_;
}
/**
* @dev modifier to check if max. token pool is not reached
*/
modifier underMaxTokenPool() {
require(maxCollectableToken > totalCollectableToken);
_;
}
/**
* @dev modifier to check if contribution is allowed
*/
modifier contributionAllowed() {
require(isAllowContribution);
_;
}
// ***** public transactional functions ***************
/**
* @dev called by owner to set the new sale start date/time
* @param _newStart new start date/time
*/
function setNewStart(uint _newStart) public onlyOwner {
require(saleStart > getCurrentDatetime());
require(_newStart > getCurrentDatetime());
require(saleEnd > _newStart);
saleStart = _newStart;
}
/**
* @dev called by owner to set the new sale end date/time
* @param _newEnd new end date/time
*/
function setNewEnd(uint _newEnd) public onlyOwner {
require(saleEnd < getCurrentDatetime());
require(_newEnd < getCurrentDatetime());
require(_newEnd > saleStart);
saleEnd = _newEnd;
}
/**
* @dev called by owner to enable / disable contribution
* @param _isAllow true - allow contribution; false - disallow contribution
*/
function enableContribution(bool _isAllow) public onlyOwner {
isAllowContribution = _isAllow;
}
/**
* @dev called by contributors to record a contribution
*/
function contribute() public payable saleIsOn overMinContribution(msg.value) underMaxTokenPool contributionAllowed {
uint256 _basicToken = getBasicTokenAmount(msg.value);
uint256 _timeBonus = getTimeBonusAmount(_basicToken);
uint256 _volumeBonus = getVolumeBonusAmount(_basicToken, msg.value);
uint256 _totalToken = _basicToken.add256(_timeBonus).add256(_volumeBonus);
lastContribitionDate[msg.sender] = getCurrentDatetime();
referralContribution[msg.sender] = referralContribution[msg.sender].add256(msg.value);
collectableToken[msg.sender] = collectableToken[msg.sender].add256(_totalToken);
totalCollectableToken = totalCollectableToken.add256(_totalToken);
assert(etherHolderWallet.send(msg.value));
LogContribution(msg.sender, msg.value, _basicToken, _timeBonus, _volumeBonus);
}
/**
* @dev called by contract owner to record a off chain contribution by Bitcoin. The token collection process is the same as those ether contributors
* @param _bitcoinAmount bitcoin amount contributed
* @param _etherAmount ether equivalent amount contributed
* @param _contributorWallet wallet address of contributor which will be used for token collection
* @param _contributionDatetime date/time of contribution. For calculating time bonus and claiming referral bonus.
*/
function contributeByBitcoin(uint256 _bitcoinAmount, uint256 _etherAmount, address _contributorWallet, uint _contributionDatetime) public overMinContribution(_etherAmount) onlyOwner contributionAllowed {
require(_contributionDatetime <= getCurrentDatetime());
uint256 _basicToken = getBasicTokenAmount(_etherAmount);
uint256 _timeBonus = getTimeBonusAmount(_basicToken);
uint256 _volumeBonus = getVolumeBonusAmount(_basicToken, _etherAmount);
uint256 _totalToken = _basicToken.add256(_timeBonus).add256(_volumeBonus);
if (_contributionDatetime > lastContribitionDate[_contributorWallet])
lastContribitionDate[_contributorWallet] = _contributionDatetime;
referralContribution[_contributorWallet] = referralContribution[_contributorWallet].add256(_etherAmount);
collectableToken[_contributorWallet] = collectableToken[_contributorWallet].add256(_totalToken);
totalCollectableToken = totalCollectableToken.add256(_totalToken);
LogContributionBitcoin(_contributorWallet, _bitcoinAmount, _etherAmount, _basicToken, _timeBonus, _volumeBonus, _contributionDatetime);
}
/**
* @dev called by contract owner to record a off chain contribution by Ether. The token are distributed off chain already. The contributor can only entitle referral bonus through this smart contract
* @param _etherAmount ether equivalent amount contributed
* @param _contributorWallet wallet address of contributor which will be used for referral bonus collection
* @param _tokenAmount amunt of token distributed to the contributor. For reference only in the event log
*/
function recordOffChainContribute(uint256 _etherAmount, address _contributorWallet, uint256 _tokenAmount) public overMinContribution(_etherAmount) onlyOwner {
lastContribitionDate[_contributorWallet] = getCurrentDatetime();
LogOffChainContribution(_contributorWallet, _etherAmount, _tokenAmount);
}
/**
* @dev called by contract owner for migration of contributors from old contract to new contract
* @param _contributorWallets wallet addresss of contributors to be migrated
*/
function migrateContributors(address[] _contributorWallets) public onlyOwner {
for (uint i = 0; i < _contributorWallets.length; i++) {
lastContribitionDate[_contributorWallets[i]] = getCurrentDatetime();
}
}
/**
* @dev called by contributor to claim the referral bonus
* @param _referrerWallet wallet address of referrer. Referrer must also be a contributor
*/
function referral(address _referrerWallet) public {
require (msg.sender != _referrerWallet);
require (referralContribution[msg.sender] > 0);
require (lastContribitionDate[_referrerWallet] > 0);
require (getCurrentDatetime() - lastContribitionDate[msg.sender] <= (4 * 24 * 60 * 60));
uint256 _referralBonus = getReferralBonusAmount(referralContribution[msg.sender]);
referralContribution[msg.sender] = 0;
collectableToken[msg.sender] = collectableToken[msg.sender].add256(_referralBonus);
collectableToken[_referrerWallet] = collectableToken[_referrerWallet].add256(_referralBonus);
totalCollectableToken = totalCollectableToken.add256(_referralBonus).add256(_referralBonus);
LogReferralAward(msg.sender, _referrerWallet, _referralBonus);
}
/**
* @dev called by contract owener to register a list of rejected clients who cannot pass the client identification process.
* @param _clients an array of wallet address clients to be set
* @param _valueToSet 1 - add to reject list, 0 - remove from reject list
*/
function setClientIdentRejectList(address[] _clients, uint8 _valueToSet) public onlyOwner {
for (uint i = 0; i < _clients.length; i++) {
if (_clients[i] != address(0) && clientIdentRejectList[_clients[i]] != _valueToSet) {
clientIdentRejectList[_clients[i]] = _valueToSet;
LogClientIdentRejectListChange(_clients[i], _valueToSet);
}
}
}
/**
* @dev called by contract owner to enable / disable token collection process
* @param _enable true - enable collection; false - disable collection
*/
function setTokenCollectable(bool _enable) public onlyOwner saleIsEnd {
isCollectTokenStart = _enable;
}
/**
* @dev called by contributor to collect tokens. If they are rejected by the client identification process, error will be thrown
*/
function collectToken() public tokenIsCollectable {
uint256 _collToken = collectableToken[msg.sender];
require(clientIdentRejectList[msg.sender] <= 0);
require(_collToken > 0);
collectableToken[msg.sender] = 0;
token.transfer(msg.sender, _collToken);
LogTokenCollected(msg.sender, _collToken);
}
/**
* @dev Allow owner to transfer out the token left in the contract
* @param _to address to transfer to
* @param _amount amount to transfer
*/
function transferTokenOut(address _to, uint256 _amount) public onlyOwner {
token.transfer(_to, _amount);
}
/**
* @dev Allow owner to transfer out the ether left in the contract
* @param _to address to transfer to
* @param _amount amount to transfer
*/
function transferEtherOut(address _to, uint256 _amount) public onlyOwner {
assert(_to.send(_amount));
}
// ***** public constant functions ***************
/**
* @dev to get the amount of token collectable by any contributor
* @param _contributor contributor to get amont
*/
function collectableTokenOf(address _contributor) public constant returns (uint256) {
return collectableToken[_contributor] ;
}
/**
* @dev to get the amount of token collectable by any contributor
* @param _contributor contributor to get amont
*/
function isClientIdentRejectedOf(address _contributor) public constant returns (uint8) {
return clientIdentRejectList[_contributor];
}
/**
* @dev Fallback function which receives ether and create the appropriate number of tokens for the
* msg.sender.
*/
function() external payable {
contribute();
}
} | * @dev to get the time bonus Percentage based on the no. of sale day(s) @param _days no of sale day to calculate the time bonus/ | function getTimeBonusPercent(uint _days) private pure returns (uint) {
if (_days <= 20)
return 50;
return 0;
}
| 993,028 | [
1,
869,
336,
326,
813,
324,
22889,
21198,
410,
2511,
603,
326,
1158,
18,
434,
272,
5349,
2548,
12,
87,
13,
225,
389,
9810,
1158,
434,
272,
5349,
2548,
358,
4604,
326,
813,
324,
22889,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
6135,
38,
22889,
8410,
12,
11890,
389,
9810,
13,
3238,
16618,
1135,
261,
11890,
13,
288,
203,
3639,
309,
261,
67,
9810,
1648,
4200,
13,
203,
5411,
327,
6437,
31,
203,
3639,
327,
374,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/56/0xb50a7dBCef6BDA5a35e27EdC9334f87736e142dB/sources/MasterChefV2.sol | Deposit LP tokens to MasterChef for PEGA allocation. | function deposit(uint256 _pid, uint256 _amount) public nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accPegaPerShare).div(1e12).sub(user.rewardDebt);
if (pending > 0) {
safePegaTransfer(msg.sender, pending);
}
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
if (pool.depositFeeBP > 0) {
uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000);
pool.lpToken.safeTransfer(feeAddress, depositFee);
user.amount = user.amount.add(_amount).sub(depositFee);
user.amount = user.amount.add(_amount);
}
}
user.rewardDebt = user.amount.mul(pool.accPegaPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
| 11,242,776 | [
1,
758,
1724,
511,
52,
2430,
358,
13453,
39,
580,
74,
364,
16628,
25043,
13481,
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,
443,
1724,
12,
11890,
5034,
389,
6610,
16,
2254,
5034,
389,
8949,
13,
1071,
1661,
426,
8230,
970,
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,
3576,
18,
15330,
15533,
203,
3639,
1089,
2864,
24899,
6610,
1769,
203,
3639,
309,
261,
1355,
18,
8949,
405,
374,
13,
288,
203,
5411,
2254,
5034,
4634,
273,
729,
18,
8949,
18,
16411,
12,
6011,
18,
8981,
52,
11061,
2173,
9535,
2934,
2892,
12,
21,
73,
2138,
2934,
1717,
12,
1355,
18,
266,
2913,
758,
23602,
1769,
203,
5411,
309,
261,
9561,
405,
374,
13,
288,
203,
7734,
4183,
52,
11061,
5912,
12,
3576,
18,
15330,
16,
4634,
1769,
203,
5411,
289,
203,
3639,
289,
203,
3639,
309,
261,
67,
8949,
405,
374,
13,
288,
203,
5411,
2845,
18,
9953,
1345,
18,
4626,
5912,
1265,
12,
2867,
12,
3576,
18,
15330,
3631,
1758,
12,
2211,
3631,
389,
8949,
1769,
203,
5411,
309,
261,
6011,
18,
323,
1724,
14667,
30573,
405,
374,
13,
288,
203,
7734,
2254,
5034,
443,
1724,
14667,
273,
389,
8949,
18,
16411,
12,
6011,
18,
323,
1724,
14667,
30573,
2934,
2892,
12,
23899,
1769,
203,
7734,
2845,
18,
9953,
1345,
18,
4626,
5912,
12,
21386,
1887,
16,
443,
1724,
14667,
1769,
203,
7734,
729,
18,
8949,
273,
729,
18,
8949,
18,
1289,
24899,
8949,
2934,
1717,
12,
323,
1724,
14667,
1769,
203,
7734,
729,
18,
8949,
273,
729,
18,
8949,
18,
1289,
24899,
8949,
1769,
203,
2
] |
pragma solidity ^0.4.11;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value)public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)public constant returns (uint256);
function transferFrom(address from, address to, uint256 value)public returns (bool);
function approve(address spender, uint256 value)public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @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) {
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 constant returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev modifier to allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused returns (bool) {
paused = true;
emit Pause();
return true;
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause()public onlyOwner whenPaused returns (bool) {
paused = false;
emit Unpause();
return true;
}
}
/**
* @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)) 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 amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value)public returns (bool) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value)public returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_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 specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender)public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title FFC Token
* @dev FFC is PausableToken
*/
contract FFCToken is StandardToken, Pausable {
string public constant name = "FFC";
string public constant symbol = "FFC";
uint256 public constant decimals = 18;
// lock
struct LockToken{
uint256 amount;
uint32 time;
}
struct LockTokenSet{
LockToken[] lockList;
}
mapping ( address => LockTokenSet ) addressTimeLock;
mapping ( address => bool ) lockAdminList;
event TransferWithLockEvt(address indexed from, address indexed to, uint256 value,uint256 lockValue,uint32 lockTime );
/**
* @dev Creates a new MPKToken instance
*/
constructor() public {
totalSupply = 10 * (10 ** 8) * (10 ** 18);
balances[msg.sender] = totalSupply;
}
function transfer(address _to, uint256 _value)public whenNotPaused returns (bool) {
assert ( balances[msg.sender].sub( getLockAmount( msg.sender ) ) >= _value );
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value)public whenNotPaused returns (bool) {
assert ( balances[_from].sub( getLockAmount( msg.sender ) ) >= _value );
return super.transferFrom(_from, _to, _value);
}
function getLockAmount( address myaddress ) public view returns ( uint256 lockSum ) {
uint256 lockAmount = 0;
for( uint32 i = 0; i < addressTimeLock[myaddress].lockList.length; i ++ ){
if( addressTimeLock[myaddress].lockList[i].time > now ){
lockAmount += addressTimeLock[myaddress].lockList[i].amount;
}
}
return lockAmount;
}
function getLockListLen( address myaddress ) public view returns ( uint256 lockAmount ){
return addressTimeLock[myaddress].lockList.length;
}
function getLockByIdx( address myaddress,uint32 idx ) public view returns ( uint256 lockAmount, uint32 lockTime ){
if( idx >= addressTimeLock[myaddress].lockList.length ){
return (0,0);
}
lockAmount = addressTimeLock[myaddress].lockList[idx].amount;
lockTime = addressTimeLock[myaddress].lockList[idx].time;
return ( lockAmount,lockTime );
}
function transferWithLock( address _to, uint256 _value,uint256 _lockValue,uint32 _lockTime )public whenNotPaused {
if( lockAdminList[msg.sender] != true ){
return;
}
assert( _lockTime > now );
assert( _lockValue > 0 && _lockValue <= _value );
transfer( _to, _value );
bool needNewLock = true;
for( uint32 i = 0 ; i< addressTimeLock[_to].lockList.length; i ++ ){
if( addressTimeLock[_to].lockList[i].time < now ){
addressTimeLock[_to].lockList[i].time = _lockTime;
addressTimeLock[_to].lockList[i].amount = _lockValue;
emit TransferWithLockEvt( msg.sender,_to,_value,_lockValue,_lockTime );
needNewLock = false;
break;
}
}
if( needNewLock == true ){
// add a lock
addressTimeLock[_to].lockList.length ++ ;
addressTimeLock[_to].lockList[(addressTimeLock[_to].lockList.length-1)].time = _lockTime;
addressTimeLock[_to].lockList[(addressTimeLock[_to].lockList.length-1)].amount = _lockValue;
emit TransferWithLockEvt( msg.sender,_to,_value,_lockValue,_lockTime);
}
}
function setLockAdmin(address _to,bool canUse)public onlyOwner{
lockAdminList[_to] = canUse;
}
function canUseLock() public view returns (bool){
return lockAdminList[msg.sender];
}
} | * @title Basic token @dev Basic version of StandardToken, with no allowances./ | contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
| 241,008 | [
1,
8252,
1147,
225,
7651,
1177,
434,
8263,
1345,
16,
598,
1158,
1699,
6872,
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,
16351,
7651,
1345,
353,
4232,
39,
3462,
8252,
288,
203,
225,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
225,
2874,
12,
2867,
516,
2254,
5034,
13,
324,
26488,
31,
203,
203,
225,
445,
7412,
12,
2867,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
1135,
261,
6430,
13,
288,
203,
565,
324,
26488,
63,
3576,
18,
15330,
65,
273,
324,
26488,
63,
3576,
18,
15330,
8009,
1717,
24899,
1132,
1769,
203,
565,
324,
26488,
63,
67,
869,
65,
273,
324,
26488,
63,
67,
869,
8009,
1289,
24899,
1132,
1769,
203,
565,
3626,
12279,
12,
3576,
18,
15330,
16,
389,
869,
16,
389,
1132,
1769,
203,
565,
327,
638,
31,
203,
225,
289,
203,
203,
225,
445,
11013,
951,
12,
2867,
389,
8443,
13,
1071,
5381,
1135,
261,
11890,
5034,
11013,
13,
288,
203,
565,
327,
324,
26488,
63,
67,
8443,
15533,
203,
225,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.8.0;
// SPDX-License-Identifier: Apache-2.0
import "../include/IERC165.sol";
import "../include/IERC721.sol";
import "../include/IERC721Metadata.sol";
import "../include/IERC721TokenReceiver.sol";
import "../lib/Address.sol";
abstract contract ERC721 is IERC165, IERC721, IERC721Metadata {
using Address for address;
/*
* bytes4(keccak256("supportsInterface(bytes4)")) == 0x01ffc9a7
*/
bytes4 internal constant INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7;
/*
* bytes4(keccak256("balanceOf(address)")) == 0x70a08231
* bytes4(keccak256("ownerOf(uint256)")) == 0x6352211e
* bytes4(keccak256("approve(address,uint256)")) == 0x095ea7b3
* bytes4(keccak256("getApproved(uint256)")) == 0x081812fc
* bytes4(keccak256("setApprovalForAll(address,bool)")) == 0xa22cb465
* bytes4(keccak256("isApprovedForAll(address,address)")) == 0xe985e9c5
* bytes4(keccak256("transferFrom(address,address,uint256)")) == 0x23b872dd
* bytes4(keccak256("safeTransferFrom(address,address,uint256)")) == 0x42842e0e
* bytes4(keccak256("safeTransferFrom(address,address,uint256,bytes)")) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant INTERFACE_SIGNATURE_ERC721 = 0x80ac58cd;
bytes4 private constant INTERFACE_SIGNATURE_ERC721Metadata = 0x5b5e139f;
bytes4 private constant ERC721_RECEIVER_RETURN = 0x150b7a02;
string public override name;
string public override symbol;
//address => ids
mapping(address => uint256[]) internal ownerTokens;
mapping(uint256 => uint256) internal tokenIndexs;
mapping(uint256 => address) internal tokenOwners;
mapping(uint256 => address) internal tokenApprovals;
mapping(address => mapping(address => bool)) internal approvalForAlls;
uint256 public totalSupply = 0;
constructor(string memory _name, string memory _symbol) {
name = _name;
symbol = _symbol;
}
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "owner is zero address");
return ownerTokens[owner].length;
}
// [startIndex, endIndex)
function tokensOf(
address owner,
uint256 startIndex,
uint256 endIndex
) public view returns (uint256[] memory) {
require(owner != address(0), "owner is zero address");
uint256[] storage tokens = ownerTokens[owner];
if (endIndex == 0) {
return tokens;
}
require(startIndex < endIndex, "invalid index");
uint256[] memory result = new uint256[](endIndex - startIndex);
for (uint256 i = startIndex; i != endIndex; ++i) {
result[i] = tokens[i];
}
return result;
}
function ownerOf(uint256 tokenId) public view override returns (address) {
address owner = tokenOwners[tokenId];
require(owner != address(0), "nobody own the token");
return owner;
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external payable override {
safeTransferFrom(from, to, tokenId, "");
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory data
) public payable virtual override {
_transferFrom(from, to, tokenId);
if (to.isContract()) {
require(IERC721TokenReceiver(to).onERC721Received(msg.sender, from, tokenId, data) == ERC721_RECEIVER_RETURN, "onERC721Received() return invalid");
}
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public payable virtual override {
_transferFrom(from, to, tokenId);
}
function _transferFrom(
address from,
address to,
uint256 tokenId
) internal {
require(from != address(0), "from is zero address");
require(to != address(0), "to is zero address");
require(from == tokenOwners[tokenId], "from must be owner");
require(msg.sender == from || msg.sender == tokenApprovals[tokenId] || approvalForAlls[from][msg.sender], "sender must be owner or approvaled");
if (tokenApprovals[tokenId] != address(0)) {
delete tokenApprovals[tokenId];
}
_removeTokenFrom(from, tokenId);
_addTokenTo(to, tokenId);
emit Transfer(from, to, tokenId);
}
// ensure everything is ok before call it
function _removeTokenFrom(address from, uint256 tokenId) internal {
uint256 index = tokenIndexs[tokenId];
uint256[] storage tokens = ownerTokens[from];
uint256 indexLast = tokens.length - 1;
uint256 tokenIdLast = tokens[indexLast];
tokens[index] = tokenIdLast;
tokenIndexs[tokenIdLast] = index;
tokens.pop();
// delete tokenIndexs[tokenId]; // save gas
delete tokenOwners[tokenId];
}
// ensure everything is ok before call it
function _addTokenTo(address to, uint256 tokenId) internal {
uint256[] storage tokens = ownerTokens[to];
tokenIndexs[tokenId] = tokens.length;
tokens.push(tokenId);
tokenOwners[tokenId] = to;
}
function approve(address to, uint256 tokenId) public payable override {
address owner = tokenOwners[tokenId];
require(msg.sender == owner || approvalForAlls[owner][msg.sender], "sender must be owner or approved for all");
tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
function setApprovalForAll(address to, bool approved) public override {
approvalForAlls[msg.sender][to] = approved;
emit ApprovalForAll(msg.sender, to, approved);
}
function getApproved(uint256 tokenId) public view override returns (address) {
require(tokenOwners[tokenId] != address(0), "nobody own then token");
return tokenApprovals[tokenId];
}
function isApprovedForAll(address owner, address operator) public view override returns (bool) {
return approvalForAlls[owner][operator];
}
function supportsInterface(bytes4 interfaceID) public pure virtual override returns (bool) {
return interfaceID == INTERFACE_SIGNATURE_ERC165 || interfaceID == INTERFACE_SIGNATURE_ERC721 || interfaceID == INTERFACE_SIGNATURE_ERC721Metadata;
}
function _burn(uint256 tokenId) internal {
address owner = tokenOwners[tokenId];
_removeTokenFrom(owner, tokenId);
if (tokenApprovals[tokenId] != address(0)) {
delete tokenApprovals[tokenId];
}
emit Transfer(owner, address(0), tokenId);
}
function _mint(address to, uint256 tokenId) internal {
_addTokenTo(to, tokenId);
++totalSupply;
emit Transfer(address(0), to, tokenId);
}
}
| ensure everything is ok before call it | function _addTokenTo(address to, uint256 tokenId) internal {
uint256[] storage tokens = ownerTokens[to];
tokenIndexs[tokenId] = tokens.length;
tokens.push(tokenId);
tokenOwners[tokenId] = to;
}
| 15,841,606 | [
1,
15735,
7756,
353,
1529,
1865,
745,
518,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
389,
1289,
1345,
774,
12,
2867,
358,
16,
2254,
5034,
1147,
548,
13,
2713,
288,
203,
3639,
2254,
5034,
8526,
2502,
2430,
273,
3410,
5157,
63,
869,
15533,
203,
3639,
1147,
1016,
87,
63,
2316,
548,
65,
273,
2430,
18,
2469,
31,
203,
3639,
2430,
18,
6206,
12,
2316,
548,
1769,
203,
203,
3639,
1147,
5460,
414,
63,
2316,
548,
65,
273,
358,
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
] |
./full_match/1/0xf607014406bc3Fa7aAB224a85A0318b4556e9C28/sources/browser/CryptographInitiator.sol | The third party cut out of 100k
| uint256 public thirdPartyCut; | 3,151,986 | [
1,
1986,
12126,
18285,
6391,
596,
434,
2130,
79,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2254,
5034,
1071,
12126,
17619,
15812,
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
] |
./full_match/137/0xdF848a8eE0c36d8A44cfC23270E4342E3802c040/sources/contracts/Locker.sol | The ownership share is minted to the creator. It should be noted that anyone can unlock the lock if they own the share. | _mint(msg.sender, lockId);
| 4,676,556 | [
1,
1986,
23178,
7433,
353,
312,
474,
329,
358,
326,
11784,
18,
2597,
1410,
506,
486,
329,
716,
1281,
476,
848,
7186,
326,
2176,
309,
2898,
4953,
326,
7433,
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
] | [
1,
1,
1,
1,
1,
1,
1,
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,
3639,
389,
81,
474,
12,
3576,
18,
15330,
16,
2176,
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,
-100,
-100,
-100,
-100
] |
./full_match/1/0xc6ceDdA94aa5938f8377e0D1E34B22fE01b0d575/sources/inariHelper.sol | **** COMPOUND/CREAM | function toCompound(ICompoundHelper cToken, uint256 underlyingAmount) external view returns (uint256 result) {
result = underlyingAmount / cToken.exchangeRateStored() / 10**18;
}
| 4,860,908 | [
1,
4208,
2419,
5240,
19,
5458,
2192,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
358,
16835,
12,
45,
16835,
2276,
276,
1345,
16,
2254,
5034,
6808,
6275,
13,
3903,
1476,
1135,
261,
11890,
5034,
563,
13,
288,
7010,
3639,
563,
273,
6808,
6275,
225,
342,
276,
1345,
18,
16641,
4727,
18005,
1435,
342,
1728,
636,
2643,
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
] |
/**
*Submitted for verification at Etherscan.io on 2022-03-09
*/
// SPDX-License-Identifier: UNLICENSED
// File: contracts/abstract/FundDistribution.sol
pragma solidity 0.8.9;
/**
* @title Fund Distribution interface that could be used by other contracts to reference
* TokenFactory/MasterChef in order to enable minting/rewarding to a designated fund address.
*/
interface FundDistribution {
/**
* @dev an operation that triggers reward distribution by minting to the designated address
* from TokenFactory. The fund address must be already configured in TokenFactory to receive
* funds, else no funds will be retrieved.
*/
function sendReward(address _fundAddress) external returns (bool);
}
// File: contracts/abstract/IERC20.sol
pragma solidity 0.8.9;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/abstract/Context.sol
pragma solidity 0.8.9;
/*
* @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) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: contracts/abstract/Ownable.sol
pragma solidity 0.8.9;
// Part: OpenZeppelin/[email protected]/Ownable
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/abstract/SafeMath.sol
pragma solidity 0.8.9;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/abstract/Address.sol
pragma solidity 0.8.9;
/**
* @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.3._
*/
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.3._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: contracts/abstract/ERC20.sol
pragma solidity 0.8.9;
/**
* @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}.
*/
abstract contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory tokenName, string memory tokenSymbol) {
_name = tokenName;
_symbol = tokenSymbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount)
public
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
virtual
override
view
returns (uint256)
{
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount)
public
virtual
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(addedValue)
);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
"ERC20: decreased allowance below zero"
)
);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(
amount,
"ERC20: transfer amount exceeds balance"
);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(
amount,
"ERC20: burn amount exceeds balance"
);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// File: contracts/abstract/MeedsToken.sol
pragma solidity 0.8.9;
contract MeedsToken is ERC20("Meeds Token", "MEED"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (TokenFactory).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
}
// File: contracts/abstract/SafeERC20.sol
pragma solidity 0.8.9;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transfer.selector, to, value)
);
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transferFrom.selector, from, to, value)
);
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, value)
);
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(
value
);
_callOptionalReturn(
token,
abi.encodeWithSelector(
token.approve.selector,
spender,
newAllowance
)
);
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(
value,
"SafeERC20: decreased allowance below zero"
);
_callOptionalReturn(
token,
abi.encodeWithSelector(
token.approve.selector,
spender,
newAllowance
)
);
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(
data,
"SafeERC20: low-level call failed"
);
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(
abi.decode(returndata, (bool)),
"SafeERC20: ERC20 operation did not succeed"
);
}
}
}
// File: contracts/TokenFactory.sol
pragma solidity 0.8.9;
/**
* @dev This contract will send MEED rewards to multiple funds by minting on MEED contract.
* Since it is the only owner of the MEED Token, all minting operations will be exclusively
* made here.
* This contract will mint for the 3 type of Rewarding mechanisms as described in MEED white paper:
* - Liquidity providers through renting and buying liquidity pools
* - User Engagment within the software
* - Work / services provided by association members to build the DOM
*
* In other words, MEEDs are created based on the involvment of three different categories
* of stake holders:
* - the capital owners
* - the users
* - the builders
*
* Consequently, there will be two kind of Fund Contracts that will be managed by this one:
* - ERC20 LP Token contracts: this contract will reward LP Token stakers
* with a proportion of minted MEED per minute
* - Fund contract : which will receive a proportion of minted MEED (unlike LP Token contract)
* to make the distribution switch its internal algorithm.
*/
contract TokenFactory is Ownable, FundDistribution {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
// Info of each user who staked LP Tokens
struct UserInfo {
uint256 amount; // How many LP tokens the user has staked
uint256 rewardDebt; // How much MEED rewards the user had received
}
// Info of each fund
// A fund can be either a Fund that will receive Minted MEED
// to use its own rewarding distribution strategy or a Liquidity Pool.
struct FundInfo {
uint256 fixedPercentage; // How many fixed percentage of minted MEEDs will be sent to this fund contract
uint256 allocationPoint; // How many allocation points assigned to this pool comparing to other pools
uint256 lastRewardTime; // Last block timestamp that MEEDs distribution has occurred
uint256 accMeedPerShare; // Accumulated MEEDs per share: price of LP Token comparing to 1 MEED (multiplied by 10^12 to make the computation more precise)
bool isLPToken; // // The Liquidity Pool rewarding distribution will be handled by this contract
// in contrary to a simple Fund Contract which will manage distribution by its own and thus, receive directly minted MEEDs.
}
// Since, the minting privilege is exclusively hold
// by the current contract and it's not transferable,
// this will be the absolute Maximum Supply of all MEED Token.
uint256 public constant MAX_MEED_SUPPLY = 1e26;
uint256 public constant MEED_REWARDING_PRECISION = 1e12;
// The MEED TOKEN!
MeedsToken public meed;
// MEEDs minted per minute
uint256 public meedPerMinute;
// List of fund addresses
address[] public fundAddresses;
// Info of each pool
mapping(address => FundInfo) public fundInfos;
// Info of each user that stakes LP tokens
mapping(address => mapping(address => UserInfo)) public userLpInfos;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocationPoints = 0;
// Total fixed percentage. Must be the sum of all allocation points in all pools.
uint256 public totalFixedPercentage = 0;
// The block time when MEED mining starts
uint256 public startRewardsTime;
// LP Operations Events
event Deposit(address indexed user, address indexed lpAddress, uint256 amount);
event Withdraw(address indexed user, address indexed lpAddress, uint256 amount);
event EmergencyWithdraw(address indexed user, address indexed lpAddress, uint256 amount);
event Harvest(address indexed user, address indexed lpAddress, uint256 amount);
// Fund Events
event FundAdded(address indexed fundAddress, uint256 allocation, bool fixedPercentage, bool isLPToken);
event FundAllocationChanged(address indexed fundAddress, uint256 allocation, bool fixedPercentage);
// Max MEED Supply Reached
event MaxSupplyReached(uint256 timestamp);
constructor (
MeedsToken _meed,
uint256 _meedPerMinute,
uint256 _startRewardsTime
) {
meed = _meed;
meedPerMinute = _meedPerMinute;
startRewardsTime = _startRewardsTime;
}
/**
* @dev changes the rewarded MEEDs per minute
*/
function setMeedPerMinute(uint256 _meedPerMinute) external onlyOwner {
require(_meedPerMinute > 0, "TokenFactory#setMeedPerMinute: _meedPerMinute must be strictly positive integer");
meedPerMinute = _meedPerMinute;
}
/**
* @dev add a new Fund Address. The address must be an ERC20 LP Token contract address.
*
* The proportion of MEED rewarding can be fixed (30% by example) or variable (using allocationPoints).
* The allocationPoint will determine the proportion (percentage) of MEED rewarding that a fund will take
* comparing to other funds using the same percentage mechanism.
*
* The computing of percentage using allocationPoint mechanism is as following:
* Allocation percentage = allocationPoint / totalAllocationPoints * (100 - totalFixedPercentage)
*
* The computing of percentage using fixedPercentage mechanism is as following:
* Allocation percentage = fixedPercentage
*
* If the rewarding didn't started yet, no fund address will receive rewards.
*
* See {sendReward} method for more details.
*/
function addLPToken(IERC20 _lpToken, uint256 _value, bool _isFixedPercentage) external onlyOwner {
require(address(_lpToken).isContract(), "TokenFactory#addLPToken: _fundAddress must be an ERC20 Token Address");
_addFund(address(_lpToken), _value, _isFixedPercentage, true);
}
/**
* @dev add a new Fund Address. The address can be a contract that will receive
* funds and distribute MEED earnings switch a specific algorithm (User and/or Employee Engagement Program,
* DAO, xMEED staking...)
*
* The proportion of MEED rewarding can be fixed (30% by example) or variable (using allocationPoints).
* The allocationPoint will determine the proportion (percentage) of MEED rewarding that a fund will take
* comparing to other funds using the same percentage mechanism.
*
* The computing of percentage using allocationPoint mechanism is as following:
* Allocation percentage = allocationPoint / totalAllocationPoints * (100 - totalFixedPercentage)
*
* The computing of percentage using fixedPercentage mechanism is as following:
* Allocation percentage = fixedPercentage
*
* If the rewarding didn't started yet, no fund will receive rewards.
*
* See {sendReward} method for more details.
*/
function addFund(address _fundAddress, uint256 _value, bool _isFixedPercentage) external onlyOwner {
_addFund(_fundAddress, _value, _isFixedPercentage, false);
}
/**
* @dev Updates the allocated rewarding ratio to the ERC20 LPToken or Fund address.
* See #addLPToken and #addFund for more information.
*/
function updateAllocation(address _fundAddress, uint256 _value, bool _isFixedPercentage) external onlyOwner {
FundInfo storage fund = fundInfos[_fundAddress];
require(fund.lastRewardTime > 0, "TokenFactory#updateAllocation: _fundAddress isn't a recognized LPToken nor a fund address");
sendReward(_fundAddress);
if (_isFixedPercentage) {
require(fund.accMeedPerShare == 0, "TokenFactory#setFundAllocation Error: can't change fund percentage from variable to fixed");
totalFixedPercentage = totalFixedPercentage.sub(fund.fixedPercentage).add(_value);
require(totalFixedPercentage <= 100, "TokenFactory#setFundAllocation: total percentage can't be greater than 100%");
fund.fixedPercentage = _value;
totalAllocationPoints = totalAllocationPoints.sub(fund.allocationPoint);
fund.allocationPoint = 0;
} else {
require(!fund.isLPToken || fund.fixedPercentage == 0, "TokenFactory#setFundAllocation Error: can't change Liquidity Pool percentage from fixed to variable");
totalAllocationPoints = totalAllocationPoints.sub(fund.allocationPoint).add(_value);
fund.allocationPoint = _value;
totalFixedPercentage = totalFixedPercentage.sub(fund.fixedPercentage);
fund.fixedPercentage = 0;
}
emit FundAllocationChanged(_fundAddress, _value, _isFixedPercentage);
}
/**
* @dev update all fund allocations and send minted MEED
* See {sendReward} method for more details.
*/
function sendAllRewards() external {
uint256 length = fundAddresses.length;
for (uint256 index = 0; index < length; index++) {
sendReward(fundAddresses[index]);
}
}
/**
* @dev update designated fund allocations and send minted MEED
* See {sendReward} method for more details.
*/
function batchSendRewards(address[] memory _fundAddresses) external {
uint256 length = _fundAddresses.length;
for (uint256 index = 0; index < length; index++) {
sendReward(fundAddresses[index]);
}
}
/**
* @dev update designated fund allocation and send minted MEED.
*
* @param _fundAddress The address can be an LP Token or another contract
* that will receive funds and distribute MEED earnings switch a specific algorithm
* (User and/or Employee Engagement Program, DAO, xMEED staking...)
*
* The proportion of MEED rewarding can be fixed (30% by example) or variable (using allocationPoints).
* The allocationPoint will determine the proportion (percentage) of MEED rewarding that a fund will take
* comparing to other funds using the same percentage mechanism.
*
* The computing of percentage using allocationPoint mechanism is as following:
* Allocation percentage = allocationPoint / totalAllocationPoints * (100 - totalFixedPercentage)
*
* The computing of percentage using fixedPercentage mechanism is as following:
* Allocation percentage = fixedPercentage
*
* If the rewarding didn't started yet, no fund will receive rewards.
*
* For LP Token funds, the reward distribution per wallet will be managed in this contract,
* thus, by calling this method, the LP Token rewards will be sent to this contract and then
* the reward distribution can be claimed wallet by wallet by using method {harvest}, {deposit}
* or {withdraw}.
* for other type of funds, the Rewards will be sent directly to the contract/wallet address
* to manage Reward distribution to wallets switch its specific algorithm outside this contract.
*/
function sendReward(address _fundAddress) public override returns (bool) {
// Minting didn't started yet
if (block.timestamp < startRewardsTime) {
return true;
}
FundInfo storage fund = fundInfos[_fundAddress];
require(fund.lastRewardTime > 0, "TokenFactory#sendReward: _fundAddress isn't a recognized LPToken nor a fund address");
uint256 pendingRewardAmount = _pendingRewardBalanceOf(fund);
if (fund.isLPToken) {
fund.accMeedPerShare = _getAccMeedPerShare(_fundAddress, pendingRewardAmount);
_mint(address(this), pendingRewardAmount);
} else {
_mint(_fundAddress, pendingRewardAmount);
}
fund.lastRewardTime = block.timestamp;
return true;
}
/**
* @dev a wallet will stake an LP Token amount to an already configured address
* (LP Token address).
*
* When staking LP Tokens, the pending MEED rewards will be sent to current wallet
* and LP Token will be staked in current contract address.
* The LP Farming algorithm is inspired from ERC-2917 Demo:
*
* https://github.com/gnufoo/ERC2917-Proposal/blob/master/contracts/ERC2917.sol
*/
function deposit(IERC20 _lpToken, uint256 _amount) public {
address _lpAddress = address(_lpToken);
FundInfo storage fund = fundInfos[_lpAddress];
require(fund.isLPToken, "TokenFactory#deposit Error: Liquidity Pool doesn't exist");
// Update & Mint MEED for the designated pool
// to ensure systematically to have enough
// MEEDs balance in current contract
sendReward(_lpAddress);
UserInfo storage user = userLpInfos[_lpAddress][msg.sender];
if (user.amount > 0) {
uint256 pending = user
.amount
.mul(fund.accMeedPerShare).div(MEED_REWARDING_PRECISION)
.sub(user.rewardDebt);
_safeMeedTransfer(msg.sender, pending);
}
IERC20(_lpAddress).safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(fund.accMeedPerShare).div(MEED_REWARDING_PRECISION);
emit Deposit(msg.sender, _lpAddress, _amount);
}
/**
* @dev a wallet will withdraw an amount of already staked LP Tokens.
*
* When this operation is triggered, the pending MEED rewards will be sent to current wallet
* and LP Token will be send back to caller address from current contract balance of staked LP Tokens.
* The LP Farming algorithm is inspired from ERC-2917 Demo:
* https://github.com/gnufoo/ERC2917-Proposal/blob/master/contracts/ERC2917.sol
*
* If the amount of withdrawn LP Tokens is 0, only {harvest}ing the pending reward will be made.
*/
function withdraw(IERC20 _lpToken, uint256 _amount) public {
address _lpAddress = address(_lpToken);
FundInfo storage fund = fundInfos[_lpAddress];
require(fund.isLPToken, "TokenFactory#withdraw Error: Liquidity Pool doesn't exist");
// Update & Mint MEED for the designated pool
// to ensure systematically to have enough
// MEEDs balance in current contract
sendReward(_lpAddress);
UserInfo storage user = userLpInfos[_lpAddress][msg.sender];
// Send pending MEED Reward to user
uint256 pendingUserReward = user.amount.mul(fund.accMeedPerShare).div(1e12).sub(
user.rewardDebt
);
_safeMeedTransfer(msg.sender, pendingUserReward);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(fund.accMeedPerShare).div(1e12);
if (_amount > 0) {
// Send pending Reward
IERC20(_lpAddress).safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _lpAddress, _amount);
} else {
emit Harvest(msg.sender, _lpAddress, pendingUserReward);
}
}
/**
* @dev Withdraw without caring about rewards. EMERGENCY ONLY.
*/
function emergencyWithdraw(IERC20 _lpToken) public {
address _lpAddress = address(_lpToken);
FundInfo storage fund = fundInfos[_lpAddress];
require(fund.isLPToken, "TokenFactory#emergencyWithdraw Error: Liquidity Pool doesn't exist");
UserInfo storage user = userLpInfos[_lpAddress][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
IERC20(_lpAddress).safeTransfer(address(msg.sender), amount);
emit EmergencyWithdraw(msg.sender, _lpAddress, amount);
}
/**
* @dev Claim reward for current wallet from designated Liquidity Pool
*/
function harvest(IERC20 _lpAddress) public {
withdraw(_lpAddress, 0);
}
function fundsLength() public view returns (uint256) {
return fundAddresses.length;
}
/**
* @dev returns the pending amount of wallet rewarding from LP Token Fund.
* this operation is possible only when the LP Token address is an ERC-20 Token.
* If the rewarding program didn't started yet, 0 will be returned.
*/
function pendingRewardBalanceOf(IERC20 _lpToken, address _user) public view returns (uint256) {
address _lpAddress = address(_lpToken);
if (block.timestamp < startRewardsTime) {
return 0;
}
FundInfo storage fund = fundInfos[_lpAddress];
if (!fund.isLPToken) {
return 0;
}
uint256 pendingRewardAmount = _pendingRewardBalanceOf(fund);
uint256 accMeedPerShare = _getAccMeedPerShare(_lpAddress, pendingRewardAmount);
UserInfo storage user = userLpInfos[_lpAddress][_user];
return user.amount.mul(accMeedPerShare).div(MEED_REWARDING_PRECISION).sub(user.rewardDebt);
}
/**
* @dev returns the pending amount of MEED rewarding for a designated Fund address.
* See {sendReward} method for more details.
*/
function pendingRewardBalanceOf(address _fundAddress) public view returns (uint256) {
if (block.timestamp < startRewardsTime) {
return 0;
}
return _pendingRewardBalanceOf(fundInfos[_fundAddress]);
}
/**
* @dev add a new Fund Address. The address can be an LP Token or another contract
* that will receive funds and distribute MEED earnings switch a specific algorithm
* (User and/or Employee Engagement Program, DAO, xMEED staking...)
*
* The proportion of MEED rewarding can be fixed (30% by example) or variable (using allocationPoints).
* The allocationPoint will determine the proportion (percentage) of MEED rewarding that a fund will take
* comparing to other funds using the same percentage mechanism.
*
* The computing of percentage using allocationPoint mechanism is as following:
* Allocation percentage = allocationPoint / totalAllocationPoints * (100 - totalFixedPercentage)
*
* The computing of percentage using fixedPercentage mechanism is as following:
* Allocation percentage = fixedPercentage
*
* If the rewarding didn't started yet, no fund will receive rewards.
*
* See {sendReward} method for more details.
*/
function _addFund(address _fundAddress, uint256 _value, bool _isFixedPercentage, bool _isLPToken) private {
require(fundInfos[_fundAddress].lastRewardTime == 0, "TokenFactory#_addFund : Fund address already exists, use #setFundAllocation to change allocation");
uint256 lastRewardTime = block.timestamp > startRewardsTime ? block.timestamp : startRewardsTime;
fundAddresses.push(_fundAddress);
fundInfos[_fundAddress] = FundInfo({
lastRewardTime: lastRewardTime,
isLPToken: _isLPToken,
allocationPoint: 0,
fixedPercentage: 0,
accMeedPerShare: 0
});
if (_isFixedPercentage) {
totalFixedPercentage = totalFixedPercentage.add(_value);
fundInfos[_fundAddress].fixedPercentage = _value;
require(totalFixedPercentage <= 100, "TokenFactory#_addFund: total percentage can't be greater than 100%");
} else {
totalAllocationPoints = totalAllocationPoints.add(_value);
fundInfos[_fundAddress].allocationPoint = _value;
}
emit FundAdded(_fundAddress, _value, _isFixedPercentage, _isLPToken);
}
function _getMultiplier(uint256 _fromTimestamp, uint256 _toTimestamp) internal view returns (uint256) {
return _toTimestamp.sub(_fromTimestamp).mul(meedPerMinute).div(1 minutes);
}
function _pendingRewardBalanceOf(FundInfo memory _fund) internal view returns (uint256) {
uint256 periodTotalMeedRewards = _getMultiplier(_fund.lastRewardTime, block.timestamp);
if (_fund.fixedPercentage > 0) {
return periodTotalMeedRewards
.mul(_fund.fixedPercentage)
.div(100);
} else if (_fund.allocationPoint > 0) {
return periodTotalMeedRewards
.mul(_fund.allocationPoint)
.mul(100 - totalFixedPercentage)
.div(totalAllocationPoints)
.div(100);
}
return 0;
}
function _getAccMeedPerShare(address _lpAddress, uint256 pendingRewardAmount) internal view returns (uint256) {
FundInfo memory fund = fundInfos[_lpAddress];
if (block.timestamp > fund.lastRewardTime) {
uint256 lpSupply = IERC20(_lpAddress).balanceOf(address(this));
if (lpSupply > 0) {
return fund.accMeedPerShare.add(pendingRewardAmount.mul(MEED_REWARDING_PRECISION).div(lpSupply));
}
}
return fund.accMeedPerShare;
}
function _safeMeedTransfer(address _to, uint256 _amount) internal {
uint256 meedBal = meed.balanceOf(address(this));
if (_amount > meedBal) {
meed.transfer(_to, meedBal);
} else {
meed.transfer(_to, _amount);
}
}
function _mint(address _to, uint256 _amount) internal {
uint256 totalSupply = meed.totalSupply();
if (totalSupply.add(_amount) > MAX_MEED_SUPPLY) {
if (MAX_MEED_SUPPLY > totalSupply) {
uint256 remainingAmount = MAX_MEED_SUPPLY.sub(totalSupply);
meed.mint(_to, remainingAmount);
emit MaxSupplyReached(block.timestamp);
}
} else {
meed.mint(_to, _amount);
}
}
} | * @dev Claim reward for current wallet from designated Liquidity Pool/ | function harvest(IERC20 _lpAddress) public {
withdraw(_lpAddress, 0);
}
| 14,983,733 | [
1,
9762,
19890,
364,
783,
9230,
628,
25264,
511,
18988,
24237,
8828,
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,
17895,
26923,
12,
45,
654,
39,
3462,
389,
9953,
1887,
13,
1071,
288,
203,
3639,
598,
9446,
24899,
9953,
1887,
16,
374,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/42/0x2B4562D92845e05b8Db39C82E887b7Ce71b1e4f5/sources/ERC721/LNKDNS.sol | 披露你的秘密竞拍出价。 对于所有正确披露的无效出价以及除最高出价以外的所有出价,你都将获得退款。 出价未能正确披露 不返还订金 | function reveal(
address _bidder,
uint[] memory _values,
bool[] memory _fakes,
bytes32[] memory _secrets
) public onlyAfter(biddingEnd) onlyBefore(revealEnd)
onlyWhitelisted nonReentrant returns(bool){
uint length = bids[_bidder].length;
require(_values.length == length);
require(_fakes.length == length);
require(_secrets.length == length);
uint refund;
for (uint i = 0; i < length; i++) {
Bid storage bid = bids[_bidder][i];
(uint value, bool fake, bytes32 secret) =(_values[i], _fakes[i], _secrets[i]);
if (bid.blindedBid != keccak256(abi.encodePacked(value, fake, secret))) {
continue;
}
refund=refund.add(bid.deposit);
if (!fake && bid.deposit >= value) {
if (placeBid(_bidder, value)){
refund=refund.sub(value);
}
}
}
_token.safeTransfer(_bidder, refund);
return true;
}
| 16,278,326 | [
1,
167,
237,
109,
170,
255,
115,
165,
126,
259,
168,
253,
231,
168,
105,
251,
166,
112,
233,
168,
109,
257,
167,
238,
240,
166,
234,
123,
165,
124,
120,
164,
227,
229,
225,
166,
112,
122,
165,
123,
241,
167,
236,
227,
167,
255,
236,
167,
260,
101,
168,
99,
111,
167,
237,
109,
170,
255,
115,
168,
253,
231,
167,
250,
259,
167,
248,
235,
166,
234,
123,
165,
124,
120,
165,
124,
103,
166,
242,
237,
170,
252,
102,
167,
255,
227,
170,
109,
251,
166,
234,
123,
165,
124,
120,
165,
124,
103,
166,
102,
249,
168,
253,
231,
167,
236,
227,
167,
255,
236,
166,
234,
123,
165,
124,
120,
176,
125,
239,
165,
126,
259,
170,
230,
126,
166,
113,
233,
169,
241,
120,
166,
127,
250,
170,
227,
227,
167,
110,
127,
164,
227,
229,
225,
166,
234,
123,
165,
124,
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,
283,
24293,
12,
203,
3639,
1758,
389,
19773,
765,
16,
203,
3639,
2254,
8526,
3778,
389,
2372,
16,
203,
3639,
1426,
8526,
3778,
389,
507,
79,
281,
16,
203,
3639,
1731,
1578,
8526,
3778,
389,
5875,
87,
203,
565,
262,
1071,
1338,
4436,
12,
70,
1873,
310,
1638,
13,
1338,
4649,
12,
266,
24293,
1638,
13,
7010,
377,
202,
3700,
18927,
329,
1661,
426,
8230,
970,
1135,
12,
6430,
15329,
203,
3639,
2254,
769,
273,
30534,
63,
67,
19773,
765,
8009,
2469,
31,
203,
3639,
2583,
24899,
2372,
18,
2469,
422,
769,
1769,
203,
3639,
2583,
24899,
507,
79,
281,
18,
2469,
422,
769,
1769,
203,
3639,
2583,
24899,
5875,
87,
18,
2469,
422,
769,
1769,
203,
3639,
2254,
16255,
31,
203,
3639,
364,
261,
11890,
277,
273,
374,
31,
277,
411,
769,
31,
277,
27245,
288,
203,
5411,
605,
350,
2502,
9949,
273,
30534,
63,
67,
19773,
765,
6362,
77,
15533,
203,
5411,
261,
11890,
460,
16,
1426,
10517,
16,
1731,
1578,
4001,
13,
273,
24899,
2372,
63,
77,
6487,
389,
507,
79,
281,
63,
77,
6487,
389,
5875,
87,
63,
77,
19226,
203,
5411,
309,
261,
19773,
18,
3083,
267,
785,
17763,
480,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
1132,
16,
10517,
16,
4001,
20349,
288,
203,
7734,
1324,
31,
203,
5411,
289,
203,
5411,
16255,
33,
1734,
1074,
18,
1289,
12,
19773,
18,
323,
1724,
1769,
203,
5411,
309,
16051,
28395,
597,
9949,
18,
323,
1724,
1545,
460,
13,
288,
203,
7734,
309,
261,
2
] |
./partial_match/1/0x149001FEd7EDC44c5A7aE7e4281Ad64aF7A02f01/sources/contracts/core/abstract/PendleForgeBase.sol | Can only be called by the respective XYT contract, before transferring XYTs/ | function updateDueInterests(
address _underlyingAsset,
uint256 _expiry,
address _user
) external override onlyXYT(_underlyingAsset, _expiry) nonReentrant {
checkNotPaused(_underlyingAsset, _expiry);
PendleTokens memory tokens = _getTokens(_underlyingAsset, _expiry);
uint256 principal = tokens.xyt.balanceOf(_user);
_updateDueInterests(principal, _underlyingAsset, _expiry, _user);
}
Conditions:
| 3,893,887 | [
1,
2568,
1338,
506,
2566,
635,
326,
17613,
18774,
56,
6835,
16,
1865,
906,
74,
20245,
18774,
17218,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1089,
30023,
2465,
25563,
12,
203,
3639,
1758,
389,
9341,
6291,
6672,
16,
203,
3639,
2254,
5034,
389,
22409,
16,
203,
3639,
1758,
389,
1355,
203,
565,
262,
3903,
3849,
1338,
8546,
56,
24899,
9341,
6291,
6672,
16,
389,
22409,
13,
1661,
426,
8230,
970,
288,
203,
3639,
866,
1248,
28590,
24899,
9341,
6291,
6672,
16,
389,
22409,
1769,
203,
3639,
453,
409,
298,
5157,
3778,
2430,
273,
389,
588,
5157,
24899,
9341,
6291,
6672,
16,
389,
22409,
1769,
203,
3639,
2254,
5034,
8897,
273,
2430,
18,
1698,
88,
18,
12296,
951,
24899,
1355,
1769,
203,
3639,
389,
2725,
30023,
2465,
25563,
12,
26138,
16,
389,
9341,
6291,
6672,
16,
389,
22409,
16,
389,
1355,
1769,
203,
565,
289,
203,
203,
565,
23261,
30,
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
] |
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Owned.sol
version: 1.1
author: Anton Jurisevic
Dominic Romanowski
date: 2018-2-26
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
An Owned contract, to be inherited by other contracts.
Requires its owner to be explicitly set in the constructor.
Provides an onlyOwner access modifier.
To change owner, the current owner must nominate the next owner,
who then has to accept the nomination. The nomination can be
cancelled before it is accepted by the new owner by having the
previous owner change the nomination (setting it to 0).
-----------------------------------------------------------------
*/
pragma solidity 0.4.24;
/**
* @title A contract with an owner.
* @notice Contract ownership can be transferred by first nominating the new owner,
* who must then accept the ownership, which prevents accidental incorrect ownership transfers.
*/
contract Owned {
address public owner;
address public nominatedOwner;
/**
* @dev Owned Constructor
*/
constructor(address _owner)
public
{
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
/**
* @notice Nominate a new owner of this contract.
* @dev Only the current owner may nominate a new owner.
*/
function nominateNewOwner(address _owner)
external
onlyOwner
{
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
/**
* @notice Accept the nomination to be 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 INFORMATION
-----------------------------------------------------------------
file: SelfDestructible.sol
version: 1.2
author: Anton Jurisevic
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
This contract allows an inheriting contract to be destroyed after
its owner indicates an intention and then waits for a period
without changing their mind. All ether contained in the contract
is forwarded to a nominated beneficiary upon destruction.
-----------------------------------------------------------------
*/
/**
* @title A contract that can be destroyed by its owner after a delay elapses.
*/
contract SelfDestructible is Owned {
uint public initiationTime;
bool public selfDestructInitiated;
address public selfDestructBeneficiary;
uint public constant SELFDESTRUCT_DELAY = 4 weeks;
/**
* @dev Constructor
* @param _owner The account which controls this contract.
*/
constructor(address _owner)
Owned(_owner)
public
{
require(_owner != address(0), "Owner must not be the zero address");
selfDestructBeneficiary = _owner;
emit SelfDestructBeneficiaryUpdated(_owner);
}
/**
* @notice Set the beneficiary address of this contract.
* @dev Only the contract owner may call this. The provided beneficiary must be non-null.
* @param _beneficiary The address to pay any eth contained in this contract to upon self-destruction.
*/
function setSelfDestructBeneficiary(address _beneficiary)
external
onlyOwner
{
require(_beneficiary != address(0), "Beneficiary must not be the zero address");
selfDestructBeneficiary = _beneficiary;
emit SelfDestructBeneficiaryUpdated(_beneficiary);
}
/**
* @notice Begin the self-destruction counter of this contract.
* Once the delay has elapsed, the contract may be self-destructed.
* @dev Only the contract owner may call this.
*/
function initiateSelfDestruct()
external
onlyOwner
{
initiationTime = now;
selfDestructInitiated = true;
emit SelfDestructInitiated(SELFDESTRUCT_DELAY);
}
/**
* @notice Terminate and reset the self-destruction timer.
* @dev Only the contract owner may call this.
*/
function terminateSelfDestruct()
external
onlyOwner
{
initiationTime = 0;
selfDestructInitiated = false;
emit SelfDestructTerminated();
}
/**
* @notice If the self-destruction delay has elapsed, destroy this contract and
* remit any ether it owns to the beneficiary address.
* @dev Only the contract owner may call this.
*/
function selfDestruct()
external
onlyOwner
{
require(selfDestructInitiated, "Self destruct has not yet been initiated");
require(initiationTime + SELFDESTRUCT_DELAY < now, "Self destruct delay has not yet elapsed");
address beneficiary = selfDestructBeneficiary;
emit SelfDestructed(beneficiary);
selfdestruct(beneficiary);
}
event SelfDestructTerminated();
event SelfDestructed(address beneficiary);
event SelfDestructInitiated(uint selfDestructDelay);
event SelfDestructBeneficiaryUpdated(address newBeneficiary);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Pausable.sol
version: 1.0
author: Kevin Brown
date: 2018-05-22
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
This contract allows an inheriting contract to be marked as
paused. It also defines a modifier which can be used by the
inheriting contract to prevent actions while paused.
-----------------------------------------------------------------
*/
/**
* @title A contract that can be paused by its owner
*/
contract Pausable is Owned {
uint public lastPauseTime;
bool public paused;
/**
* @dev Constructor
* @param _owner The account which controls this contract.
*/
constructor(address _owner)
Owned(_owner)
public
{
// Paused will be false, and lastPauseTime will be 0 upon initialisation
}
/**
* @notice Change the paused state of the contract
* @dev Only the contract owner may call this.
*/
function setPaused(bool _paused)
external
onlyOwner
{
// Ensure we're actually changing the state before we do anything
if (_paused == paused) {
return;
}
// Set our paused state.
paused = _paused;
// If applicable, set the last pause time.
if (paused) {
lastPauseTime = now;
}
// Let everyone know that our pause state has changed.
emit PauseChanged(paused);
}
event PauseChanged(bool isPaused);
modifier notPaused {
require(!paused, "This action cannot be performed while the contract is paused");
_;
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: SafeDecimalMath.sol
version: 1.0
author: Anton Jurisevic
date: 2018-2-5
checked: Mike Spain
approved: Samuel Brooks
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A fixed point decimal library that provides basic mathematical
operations, and checks for unsafe arguments, for example that
would lead to overflows.
Exceptions are thrown whenever those unsafe operations
occur.
-----------------------------------------------------------------
*/
/**
* @title Safely manipulate unsigned fixed-point decimals at a given precision level.
* @dev Functions accepting uints in this contract and derived contracts
* are taken to be such fixed point decimals (including fiat, ether, and nomin quantities).
*/
contract SafeDecimalMath {
/* Number of decimal places in the representation. */
uint8 public constant decimals = 18;
/* The number representing 1.0. */
uint public constant UNIT = 10 ** uint(decimals);
/**
* @return True iff adding x and y will not overflow.
*/
function addIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
return x + y >= y;
}
/**
* @return The result of adding x and y, throwing an exception in case of overflow.
*/
function safeAdd(uint x, uint y)
pure
internal
returns (uint)
{
require(x + y >= y, "Safe add failed");
return x + y;
}
/**
* @return True iff subtracting y from x will not overflow in the negative direction.
*/
function subIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
return y <= x;
}
/**
* @return The result of subtracting y from x, throwing an exception in case of overflow.
*/
function safeSub(uint x, uint y)
pure
internal
returns (uint)
{
require(y <= x, "Safe sub failed");
return x - y;
}
/**
* @return True iff multiplying x and y would not overflow.
*/
function mulIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
if (x == 0) {
return true;
}
return (x * y) / x == y;
}
/**
* @return The result of multiplying x and y, throwing an exception in case of overflow.
*/
function safeMul(uint x, uint y)
pure
internal
returns (uint)
{
if (x == 0) {
return 0;
}
uint p = x * y;
require(p / x == y, "Safe mul failed");
return p;
}
/**
* @return The result of multiplying x and y, interpreting the operands as fixed-point
* decimals. Throws an exception in case of overflow.
*
* @dev A unit factor is divided out after the product of x and y is evaluated,
* so that product must be less than 2**256.
* Incidentally, the internal division always rounds down: one could have rounded to the nearest integer,
* but then one would be spending a significant fraction of a cent (of order a microether
* at present gas prices) in order to save less than one part in 0.5 * 10^18 per operation, if the operands
* contain small enough fractional components. It would also marginally diminish the
* domain this function is defined upon.
*/
function safeMul_dec(uint x, uint y)
pure
internal
returns (uint)
{
/* Divide by UNIT to remove the extra factor introduced by the product. */
return safeMul(x, y) / UNIT;
}
/**
* @return True iff the denominator of x/y is nonzero.
*/
function divIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
return y != 0;
}
/**
* @return The result of dividing x by y, throwing an exception if the divisor is zero.
*/
function safeDiv(uint x, uint y)
pure
internal
returns (uint)
{
/* Although a 0 denominator already throws an exception,
* it is equivalent to a THROW operation, which consumes all gas.
* A require statement emits REVERT instead, which remits remaining gas. */
require(y != 0, "Denominator cannot be zero");
return x / y;
}
/**
* @return The result of dividing x by y, interpreting the operands as fixed point decimal numbers.
* @dev Throws an exception in case of overflow or zero divisor; x must be less than 2^256 / UNIT.
* Internal rounding is downward: a similar caveat holds as with safeDecMul().
*/
function safeDiv_dec(uint x, uint y)
pure
internal
returns (uint)
{
/* Reintroduce the UNIT factor that will be divided out by y. */
return safeDiv(safeMul(x, UNIT), y);
}
/**
* @dev Convert an unsigned integer to a unsigned fixed-point decimal.
* Throw an exception if the result would be out of range.
*/
function intToDec(uint i)
pure
internal
returns (uint)
{
return safeMul(i, UNIT);
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: State.sol
version: 1.1
author: Dominic Romanowski
Anton Jurisevic
date: 2018-05-15
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
This contract is used side by side with external state token
contracts, such as Havven and Nomin.
It provides an easy way to upgrade contract logic while
maintaining all user balances and allowances. This is designed
to make the changeover as easy as possible, since mappings
are not so cheap or straightforward to migrate.
The first deployed contract would create this state contract,
using it as its store of balances.
When a new contract is deployed, it links to the existing
state contract, whose owner would then change its associated
contract to the new one.
-----------------------------------------------------------------
*/
contract State is Owned {
// the address of the contract that can modify variables
// this can only be changed by the owner of this contract
address public associatedContract;
constructor(address _owner, address _associatedContract)
Owned(_owner)
public
{
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
/* ========== SETTERS ========== */
// Change the associated contract to a new address
function setAssociatedContract(address _associatedContract)
external
onlyOwner
{
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
/* ========== MODIFIERS ========== */
modifier onlyAssociatedContract
{
require(msg.sender == associatedContract, "Only the associated contract can perform this action");
_;
}
/* ========== EVENTS ========== */
event AssociatedContractUpdated(address associatedContract);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: TokenState.sol
version: 1.1
author: Dominic Romanowski
Anton Jurisevic
date: 2018-05-15
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A contract that holds the state of an ERC20 compliant token.
This contract is used side by side with external state token
contracts, such as Havven and Nomin.
It provides an easy way to upgrade contract logic while
maintaining all user balances and allowances. This is designed
to make the changeover as easy as possible, since mappings
are not so cheap or straightforward to migrate.
The first deployed contract would create this state contract,
using it as its store of balances.
When a new contract is deployed, it links to the existing
state contract, whose owner would then change its associated
contract to the new one.
-----------------------------------------------------------------
*/
/**
* @title ERC20 Token State
* @notice Stores balance information of an ERC20 token contract.
*/
contract TokenState is State {
/* ERC20 fields. */
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
/**
* @dev Constructor
* @param _owner The address which controls this contract.
* @param _associatedContract The ERC20 contract whose state this composes.
*/
constructor(address _owner, address _associatedContract)
State(_owner, _associatedContract)
public
{}
/* ========== SETTERS ========== */
/**
* @notice Set ERC20 allowance.
* @dev Only the associated contract may call this.
* @param tokenOwner The authorising party.
* @param spender The authorised party.
* @param value The total value the authorised party may spend on the
* authorising party's behalf.
*/
function setAllowance(address tokenOwner, address spender, uint value)
external
onlyAssociatedContract
{
allowance[tokenOwner][spender] = value;
}
/**
* @notice Set the balance in a given account
* @dev Only the associated contract may call this.
* @param account The account whose value to set.
* @param value The new balance of the given account.
*/
function setBalanceOf(address account, uint value)
external
onlyAssociatedContract
{
balanceOf[account] = value;
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Proxy.sol
version: 1.3
author: Anton Jurisevic
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A proxy contract that, if it does not recognise the function
being called on it, passes all value and call data to an
underlying target contract.
This proxy has the capacity to toggle between DELEGATECALL
and CALL style proxy functionality.
The former executes in the proxy's context, and so will preserve
msg.sender and store data at the proxy address. The latter will not.
Therefore, any contract the proxy wraps in the CALL style must
implement the Proxyable interface, in order that it can pass msg.sender
into the underlying contract as the state parameter, messageSender.
-----------------------------------------------------------------
*/
contract Proxy is Owned {
Proxyable public target;
bool public useDELEGATECALL;
constructor(address _owner)
Owned(_owner)
public
{}
function setTarget(Proxyable _target)
external
onlyOwner
{
target = _target;
emit TargetUpdated(_target);
}
function setUseDELEGATECALL(bool value)
external
onlyOwner
{
useDELEGATECALL = value;
}
function _emit(bytes callData, uint numTopics,
bytes32 topic1, bytes32 topic2,
bytes32 topic3, bytes32 topic4)
external
onlyTarget
{
uint size = callData.length;
bytes memory _callData = callData;
assembly {
/* The first 32 bytes of callData contain its length (as specified by the abi).
* Length is assumed to be a uint256 and therefore maximum of 32 bytes
* in length. It is also leftpadded to be a multiple of 32 bytes.
* This means moving call_data across 32 bytes guarantees we correctly access
* the data itself. */
switch numTopics
case 0 {
log0(add(_callData, 32), size)
}
case 1 {
log1(add(_callData, 32), size, topic1)
}
case 2 {
log2(add(_callData, 32), size, topic1, topic2)
}
case 3 {
log3(add(_callData, 32), size, topic1, topic2, topic3)
}
case 4 {
log4(add(_callData, 32), size, topic1, topic2, topic3, topic4)
}
}
}
function()
external
payable
{
if (useDELEGATECALL) {
assembly {
/* Copy call data into free memory region. */
let free_ptr := mload(0x40)
calldatacopy(free_ptr, 0, calldatasize)
/* Forward all gas and call data to the target contract. */
let result := delegatecall(gas, sload(target_slot), free_ptr, calldatasize, 0, 0)
returndatacopy(free_ptr, 0, returndatasize)
/* Revert if the call failed, otherwise return the result. */
if iszero(result) { revert(free_ptr, returndatasize) }
return(free_ptr, returndatasize)
}
} else {
/* Here we are as above, but must send the messageSender explicitly
* since we are using CALL rather than DELEGATECALL. */
target.setMessageSender(msg.sender);
assembly {
let free_ptr := mload(0x40)
calldatacopy(free_ptr, 0, calldatasize)
/* We must explicitly forward ether to the underlying contract as well. */
let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0)
returndatacopy(free_ptr, 0, returndatasize)
if iszero(result) { revert(free_ptr, returndatasize) }
return(free_ptr, returndatasize)
}
}
}
modifier onlyTarget {
require(Proxyable(msg.sender) == target, "This action can only be performed by the proxy target");
_;
}
event TargetUpdated(Proxyable newTarget);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Proxyable.sol
version: 1.1
author: Anton Jurisevic
date: 2018-05-15
checked: Mike Spain
approved: Samuel Brooks
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A proxyable contract that works hand in hand with the Proxy contract
to allow for anyone to interact with the underlying contract both
directly and through the proxy.
-----------------------------------------------------------------
*/
// This contract should be treated like an abstract contract
contract Proxyable is Owned {
/* The proxy this contract exists behind. */
Proxy public proxy;
/* The caller of the proxy, passed through to this contract.
* Note that every function using this member must apply the onlyProxy or
* optionalProxy modifiers, otherwise their invocations can use stale values. */
address messageSender;
constructor(address _proxy, address _owner)
Owned(_owner)
public
{
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setProxy(address _proxy)
external
onlyOwner
{
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setMessageSender(address sender)
external
onlyProxy
{
messageSender = sender;
}
modifier onlyProxy {
require(Proxy(msg.sender) == proxy, "Only the proxy can call this function");
_;
}
modifier optionalProxy
{
if (Proxy(msg.sender) != proxy) {
messageSender = msg.sender;
}
_;
}
modifier optionalProxy_onlyOwner
{
if (Proxy(msg.sender) != proxy) {
messageSender = msg.sender;
}
require(messageSender == owner, "This action can only be performed by the owner");
_;
}
event ProxyUpdated(address proxyAddress);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: ExternStateToken.sol
version: 1.0
author: Kevin Brown
date: 2018-08-06
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
This contract offers a modifer that can prevent reentrancy on
particular actions. It will not work if you put it on multiple
functions that can be called from each other. Specifically guard
external entry points to the contract with the modifier only.
-----------------------------------------------------------------
*/
contract ReentrancyPreventer {
/* ========== MODIFIERS ========== */
bool isInFunctionBody = false;
modifier preventReentrancy {
require(!isInFunctionBody, "Reverted to prevent reentrancy");
isInFunctionBody = true;
_;
isInFunctionBody = false;
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: ExternStateToken.sol
version: 1.3
author: Anton Jurisevic
Dominic Romanowski
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A partial ERC20 token contract, designed to operate with a proxy.
To produce a complete ERC20 token, transfer and transferFrom
tokens must be implemented, using the provided _byProxy internal
functions.
This contract utilises an external state for upgradeability.
-----------------------------------------------------------------
*/
/**
* @title ERC20 Token contract, with detached state and designed to operate behind a proxy.
*/
contract ExternStateToken is SafeDecimalMath, SelfDestructible, Proxyable, ReentrancyPreventer {
/* ========== STATE VARIABLES ========== */
/* Stores balances and allowances. */
TokenState public tokenState;
/* Other ERC20 fields.
* Note that the decimals field is defined in SafeDecimalMath.*/
string public name;
string public symbol;
uint public totalSupply;
/**
* @dev Constructor.
* @param _proxy The proxy associated with this contract.
* @param _name Token's ERC20 name.
* @param _symbol Token's ERC20 symbol.
* @param _totalSupply The total supply of the token.
* @param _tokenState The TokenState contract address.
* @param _owner The owner of this contract.
*/
constructor(address _proxy, TokenState _tokenState,
string _name, string _symbol, uint _totalSupply,
address _owner)
SelfDestructible(_owner)
Proxyable(_proxy, _owner)
public
{
name = _name;
symbol = _symbol;
totalSupply = _totalSupply;
tokenState = _tokenState;
}
/* ========== VIEWS ========== */
/**
* @notice Returns the ERC20 allowance of one party to spend on behalf of another.
* @param owner The party authorising spending of their funds.
* @param spender The party spending tokenOwner's funds.
*/
function allowance(address owner, address spender)
public
view
returns (uint)
{
return tokenState.allowance(owner, spender);
}
/**
* @notice Returns the ERC20 token balance of a given account.
*/
function balanceOf(address account)
public
view
returns (uint)
{
return tokenState.balanceOf(account);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Set the address of the TokenState contract.
* @dev This can be used to "pause" transfer functionality, by pointing the tokenState at 0x000..
* as balances would be unreachable.
*/
function setTokenState(TokenState _tokenState)
external
optionalProxy_onlyOwner
{
tokenState = _tokenState;
emitTokenStateUpdated(_tokenState);
}
function _internalTransfer(address from, address to, uint value)
internal
preventReentrancy
returns (bool)
{
/* Disallow transfers to irretrievable-addresses. */
require(to != address(0), "Cannot transfer to the 0 address");
require(to != address(this), "Cannot transfer to the underlying contract");
require(to != address(proxy), "Cannot transfer to the proxy contract");
/* Insufficient balance will be handled by the safe subtraction. */
tokenState.setBalanceOf(from, safeSub(tokenState.balanceOf(from), value));
tokenState.setBalanceOf(to, safeAdd(tokenState.balanceOf(to), value));
/*
If we're transferring to a contract and it implements the havvenTokenFallback function, call it.
This isn't ERC223 compliant because:
1. We don't revert if the contract doesn't implement havvenTokenFallback.
This is because many DEXes and other contracts that expect to work with the standard
approve / transferFrom workflow don't implement tokenFallback but can still process our tokens as
usual, so it feels very harsh and likely to cause trouble if we add this restriction after having
previously gone live with a vanilla ERC20.
2. We don't pass the bytes parameter.
This is because of this solidity bug: https://github.com/ethereum/solidity/issues/2884
3. We also don't let the user use a custom tokenFallback. We figure as we're already not standards
compliant, there won't be a use case where users can't just implement our specific function.
As such we've called the function havvenTokenFallback to be clear that we are not following the standard.
*/
// Is the to address a contract? We can check the code size on that address and know.
uint length;
// solium-disable-next-line security/no-inline-assembly
assembly {
// Retrieve the size of the code on the recipient address
length := extcodesize(to)
}
// If there's code there, it's a contract
if (length > 0) {
// Now we need to optionally call havvenTokenFallback(address from, uint value).
// We can't call it the normal way because that reverts when the recipient doesn't implement the function.
// We'll use .call(), which means we need the function selector. We've pre-computed
// abi.encodeWithSignature("havvenTokenFallback(address,uint256)"), to save some gas.
// solium-disable-next-line security/no-low-level-calls
to.call(0xcbff5d96, messageSender, value);
// And yes, we specifically don't care if this call fails, so we're not checking the return value.
}
// Emit a standard ERC20 transfer event
emitTransfer(from, to, value);
return true;
}
/**
* @dev Perform an ERC20 token transfer. Designed to be called by transfer functions possessing
* the onlyProxy or optionalProxy modifiers.
*/
function _transfer_byProxy(address from, address to, uint value)
internal
returns (bool)
{
return _internalTransfer(from, to, value);
}
/**
* @dev Perform an ERC20 token transferFrom. Designed to be called by transferFrom functions
* possessing the optionalProxy or optionalProxy modifiers.
*/
function _transferFrom_byProxy(address sender, address from, address to, uint value)
internal
returns (bool)
{
/* Insufficient allowance will be handled by the safe subtraction. */
tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), value));
return _internalTransfer(from, to, value);
}
/**
* @notice Approves spender to transfer on the message sender's behalf.
*/
function approve(address spender, uint value)
public
optionalProxy
returns (bool)
{
address sender = messageSender;
tokenState.setAllowance(sender, spender, value);
emitApproval(sender, spender, value);
return true;
}
/* ========== EVENTS ========== */
event Transfer(address indexed from, address indexed to, uint value);
bytes32 constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)");
function emitTransfer(address from, address to, uint value) internal {
proxy._emit(abi.encode(value), 3, TRANSFER_SIG, bytes32(from), bytes32(to), 0);
}
event Approval(address indexed owner, address indexed spender, uint value);
bytes32 constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)");
function emitApproval(address owner, address spender, uint value) internal {
proxy._emit(abi.encode(value), 3, APPROVAL_SIG, bytes32(owner), bytes32(spender), 0);
}
event TokenStateUpdated(address newTokenState);
bytes32 constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)");
function emitTokenStateUpdated(address newTokenState) internal {
proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0);
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: FeeToken.sol
version: 1.3
author: Anton Jurisevic
Dominic Romanowski
Kevin Brown
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A token which also has a configurable fee rate
charged on its transfers. This is designed to be overridden in
order to produce an ERC20-compliant token.
These fees accrue into a pool, from which a nominated authority
may withdraw.
This contract utilises an external state for upgradeability.
-----------------------------------------------------------------
*/
/**
* @title ERC20 Token contract, with detached state.
* Additionally charges fees on each transfer.
*/
contract FeeToken is ExternStateToken {
/* ========== STATE VARIABLES ========== */
/* ERC20 members are declared in ExternStateToken. */
/* A percentage fee charged on each transfer. */
uint public transferFeeRate;
/* Fee may not exceed 10%. */
uint constant MAX_TRANSFER_FEE_RATE = UNIT / 10;
/* The address with the authority to distribute fees. */
address public feeAuthority;
/* The address that fees will be pooled in. */
address public constant FEE_ADDRESS = 0xfeefeefeefeefeefeefeefeefeefeefeefeefeef;
/* ========== CONSTRUCTOR ========== */
/**
* @dev Constructor.
* @param _proxy The proxy associated with this contract.
* @param _name Token's ERC20 name.
* @param _symbol Token's ERC20 symbol.
* @param _totalSupply The total supply of the token.
* @param _transferFeeRate The fee rate to charge on transfers.
* @param _feeAuthority The address which has the authority to withdraw fees from the accumulated pool.
* @param _owner The owner of this contract.
*/
constructor(address _proxy, TokenState _tokenState, string _name, string _symbol, uint _totalSupply,
uint _transferFeeRate, address _feeAuthority, address _owner)
ExternStateToken(_proxy, _tokenState,
_name, _symbol, _totalSupply,
_owner)
public
{
feeAuthority = _feeAuthority;
/* Constructed transfer fee rate should respect the maximum fee rate. */
require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE, "Constructed transfer fee rate should respect the maximum fee rate");
transferFeeRate = _transferFeeRate;
}
/* ========== SETTERS ========== */
/**
* @notice Set the transfer fee, anywhere within the range 0-10%.
* @dev The fee rate is in decimal format, with UNIT being the value of 100%.
*/
function setTransferFeeRate(uint _transferFeeRate)
external
optionalProxy_onlyOwner
{
require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE, "Transfer fee rate must be below MAX_TRANSFER_FEE_RATE");
transferFeeRate = _transferFeeRate;
emitTransferFeeRateUpdated(_transferFeeRate);
}
/**
* @notice Set the address of the user/contract responsible for collecting or
* distributing fees.
*/
function setFeeAuthority(address _feeAuthority)
public
optionalProxy_onlyOwner
{
feeAuthority = _feeAuthority;
emitFeeAuthorityUpdated(_feeAuthority);
}
/* ========== VIEWS ========== */
/**
* @notice Calculate the Fee charged on top of a value being sent
* @return Return the fee charged
*/
function transferFeeIncurred(uint value)
public
view
returns (uint)
{
return safeMul_dec(value, transferFeeRate);
/* Transfers less than the reciprocal of transferFeeRate should be completely eaten up by fees.
* This is on the basis that transfers less than this value will result in a nil fee.
* Probably too insignificant to worry about, but the following code will achieve it.
* if (fee == 0 && transferFeeRate != 0) {
* return _value;
* }
* return fee;
*/
}
/**
* @notice The value that you would need to send so that the recipient receives
* a specified value.
*/
function transferPlusFee(uint value)
external
view
returns (uint)
{
return safeAdd(value, transferFeeIncurred(value));
}
/**
* @notice The amount the recipient will receive if you send a certain number of tokens.
*/
function amountReceived(uint value)
public
view
returns (uint)
{
return safeDiv_dec(value, safeAdd(UNIT, transferFeeRate));
}
/**
* @notice Collected fees sit here until they are distributed.
* @dev The balance of the nomin contract itself is the fee pool.
*/
function feePool()
external
view
returns (uint)
{
return tokenState.balanceOf(FEE_ADDRESS);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Base of transfer functions
*/
function _internalTransfer(address from, address to, uint amount, uint fee)
internal
returns (bool)
{
/* Disallow transfers to irretrievable-addresses. */
require(to != address(0), "Cannot transfer to the 0 address");
require(to != address(this), "Cannot transfer to the underlying contract");
require(to != address(proxy), "Cannot transfer to the proxy contract");
/* Insufficient balance will be handled by the safe subtraction. */
tokenState.setBalanceOf(from, safeSub(tokenState.balanceOf(from), safeAdd(amount, fee)));
tokenState.setBalanceOf(to, safeAdd(tokenState.balanceOf(to), amount));
tokenState.setBalanceOf(FEE_ADDRESS, safeAdd(tokenState.balanceOf(FEE_ADDRESS), fee));
/* Emit events for both the transfer itself and the fee. */
emitTransfer(from, to, amount);
emitTransfer(from, FEE_ADDRESS, fee);
return true;
}
/**
* @notice ERC20 friendly transfer function.
*/
function _transfer_byProxy(address sender, address to, uint value)
internal
returns (bool)
{
uint received = amountReceived(value);
uint fee = safeSub(value, received);
return _internalTransfer(sender, to, received, fee);
}
/**
* @notice ERC20 friendly transferFrom function.
*/
function _transferFrom_byProxy(address sender, address from, address to, uint value)
internal
returns (bool)
{
/* The fee is deducted from the amount sent. */
uint received = amountReceived(value);
uint fee = safeSub(value, received);
/* Reduce the allowance by the amount we're transferring.
* The safeSub call will handle an insufficient allowance. */
tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), value));
return _internalTransfer(from, to, received, fee);
}
/**
* @notice Ability to transfer where the sender pays the fees (not ERC20)
*/
function _transferSenderPaysFee_byProxy(address sender, address to, uint value)
internal
returns (bool)
{
/* The fee is added to the amount sent. */
uint fee = transferFeeIncurred(value);
return _internalTransfer(sender, to, value, fee);
}
/**
* @notice Ability to transferFrom where they sender pays the fees (not ERC20).
*/
function _transferFromSenderPaysFee_byProxy(address sender, address from, address to, uint value)
internal
returns (bool)
{
/* The fee is added to the amount sent. */
uint fee = transferFeeIncurred(value);
uint total = safeAdd(value, fee);
/* Reduce the allowance by the amount we're transferring. */
tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), total));
return _internalTransfer(from, to, value, fee);
}
/**
* @notice Withdraw tokens from the fee pool into a given account.
* @dev Only the fee authority may call this.
*/
function withdrawFees(address account, uint value)
external
onlyFeeAuthority
returns (bool)
{
require(account != address(0), "Must supply an account address to withdraw fees");
/* 0-value withdrawals do nothing. */
if (value == 0) {
return false;
}
/* Safe subtraction ensures an exception is thrown if the balance is insufficient. */
tokenState.setBalanceOf(FEE_ADDRESS, safeSub(tokenState.balanceOf(FEE_ADDRESS), value));
tokenState.setBalanceOf(account, safeAdd(tokenState.balanceOf(account), value));
emitFeesWithdrawn(account, value);
emitTransfer(FEE_ADDRESS, account, value);
return true;
}
/**
* @notice Donate tokens from the sender's balance into the fee pool.
*/
function donateToFeePool(uint n)
external
optionalProxy
returns (bool)
{
address sender = messageSender;
/* Empty donations are disallowed. */
uint balance = tokenState.balanceOf(sender);
require(balance != 0, "Must have a balance in order to donate to the fee pool");
/* safeSub ensures the donor has sufficient balance. */
tokenState.setBalanceOf(sender, safeSub(balance, n));
tokenState.setBalanceOf(FEE_ADDRESS, safeAdd(tokenState.balanceOf(FEE_ADDRESS), n));
emitFeesDonated(sender, n);
emitTransfer(sender, FEE_ADDRESS, n);
return true;
}
/* ========== MODIFIERS ========== */
modifier onlyFeeAuthority
{
require(msg.sender == feeAuthority, "Only the fee authority can do this action");
_;
}
/* ========== EVENTS ========== */
event TransferFeeRateUpdated(uint newFeeRate);
bytes32 constant TRANSFERFEERATEUPDATED_SIG = keccak256("TransferFeeRateUpdated(uint256)");
function emitTransferFeeRateUpdated(uint newFeeRate) internal {
proxy._emit(abi.encode(newFeeRate), 1, TRANSFERFEERATEUPDATED_SIG, 0, 0, 0);
}
event FeeAuthorityUpdated(address newFeeAuthority);
bytes32 constant FEEAUTHORITYUPDATED_SIG = keccak256("FeeAuthorityUpdated(address)");
function emitFeeAuthorityUpdated(address newFeeAuthority) internal {
proxy._emit(abi.encode(newFeeAuthority), 1, FEEAUTHORITYUPDATED_SIG, 0, 0, 0);
}
event FeesWithdrawn(address indexed account, uint value);
bytes32 constant FEESWITHDRAWN_SIG = keccak256("FeesWithdrawn(address,uint256)");
function emitFeesWithdrawn(address account, uint value) internal {
proxy._emit(abi.encode(value), 2, FEESWITHDRAWN_SIG, bytes32(account), 0, 0);
}
event FeesDonated(address indexed donor, uint value);
bytes32 constant FEESDONATED_SIG = keccak256("FeesDonated(address,uint256)");
function emitFeesDonated(address donor, uint value) internal {
proxy._emit(abi.encode(value), 2, FEESDONATED_SIG, bytes32(donor), 0, 0);
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Nomin.sol
version: 1.2
author: Anton Jurisevic
Mike Spain
Dominic Romanowski
Kevin Brown
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
Havven-backed nomin stablecoin contract.
This contract issues nomins, which are tokens worth 1 USD each.
Nomins are issuable by Havven holders who have to lock up some
value of their havvens to issue H * Cmax nomins. Where Cmax is
some value less than 1.
A configurable fee is charged on nomin transfers and deposited
into a common pot, which havven holders may withdraw from once
per fee period.
-----------------------------------------------------------------
*/
contract Nomin is FeeToken {
/* ========== STATE VARIABLES ========== */
Havven public havven;
// Accounts which have lost the privilege to transact in nomins.
mapping(address => bool) public frozen;
// Nomin transfers incur a 15 bp fee by default.
uint constant TRANSFER_FEE_RATE = 15 * UNIT / 10000;
string constant TOKEN_NAME = "Nomin USD";
string constant TOKEN_SYMBOL = "nUSD";
/* ========== CONSTRUCTOR ========== */
constructor(address _proxy, TokenState _tokenState, Havven _havven,
uint _totalSupply,
address _owner)
FeeToken(_proxy, _tokenState,
TOKEN_NAME, TOKEN_SYMBOL, _totalSupply,
TRANSFER_FEE_RATE,
_havven, // The havven contract is the fee authority.
_owner)
public
{
require(_proxy != 0, "_proxy cannot be 0");
require(address(_havven) != 0, "_havven cannot be 0");
require(_owner != 0, "_owner cannot be 0");
// It should not be possible to transfer to the fee pool directly (or confiscate its balance).
frozen[FEE_ADDRESS] = true;
havven = _havven;
}
/* ========== SETTERS ========== */
function setHavven(Havven _havven)
external
optionalProxy_onlyOwner
{
// havven should be set as the feeAuthority after calling this depending on
// havven's internal logic
havven = _havven;
setFeeAuthority(_havven);
emitHavvenUpdated(_havven);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/* Override ERC20 transfer function in order to check
* whether the recipient account is frozen. Note that there is
* no need to check whether the sender has a frozen account,
* since their funds have already been confiscated,
* and no new funds can be transferred to it.*/
function transfer(address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to], "Cannot transfer to frozen address");
return _transfer_byProxy(messageSender, to, value);
}
/* Override ERC20 transferFrom function in order to check
* whether the recipient account is frozen. */
function transferFrom(address from, address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to], "Cannot transfer to frozen address");
return _transferFrom_byProxy(messageSender, from, to, value);
}
function transferSenderPaysFee(address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to], "Cannot transfer to frozen address");
return _transferSenderPaysFee_byProxy(messageSender, to, value);
}
function transferFromSenderPaysFee(address from, address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to], "Cannot transfer to frozen address");
return _transferFromSenderPaysFee_byProxy(messageSender, from, to, value);
}
/* The owner may allow a previously-frozen contract to once
* again accept and transfer nomins. */
function unfreezeAccount(address target)
external
optionalProxy_onlyOwner
{
require(frozen[target] && target != FEE_ADDRESS, "Account must be frozen, and cannot be the fee address");
frozen[target] = false;
emitAccountUnfrozen(target);
}
/* Allow havven to issue a certain number of
* nomins from an account. */
function issue(address account, uint amount)
external
onlyHavven
{
tokenState.setBalanceOf(account, safeAdd(tokenState.balanceOf(account), amount));
totalSupply = safeAdd(totalSupply, amount);
emitTransfer(address(0), account, amount);
emitIssued(account, amount);
}
/* Allow havven to burn a certain number of
* nomins from an account. */
function burn(address account, uint amount)
external
onlyHavven
{
tokenState.setBalanceOf(account, safeSub(tokenState.balanceOf(account), amount));
totalSupply = safeSub(totalSupply, amount);
emitTransfer(account, address(0), amount);
emitBurned(account, amount);
}
/* ========== MODIFIERS ========== */
modifier onlyHavven() {
require(Havven(msg.sender) == havven, "Only the Havven contract can perform this action");
_;
}
/* ========== EVENTS ========== */
event HavvenUpdated(address newHavven);
bytes32 constant HAVVENUPDATED_SIG = keccak256("HavvenUpdated(address)");
function emitHavvenUpdated(address newHavven) internal {
proxy._emit(abi.encode(newHavven), 1, HAVVENUPDATED_SIG, 0, 0, 0);
}
event AccountFrozen(address indexed target, uint balance);
bytes32 constant ACCOUNTFROZEN_SIG = keccak256("AccountFrozen(address,uint256)");
function emitAccountFrozen(address target, uint balance) internal {
proxy._emit(abi.encode(balance), 2, ACCOUNTFROZEN_SIG, bytes32(target), 0, 0);
}
event AccountUnfrozen(address indexed target);
bytes32 constant ACCOUNTUNFROZEN_SIG = keccak256("AccountUnfrozen(address)");
function emitAccountUnfrozen(address target) internal {
proxy._emit(abi.encode(), 2, ACCOUNTUNFROZEN_SIG, bytes32(target), 0, 0);
}
event Issued(address indexed account, uint amount);
bytes32 constant ISSUED_SIG = keccak256("Issued(address,uint256)");
function emitIssued(address account, uint amount) internal {
proxy._emit(abi.encode(amount), 2, ISSUED_SIG, bytes32(account), 0, 0);
}
event Burned(address indexed account, uint amount);
bytes32 constant BURNED_SIG = keccak256("Burned(address,uint256)");
function emitBurned(address account, uint amount) internal {
proxy._emit(abi.encode(amount), 2, BURNED_SIG, bytes32(account), 0, 0);
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: LimitedSetup.sol
version: 1.1
author: Anton Jurisevic
date: 2018-05-15
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A contract with a limited setup period. Any function modified
with the setup modifier will cease to work after the
conclusion of the configurable-length post-construction setup period.
-----------------------------------------------------------------
*/
/**
* @title Any function decorated with the modifier this contract provides
* deactivates after a specified setup period.
*/
contract LimitedSetup {
uint setupExpiryTime;
/**
* @dev LimitedSetup Constructor.
* @param setupDuration The time the setup period will last for.
*/
constructor(uint setupDuration)
public
{
setupExpiryTime = now + setupDuration;
}
modifier onlyDuringSetup
{
require(now < setupExpiryTime, "Can only perform this action during setup");
_;
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: HavvenEscrow.sol
version: 1.1
author: Anton Jurisevic
Dominic Romanowski
Mike Spain
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
This contract allows the foundation to apply unique vesting
schedules to havven funds sold at various discounts in the token
sale. HavvenEscrow gives users the ability to inspect their
vested funds, their quantities and vesting dates, and to withdraw
the fees that accrue on those funds.
The fees are handled by withdrawing the entire fee allocation
for all havvens inside the escrow contract, and then allowing
the contract itself to subdivide that pool up proportionally within
itself. Every time the fee period rolls over in the main Havven
contract, the HavvenEscrow fee pool is remitted back into the
main fee pool to be redistributed in the next fee period.
-----------------------------------------------------------------
*/
/**
* @title A contract to hold escrowed havvens and free them at given schedules.
*/
contract HavvenEscrow is SafeDecimalMath, Owned, LimitedSetup(8 weeks) {
/* The corresponding Havven contract. */
Havven public havven;
/* Lists of (timestamp, quantity) pairs per account, sorted in ascending time order.
* These are the times at which each given quantity of havvens vests. */
mapping(address => uint[2][]) public vestingSchedules;
/* An account's total vested havven balance to save recomputing this for fee extraction purposes. */
mapping(address => uint) public totalVestedAccountBalance;
/* The total remaining vested balance, for verifying the actual havven balance of this contract against. */
uint public totalVestedBalance;
uint constant TIME_INDEX = 0;
uint constant QUANTITY_INDEX = 1;
/* Limit vesting entries to disallow unbounded iteration over vesting schedules. */
uint constant MAX_VESTING_ENTRIES = 20;
/* ========== CONSTRUCTOR ========== */
constructor(address _owner, Havven _havven)
Owned(_owner)
public
{
havven = _havven;
}
/* ========== SETTERS ========== */
function setHavven(Havven _havven)
external
onlyOwner
{
havven = _havven;
emit HavvenUpdated(_havven);
}
/* ========== VIEW FUNCTIONS ========== */
/**
* @notice A simple alias to totalVestedAccountBalance: provides ERC20 balance integration.
*/
function balanceOf(address account)
public
view
returns (uint)
{
return totalVestedAccountBalance[account];
}
/**
* @notice The number of vesting dates in an account's schedule.
*/
function numVestingEntries(address account)
public
view
returns (uint)
{
return vestingSchedules[account].length;
}
/**
* @notice Get a particular schedule entry for an account.
* @return A pair of uints: (timestamp, havven quantity).
*/
function getVestingScheduleEntry(address account, uint index)
public
view
returns (uint[2])
{
return vestingSchedules[account][index];
}
/**
* @notice Get the time at which a given schedule entry will vest.
*/
function getVestingTime(address account, uint index)
public
view
returns (uint)
{
return getVestingScheduleEntry(account,index)[TIME_INDEX];
}
/**
* @notice Get the quantity of havvens associated with a given schedule entry.
*/
function getVestingQuantity(address account, uint index)
public
view
returns (uint)
{
return getVestingScheduleEntry(account,index)[QUANTITY_INDEX];
}
/**
* @notice Obtain the index of the next schedule entry that will vest for a given user.
*/
function getNextVestingIndex(address account)
public
view
returns (uint)
{
uint len = numVestingEntries(account);
for (uint i = 0; i < len; i++) {
if (getVestingTime(account, i) != 0) {
return i;
}
}
return len;
}
/**
* @notice Obtain the next schedule entry that will vest for a given user.
* @return A pair of uints: (timestamp, havven quantity). */
function getNextVestingEntry(address account)
public
view
returns (uint[2])
{
uint index = getNextVestingIndex(account);
if (index == numVestingEntries(account)) {
return [uint(0), 0];
}
return getVestingScheduleEntry(account, index);
}
/**
* @notice Obtain the time at which the next schedule entry will vest for a given user.
*/
function getNextVestingTime(address account)
external
view
returns (uint)
{
return getNextVestingEntry(account)[TIME_INDEX];
}
/**
* @notice Obtain the quantity which the next schedule entry will vest for a given user.
*/
function getNextVestingQuantity(address account)
external
view
returns (uint)
{
return getNextVestingEntry(account)[QUANTITY_INDEX];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Withdraws a quantity of havvens back to the havven contract.
* @dev This may only be called by the owner during the contract's setup period.
*/
function withdrawHavvens(uint quantity)
external
onlyOwner
onlyDuringSetup
{
havven.transfer(havven, quantity);
}
/**
* @notice Destroy the vesting information associated with an account.
*/
function purgeAccount(address account)
external
onlyOwner
onlyDuringSetup
{
delete vestingSchedules[account];
totalVestedBalance = safeSub(totalVestedBalance, totalVestedAccountBalance[account]);
delete totalVestedAccountBalance[account];
}
/**
* @notice Add a new vesting entry at a given time and quantity to an account's schedule.
* @dev A call to this should be accompanied by either enough balance already available
* in this contract, or a corresponding call to havven.endow(), to ensure that when
* the funds are withdrawn, there is enough balance, as well as correctly calculating
* the fees.
* This may only be called by the owner during the contract's setup period.
* Note; although this function could technically be used to produce unbounded
* arrays, it's only in the foundation's command to add to these lists.
* @param account The account to append a new vesting entry to.
* @param time The absolute unix timestamp after which the vested quantity may be withdrawn.
* @param quantity The quantity of havvens that will vest.
*/
function appendVestingEntry(address account, uint time, uint quantity)
public
onlyOwner
onlyDuringSetup
{
/* No empty or already-passed vesting entries allowed. */
require(now < time, "Time must be in the future");
require(quantity != 0, "Quantity cannot be zero");
/* There must be enough balance in the contract to provide for the vesting entry. */
totalVestedBalance = safeAdd(totalVestedBalance, quantity);
require(totalVestedBalance <= havven.balanceOf(this), "Must be enough balance in the contract to provide for the vesting entry");
/* Disallow arbitrarily long vesting schedules in light of the gas limit. */
uint scheduleLength = vestingSchedules[account].length;
require(scheduleLength <= MAX_VESTING_ENTRIES, "Vesting schedule is too long");
if (scheduleLength == 0) {
totalVestedAccountBalance[account] = quantity;
} else {
/* Disallow adding new vested havvens earlier than the last one.
* Since entries are only appended, this means that no vesting date can be repeated. */
require(getVestingTime(account, numVestingEntries(account) - 1) < time, "Cannot add new vested entries earlier than the last one");
totalVestedAccountBalance[account] = safeAdd(totalVestedAccountBalance[account], quantity);
}
vestingSchedules[account].push([time, quantity]);
}
/**
* @notice Construct a vesting schedule to release a quantities of havvens
* over a series of intervals.
* @dev Assumes that the quantities are nonzero
* and that the sequence of timestamps is strictly increasing.
* This may only be called by the owner during the contract's setup period.
*/
function addVestingSchedule(address account, uint[] times, uint[] quantities)
external
onlyOwner
onlyDuringSetup
{
for (uint i = 0; i < times.length; i++) {
appendVestingEntry(account, times[i], quantities[i]);
}
}
/**
* @notice Allow a user to withdraw any havvens in their schedule that have vested.
*/
function vest()
external
{
uint numEntries = numVestingEntries(msg.sender);
uint total;
for (uint i = 0; i < numEntries; i++) {
uint time = getVestingTime(msg.sender, i);
/* The list is sorted; when we reach the first future time, bail out. */
if (time > now) {
break;
}
uint qty = getVestingQuantity(msg.sender, i);
if (qty == 0) {
continue;
}
vestingSchedules[msg.sender][i] = [0, 0];
total = safeAdd(total, qty);
}
if (total != 0) {
totalVestedBalance = safeSub(totalVestedBalance, total);
totalVestedAccountBalance[msg.sender] = safeSub(totalVestedAccountBalance[msg.sender], total);
havven.transfer(msg.sender, total);
emit Vested(msg.sender, now, total);
}
}
/* ========== EVENTS ========== */
event HavvenUpdated(address newHavven);
event Vested(address indexed beneficiary, uint time, uint value);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Havven.sol
version: 1.2
author: Anton Jurisevic
Dominic Romanowski
date: 2018-05-15
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
Havven token contract. Havvens are transferable ERC20 tokens,
and also give their holders the following privileges.
An owner of havvens may participate in nomin confiscation votes, they
may also have the right to issue nomins at the discretion of the
foundation for this version of the contract.
After a fee period terminates, the duration and fees collected for that
period are computed, and the next period begins. Thus an account may only
withdraw the fees owed to them for the previous period, and may only do
so once per period. Any unclaimed fees roll over into the common pot for
the next period.
== Average Balance Calculations ==
The fee entitlement of a havven holder is proportional to their average
issued nomin balance over the last fee period. This is computed by
measuring the area under the graph of a user's issued nomin balance over
time, and then when a new fee period begins, dividing through by the
duration of the fee period.
We need only update values when the balances of an account is modified.
This occurs when issuing or burning for issued nomin balances,
and when transferring for havven balances. This is for efficiency,
and adds an implicit friction to interacting with havvens.
A havven holder pays for his own recomputation whenever he wants to change
his position, which saves the foundation having to maintain a pot dedicated
to resourcing this.
A hypothetical user's balance history over one fee period, pictorially:
s ____
| |
| |___ p
|____|___|___ __ _ _
f t n
Here, the balance was s between times f and t, at which time a transfer
occurred, updating the balance to p, until n, when the present transfer occurs.
When a new transfer occurs at time n, the balance being p,
we must:
- Add the area p * (n - t) to the total area recorded so far
- Update the last transfer time to n
So if this graph represents the entire current fee period,
the average havvens held so far is ((t-f)*s + (n-t)*p) / (n-f).
The complementary computations must be performed for both sender and
recipient.
Note that a transfer keeps global supply of havvens invariant.
The sum of all balances is constant, and unmodified by any transfer.
So the sum of all balances multiplied by the duration of a fee period is also
constant, and this is equivalent to the sum of the area of every user's
time/balance graph. Dividing through by that duration yields back the total
havven supply. So, at the end of a fee period, we really do yield a user's
average share in the havven supply over that period.
A slight wrinkle is introduced if we consider the time r when the fee period
rolls over. Then the previous fee period k-1 is before r, and the current fee
period k is afterwards. If the last transfer took place before r,
but the latest transfer occurred afterwards:
k-1 | k
s __|_
| | |
| | |____ p
|__|_|____|___ __ _ _
|
f | t n
r
In this situation the area (r-f)*s contributes to fee period k-1, while
the area (t-r)*s contributes to fee period k. We will implicitly consider a
zero-value transfer to have occurred at time r. Their fee entitlement for the
previous period will be finalised at the time of their first transfer during the
current fee period, or when they query or withdraw their fee entitlement.
In the implementation, the duration of different fee periods may be slightly irregular,
as the check that they have rolled over occurs only when state-changing havven
operations are performed.
== Issuance and Burning ==
In this version of the havven contract, nomins can only be issued by
those that have been nominated by the havven foundation. Nomins are assumed
to be valued at $1, as they are a stable unit of account.
All nomins issued require a proportional value of havvens to be locked,
where the proportion is governed by the current issuance ratio. This
means for every $1 of Havvens locked up, $(issuanceRatio) nomins can be issued.
i.e. to issue 100 nomins, 100/issuanceRatio dollars of havvens need to be locked up.
To determine the value of some amount of havvens(H), an oracle is used to push
the price of havvens (P_H) in dollars to the contract. The value of H
would then be: H * P_H.
Any havvens that are locked up by this issuance process cannot be transferred.
The amount that is locked floats based on the price of havvens. If the price
of havvens moves up, less havvens are locked, so they can be issued against,
or transferred freely. If the price of havvens moves down, more havvens are locked,
even going above the initial wallet balance.
-----------------------------------------------------------------
*/
/**
* @title Havven ERC20 contract.
* @notice The Havven contracts does not only facilitate transfers and track balances,
* but it also computes the quantity of fees each havven holder is entitled to.
*/
contract Havven is ExternStateToken {
/* ========== STATE VARIABLES ========== */
/* A struct for handing values associated with average balance calculations */
struct IssuanceData {
/* Sums of balances*duration in the current fee period.
/* range: decimals; units: havven-seconds */
uint currentBalanceSum;
/* The last period's average balance */
uint lastAverageBalance;
/* The last time the data was calculated */
uint lastModified;
}
/* Issued nomin balances for individual fee entitlements */
mapping(address => IssuanceData) public issuanceData;
/* The total number of issued nomins for determining fee entitlements */
IssuanceData public totalIssuanceData;
/* The time the current fee period began */
uint public feePeriodStartTime;
/* The time the last fee period began */
uint public lastFeePeriodStartTime;
/* Fee periods will roll over in no shorter a time than this.
* The fee period cannot actually roll over until a fee-relevant
* operation such as withdrawal or a fee period duration update occurs,
* so this is just a target, and the actual duration may be slightly longer. */
uint public feePeriodDuration = 4 weeks;
/* ...and must target between 1 day and six months. */
uint constant MIN_FEE_PERIOD_DURATION = 1 days;
uint constant MAX_FEE_PERIOD_DURATION = 26 weeks;
/* The quantity of nomins that were in the fee pot at the time */
/* of the last fee rollover, at feePeriodStartTime. */
uint public lastFeesCollected;
/* Whether a user has withdrawn their last fees */
mapping(address => bool) public hasWithdrawnFees;
Nomin public nomin;
HavvenEscrow public escrow;
/* The address of the oracle which pushes the havven price to this contract */
address public oracle;
/* The price of havvens written in UNIT */
uint public price;
/* The time the havven price was last updated */
uint public lastPriceUpdateTime;
/* How long will the contract assume the price of havvens is correct */
uint public priceStalePeriod = 3 hours;
/* A quantity of nomins greater than this ratio
* may not be issued against a given value of havvens. */
uint public issuanceRatio = UNIT / 5;
/* No more nomins may be issued than the value of havvens backing them. */
uint constant MAX_ISSUANCE_RATIO = UNIT;
/* Whether the address can issue nomins or not. */
mapping(address => bool) public isIssuer;
/* The number of currently-outstanding nomins the user has issued. */
mapping(address => uint) public nominsIssued;
uint constant HAVVEN_SUPPLY = 1e8 * UNIT;
uint constant ORACLE_FUTURE_LIMIT = 10 minutes;
string constant TOKEN_NAME = "Havven";
string constant TOKEN_SYMBOL = "HAV";
/* ========== CONSTRUCTOR ========== */
/**
* @dev Constructor
* @param _tokenState A pre-populated contract containing token balances.
* If the provided address is 0x0, then a fresh one will be constructed with the contract owning all tokens.
* @param _owner The owner of this contract.
*/
constructor(address _proxy, TokenState _tokenState, address _owner, address _oracle,
uint _price, address[] _issuers, Havven _oldHavven)
ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, HAVVEN_SUPPLY, _owner)
public
{
oracle = _oracle;
price = _price;
lastPriceUpdateTime = now;
uint i;
if (_oldHavven == address(0)) {
feePeriodStartTime = now;
lastFeePeriodStartTime = now - feePeriodDuration;
for (i = 0; i < _issuers.length; i++) {
isIssuer[_issuers[i]] = true;
}
} else {
feePeriodStartTime = _oldHavven.feePeriodStartTime();
lastFeePeriodStartTime = _oldHavven.lastFeePeriodStartTime();
uint cbs;
uint lab;
uint lm;
(cbs, lab, lm) = _oldHavven.totalIssuanceData();
totalIssuanceData.currentBalanceSum = cbs;
totalIssuanceData.lastAverageBalance = lab;
totalIssuanceData.lastModified = lm;
for (i = 0; i < _issuers.length; i++) {
address issuer = _issuers[i];
isIssuer[issuer] = true;
uint nomins = _oldHavven.nominsIssued(issuer);
if (nomins == 0) {
// It is not valid in general to skip those with no currently-issued nomins.
// But for this release, issuers with nonzero issuanceData have current issuance.
continue;
}
(cbs, lab, lm) = _oldHavven.issuanceData(issuer);
nominsIssued[issuer] = nomins;
issuanceData[issuer].currentBalanceSum = cbs;
issuanceData[issuer].lastAverageBalance = lab;
issuanceData[issuer].lastModified = lm;
}
}
}
/* ========== SETTERS ========== */
/**
* @notice Set the associated Nomin contract to collect fees from.
* @dev Only the contract owner may call this.
*/
function setNomin(Nomin _nomin)
external
optionalProxy_onlyOwner
{
nomin = _nomin;
emitNominUpdated(_nomin);
}
/**
* @notice Set the associated havven escrow contract.
* @dev Only the contract owner may call this.
*/
function setEscrow(HavvenEscrow _escrow)
external
optionalProxy_onlyOwner
{
escrow = _escrow;
emitEscrowUpdated(_escrow);
}
/**
* @notice Set the targeted fee period duration.
* @dev Only callable by the contract owner. The duration must fall within
* acceptable bounds (1 day to 26 weeks). Upon resetting this the fee period
* may roll over if the target duration was shortened sufficiently.
*/
function setFeePeriodDuration(uint duration)
external
optionalProxy_onlyOwner
{
require(MIN_FEE_PERIOD_DURATION <= duration && duration <= MAX_FEE_PERIOD_DURATION,
"Duration must be between MIN_FEE_PERIOD_DURATION and MAX_FEE_PERIOD_DURATION");
feePeriodDuration = duration;
emitFeePeriodDurationUpdated(duration);
rolloverFeePeriodIfElapsed();
}
/**
* @notice Set the Oracle that pushes the havven price to this contract
*/
function setOracle(address _oracle)
external
optionalProxy_onlyOwner
{
oracle = _oracle;
emitOracleUpdated(_oracle);
}
/**
* @notice Set the stale period on the updated havven price
* @dev No max/minimum, as changing it wont influence anything but issuance by the foundation
*/
function setPriceStalePeriod(uint time)
external
optionalProxy_onlyOwner
{
priceStalePeriod = time;
}
/**
* @notice Set the issuanceRatio for issuance calculations.
* @dev Only callable by the contract owner.
*/
function setIssuanceRatio(uint _issuanceRatio)
external
optionalProxy_onlyOwner
{
require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio must be less than or equal to MAX_ISSUANCE_RATIO");
issuanceRatio = _issuanceRatio;
emitIssuanceRatioUpdated(_issuanceRatio);
}
/**
* @notice Set whether the specified can issue nomins or not.
*/
function setIssuer(address account, bool value)
external
optionalProxy_onlyOwner
{
isIssuer[account] = value;
emitIssuersUpdated(account, value);
}
/* ========== VIEWS ========== */
function issuanceCurrentBalanceSum(address account)
external
view
returns (uint)
{
return issuanceData[account].currentBalanceSum;
}
function issuanceLastAverageBalance(address account)
external
view
returns (uint)
{
return issuanceData[account].lastAverageBalance;
}
function issuanceLastModified(address account)
external
view
returns (uint)
{
return issuanceData[account].lastModified;
}
function totalIssuanceCurrentBalanceSum()
external
view
returns (uint)
{
return totalIssuanceData.currentBalanceSum;
}
function totalIssuanceLastAverageBalance()
external
view
returns (uint)
{
return totalIssuanceData.lastAverageBalance;
}
function totalIssuanceLastModified()
external
view
returns (uint)
{
return totalIssuanceData.lastModified;
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice ERC20 transfer function.
*/
function transfer(address to, uint value)
public
optionalProxy
returns (bool)
{
address sender = messageSender;
require(nominsIssued[sender] == 0 || value <= transferableHavvens(sender), "Value to transfer exceeds available havvens");
/* Perform the transfer: if there is a problem,
* an exception will be thrown in this call. */
_transfer_byProxy(sender, to, value);
return true;
}
/**
* @notice ERC20 transferFrom function.
*/
function transferFrom(address from, address to, uint value)
public
optionalProxy
returns (bool)
{
address sender = messageSender;
require(nominsIssued[from] == 0 || value <= transferableHavvens(from), "Value to transfer exceeds available havvens");
/* Perform the transfer: if there is a problem,
* an exception will be thrown in this call. */
_transferFrom_byProxy(sender, from, to, value);
return true;
}
/**
* @notice Compute the last period's fee entitlement for the message sender
* and then deposit it into their nomin account.
*/
function withdrawFees()
external
optionalProxy
{
address sender = messageSender;
rolloverFeePeriodIfElapsed();
/* Do not deposit fees into frozen accounts. */
require(!nomin.frozen(sender), "Cannot deposit fees into frozen accounts");
/* Check the period has rolled over first. */
updateIssuanceData(sender, nominsIssued[sender], nomin.totalSupply());
/* Only allow accounts to withdraw fees once per period. */
require(!hasWithdrawnFees[sender], "Fees have already been withdrawn in this period");
uint feesOwed;
uint lastTotalIssued = totalIssuanceData.lastAverageBalance;
if (lastTotalIssued > 0) {
/* Sender receives a share of last period's collected fees proportional
* with their average fraction of the last period's issued nomins. */
feesOwed = safeDiv_dec(
safeMul_dec(issuanceData[sender].lastAverageBalance, lastFeesCollected),
lastTotalIssued
);
}
hasWithdrawnFees[sender] = true;
if (feesOwed != 0) {
nomin.withdrawFees(sender, feesOwed);
}
emitFeesWithdrawn(messageSender, feesOwed);
}
/**
* @notice Update the havven balance averages since the last transfer
* or entitlement adjustment.
* @dev Since this updates the last transfer timestamp, if invoked
* consecutively, this function will do nothing after the first call.
* Also, this will adjust the total issuance at the same time.
*/
function updateIssuanceData(address account, uint preBalance, uint lastTotalSupply)
internal
{
/* update the total balances first */
totalIssuanceData = computeIssuanceData(lastTotalSupply, totalIssuanceData);
if (issuanceData[account].lastModified < feePeriodStartTime) {
hasWithdrawnFees[account] = false;
}
issuanceData[account] = computeIssuanceData(preBalance, issuanceData[account]);
}
/**
* @notice Compute the new IssuanceData on the old balance
*/
function computeIssuanceData(uint preBalance, IssuanceData preIssuance)
internal
view
returns (IssuanceData)
{
uint currentBalanceSum = preIssuance.currentBalanceSum;
uint lastAverageBalance = preIssuance.lastAverageBalance;
uint lastModified = preIssuance.lastModified;
if (lastModified < feePeriodStartTime) {
if (lastModified < lastFeePeriodStartTime) {
/* The balance was last updated before the previous fee period, so the average
* balance in this period is their pre-transfer balance. */
lastAverageBalance = preBalance;
} else {
/* The balance was last updated during the previous fee period. */
/* No overflow or zero denominator problems, since lastFeePeriodStartTime < feePeriodStartTime < lastModified.
* implies these quantities are strictly positive. */
uint timeUpToRollover = feePeriodStartTime - lastModified;
uint lastFeePeriodDuration = feePeriodStartTime - lastFeePeriodStartTime;
uint lastBalanceSum = safeAdd(currentBalanceSum, safeMul(preBalance, timeUpToRollover));
lastAverageBalance = lastBalanceSum / lastFeePeriodDuration;
}
/* Roll over to the next fee period. */
currentBalanceSum = safeMul(preBalance, now - feePeriodStartTime);
} else {
/* The balance was last updated during the current fee period. */
currentBalanceSum = safeAdd(
currentBalanceSum,
safeMul(preBalance, now - lastModified)
);
}
return IssuanceData(currentBalanceSum, lastAverageBalance, now);
}
/**
* @notice Recompute and return the given account's last average balance.
*/
function recomputeLastAverageBalance(address account)
external
returns (uint)
{
updateIssuanceData(account, nominsIssued[account], nomin.totalSupply());
return issuanceData[account].lastAverageBalance;
}
/**
* @notice Issue nomins against the sender's havvens.
* @dev Issuance is only allowed if the havven price isn't stale and the sender is an issuer.
*/
function issueNomins(uint amount)
public
optionalProxy
requireIssuer(messageSender)
/* No need to check if price is stale, as it is checked in issuableNomins. */
{
address sender = messageSender;
require(amount <= remainingIssuableNomins(sender), "Amount must be less than or equal to remaining issuable nomins");
uint lastTot = nomin.totalSupply();
uint preIssued = nominsIssued[sender];
nomin.issue(sender, amount);
nominsIssued[sender] = safeAdd(preIssued, amount);
updateIssuanceData(sender, preIssued, lastTot);
}
function issueMaxNomins()
external
optionalProxy
{
issueNomins(remainingIssuableNomins(messageSender));
}
/**
* @notice Burn nomins to clear issued nomins/free havvens.
*/
function burnNomins(uint amount)
/* it doesn't matter if the price is stale or if the user is an issuer, as non-issuers have issued no nomins.*/
external
optionalProxy
{
address sender = messageSender;
uint lastTot = nomin.totalSupply();
uint preIssued = nominsIssued[sender];
/* nomin.burn does a safeSub on balance (so it will revert if there are not enough nomins). */
nomin.burn(sender, amount);
/* This safe sub ensures amount <= number issued */
nominsIssued[sender] = safeSub(preIssued, amount);
updateIssuanceData(sender, preIssued, lastTot);
}
/**
* @notice Check if the fee period has rolled over. If it has, set the new fee period start
* time, and record the fees collected in the nomin contract.
*/
function rolloverFeePeriodIfElapsed()
public
{
/* If the fee period has rolled over... */
if (now >= feePeriodStartTime + feePeriodDuration) {
lastFeesCollected = nomin.feePool();
lastFeePeriodStartTime = feePeriodStartTime;
feePeriodStartTime = now;
emitFeePeriodRollover(now);
}
}
/* ========== Issuance/Burning ========== */
/**
* @notice The maximum nomins an issuer can issue against their total havven quantity. This ignores any
* already issued nomins.
*/
function maxIssuableNomins(address issuer)
view
public
priceNotStale
returns (uint)
{
if (!isIssuer[issuer]) {
return 0;
}
if (escrow != HavvenEscrow(0)) {
uint totalOwnedHavvens = safeAdd(tokenState.balanceOf(issuer), escrow.balanceOf(issuer));
return safeMul_dec(HAVtoUSD(totalOwnedHavvens), issuanceRatio);
} else {
return safeMul_dec(HAVtoUSD(tokenState.balanceOf(issuer)), issuanceRatio);
}
}
/**
* @notice The remaining nomins an issuer can issue against their total havven quantity.
*/
function remainingIssuableNomins(address issuer)
view
public
returns (uint)
{
uint issued = nominsIssued[issuer];
uint max = maxIssuableNomins(issuer);
if (issued > max) {
return 0;
} else {
return safeSub(max, issued);
}
}
/**
* @notice The total havvens owned by this account, both escrowed and unescrowed,
* against which nomins can be issued.
* This includes those already being used as collateral (locked), and those
* available for further issuance (unlocked).
*/
function collateral(address account)
public
view
returns (uint)
{
uint bal = tokenState.balanceOf(account);
if (escrow != address(0)) {
bal = safeAdd(bal, escrow.balanceOf(account));
}
return bal;
}
/**
* @notice The collateral that would be locked by issuance, which can exceed the account's actual collateral.
*/
function issuanceDraft(address account)
public
view
returns (uint)
{
uint issued = nominsIssued[account];
if (issued == 0) {
return 0;
}
return USDtoHAV(safeDiv_dec(issued, issuanceRatio));
}
/**
* @notice Collateral that has been locked due to issuance, and cannot be
* transferred to other addresses. This is capped at the account's total collateral.
*/
function lockedCollateral(address account)
public
view
returns (uint)
{
uint debt = issuanceDraft(account);
uint collat = collateral(account);
if (debt > collat) {
return collat;
}
return debt;
}
/**
* @notice Collateral that is not locked and available for issuance.
*/
function unlockedCollateral(address account)
public
view
returns (uint)
{
uint locked = lockedCollateral(account);
uint collat = collateral(account);
return safeSub(collat, locked);
}
/**
* @notice The number of havvens that are free to be transferred by an account.
* @dev If they have enough available Havvens, it could be that
* their havvens are escrowed, however the transfer would then
* fail. This means that escrowed havvens are locked first,
* and then the actual transferable ones.
*/
function transferableHavvens(address account)
public
view
returns (uint)
{
uint draft = issuanceDraft(account);
uint collat = collateral(account);
// In the case where the issuanceDraft exceeds the collateral, nothing is free
if (draft > collat) {
return 0;
}
uint bal = balanceOf(account);
// In the case where the draft exceeds the escrow, but not the whole collateral
// return the fraction of the balance that remains free
if (draft > safeSub(collat, bal)) {
return safeSub(collat, draft);
}
// In the case where the draft doesn't exceed the escrow, return the entire balance
return bal;
}
/**
* @notice The value in USD for a given amount of HAV
*/
function HAVtoUSD(uint hav_dec)
public
view
priceNotStale
returns (uint)
{
return safeMul_dec(hav_dec, price);
}
/**
* @notice The value in HAV for a given amount of USD
*/
function USDtoHAV(uint usd_dec)
public
view
priceNotStale
returns (uint)
{
return safeDiv_dec(usd_dec, price);
}
/**
* @notice Access point for the oracle to update the price of havvens.
*/
function updatePrice(uint newPrice, uint timeSent)
external
onlyOracle /* Should be callable only by the oracle. */
{
/* Must be the most recently sent price, but not too far in the future.
* (so we can't lock ourselves out of updating the oracle for longer than this) */
require(lastPriceUpdateTime < timeSent && timeSent < now + ORACLE_FUTURE_LIMIT,
"Time sent must be bigger than the last update, and must be less than now + ORACLE_FUTURE_LIMIT");
price = newPrice;
lastPriceUpdateTime = timeSent;
emitPriceUpdated(newPrice, timeSent);
/* Check the fee period rollover within this as the price should be pushed every 15min. */
rolloverFeePeriodIfElapsed();
}
/**
* @notice Check if the price of havvens hasn't been updated for longer than the stale period.
*/
function priceIsStale()
public
view
returns (bool)
{
return safeAdd(lastPriceUpdateTime, priceStalePeriod) < now;
}
/* ========== MODIFIERS ========== */
modifier requireIssuer(address account)
{
require(isIssuer[account], "Must be issuer to perform this action");
_;
}
modifier onlyOracle
{
require(msg.sender == oracle, "Must be oracle to perform this action");
_;
}
modifier priceNotStale
{
require(!priceIsStale(), "Price must not be stale to perform this action");
_;
}
/* ========== EVENTS ========== */
event PriceUpdated(uint newPrice, uint timestamp);
bytes32 constant PRICEUPDATED_SIG = keccak256("PriceUpdated(uint256,uint256)");
function emitPriceUpdated(uint newPrice, uint timestamp) internal {
proxy._emit(abi.encode(newPrice, timestamp), 1, PRICEUPDATED_SIG, 0, 0, 0);
}
event IssuanceRatioUpdated(uint newRatio);
bytes32 constant ISSUANCERATIOUPDATED_SIG = keccak256("IssuanceRatioUpdated(uint256)");
function emitIssuanceRatioUpdated(uint newRatio) internal {
proxy._emit(abi.encode(newRatio), 1, ISSUANCERATIOUPDATED_SIG, 0, 0, 0);
}
event FeePeriodRollover(uint timestamp);
bytes32 constant FEEPERIODROLLOVER_SIG = keccak256("FeePeriodRollover(uint256)");
function emitFeePeriodRollover(uint timestamp) internal {
proxy._emit(abi.encode(timestamp), 1, FEEPERIODROLLOVER_SIG, 0, 0, 0);
}
event FeePeriodDurationUpdated(uint duration);
bytes32 constant FEEPERIODDURATIONUPDATED_SIG = keccak256("FeePeriodDurationUpdated(uint256)");
function emitFeePeriodDurationUpdated(uint duration) internal {
proxy._emit(abi.encode(duration), 1, FEEPERIODDURATIONUPDATED_SIG, 0, 0, 0);
}
event FeesWithdrawn(address indexed account, uint value);
bytes32 constant FEESWITHDRAWN_SIG = keccak256("FeesWithdrawn(address,uint256)");
function emitFeesWithdrawn(address account, uint value) internal {
proxy._emit(abi.encode(value), 2, FEESWITHDRAWN_SIG, bytes32(account), 0, 0);
}
event OracleUpdated(address newOracle);
bytes32 constant ORACLEUPDATED_SIG = keccak256("OracleUpdated(address)");
function emitOracleUpdated(address newOracle) internal {
proxy._emit(abi.encode(newOracle), 1, ORACLEUPDATED_SIG, 0, 0, 0);
}
event NominUpdated(address newNomin);
bytes32 constant NOMINUPDATED_SIG = keccak256("NominUpdated(address)");
function emitNominUpdated(address newNomin) internal {
proxy._emit(abi.encode(newNomin), 1, NOMINUPDATED_SIG, 0, 0, 0);
}
event EscrowUpdated(address newEscrow);
bytes32 constant ESCROWUPDATED_SIG = keccak256("EscrowUpdated(address)");
function emitEscrowUpdated(address newEscrow) internal {
proxy._emit(abi.encode(newEscrow), 1, ESCROWUPDATED_SIG, 0, 0, 0);
}
event IssuersUpdated(address indexed account, bool indexed value);
bytes32 constant ISSUERSUPDATED_SIG = keccak256("IssuersUpdated(address,bool)");
function emitIssuersUpdated(address account, bool value) internal {
proxy._emit(abi.encode(), 3, ISSUERSUPDATED_SIG, bytes32(account), bytes32(value ? 1 : 0), 0);
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION -----------------------------------------------------------------
file: IssuanceController.sol
version: 2.0
author: Kevin Brown
date: 2018-07-18
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
Issuance controller contract. The issuance controller provides
a way for users to acquire nomins (Nomin.sol) and havvens
(Havven.sol) by paying ETH and a way for users to acquire havvens
(Havven.sol) by paying nomins. Users can also deposit their nomins
and allow other users to purchase them with ETH. The ETH is sent
to the user who offered their nomins for sale.
This smart contract contains a balance of each currency, and
allows the owner of the contract (the Havven Foundation) to
manage the available balance of havven at their discretion, while
users are allowed to deposit and withdraw their own nomin deposits
if they have not yet been taken up by another user.
-----------------------------------------------------------------
*/
/**
* @title Issuance Controller Contract.
*/
contract IssuanceController is SafeDecimalMath, SelfDestructible, Pausable {
/* ========== STATE VARIABLES ========== */
Havven public havven;
Nomin public nomin;
// Address where the ether raised is transfered to
address public fundsWallet;
/* The address of the oracle which pushes the USD price havvens and ether to this contract */
address public oracle;
/* Do not allow the oracle to submit times any further forward into the future than
this constant. */
uint constant ORACLE_FUTURE_LIMIT = 10 minutes;
/* How long will the contract assume the price of any asset is correct */
uint public priceStalePeriod = 3 hours;
/* The time the prices were last updated */
uint public lastPriceUpdateTime;
/* The USD price of havvens denominated in UNIT */
uint public usdToHavPrice;
/* The USD price of ETH denominated in UNIT */
uint public usdToEthPrice;
/* ========== CONSTRUCTOR ========== */
/**
* @dev Constructor
* @param _owner The owner of this contract.
* @param _fundsWallet The recipient of ETH and Nomins that are sent to this contract while exchanging.
* @param _havven The Havven contract we'll interact with for balances and sending.
* @param _nomin The Nomin contract we'll interact with for balances and sending.
* @param _oracle The address which is able to update price information.
* @param _usdToEthPrice The current price of ETH in USD, expressed in UNIT.
* @param _usdToHavPrice The current price of Havven in USD, expressed in UNIT.
*/
constructor(
// Ownable
address _owner,
// Funds Wallet
address _fundsWallet,
// Other contracts needed
Havven _havven,
Nomin _nomin,
// Oracle values - Allows for price updates
address _oracle,
uint _usdToEthPrice,
uint _usdToHavPrice
)
/* Owned is initialised in SelfDestructible */
SelfDestructible(_owner)
Pausable(_owner)
public
{
fundsWallet = _fundsWallet;
havven = _havven;
nomin = _nomin;
oracle = _oracle;
usdToEthPrice = _usdToEthPrice;
usdToHavPrice = _usdToHavPrice;
lastPriceUpdateTime = now;
}
/* ========== SETTERS ========== */
/**
* @notice Set the funds wallet where ETH raised is held
* @param _fundsWallet The new address to forward ETH and Nomins to
*/
function setFundsWallet(address _fundsWallet)
external
onlyOwner
{
fundsWallet = _fundsWallet;
emit FundsWalletUpdated(fundsWallet);
}
/**
* @notice Set the Oracle that pushes the havven price to this contract
* @param _oracle The new oracle address
*/
function setOracle(address _oracle)
external
onlyOwner
{
oracle = _oracle;
emit OracleUpdated(oracle);
}
/**
* @notice Set the Nomin contract that the issuance controller uses to issue Nomins.
* @param _nomin The new nomin contract target
*/
function setNomin(Nomin _nomin)
external
onlyOwner
{
nomin = _nomin;
emit NominUpdated(_nomin);
}
/**
* @notice Set the Havven contract that the issuance controller uses to issue Havvens.
* @param _havven The new havven contract target
*/
function setHavven(Havven _havven)
external
onlyOwner
{
havven = _havven;
emit HavvenUpdated(_havven);
}
/**
* @notice Set the stale period on the updated price variables
* @param _time The new priceStalePeriod
*/
function setPriceStalePeriod(uint _time)
external
onlyOwner
{
priceStalePeriod = _time;
emit PriceStalePeriodUpdated(priceStalePeriod);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Access point for the oracle to update the prices of havvens / eth.
* @param newEthPrice The current price of ether in USD, specified to 18 decimal places.
* @param newHavvenPrice The current price of havvens in USD, specified to 18 decimal places.
* @param timeSent The timestamp from the oracle when the transaction was created. This ensures we don't consider stale prices as current in times of heavy network congestion.
*/
function updatePrices(uint newEthPrice, uint newHavvenPrice, uint timeSent)
external
onlyOracle
{
/* Must be the most recently sent price, but not too far in the future.
* (so we can't lock ourselves out of updating the oracle for longer than this) */
require(lastPriceUpdateTime < timeSent && timeSent < now + ORACLE_FUTURE_LIMIT,
"Time sent must be bigger than the last update, and must be less than now + ORACLE_FUTURE_LIMIT");
usdToEthPrice = newEthPrice;
usdToHavPrice = newHavvenPrice;
lastPriceUpdateTime = timeSent;
emit PricesUpdated(usdToEthPrice, usdToHavPrice, lastPriceUpdateTime);
}
/**
* @notice Fallback function (exchanges ETH to nUSD)
*/
function ()
external
payable
{
exchangeEtherForNomins();
}
/**
* @notice Exchange ETH to nUSD.
*/
function exchangeEtherForNomins()
public
payable
pricesNotStale
notPaused
returns (uint) // Returns the number of Nomins (nUSD) received
{
// The multiplication works here because usdToEthPrice is specified in
// 18 decimal places, just like our currency base.
uint requestedToPurchase = safeMul_dec(msg.value, usdToEthPrice);
// Store the ETH in our funds wallet
fundsWallet.transfer(msg.value);
// Send the nomins.
// Note: Fees are calculated by the Nomin contract, so when
// we request a specific transfer here, the fee is
// automatically deducted and sent to the fee pool.
nomin.transfer(msg.sender, requestedToPurchase);
emit Exchange("ETH", msg.value, "nUSD", requestedToPurchase);
return requestedToPurchase;
}
/**
* @notice Exchange ETH to nUSD while insisting on a particular rate. This allows a user to
* exchange while protecting against frontrunning by the contract owner on the exchange rate.
* @param guaranteedRate The exchange rate (ether price) which must be honored or the call will revert.
*/
function exchangeEtherForNominsAtRate(uint guaranteedRate)
public
payable
pricesNotStale
notPaused
returns (uint) // Returns the number of Nomins (nUSD) received
{
require(guaranteedRate == usdToEthPrice);
return exchangeEtherForNomins();
}
/**
* @notice Exchange ETH to HAV.
*/
function exchangeEtherForHavvens()
public
payable
pricesNotStale
notPaused
returns (uint) // Returns the number of Havvens (HAV) received
{
// How many Havvens are they going to be receiving?
uint havvensToSend = havvensReceivedForEther(msg.value);
// Store the ETH in our funds wallet
fundsWallet.transfer(msg.value);
// And send them the Havvens.
havven.transfer(msg.sender, havvensToSend);
emit Exchange("ETH", msg.value, "HAV", havvensToSend);
return havvensToSend;
}
/**
* @notice Exchange ETH to HAV while insisting on a particular set of rates. This allows a user to
* exchange while protecting against frontrunning by the contract owner on the exchange rates.
* @param guaranteedEtherRate The ether exchange rate which must be honored or the call will revert.
* @param guaranteedHavvenRate The havven exchange rate which must be honored or the call will revert.
*/
function exchangeEtherForHavvensAtRate(uint guaranteedEtherRate, uint guaranteedHavvenRate)
public
payable
pricesNotStale
notPaused
returns (uint) // Returns the number of Havvens (HAV) received
{
require(guaranteedEtherRate == usdToEthPrice);
require(guaranteedHavvenRate == usdToHavPrice);
return exchangeEtherForHavvens();
}
/**
* @notice Exchange nUSD for Havvens
* @param nominAmount The amount of nomins the user wishes to exchange.
*/
function exchangeNominsForHavvens(uint nominAmount)
public
pricesNotStale
notPaused
returns (uint) // Returns the number of Havvens (HAV) received
{
// How many Havvens are they going to be receiving?
uint havvensToSend = havvensReceivedForNomins(nominAmount);
// Ok, transfer the Nomins to our address.
nomin.transferFrom(msg.sender, this, nominAmount);
// And send them the Havvens.
havven.transfer(msg.sender, havvensToSend);
emit Exchange("nUSD", nominAmount, "HAV", havvensToSend);
return havvensToSend;
}
/**
* @notice Exchange nUSD for Havvens while insisting on a particular rate. This allows a user to
* exchange while protecting against frontrunning by the contract owner on the exchange rate.
* @param nominAmount The amount of nomins the user wishes to exchange.
* @param guaranteedRate A rate (havven price) the caller wishes to insist upon.
*/
function exchangeNominsForHavvensAtRate(uint nominAmount, uint guaranteedRate)
public
pricesNotStale
notPaused
returns (uint) // Returns the number of Havvens (HAV) received
{
require(guaranteedRate == usdToHavPrice);
return exchangeNominsForHavvens(nominAmount);
}
/**
* @notice Allows the owner to withdraw havvens from this contract if needed.
* @param amount The amount of havvens to attempt to withdraw (in 18 decimal places).
*/
function withdrawHavvens(uint amount)
external
onlyOwner
{
havven.transfer(owner, amount);
// We don't emit our own events here because we assume that anyone
// who wants to watch what the Issuance Controller is doing can
// just watch ERC20 events from the Nomin and/or Havven contracts
// filtered to our address.
}
/**
* @notice Withdraw nomins: Allows the owner to withdraw nomins from this contract if needed.
* @param amount The amount of nomins to attempt to withdraw (in 18 decimal places).
*/
function withdrawNomins(uint amount)
external
onlyOwner
{
nomin.transfer(owner, amount);
// We don't emit our own events here because we assume that anyone
// who wants to watch what the Issuance Controller is doing can
// just watch ERC20 events from the Nomin and/or Havven contracts
// filtered to our address.
}
/* ========== VIEWS ========== */
/**
* @notice Check if the prices haven't been updated for longer than the stale period.
*/
function pricesAreStale()
public
view
returns (bool)
{
return safeAdd(lastPriceUpdateTime, priceStalePeriod) < now;
}
/**
* @notice Calculate how many havvens you will receive if you transfer
* an amount of nomins.
* @param amount The amount of nomins (in 18 decimal places) you want to ask about
*/
function havvensReceivedForNomins(uint amount)
public
view
returns (uint)
{
// How many nomins would we receive after the transfer fee?
uint nominsReceived = nomin.amountReceived(amount);
// And what would that be worth in havvens based on the current price?
return safeDiv_dec(nominsReceived, usdToHavPrice);
}
/**
* @notice Calculate how many havvens you will receive if you transfer
* an amount of ether.
* @param amount The amount of ether (in wei) you want to ask about
*/
function havvensReceivedForEther(uint amount)
public
view
returns (uint)
{
// How much is the ETH they sent us worth in nUSD (ignoring the transfer fee)?
uint valueSentInNomins = safeMul_dec(amount, usdToEthPrice);
// Now, how many HAV will that USD amount buy?
return havvensReceivedForNomins(valueSentInNomins);
}
/**
* @notice Calculate how many nomins you will receive if you transfer
* an amount of ether.
* @param amount The amount of ether (in wei) you want to ask about
*/
function nominsReceivedForEther(uint amount)
public
view
returns (uint)
{
// How many nomins would that amount of ether be worth?
uint nominsTransferred = safeMul_dec(amount, usdToEthPrice);
// And how many of those would you receive after a transfer (deducting the transfer fee)
return nomin.amountReceived(nominsTransferred);
}
/* ========== MODIFIERS ========== */
modifier onlyOracle
{
require(msg.sender == oracle, "Must be oracle to perform this action");
_;
}
modifier pricesNotStale
{
require(!pricesAreStale(), "Prices must not be stale to perform this action");
_;
}
/* ========== EVENTS ========== */
event FundsWalletUpdated(address newFundsWallet);
event OracleUpdated(address newOracle);
event NominUpdated(Nomin newNominContract);
event HavvenUpdated(Havven newHavvenContract);
event PriceStalePeriodUpdated(uint priceStalePeriod);
event PricesUpdated(uint newEthPrice, uint newHavvenPrice, uint timeSent);
event Exchange(string fromCurrency, uint fromAmount, string toCurrency, uint toAmount);
} | * @notice Set whether the specified can issue nomins or not./ | function setIssuer(address account, bool value)
external
optionalProxy_onlyOwner
{
isIssuer[account] = value;
emitIssuersUpdated(account, value);
}
| 2,140,172 | [
1,
694,
2856,
326,
1269,
848,
5672,
12457,
2679,
578,
486,
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,
444,
16667,
12,
2867,
2236,
16,
1426,
460,
13,
203,
3639,
3903,
203,
3639,
3129,
3886,
67,
3700,
5541,
203,
565,
288,
203,
3639,
353,
16667,
63,
4631,
65,
273,
460,
31,
203,
3639,
3626,
7568,
27307,
7381,
12,
4631,
16,
460,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.18;
/**
* @title Owned contract with safe ownership pass.
*
* Note: all the non constant functions return false instead of throwing in case if state change
* didn't happen yet.
*/
contract Owned {
/**
* Contract owner address
*/
address public contractOwner;
/**
* Contract owner address
*/
address public pendingContractOwner;
function Owned() {
contractOwner = msg.sender;
}
/**
* @dev Owner check modifier
*/
modifier onlyContractOwner() {
if (contractOwner == msg.sender) {
_;
}
}
/**
* @dev Destroy contract and scrub a data
* @notice Only owner can call it
*/
function destroy() onlyContractOwner {
suicide(msg.sender);
}
/**
* Prepares ownership pass.
*
* Can only be called by current owner.
*
* @param _to address of the next owner. 0x0 is not allowed.
*
* @return success.
*/
function changeContractOwnership(address _to) onlyContractOwner() returns(bool) {
if (_to == 0x0) {
return false;
}
pendingContractOwner = _to;
return true;
}
/**
* Finalize ownership pass.
*
* Can only be called by pending owner.
*
* @return success.
*/
function claimContractOwnership() returns(bool) {
if (pendingContractOwner != msg.sender) {
return false;
}
contractOwner = pendingContractOwner;
delete pendingContractOwner;
return true;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/// @title Provides possibility manage holders? country limits and limits for holders.
contract DataControllerInterface {
/// @notice Checks user is holder.
/// @param _address - checking address.
/// @return `true` if _address is registered holder, `false` otherwise.
function isHolderAddress(address _address) public view returns (bool);
function allowance(address _user) public view returns (uint);
function changeAllowance(address _holder, uint _value) public returns (uint);
}
/// @title ServiceController
///
/// Base implementation
/// Serves for managing service instances
contract ServiceControllerInterface {
/// @notice Check target address is service
/// @param _address target address
/// @return `true` when an address is a service, `false` otherwise
function isService(address _address) public view returns (bool);
}
contract ATxAssetInterface {
DataControllerInterface public dataController;
ServiceControllerInterface public serviceController;
function __transferWithReference(address _to, uint _value, string _reference, address _sender) public returns (bool);
function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) public returns (bool);
function __approve(address _spender, uint _value, address _sender) public returns (bool);
function __process(bytes /*_data*/, address /*_sender*/) payable public {
revert();
}
}
contract ERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed from, address indexed spender, uint256 value);
string public symbol;
function totalSupply() constant returns (uint256 supply);
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
}
contract AssetProxy is ERC20 {
bytes32 public smbl;
address public platform;
function __transferWithReference(address _to, uint _value, string _reference, address _sender) public returns (bool);
function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) public returns (bool);
function __approve(address _spender, uint _value, address _sender) public returns (bool);
function getLatestVersion() public returns (address);
function init(address _bmcPlatform, string _symbol, string _name) public;
function proposeUpgrade(address _newVersion) public;
}
contract BasicAsset is ATxAssetInterface {
// Assigned asset proxy contract, immutable.
address public proxy;
/**
* Only assigned proxy is allowed to call.
*/
modifier onlyProxy() {
if (proxy == msg.sender) {
_;
}
}
/**
* Sets asset proxy address.
*
* Can be set only once.
*
* @param _proxy asset proxy contract address.
*
* @return success.
* @dev function is final, and must not be overridden.
*/
function init(address _proxy) public returns (bool) {
if (address(proxy) != 0x0) {
return false;
}
proxy = _proxy;
return true;
}
/**
* Passes execution into virtual function.
*
* Can only be called by assigned asset proxy.
*
* @return success.
* @dev function is final, and must not be overridden.
*/
function __transferWithReference(address _to, uint _value, string _reference, address _sender) public onlyProxy returns (bool) {
return _transferWithReference(_to, _value, _reference, _sender);
}
/**
* Passes execution into virtual function.
*
* Can only be called by assigned asset proxy.
*
* @return success.
* @dev function is final, and must not be overridden.
*/
function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) public onlyProxy returns (bool) {
return _transferFromWithReference(_from, _to, _value, _reference, _sender);
}
/**
* Passes execution into virtual function.
*
* Can only be called by assigned asset proxy.
*
* @return success.
* @dev function is final, and must not be overridden.
*/
function __approve(address _spender, uint _value, address _sender) public onlyProxy returns (bool) {
return _approve(_spender, _value, _sender);
}
/**
* Calls back without modifications.
*
* @return success.
* @dev function is virtual, and meant to be overridden.
*/
function _transferWithReference(address _to, uint _value, string _reference, address _sender) internal returns (bool) {
return AssetProxy(proxy).__transferWithReference(_to, _value, _reference, _sender);
}
/**
* Calls back without modifications.
*
* @return success.
* @dev function is virtual, and meant to be overridden.
*/
function _transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) internal returns (bool) {
return AssetProxy(proxy).__transferFromWithReference(_from, _to, _value, _reference, _sender);
}
/**
* Calls back without modifications.
*
* @return success.
* @dev function is virtual, and meant to be overridden.
*/
function _approve(address _spender, uint _value, address _sender) internal returns (bool) {
return AssetProxy(proxy).__approve(_spender, _value, _sender);
}
}
/// @title ServiceAllowance.
///
/// Provides a way to delegate operation allowance decision to a service contract
contract ServiceAllowance {
function isTransferAllowed(address _from, address _to, address _sender, address _token, uint _value) public view returns (bool);
}
contract ERC20Interface {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed from, address indexed spender, uint256 value);
string public symbol;
function totalSupply() constant returns (uint256 supply);
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
}
/**
* @title Generic owned destroyable contract
*/
contract Object is Owned {
/**
* Common result code. Means everything is fine.
*/
uint constant OK = 1;
uint constant OWNED_ACCESS_DENIED_ONLY_CONTRACT_OWNER = 8;
function withdrawnTokens(address[] tokens, address _to) onlyContractOwner returns(uint) {
for(uint i=0;i<tokens.length;i++) {
address token = tokens[i];
uint balance = ERC20Interface(token).balanceOf(this);
if(balance != 0)
ERC20Interface(token).transfer(_to,balance);
}
return OK;
}
function checkOnlyContractOwner() internal constant returns(uint) {
if (contractOwner == msg.sender) {
return OK;
}
return OWNED_ACCESS_DENIED_ONLY_CONTRACT_OWNER;
}
}
contract GroupsAccessManagerEmitter {
event UserCreated(address user);
event UserDeleted(address user);
event GroupCreated(bytes32 groupName);
event GroupActivated(bytes32 groupName);
event GroupDeactivated(bytes32 groupName);
event UserToGroupAdded(address user, bytes32 groupName);
event UserFromGroupRemoved(address user, bytes32 groupName);
}
/// @title Group Access Manager
///
/// Base implementation
/// This contract serves as group manager
contract GroupsAccessManager is Object, GroupsAccessManagerEmitter {
uint constant USER_MANAGER_SCOPE = 111000;
uint constant USER_MANAGER_MEMBER_ALREADY_EXIST = USER_MANAGER_SCOPE + 1;
uint constant USER_MANAGER_GROUP_ALREADY_EXIST = USER_MANAGER_SCOPE + 2;
uint constant USER_MANAGER_OBJECT_ALREADY_SECURED = USER_MANAGER_SCOPE + 3;
uint constant USER_MANAGER_CONFIRMATION_HAS_COMPLETED = USER_MANAGER_SCOPE + 4;
uint constant USER_MANAGER_USER_HAS_CONFIRMED = USER_MANAGER_SCOPE + 5;
uint constant USER_MANAGER_NOT_ENOUGH_GAS = USER_MANAGER_SCOPE + 6;
uint constant USER_MANAGER_INVALID_INVOCATION = USER_MANAGER_SCOPE + 7;
uint constant USER_MANAGER_DONE = USER_MANAGER_SCOPE + 11;
uint constant USER_MANAGER_CANCELLED = USER_MANAGER_SCOPE + 12;
using SafeMath for uint;
struct Member {
address addr;
uint groupsCount;
mapping(bytes32 => uint) groupName2index;
mapping(uint => uint) index2globalIndex;
}
struct Group {
bytes32 name;
uint priority;
uint membersCount;
mapping(address => uint) memberAddress2index;
mapping(uint => uint) index2globalIndex;
}
uint public membersCount;
mapping(uint => address) index2memberAddress;
mapping(address => uint) memberAddress2index;
mapping(address => Member) address2member;
uint public groupsCount;
mapping(uint => bytes32) index2groupName;
mapping(bytes32 => uint) groupName2index;
mapping(bytes32 => Group) groupName2group;
mapping(bytes32 => bool) public groupsBlocked; // if groupName => true, then couldn't be used for confirmation
function() payable public {
revert();
}
/// @notice Register user
/// Can be called only by contract owner
///
/// @param _user user address
///
/// @return code
function registerUser(address _user) external onlyContractOwner returns (uint) {
require(_user != 0x0);
if (isRegisteredUser(_user)) {
return USER_MANAGER_MEMBER_ALREADY_EXIST;
}
uint _membersCount = membersCount.add(1);
membersCount = _membersCount;
memberAddress2index[_user] = _membersCount;
index2memberAddress[_membersCount] = _user;
address2member[_user] = Member(_user, 0);
UserCreated(_user);
return OK;
}
/// @notice Discard user registration
/// Can be called only by contract owner
///
/// @param _user user address
///
/// @return code
function unregisterUser(address _user) external onlyContractOwner returns (uint) {
require(_user != 0x0);
uint _memberIndex = memberAddress2index[_user];
if (_memberIndex == 0 || address2member[_user].groupsCount != 0) {
return USER_MANAGER_INVALID_INVOCATION;
}
uint _membersCount = membersCount;
delete memberAddress2index[_user];
if (_memberIndex != _membersCount) {
address _lastUser = index2memberAddress[_membersCount];
index2memberAddress[_memberIndex] = _lastUser;
memberAddress2index[_lastUser] = _memberIndex;
}
delete address2member[_user];
delete index2memberAddress[_membersCount];
delete memberAddress2index[_user];
membersCount = _membersCount.sub(1);
UserDeleted(_user);
return OK;
}
/// @notice Create group
/// Can be called only by contract owner
///
/// @param _groupName group name
/// @param _priority group priority
///
/// @return code
function createGroup(bytes32 _groupName, uint _priority) external onlyContractOwner returns (uint) {
require(_groupName != bytes32(0));
if (isGroupExists(_groupName)) {
return USER_MANAGER_GROUP_ALREADY_EXIST;
}
uint _groupsCount = groupsCount.add(1);
groupName2index[_groupName] = _groupsCount;
index2groupName[_groupsCount] = _groupName;
groupName2group[_groupName] = Group(_groupName, _priority, 0);
groupsCount = _groupsCount;
GroupCreated(_groupName);
return OK;
}
/// @notice Change group status
/// Can be called only by contract owner
///
/// @param _groupName group name
/// @param _blocked block status
///
/// @return code
function changeGroupActiveStatus(bytes32 _groupName, bool _blocked) external onlyContractOwner returns (uint) {
require(isGroupExists(_groupName));
groupsBlocked[_groupName] = _blocked;
return OK;
}
/// @notice Add users in group
/// Can be called only by contract owner
///
/// @param _groupName group name
/// @param _users user array
///
/// @return code
function addUsersToGroup(bytes32 _groupName, address[] _users) external onlyContractOwner returns (uint) {
require(isGroupExists(_groupName));
Group storage _group = groupName2group[_groupName];
uint _groupMembersCount = _group.membersCount;
for (uint _userIdx = 0; _userIdx < _users.length; ++_userIdx) {
address _user = _users[_userIdx];
uint _memberIndex = memberAddress2index[_user];
require(_memberIndex != 0);
if (_group.memberAddress2index[_user] != 0) {
continue;
}
_groupMembersCount = _groupMembersCount.add(1);
_group.memberAddress2index[_user] = _groupMembersCount;
_group.index2globalIndex[_groupMembersCount] = _memberIndex;
_addGroupToMember(_user, _groupName);
UserToGroupAdded(_user, _groupName);
}
_group.membersCount = _groupMembersCount;
return OK;
}
/// @notice Remove users in group
/// Can be called only by contract owner
///
/// @param _groupName group name
/// @param _users user array
///
/// @return code
function removeUsersFromGroup(bytes32 _groupName, address[] _users) external onlyContractOwner returns (uint) {
require(isGroupExists(_groupName));
Group storage _group = groupName2group[_groupName];
uint _groupMembersCount = _group.membersCount;
for (uint _userIdx = 0; _userIdx < _users.length; ++_userIdx) {
address _user = _users[_userIdx];
uint _memberIndex = memberAddress2index[_user];
uint _groupMemberIndex = _group.memberAddress2index[_user];
if (_memberIndex == 0 || _groupMemberIndex == 0) {
continue;
}
if (_groupMemberIndex != _groupMembersCount) {
uint _lastUserGlobalIndex = _group.index2globalIndex[_groupMembersCount];
address _lastUser = index2memberAddress[_lastUserGlobalIndex];
_group.index2globalIndex[_groupMemberIndex] = _lastUserGlobalIndex;
_group.memberAddress2index[_lastUser] = _groupMemberIndex;
}
delete _group.memberAddress2index[_user];
delete _group.index2globalIndex[_groupMembersCount];
_groupMembersCount = _groupMembersCount.sub(1);
_removeGroupFromMember(_user, _groupName);
UserFromGroupRemoved(_user, _groupName);
}
_group.membersCount = _groupMembersCount;
return OK;
}
/// @notice Check is user registered
///
/// @param _user user address
///
/// @return status
function isRegisteredUser(address _user) public view returns (bool) {
return memberAddress2index[_user] != 0;
}
/// @notice Check is user in group
///
/// @param _groupName user array
/// @param _user user array
///
/// @return status
function isUserInGroup(bytes32 _groupName, address _user) public view returns (bool) {
return isRegisteredUser(_user) && address2member[_user].groupName2index[_groupName] != 0;
}
/// @notice Check is group exist
///
/// @param _groupName group name
///
/// @return status
function isGroupExists(bytes32 _groupName) public view returns (bool) {
return groupName2index[_groupName] != 0;
}
/// @notice Get current group names
///
/// @return group names
function getGroups() public view returns (bytes32[] _groups) {
uint _groupsCount = groupsCount;
_groups = new bytes32[](_groupsCount);
for (uint _groupIdx = 0; _groupIdx < _groupsCount; ++_groupIdx) {
_groups[_groupIdx] = index2groupName[_groupIdx + 1];
}
}
// PRIVATE
function _removeGroupFromMember(address _user, bytes32 _groupName) private {
Member storage _member = address2member[_user];
uint _memberGroupsCount = _member.groupsCount;
uint _memberGroupIndex = _member.groupName2index[_groupName];
if (_memberGroupIndex != _memberGroupsCount) {
uint _lastGroupGlobalIndex = _member.index2globalIndex[_memberGroupsCount];
bytes32 _lastGroupName = index2groupName[_lastGroupGlobalIndex];
_member.index2globalIndex[_memberGroupIndex] = _lastGroupGlobalIndex;
_member.groupName2index[_lastGroupName] = _memberGroupIndex;
}
delete _member.groupName2index[_groupName];
delete _member.index2globalIndex[_memberGroupsCount];
_member.groupsCount = _memberGroupsCount.sub(1);
}
function _addGroupToMember(address _user, bytes32 _groupName) private {
Member storage _member = address2member[_user];
uint _memberGroupsCount = _member.groupsCount.add(1);
_member.groupName2index[_groupName] = _memberGroupsCount;
_member.index2globalIndex[_memberGroupsCount] = groupName2index[_groupName];
_member.groupsCount = _memberGroupsCount;
}
}
contract PendingManagerEmitter {
event PolicyRuleAdded(bytes4 sig, address contractAddress, bytes32 key, bytes32 groupName, uint acceptLimit, uint declinesLimit);
event PolicyRuleRemoved(bytes4 sig, address contractAddress, bytes32 key, bytes32 groupName);
event ProtectionTxAdded(bytes32 key, bytes32 sig, uint blockNumber);
event ProtectionTxAccepted(bytes32 key, address indexed sender, bytes32 groupNameVoted);
event ProtectionTxDone(bytes32 key);
event ProtectionTxDeclined(bytes32 key, address indexed sender, bytes32 groupNameVoted);
event ProtectionTxCancelled(bytes32 key);
event ProtectionTxVoteRevoked(bytes32 key, address indexed sender, bytes32 groupNameVoted);
event TxDeleted(bytes32 key);
event Error(uint errorCode);
function _emitError(uint _errorCode) internal returns (uint) {
Error(_errorCode);
return _errorCode;
}
}
contract PendingManagerInterface {
function signIn(address _contract) external returns (uint);
function signOut(address _contract) external returns (uint);
function addPolicyRule(
bytes4 _sig,
address _contract,
bytes32 _groupName,
uint _acceptLimit,
uint _declineLimit
)
external returns (uint);
function removePolicyRule(
bytes4 _sig,
address _contract,
bytes32 _groupName
)
external returns (uint);
function addTx(bytes32 _key, bytes4 _sig, address _contract) external returns (uint);
function deleteTx(bytes32 _key) external returns (uint);
function accept(bytes32 _key, bytes32 _votingGroupName) external returns (uint);
function decline(bytes32 _key, bytes32 _votingGroupName) external returns (uint);
function revoke(bytes32 _key) external returns (uint);
function hasConfirmedRecord(bytes32 _key) public view returns (uint);
function getPolicyDetails(bytes4 _sig, address _contract) public view returns (
bytes32[] _groupNames,
uint[] _acceptLimits,
uint[] _declineLimits,
uint _totalAcceptedLimit,
uint _totalDeclinedLimit
);
}
/// @title PendingManager
///
/// Base implementation
/// This contract serves as pending manager for transaction status
contract PendingManager is Object, PendingManagerEmitter, PendingManagerInterface {
uint constant NO_RECORDS_WERE_FOUND = 4;
uint constant PENDING_MANAGER_SCOPE = 4000;
uint constant PENDING_MANAGER_INVALID_INVOCATION = PENDING_MANAGER_SCOPE + 1;
uint constant PENDING_MANAGER_HASNT_VOTED = PENDING_MANAGER_SCOPE + 2;
uint constant PENDING_DUPLICATE_TX = PENDING_MANAGER_SCOPE + 3;
uint constant PENDING_MANAGER_CONFIRMED = PENDING_MANAGER_SCOPE + 4;
uint constant PENDING_MANAGER_REJECTED = PENDING_MANAGER_SCOPE + 5;
uint constant PENDING_MANAGER_IN_PROCESS = PENDING_MANAGER_SCOPE + 6;
uint constant PENDING_MANAGER_TX_DOESNT_EXIST = PENDING_MANAGER_SCOPE + 7;
uint constant PENDING_MANAGER_TX_WAS_DECLINED = PENDING_MANAGER_SCOPE + 8;
uint constant PENDING_MANAGER_TX_WAS_NOT_CONFIRMED = PENDING_MANAGER_SCOPE + 9;
uint constant PENDING_MANAGER_INSUFFICIENT_GAS = PENDING_MANAGER_SCOPE + 10;
uint constant PENDING_MANAGER_POLICY_NOT_FOUND = PENDING_MANAGER_SCOPE + 11;
using SafeMath for uint;
enum GuardState {
Decline, Confirmed, InProcess
}
struct Requirements {
bytes32 groupName;
uint acceptLimit;
uint declineLimit;
}
struct Policy {
uint groupsCount;
mapping(uint => Requirements) participatedGroups; // index => globalGroupIndex
mapping(bytes32 => uint) groupName2index; // groupName => localIndex
uint totalAcceptedLimit;
uint totalDeclinedLimit;
uint securesCount;
mapping(uint => uint) index2txIndex;
mapping(uint => uint) txIndex2index;
}
struct Vote {
bytes32 groupName;
bool accepted;
}
struct Guard {
GuardState state;
uint basePolicyIndex;
uint alreadyAccepted;
uint alreadyDeclined;
mapping(address => Vote) votes; // member address => vote
mapping(bytes32 => uint) acceptedCount; // groupName => how many from group has already accepted
mapping(bytes32 => uint) declinedCount; // groupName => how many from group has already declined
}
address public accessManager;
mapping(address => bool) public authorized;
uint public policiesCount;
mapping(uint => bytes32) index2PolicyId; // index => policy hash
mapping(bytes32 => uint) policyId2Index; // policy hash => index
mapping(bytes32 => Policy) policyId2policy; // policy hash => policy struct
uint public txCount;
mapping(uint => bytes32) index2txKey;
mapping(bytes32 => uint) txKey2index; // tx key => index
mapping(bytes32 => Guard) txKey2guard;
/// @dev Execution is allowed only by authorized contract
modifier onlyAuthorized {
if (authorized[msg.sender] || address(this) == msg.sender) {
_;
}
}
/// @dev Pending Manager's constructor
///
/// @param _accessManager access manager's address
function PendingManager(address _accessManager) public {
require(_accessManager != 0x0);
accessManager = _accessManager;
}
function() payable public {
revert();
}
/// @notice Update access manager address
///
/// @param _accessManager access manager's address
function setAccessManager(address _accessManager) external onlyContractOwner returns (uint) {
require(_accessManager != 0x0);
accessManager = _accessManager;
return OK;
}
/// @notice Sign in contract
///
/// @param _contract contract's address
function signIn(address _contract) external onlyContractOwner returns (uint) {
require(_contract != 0x0);
authorized[_contract] = true;
return OK;
}
/// @notice Sign out contract
///
/// @param _contract contract's address
function signOut(address _contract) external onlyContractOwner returns (uint) {
require(_contract != 0x0);
delete authorized[_contract];
return OK;
}
/// @notice Register new policy rule
/// Can be called only by contract owner
///
/// @param _sig target method signature
/// @param _contract target contract address
/// @param _groupName group's name
/// @param _acceptLimit accepted vote limit
/// @param _declineLimit decline vote limit
///
/// @return code
function addPolicyRule(
bytes4 _sig,
address _contract,
bytes32 _groupName,
uint _acceptLimit,
uint _declineLimit
)
onlyContractOwner
external
returns (uint)
{
require(_sig != 0x0);
require(_contract != 0x0);
require(GroupsAccessManager(accessManager).isGroupExists(_groupName));
require(_acceptLimit != 0);
require(_declineLimit != 0);
bytes32 _policyHash = keccak256(_sig, _contract);
if (policyId2Index[_policyHash] == 0) {
uint _policiesCount = policiesCount.add(1);
index2PolicyId[_policiesCount] = _policyHash;
policyId2Index[_policyHash] = _policiesCount;
policiesCount = _policiesCount;
}
Policy storage _policy = policyId2policy[_policyHash];
uint _policyGroupsCount = _policy.groupsCount;
if (_policy.groupName2index[_groupName] == 0) {
_policyGroupsCount += 1;
_policy.groupName2index[_groupName] = _policyGroupsCount;
_policy.participatedGroups[_policyGroupsCount].groupName = _groupName;
_policy.groupsCount = _policyGroupsCount;
}
uint _previousAcceptLimit = _policy.participatedGroups[_policyGroupsCount].acceptLimit;
uint _previousDeclineLimit = _policy.participatedGroups[_policyGroupsCount].declineLimit;
_policy.participatedGroups[_policyGroupsCount].acceptLimit = _acceptLimit;
_policy.participatedGroups[_policyGroupsCount].declineLimit = _declineLimit;
_policy.totalAcceptedLimit = _policy.totalAcceptedLimit.sub(_previousAcceptLimit).add(_acceptLimit);
_policy.totalDeclinedLimit = _policy.totalDeclinedLimit.sub(_previousDeclineLimit).add(_declineLimit);
PolicyRuleAdded(_sig, _contract, _policyHash, _groupName, _acceptLimit, _declineLimit);
return OK;
}
/// @notice Remove policy rule
/// Can be called only by contract owner
///
/// @param _groupName group's name
///
/// @return code
function removePolicyRule(
bytes4 _sig,
address _contract,
bytes32 _groupName
)
onlyContractOwner
external
returns (uint)
{
require(_sig != bytes4(0));
require(_contract != 0x0);
require(GroupsAccessManager(accessManager).isGroupExists(_groupName));
bytes32 _policyHash = keccak256(_sig, _contract);
Policy storage _policy = policyId2policy[_policyHash];
uint _policyGroupNameIndex = _policy.groupName2index[_groupName];
if (_policyGroupNameIndex == 0) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
uint _policyGroupsCount = _policy.groupsCount;
if (_policyGroupNameIndex != _policyGroupsCount) {
Requirements storage _requirements = _policy.participatedGroups[_policyGroupsCount];
_policy.participatedGroups[_policyGroupNameIndex] = _requirements;
_policy.groupName2index[_requirements.groupName] = _policyGroupNameIndex;
}
_policy.totalAcceptedLimit = _policy.totalAcceptedLimit.sub(_policy.participatedGroups[_policyGroupsCount].acceptLimit);
_policy.totalDeclinedLimit = _policy.totalDeclinedLimit.sub(_policy.participatedGroups[_policyGroupsCount].declineLimit);
delete _policy.groupName2index[_groupName];
delete _policy.participatedGroups[_policyGroupsCount];
_policy.groupsCount = _policyGroupsCount.sub(1);
PolicyRuleRemoved(_sig, _contract, _policyHash, _groupName);
return OK;
}
/// @notice Add transaction
///
/// @param _key transaction id
///
/// @return code
function addTx(bytes32 _key, bytes4 _sig, address _contract) external onlyAuthorized returns (uint) {
require(_key != bytes32(0));
require(_sig != bytes4(0));
require(_contract != 0x0);
bytes32 _policyHash = keccak256(_sig, _contract);
require(isPolicyExist(_policyHash));
if (isTxExist(_key)) {
return _emitError(PENDING_DUPLICATE_TX);
}
if (_policyHash == bytes32(0)) {
return _emitError(PENDING_MANAGER_POLICY_NOT_FOUND);
}
uint _index = txCount.add(1);
txCount = _index;
index2txKey[_index] = _key;
txKey2index[_key] = _index;
Guard storage _guard = txKey2guard[_key];
_guard.basePolicyIndex = policyId2Index[_policyHash];
_guard.state = GuardState.InProcess;
Policy storage _policy = policyId2policy[_policyHash];
uint _counter = _policy.securesCount.add(1);
_policy.securesCount = _counter;
_policy.index2txIndex[_counter] = _index;
_policy.txIndex2index[_index] = _counter;
ProtectionTxAdded(_key, _policyHash, block.number);
return OK;
}
/// @notice Delete transaction
/// @param _key transaction id
/// @return code
function deleteTx(bytes32 _key) external onlyContractOwner returns (uint) {
require(_key != bytes32(0));
if (!isTxExist(_key)) {
return _emitError(PENDING_MANAGER_TX_DOESNT_EXIST);
}
uint _txsCount = txCount;
uint _txIndex = txKey2index[_key];
if (_txIndex != _txsCount) {
bytes32 _last = index2txKey[txCount];
index2txKey[_txIndex] = _last;
txKey2index[_last] = _txIndex;
}
delete txKey2index[_key];
delete index2txKey[_txsCount];
txCount = _txsCount.sub(1);
uint _basePolicyIndex = txKey2guard[_key].basePolicyIndex;
Policy storage _policy = policyId2policy[index2PolicyId[_basePolicyIndex]];
uint _counter = _policy.securesCount;
uint _policyTxIndex = _policy.txIndex2index[_txIndex];
if (_policyTxIndex != _counter) {
uint _movedTxIndex = _policy.index2txIndex[_counter];
_policy.index2txIndex[_policyTxIndex] = _movedTxIndex;
_policy.txIndex2index[_movedTxIndex] = _policyTxIndex;
}
delete _policy.index2txIndex[_counter];
delete _policy.txIndex2index[_txIndex];
_policy.securesCount = _counter.sub(1);
TxDeleted(_key);
return OK;
}
/// @notice Accept transaction
/// Can be called only by registered user in GroupsAccessManager
///
/// @param _key transaction id
///
/// @return code
function accept(bytes32 _key, bytes32 _votingGroupName) external returns (uint) {
if (!isTxExist(_key)) {
return _emitError(PENDING_MANAGER_TX_DOESNT_EXIST);
}
if (!GroupsAccessManager(accessManager).isUserInGroup(_votingGroupName, msg.sender)) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
Guard storage _guard = txKey2guard[_key];
if (_guard.state != GuardState.InProcess) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
if (_guard.votes[msg.sender].groupName != bytes32(0) && _guard.votes[msg.sender].accepted) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
Policy storage _policy = policyId2policy[index2PolicyId[_guard.basePolicyIndex]];
uint _policyGroupIndex = _policy.groupName2index[_votingGroupName];
uint _groupAcceptedVotesCount = _guard.acceptedCount[_votingGroupName];
if (_groupAcceptedVotesCount == _policy.participatedGroups[_policyGroupIndex].acceptLimit) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
_guard.votes[msg.sender] = Vote(_votingGroupName, true);
_guard.acceptedCount[_votingGroupName] = _groupAcceptedVotesCount + 1;
uint _alreadyAcceptedCount = _guard.alreadyAccepted + 1;
_guard.alreadyAccepted = _alreadyAcceptedCount;
ProtectionTxAccepted(_key, msg.sender, _votingGroupName);
if (_alreadyAcceptedCount == _policy.totalAcceptedLimit) {
_guard.state = GuardState.Confirmed;
ProtectionTxDone(_key);
}
return OK;
}
/// @notice Decline transaction
/// Can be called only by registered user in GroupsAccessManager
///
/// @param _key transaction id
///
/// @return code
function decline(bytes32 _key, bytes32 _votingGroupName) external returns (uint) {
if (!isTxExist(_key)) {
return _emitError(PENDING_MANAGER_TX_DOESNT_EXIST);
}
if (!GroupsAccessManager(accessManager).isUserInGroup(_votingGroupName, msg.sender)) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
Guard storage _guard = txKey2guard[_key];
if (_guard.state != GuardState.InProcess) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
if (_guard.votes[msg.sender].groupName != bytes32(0) && !_guard.votes[msg.sender].accepted) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
Policy storage _policy = policyId2policy[index2PolicyId[_guard.basePolicyIndex]];
uint _policyGroupIndex = _policy.groupName2index[_votingGroupName];
uint _groupDeclinedVotesCount = _guard.declinedCount[_votingGroupName];
if (_groupDeclinedVotesCount == _policy.participatedGroups[_policyGroupIndex].declineLimit) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
_guard.votes[msg.sender] = Vote(_votingGroupName, false);
_guard.declinedCount[_votingGroupName] = _groupDeclinedVotesCount + 1;
uint _alreadyDeclinedCount = _guard.alreadyDeclined + 1;
_guard.alreadyDeclined = _alreadyDeclinedCount;
ProtectionTxDeclined(_key, msg.sender, _votingGroupName);
if (_alreadyDeclinedCount == _policy.totalDeclinedLimit) {
_guard.state = GuardState.Decline;
ProtectionTxCancelled(_key);
}
return OK;
}
/// @notice Revoke user votes for transaction
/// Can be called only by contract owner
///
/// @param _key transaction id
/// @param _user target user address
///
/// @return code
function forceRejectVotes(bytes32 _key, address _user) external onlyContractOwner returns (uint) {
return _revoke(_key, _user);
}
/// @notice Revoke vote for transaction
/// Can be called only by authorized user
/// @param _key transaction id
/// @return code
function revoke(bytes32 _key) external returns (uint) {
return _revoke(_key, msg.sender);
}
/// @notice Check transaction status
/// @param _key transaction id
/// @return code
function hasConfirmedRecord(bytes32 _key) public view returns (uint) {
require(_key != bytes32(0));
if (!isTxExist(_key)) {
return NO_RECORDS_WERE_FOUND;
}
Guard storage _guard = txKey2guard[_key];
return _guard.state == GuardState.InProcess
? PENDING_MANAGER_IN_PROCESS
: _guard.state == GuardState.Confirmed
? OK
: PENDING_MANAGER_REJECTED;
}
/// @notice Check policy details
///
/// @return _groupNames group names included in policies
/// @return _acceptLimits accept limit for group
/// @return _declineLimits decline limit for group
function getPolicyDetails(bytes4 _sig, address _contract)
public
view
returns (
bytes32[] _groupNames,
uint[] _acceptLimits,
uint[] _declineLimits,
uint _totalAcceptedLimit,
uint _totalDeclinedLimit
) {
require(_sig != bytes4(0));
require(_contract != 0x0);
bytes32 _policyHash = keccak256(_sig, _contract);
uint _policyIdx = policyId2Index[_policyHash];
if (_policyIdx == 0) {
return;
}
Policy storage _policy = policyId2policy[_policyHash];
uint _policyGroupsCount = _policy.groupsCount;
_groupNames = new bytes32[](_policyGroupsCount);
_acceptLimits = new uint[](_policyGroupsCount);
_declineLimits = new uint[](_policyGroupsCount);
for (uint _idx = 0; _idx < _policyGroupsCount; ++_idx) {
Requirements storage _requirements = _policy.participatedGroups[_idx + 1];
_groupNames[_idx] = _requirements.groupName;
_acceptLimits[_idx] = _requirements.acceptLimit;
_declineLimits[_idx] = _requirements.declineLimit;
}
(_totalAcceptedLimit, _totalDeclinedLimit) = (_policy.totalAcceptedLimit, _policy.totalDeclinedLimit);
}
/// @notice Check policy include target group
/// @param _policyHash policy hash (sig, contract address)
/// @param _groupName group id
/// @return bool
function isGroupInPolicy(bytes32 _policyHash, bytes32 _groupName) public view returns (bool) {
Policy storage _policy = policyId2policy[_policyHash];
return _policy.groupName2index[_groupName] != 0;
}
/// @notice Check is policy exist
/// @param _policyHash policy hash (sig, contract address)
/// @return bool
function isPolicyExist(bytes32 _policyHash) public view returns (bool) {
return policyId2Index[_policyHash] != 0;
}
/// @notice Check is transaction exist
/// @param _key transaction id
/// @return bool
function isTxExist(bytes32 _key) public view returns (bool){
return txKey2index[_key] != 0;
}
function _updateTxState(Policy storage _policy, Guard storage _guard, uint confirmedAmount, uint declineAmount) private {
if (declineAmount != 0 && _guard.state != GuardState.Decline) {
_guard.state = GuardState.Decline;
} else if (confirmedAmount >= _policy.groupsCount && _guard.state != GuardState.Confirmed) {
_guard.state = GuardState.Confirmed;
} else if (_guard.state != GuardState.InProcess) {
_guard.state = GuardState.InProcess;
}
}
function _revoke(bytes32 _key, address _user) private returns (uint) {
require(_key != bytes32(0));
require(_user != 0x0);
if (!isTxExist(_key)) {
return _emitError(PENDING_MANAGER_TX_DOESNT_EXIST);
}
Guard storage _guard = txKey2guard[_key];
if (_guard.state != GuardState.InProcess) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
bytes32 _votedGroupName = _guard.votes[_user].groupName;
if (_votedGroupName == bytes32(0)) {
return _emitError(PENDING_MANAGER_HASNT_VOTED);
}
bool isAcceptedVote = _guard.votes[_user].accepted;
if (isAcceptedVote) {
_guard.acceptedCount[_votedGroupName] = _guard.acceptedCount[_votedGroupName].sub(1);
_guard.alreadyAccepted = _guard.alreadyAccepted.sub(1);
} else {
_guard.declinedCount[_votedGroupName] = _guard.declinedCount[_votedGroupName].sub(1);
_guard.alreadyDeclined = _guard.alreadyDeclined.sub(1);
}
delete _guard.votes[_user];
ProtectionTxVoteRevoked(_key, _user, _votedGroupName);
return OK;
}
}
/// @title MultiSigAdapter
///
/// Abstract implementation
/// This contract serves as transaction signer
contract MultiSigAdapter is Object {
uint constant MULTISIG_ADDED = 3;
uint constant NO_RECORDS_WERE_FOUND = 4;
modifier isAuthorized {
if (msg.sender == contractOwner || msg.sender == getPendingManager()) {
_;
}
}
/// @notice Get pending address
/// @dev abstract. Needs child implementation
///
/// @return pending address
function getPendingManager() public view returns (address);
/// @notice Sign current transaction and add it to transaction pending queue
///
/// @return code
function _multisig(bytes32 _args, uint _block) internal returns (uint _code) {
bytes32 _txHash = _getKey(_args, _block);
address _manager = getPendingManager();
_code = PendingManager(_manager).hasConfirmedRecord(_txHash);
if (_code != NO_RECORDS_WERE_FOUND) {
return _code;
}
if (OK != PendingManager(_manager).addTx(_txHash, msg.sig, address(this))) {
revert();
}
return MULTISIG_ADDED;
}
function _isTxExistWithArgs(bytes32 _args, uint _block) internal view returns (bool) {
bytes32 _txHash = _getKey(_args, _block);
address _manager = getPendingManager();
return PendingManager(_manager).isTxExist(_txHash);
}
function _getKey(bytes32 _args, uint _block) private view returns (bytes32 _txHash) {
_block = _block != 0 ? _block : block.number;
_txHash = keccak256(msg.sig, _args, _block);
}
}
/// @title ServiceController
///
/// Base implementation
/// Serves for managing service instances
contract ServiceController is MultiSigAdapter {
event Error(uint _errorCode);
uint constant SERVICE_CONTROLLER = 350000;
uint constant SERVICE_CONTROLLER_EMISSION_EXIST = SERVICE_CONTROLLER + 1;
uint constant SERVICE_CONTROLLER_BURNING_MAN_EXIST = SERVICE_CONTROLLER + 2;
uint constant SERVICE_CONTROLLER_ALREADY_INITIALIZED = SERVICE_CONTROLLER + 3;
uint constant SERVICE_CONTROLLER_SERVICE_EXIST = SERVICE_CONTROLLER + 4;
address public profiterole;
address public treasury;
address public pendingManager;
address public proxy;
uint public sideServicesCount;
mapping(uint => address) public index2sideService;
mapping(address => uint) public sideService2index;
mapping(address => bool) public sideServices;
uint public emissionProvidersCount;
mapping(uint => address) public index2emissionProvider;
mapping(address => uint) public emissionProvider2index;
mapping(address => bool) public emissionProviders;
uint public burningMansCount;
mapping(uint => address) public index2burningMan;
mapping(address => uint) public burningMan2index;
mapping(address => bool) public burningMans;
/// @notice Default ServiceController's constructor
///
/// @param _pendingManager pending manager address
/// @param _proxy ERC20 proxy address
/// @param _profiterole profiterole address
/// @param _treasury treasury address
function ServiceController(address _pendingManager, address _proxy, address _profiterole, address _treasury) public {
require(_pendingManager != 0x0);
require(_proxy != 0x0);
require(_profiterole != 0x0);
require(_treasury != 0x0);
pendingManager = _pendingManager;
proxy = _proxy;
profiterole = _profiterole;
treasury = _treasury;
}
/// @notice Return pending manager address
///
/// @return code
function getPendingManager() public view returns (address) {
return pendingManager;
}
/// @notice Add emission provider
///
/// @param _provider emission provider address
///
/// @return code
function addEmissionProvider(address _provider, uint _block) public returns (uint _code) {
if (emissionProviders[_provider]) {
return _emitError(SERVICE_CONTROLLER_EMISSION_EXIST);
}
_code = _multisig(keccak256(_provider), _block);
if (OK != _code) {
return _code;
}
emissionProviders[_provider] = true;
uint _count = emissionProvidersCount + 1;
index2emissionProvider[_count] = _provider;
emissionProvider2index[_provider] = _count;
emissionProvidersCount = _count;
return OK;
}
/// @notice Remove emission provider
///
/// @param _provider emission provider address
///
/// @return code
function removeEmissionProvider(address _provider, uint _block) public returns (uint _code) {
_code = _multisig(keccak256(_provider), _block);
if (OK != _code) {
return _code;
}
uint _idx = emissionProvider2index[_provider];
uint _lastIdx = emissionProvidersCount;
if (_idx != 0) {
if (_idx != _lastIdx) {
address _lastEmissionProvider = index2emissionProvider[_lastIdx];
index2emissionProvider[_idx] = _lastEmissionProvider;
emissionProvider2index[_lastEmissionProvider] = _idx;
}
delete emissionProvider2index[_provider];
delete index2emissionProvider[_lastIdx];
delete emissionProviders[_provider];
emissionProvidersCount = _lastIdx - 1;
}
return OK;
}
/// @notice Add burning man
///
/// @param _burningMan burning man address
///
/// @return code
function addBurningMan(address _burningMan, uint _block) public returns (uint _code) {
if (burningMans[_burningMan]) {
return _emitError(SERVICE_CONTROLLER_BURNING_MAN_EXIST);
}
_code = _multisig(keccak256(_burningMan), _block);
if (OK != _code) {
return _code;
}
burningMans[_burningMan] = true;
uint _count = burningMansCount + 1;
index2burningMan[_count] = _burningMan;
burningMan2index[_burningMan] = _count;
burningMansCount = _count;
return OK;
}
/// @notice Remove burning man
///
/// @param _burningMan burning man address
///
/// @return code
function removeBurningMan(address _burningMan, uint _block) public returns (uint _code) {
_code = _multisig(keccak256(_burningMan), _block);
if (OK != _code) {
return _code;
}
uint _idx = burningMan2index[_burningMan];
uint _lastIdx = burningMansCount;
if (_idx != 0) {
if (_idx != _lastIdx) {
address _lastBurningMan = index2burningMan[_lastIdx];
index2burningMan[_idx] = _lastBurningMan;
burningMan2index[_lastBurningMan] = _idx;
}
delete burningMan2index[_burningMan];
delete index2burningMan[_lastIdx];
delete burningMans[_burningMan];
burningMansCount = _lastIdx - 1;
}
return OK;
}
/// @notice Update a profiterole address
///
/// @param _profiterole profiterole address
///
/// @return result code of an operation
function updateProfiterole(address _profiterole, uint _block) public returns (uint _code) {
_code = _multisig(keccak256(_profiterole), _block);
if (OK != _code) {
return _code;
}
profiterole = _profiterole;
return OK;
}
/// @notice Update a treasury address
///
/// @param _treasury treasury address
///
/// @return result code of an operation
function updateTreasury(address _treasury, uint _block) public returns (uint _code) {
_code = _multisig(keccak256(_treasury), _block);
if (OK != _code) {
return _code;
}
treasury = _treasury;
return OK;
}
/// @notice Update pending manager address
///
/// @param _pendingManager pending manager address
///
/// @return result code of an operation
function updatePendingManager(address _pendingManager, uint _block) public returns (uint _code) {
_code = _multisig(keccak256(_pendingManager), _block);
if (OK != _code) {
return _code;
}
pendingManager = _pendingManager;
return OK;
}
function addSideService(address _service, uint _block) public returns (uint _code) {
if (sideServices[_service]) {
return SERVICE_CONTROLLER_SERVICE_EXIST;
}
_code = _multisig(keccak256(_service), _block);
if (OK != _code) {
return _code;
}
sideServices[_service] = true;
uint _count = sideServicesCount + 1;
index2sideService[_count] = _service;
sideService2index[_service] = _count;
sideServicesCount = _count;
return OK;
}
function removeSideService(address _service, uint _block) public returns (uint _code) {
_code = _multisig(keccak256(_service), _block);
if (OK != _code) {
return _code;
}
uint _idx = sideService2index[_service];
uint _lastIdx = sideServicesCount;
if (_idx != 0) {
if (_idx != _lastIdx) {
address _lastSideService = index2sideService[_lastIdx];
index2sideService[_idx] = _lastSideService;
sideService2index[_lastSideService] = _idx;
}
delete sideService2index[_service];
delete index2sideService[_lastIdx];
delete sideServices[_service];
sideServicesCount = _lastIdx - 1;
}
return OK;
}
function getEmissionProviders()
public
view
returns (address[] _emissionProviders)
{
_emissionProviders = new address[](emissionProvidersCount);
for (uint _idx = 0; _idx < _emissionProviders.length; ++_idx) {
_emissionProviders[_idx] = index2emissionProvider[_idx + 1];
}
}
function getBurningMans()
public
view
returns (address[] _burningMans)
{
_burningMans = new address[](burningMansCount);
for (uint _idx = 0; _idx < _burningMans.length; ++_idx) {
_burningMans[_idx] = index2burningMan[_idx + 1];
}
}
function getSideServices()
public
view
returns (address[] _sideServices)
{
_sideServices = new address[](sideServicesCount);
for (uint _idx = 0; _idx < _sideServices.length; ++_idx) {
_sideServices[_idx] = index2sideService[_idx + 1];
}
}
/// @notice Check target address is service
///
/// @param _address target address
///
/// @return `true` when an address is a service, `false` otherwise
function isService(address _address) public view returns (bool check) {
return _address == profiterole ||
_address == treasury ||
_address == proxy ||
_address == pendingManager ||
emissionProviders[_address] ||
burningMans[_address] ||
sideServices[_address];
}
function _emitError(uint _errorCode) internal returns (uint) {
Error(_errorCode);
return _errorCode;
}
}
contract OracleMethodAdapter is Object {
event OracleAdded(bytes4 _sig, address _oracle);
event OracleRemoved(bytes4 _sig, address _oracle);
mapping(bytes4 => mapping(address => bool)) public oracles;
/// @dev Allow access only for oracle
modifier onlyOracle {
if (oracles[msg.sig][msg.sender]) {
_;
}
}
modifier onlyOracleOrOwner {
if (oracles[msg.sig][msg.sender] || msg.sender == contractOwner) {
_;
}
}
function addOracles(
bytes4[] _signatures,
address[] _oracles
)
onlyContractOwner
external
returns (uint)
{
require(_signatures.length == _oracles.length);
bytes4 _sig;
address _oracle;
for (uint _idx = 0; _idx < _signatures.length; ++_idx) {
(_sig, _oracle) = (_signatures[_idx], _oracles[_idx]);
if (_oracle != 0x0
&& _sig != bytes4(0)
&& !oracles[_sig][_oracle]
) {
oracles[_sig][_oracle] = true;
_emitOracleAdded(_sig, _oracle);
}
}
return OK;
}
function removeOracles(
bytes4[] _signatures,
address[] _oracles
)
onlyContractOwner
external
returns (uint)
{
require(_signatures.length == _oracles.length);
bytes4 _sig;
address _oracle;
for (uint _idx = 0; _idx < _signatures.length; ++_idx) {
(_sig, _oracle) = (_signatures[_idx], _oracles[_idx]);
if (_oracle != 0x0
&& _sig != bytes4(0)
&& oracles[_sig][_oracle]
) {
delete oracles[_sig][_oracle];
_emitOracleRemoved(_sig, _oracle);
}
}
return OK;
}
function _emitOracleAdded(bytes4 _sig, address _oracle) internal {
OracleAdded(_sig, _oracle);
}
function _emitOracleRemoved(bytes4 _sig, address _oracle) internal {
OracleRemoved(_sig, _oracle);
}
}
contract Platform {
mapping(bytes32 => address) public proxies;
function name(bytes32 _symbol) public view returns (string);
function setProxy(address _address, bytes32 _symbol) public returns (uint errorCode);
function isOwner(address _owner, bytes32 _symbol) public view returns (bool);
function totalSupply(bytes32 _symbol) public view returns (uint);
function balanceOf(address _holder, bytes32 _symbol) public view returns (uint);
function allowance(address _from, address _spender, bytes32 _symbol) public view returns (uint);
function baseUnit(bytes32 _symbol) public view returns (uint8);
function proxyTransferWithReference(address _to, uint _value, bytes32 _symbol, string _reference, address _sender) public returns (uint errorCode);
function proxyTransferFromWithReference(address _from, address _to, uint _value, bytes32 _symbol, string _reference, address _sender) public returns (uint errorCode);
function proxyApprove(address _spender, uint _value, bytes32 _symbol, address _sender) public returns (uint errorCode);
function issueAsset(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable) public returns (uint errorCode);
function reissueAsset(bytes32 _symbol, uint _value) public returns (uint errorCode);
function revokeAsset(bytes32 _symbol, uint _value) public returns (uint errorCode);
function isReissuable(bytes32 _symbol) public view returns (bool);
function changeOwnership(bytes32 _symbol, address _newOwner) public returns (uint errorCode);
}
contract ATxAssetProxy is ERC20, Object, ServiceAllowance {
using SafeMath for uint;
/**
* Indicates an upgrade freeze-time start, and the next asset implementation contract.
*/
event UpgradeProposal(address newVersion);
// Current asset implementation contract address.
address latestVersion;
// Assigned platform, immutable.
Platform public platform;
// Assigned symbol, immutable.
bytes32 public smbl;
// Assigned name, immutable.
string public name;
/**
* Only platform is allowed to call.
*/
modifier onlyPlatform() {
if (msg.sender == address(platform)) {
_;
}
}
/**
* Only current asset owner is allowed to call.
*/
modifier onlyAssetOwner() {
if (platform.isOwner(msg.sender, smbl)) {
_;
}
}
/**
* Only asset implementation contract assigned to sender is allowed to call.
*/
modifier onlyAccess(address _sender) {
if (getLatestVersion() == msg.sender) {
_;
}
}
/**
* Resolves asset implementation contract for the caller and forwards there transaction data,
* along with the value. This allows for proxy interface growth.
*/
function() public payable {
_getAsset().__process.value(msg.value)(msg.data, msg.sender);
}
/**
* Sets platform address, assigns symbol and name.
*
* Can be set only once.
*
* @param _platform platform contract address.
* @param _symbol assigned symbol.
* @param _name assigned name.
*
* @return success.
*/
function init(Platform _platform, string _symbol, string _name) public returns (bool) {
if (address(platform) != 0x0) {
return false;
}
platform = _platform;
symbol = _symbol;
smbl = stringToBytes32(_symbol);
name = _name;
return true;
}
/**
* Returns asset total supply.
*
* @return asset total supply.
*/
function totalSupply() public view returns (uint) {
return platform.totalSupply(smbl);
}
/**
* Returns asset balance for a particular holder.
*
* @param _owner holder address.
*
* @return holder balance.
*/
function balanceOf(address _owner) public view returns (uint) {
return platform.balanceOf(_owner, smbl);
}
/**
* Returns asset allowance from one holder to another.
*
* @param _from holder that allowed spending.
* @param _spender holder that is allowed to spend.
*
* @return holder to spender allowance.
*/
function allowance(address _from, address _spender) public view returns (uint) {
return platform.allowance(_from, _spender, smbl);
}
/**
* Returns asset decimals.
*
* @return asset decimals.
*/
function decimals() public view returns (uint8) {
return platform.baseUnit(smbl);
}
/**
* Transfers asset balance from the caller to specified receiver.
*
* @param _to holder address to give to.
* @param _value amount to transfer.
*
* @return success.
*/
function transfer(address _to, uint _value) public returns (bool) {
if (_to != 0x0) {
return _transferWithReference(_to, _value, "");
}
else {
return false;
}
}
/**
* Transfers asset balance from the caller to specified receiver adding specified comment.
*
* @param _to holder address to give to.
* @param _value amount to transfer.
* @param _reference transfer comment to be included in a platform's Transfer event.
*
* @return success.
*/
function transferWithReference(address _to, uint _value, string _reference) public returns (bool) {
if (_to != 0x0) {
return _transferWithReference(_to, _value, _reference);
}
else {
return false;
}
}
/**
* Performs transfer call on the platform by the name of specified sender.
*
* Can only be called by asset implementation contract assigned to sender.
*
* @param _to holder address to give to.
* @param _value amount to transfer.
* @param _reference transfer comment to be included in a platform's Transfer event.
* @param _sender initial caller.
*
* @return success.
*/
function __transferWithReference(address _to, uint _value, string _reference, address _sender) public onlyAccess(_sender) returns (bool) {
return platform.proxyTransferWithReference(_to, _value, smbl, _reference, _sender) == OK;
}
/**
* Prforms allowance transfer of asset balance between holders.
*
* @param _from holder address to take from.
* @param _to holder address to give to.
* @param _value amount to transfer.
*
* @return success.
*/
function transferFrom(address _from, address _to, uint _value) public returns (bool) {
if (_to != 0x0) {
return _getAsset().__transferFromWithReference(_from, _to, _value, "", msg.sender);
}
else {
return false;
}
}
/**
* Performs allowance transfer call on the platform by the name of specified sender.
*
* Can only be called by asset implementation contract assigned to sender.
*
* @param _from holder address to take from.
* @param _to holder address to give to.
* @param _value amount to transfer.
* @param _reference transfer comment to be included in a platform's Transfer event.
* @param _sender initial caller.
*
* @return success.
*/
function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) public onlyAccess(_sender) returns (bool) {
return platform.proxyTransferFromWithReference(_from, _to, _value, smbl, _reference, _sender) == OK;
}
/**
* Sets asset spending allowance for a specified spender.
*
* @param _spender holder address to set allowance to.
* @param _value amount to allow.
*
* @return success.
*/
function approve(address _spender, uint _value) public returns (bool) {
if (_spender != 0x0) {
return _getAsset().__approve(_spender, _value, msg.sender);
}
else {
return false;
}
}
/**
* Performs allowance setting call on the platform by the name of specified sender.
*
* Can only be called by asset implementation contract assigned to sender.
*
* @param _spender holder address to set allowance to.
* @param _value amount to allow.
* @param _sender initial caller.
*
* @return success.
*/
function __approve(address _spender, uint _value, address _sender) public onlyAccess(_sender) returns (bool) {
return platform.proxyApprove(_spender, _value, smbl, _sender) == OK;
}
/**
* Emits ERC20 Transfer event on this contract.
*
* Can only be, and, called by assigned platform when asset transfer happens.
*/
function emitTransfer(address _from, address _to, uint _value) public onlyPlatform() {
Transfer(_from, _to, _value);
}
/**
* Emits ERC20 Approval event on this contract.
*
* Can only be, and, called by assigned platform when asset allowance set happens.
*/
function emitApprove(address _from, address _spender, uint _value) public onlyPlatform() {
Approval(_from, _spender, _value);
}
/**
* Returns current asset implementation contract address.
*
* @return asset implementation contract address.
*/
function getLatestVersion() public view returns (address) {
return latestVersion;
}
/**
* Propose next asset implementation contract address.
*
* Can only be called by current asset owner.
*
* Note: freeze-time should not be applied for the initial setup.
*
* @param _newVersion asset implementation contract address.
*
* @return success.
*/
function proposeUpgrade(address _newVersion) public onlyAssetOwner returns (bool) {
// New version address should be other than 0x0.
if (_newVersion == 0x0) {
return false;
}
latestVersion = _newVersion;
UpgradeProposal(_newVersion);
return true;
}
function isTransferAllowed(address, address, address, address, uint) public view returns (bool) {
return true;
}
/**
* Returns asset implementation contract for current caller.
*
* @return asset implementation contract.
*/
function _getAsset() internal view returns (ATxAssetInterface) {
return ATxAssetInterface(getLatestVersion());
}
/**
* Resolves asset implementation contract for the caller and forwards there arguments along with
* the caller address.
*
* @return success.
*/
function _transferWithReference(address _to, uint _value, string _reference) internal returns (bool) {
return _getAsset().__transferWithReference(_to, _value, _reference, msg.sender);
}
function stringToBytes32(string memory source) private pure returns (bytes32 result) {
assembly {
result := mload(add(source, 32))
}
}
}
contract DataControllerEmitter {
event CountryCodeAdded(uint _countryCode, uint _countryId, uint _maxHolderCount);
event CountryCodeChanged(uint _countryCode, uint _countryId, uint _maxHolderCount);
event HolderRegistered(bytes32 _externalHolderId, uint _accessIndex, uint _countryCode);
event HolderAddressAdded(bytes32 _externalHolderId, address _holderPrototype, uint _accessIndex);
event HolderAddressRemoved(bytes32 _externalHolderId, address _holderPrototype, uint _accessIndex);
event HolderOperationalChanged(bytes32 _externalHolderId, bool _operational);
event DayLimitChanged(bytes32 _externalHolderId, uint _from, uint _to);
event MonthLimitChanged(bytes32 _externalHolderId, uint _from, uint _to);
event Error(uint _errorCode);
function _emitHolderAddressAdded(bytes32 _externalHolderId, address _holderPrototype, uint _accessIndex) internal {
HolderAddressAdded(_externalHolderId, _holderPrototype, _accessIndex);
}
function _emitHolderAddressRemoved(bytes32 _externalHolderId, address _holderPrototype, uint _accessIndex) internal {
HolderAddressRemoved(_externalHolderId, _holderPrototype, _accessIndex);
}
function _emitHolderRegistered(bytes32 _externalHolderId, uint _accessIndex, uint _countryCode) internal {
HolderRegistered(_externalHolderId, _accessIndex, _countryCode);
}
function _emitHolderOperationalChanged(bytes32 _externalHolderId, bool _operational) internal {
HolderOperationalChanged(_externalHolderId, _operational);
}
function _emitCountryCodeAdded(uint _countryCode, uint _countryId, uint _maxHolderCount) internal {
CountryCodeAdded(_countryCode, _countryId, _maxHolderCount);
}
function _emitCountryCodeChanged(uint _countryCode, uint _countryId, uint _maxHolderCount) internal {
CountryCodeChanged(_countryCode, _countryId, _maxHolderCount);
}
function _emitDayLimitChanged(bytes32 _externalHolderId, uint _from, uint _to) internal {
DayLimitChanged(_externalHolderId, _from, _to);
}
function _emitMonthLimitChanged(bytes32 _externalHolderId, uint _from, uint _to) internal {
MonthLimitChanged(_externalHolderId, _from, _to);
}
function _emitError(uint _errorCode) internal returns (uint) {
Error(_errorCode);
return _errorCode;
}
}
/// @title Provides possibility manage holders? country limits and limits for holders.
contract DataController is OracleMethodAdapter, DataControllerEmitter {
/* CONSTANTS */
uint constant DATA_CONTROLLER = 109000;
uint constant DATA_CONTROLLER_ERROR = DATA_CONTROLLER + 1;
uint constant DATA_CONTROLLER_CURRENT_WRONG_LIMIT = DATA_CONTROLLER + 2;
uint constant DATA_CONTROLLER_WRONG_ALLOWANCE = DATA_CONTROLLER + 3;
uint constant DATA_CONTROLLER_COUNTRY_CODE_ALREADY_EXISTS = DATA_CONTROLLER + 4;
uint constant MAX_TOKEN_HOLDER_NUMBER = 2 ** 256 - 1;
using SafeMath for uint;
/* STRUCTS */
/// @title HoldersData couldn't be public because of internal structures, so needed to provide getters for different parts of _holderData
struct HoldersData {
uint countryCode;
uint sendLimPerDay;
uint sendLimPerMonth;
bool operational;
bytes text;
uint holderAddressCount;
mapping(uint => address) index2Address;
mapping(address => uint) address2Index;
}
struct CountryLimits {
uint countryCode;
uint maxTokenHolderNumber;
uint currentTokenHolderNumber;
}
/* FIELDS */
address public withdrawal;
address assetAddress;
address public serviceController;
mapping(address => uint) public allowance;
// Iterable mapping pattern is used for holders.
/// @dev This is an access address mapping. Many addresses may have access to a single holder.
uint public holdersCount;
mapping(uint => HoldersData) holders;
mapping(address => bytes32) holderAddress2Id;
mapping(bytes32 => uint) public holderIndex;
// This is an access address mapping. Many addresses may have access to a single holder.
uint public countriesCount;
mapping(uint => CountryLimits) countryLimitsList;
mapping(uint => uint) countryIndex;
/* MODIFIERS */
modifier onlyWithdrawal {
if (msg.sender != withdrawal) {
revert();
}
_;
}
modifier onlyAsset {
if (msg.sender == _getATxToken().getLatestVersion()) {
_;
}
}
modifier onlyContractOwner {
if (msg.sender == contractOwner) {
_;
}
}
/// @notice Constructor for _holderData controller.
/// @param _serviceController service controller
function DataController(address _serviceController) public {
require(_serviceController != 0x0);
serviceController = _serviceController;
}
function() payable public {
revert();
}
function setWithdraw(address _withdrawal) onlyContractOwner external returns (uint) {
require(_withdrawal != 0x0);
withdrawal = _withdrawal;
return OK;
}
function setServiceController(address _serviceController)
onlyContractOwner
external
returns (uint)
{
require(_serviceController != 0x0);
serviceController = _serviceController;
return OK;
}
function getPendingManager() public view returns (address) {
return ServiceController(serviceController).getPendingManager();
}
function getHolderInfo(bytes32 _externalHolderId) public view returns (
uint _countryCode,
uint _limPerDay,
uint _limPerMonth,
bool _operational,
bytes _text
) {
HoldersData storage _data = holders[holderIndex[_externalHolderId]];
return (_data.countryCode, _data.sendLimPerDay, _data.sendLimPerMonth, _data.operational, _data.text);
}
function getHolderAddresses(bytes32 _externalHolderId) public view returns (address[] _addresses) {
HoldersData storage _holderData = holders[holderIndex[_externalHolderId]];
uint _addressesCount = _holderData.holderAddressCount;
_addresses = new address[](_addressesCount);
for (uint _holderAddressIdx = 0; _holderAddressIdx < _addressesCount; ++_holderAddressIdx) {
_addresses[_holderAddressIdx] = _holderData.index2Address[_holderAddressIdx + 1];
}
}
function getHolderCountryCode(bytes32 _externalHolderId) public view returns (uint) {
return holders[holderIndex[_externalHolderId]].countryCode;
}
function getHolderExternalIdByAddress(address _address) public view returns (bytes32) {
return holderAddress2Id[_address];
}
/// @notice Checks user is holder.
/// @param _address checking address.
/// @return `true` if _address is registered holder, `false` otherwise.
function isRegisteredAddress(address _address) public view returns (bool) {
return holderIndex[holderAddress2Id[_address]] != 0;
}
function isHolderOwnAddress(
bytes32 _externalHolderId,
address _address
)
public
view
returns (bool)
{
uint _holderIndex = holderIndex[_externalHolderId];
if (_holderIndex == 0) {
return false;
}
return holders[_holderIndex].address2Index[_address] != 0;
}
function getCountryInfo(uint _countryCode)
public
view
returns (
uint _maxHolderNumber,
uint _currentHolderCount
) {
CountryLimits storage _data = countryLimitsList[countryIndex[_countryCode]];
return (_data.maxTokenHolderNumber, _data.currentTokenHolderNumber);
}
function getCountryLimit(uint _countryCode) public view returns (uint limit) {
uint _index = countryIndex[_countryCode];
require(_index != 0);
return countryLimitsList[_index].maxTokenHolderNumber;
}
function addCountryCode(uint _countryCode) onlyContractOwner public returns (uint) {
var (,_created) = _createCountryId(_countryCode);
if (!_created) {
return _emitError(DATA_CONTROLLER_COUNTRY_CODE_ALREADY_EXISTS);
}
return OK;
}
/// @notice Returns holder id for the specified address, creates it if needed.
/// @param _externalHolderId holder address.
/// @param _countryCode country code.
/// @return error code.
function registerHolder(
bytes32 _externalHolderId,
address _holderAddress,
uint _countryCode
)
onlyOracleOrOwner
external
returns (uint)
{
require(_holderAddress != 0x0);
require(holderIndex[_externalHolderId] == 0);
uint _holderIndex = holderIndex[holderAddress2Id[_holderAddress]];
require(_holderIndex == 0);
_createCountryId(_countryCode);
_holderIndex = holdersCount.add(1);
holdersCount = _holderIndex;
HoldersData storage _holderData = holders[_holderIndex];
_holderData.countryCode = _countryCode;
_holderData.operational = true;
_holderData.sendLimPerDay = MAX_TOKEN_HOLDER_NUMBER;
_holderData.sendLimPerMonth = MAX_TOKEN_HOLDER_NUMBER;
uint _firstAddressIndex = 1;
_holderData.holderAddressCount = _firstAddressIndex;
_holderData.address2Index[_holderAddress] = _firstAddressIndex;
_holderData.index2Address[_firstAddressIndex] = _holderAddress;
holderIndex[_externalHolderId] = _holderIndex;
holderAddress2Id[_holderAddress] = _externalHolderId;
_emitHolderRegistered(_externalHolderId, _holderIndex, _countryCode);
return OK;
}
/// @notice Adds new address equivalent to holder.
/// @param _externalHolderId external holder identifier.
/// @param _newAddress adding address.
/// @return error code.
function addHolderAddress(
bytes32 _externalHolderId,
address _newAddress
)
onlyOracleOrOwner
external
returns (uint)
{
uint _holderIndex = holderIndex[_externalHolderId];
require(_holderIndex != 0);
uint _newAddressId = holderIndex[holderAddress2Id[_newAddress]];
require(_newAddressId == 0);
HoldersData storage _holderData = holders[_holderIndex];
if (_holderData.address2Index[_newAddress] == 0) {
_holderData.holderAddressCount = _holderData.holderAddressCount.add(1);
_holderData.address2Index[_newAddress] = _holderData.holderAddressCount;
_holderData.index2Address[_holderData.holderAddressCount] = _newAddress;
}
holderAddress2Id[_newAddress] = _externalHolderId;
_emitHolderAddressAdded(_externalHolderId, _newAddress, _holderIndex);
return OK;
}
/// @notice Remove an address owned by a holder.
/// @param _externalHolderId external holder identifier.
/// @param _address removing address.
/// @return error code.
function removeHolderAddress(
bytes32 _externalHolderId,
address _address
)
onlyOracleOrOwner
external
returns (uint)
{
uint _holderIndex = holderIndex[_externalHolderId];
require(_holderIndex != 0);
HoldersData storage _holderData = holders[_holderIndex];
uint _tempIndex = _holderData.address2Index[_address];
require(_tempIndex != 0);
address _lastAddress = _holderData.index2Address[_holderData.holderAddressCount];
_holderData.address2Index[_lastAddress] = _tempIndex;
_holderData.index2Address[_tempIndex] = _lastAddress;
delete _holderData.address2Index[_address];
_holderData.holderAddressCount = _holderData.holderAddressCount.sub(1);
delete holderAddress2Id[_address];
_emitHolderAddressRemoved(_externalHolderId, _address, _holderIndex);
return OK;
}
/// @notice Change operational status for holder.
/// Can be accessed by contract owner or oracle only.
///
/// @param _externalHolderId external holder identifier.
/// @param _operational operational status.
///
/// @return result code.
function changeOperational(
bytes32 _externalHolderId,
bool _operational
)
onlyOracleOrOwner
external
returns (uint)
{
uint _holderIndex = holderIndex[_externalHolderId];
require(_holderIndex != 0);
holders[_holderIndex].operational = _operational;
_emitHolderOperationalChanged(_externalHolderId, _operational);
return OK;
}
/// @notice Changes text for holder.
/// Can be accessed by contract owner or oracle only.
///
/// @param _externalHolderId external holder identifier.
/// @param _text changing text.
///
/// @return result code.
function updateTextForHolder(
bytes32 _externalHolderId,
bytes _text
)
onlyOracleOrOwner
external
returns (uint)
{
uint _holderIndex = holderIndex[_externalHolderId];
require(_holderIndex != 0);
holders[_holderIndex].text = _text;
return OK;
}
/// @notice Updates limit per day for holder.
///
/// Can be accessed by contract owner only.
///
/// @param _externalHolderId external holder identifier.
/// @param _limit limit value.
///
/// @return result code.
function updateLimitPerDay(
bytes32 _externalHolderId,
uint _limit
)
onlyOracleOrOwner
external
returns (uint)
{
uint _holderIndex = holderIndex[_externalHolderId];
require(_holderIndex != 0);
uint _currentLimit = holders[_holderIndex].sendLimPerDay;
holders[_holderIndex].sendLimPerDay = _limit;
_emitDayLimitChanged(_externalHolderId, _currentLimit, _limit);
return OK;
}
/// @notice Updates limit per month for holder.
/// Can be accessed by contract owner or oracle only.
///
/// @param _externalHolderId external holder identifier.
/// @param _limit limit value.
///
/// @return result code.
function updateLimitPerMonth(
bytes32 _externalHolderId,
uint _limit
)
onlyOracleOrOwner
external
returns (uint)
{
uint _holderIndex = holderIndex[_externalHolderId];
require(_holderIndex != 0);
uint _currentLimit = holders[_holderIndex].sendLimPerDay;
holders[_holderIndex].sendLimPerMonth = _limit;
_emitMonthLimitChanged(_externalHolderId, _currentLimit, _limit);
return OK;
}
/// @notice Change country limits.
/// Can be accessed by contract owner or oracle only.
///
/// @param _countryCode country code.
/// @param _limit limit value.
///
/// @return result code.
function changeCountryLimit(
uint _countryCode,
uint _limit
)
onlyOracleOrOwner
external
returns (uint)
{
uint _countryIndex = countryIndex[_countryCode];
require(_countryIndex != 0);
uint _currentTokenHolderNumber = countryLimitsList[_countryIndex].currentTokenHolderNumber;
if (_currentTokenHolderNumber > _limit) {
return _emitError(DATA_CONTROLLER_CURRENT_WRONG_LIMIT);
}
countryLimitsList[_countryIndex].maxTokenHolderNumber = _limit;
_emitCountryCodeChanged(_countryIndex, _countryCode, _limit);
return OK;
}
function withdrawFrom(
address _holderAddress,
uint _value
)
onlyAsset
public
returns (uint)
{
bytes32 _externalHolderId = holderAddress2Id[_holderAddress];
HoldersData storage _holderData = holders[holderIndex[_externalHolderId]];
_holderData.sendLimPerDay = _holderData.sendLimPerDay.sub(_value);
_holderData.sendLimPerMonth = _holderData.sendLimPerMonth.sub(_value);
return OK;
}
function depositTo(
address _holderAddress,
uint _value
)
onlyAsset
public
returns (uint)
{
bytes32 _externalHolderId = holderAddress2Id[_holderAddress];
HoldersData storage _holderData = holders[holderIndex[_externalHolderId]];
_holderData.sendLimPerDay = _holderData.sendLimPerDay.add(_value);
_holderData.sendLimPerMonth = _holderData.sendLimPerMonth.add(_value);
return OK;
}
function updateCountryHoldersCount(
uint _countryCode,
uint _updatedHolderCount
)
public
onlyAsset
returns (uint)
{
CountryLimits storage _data = countryLimitsList[countryIndex[_countryCode]];
assert(_data.maxTokenHolderNumber >= _updatedHolderCount);
_data.currentTokenHolderNumber = _updatedHolderCount;
return OK;
}
function changeAllowance(address _from, uint _value) public onlyWithdrawal returns (uint) {
ATxAssetProxy token = _getATxToken();
if (token.balanceOf(_from) < _value) {
return _emitError(DATA_CONTROLLER_WRONG_ALLOWANCE);
}
allowance[_from] = _value;
return OK;
}
function _createCountryId(uint _countryCode) internal returns (uint, bool _created) {
uint countryId = countryIndex[_countryCode];
if (countryId == 0) {
uint _countriesCount = countriesCount;
countryId = _countriesCount.add(1);
countriesCount = countryId;
CountryLimits storage limits = countryLimitsList[countryId];
limits.countryCode = _countryCode;
limits.maxTokenHolderNumber = MAX_TOKEN_HOLDER_NUMBER;
countryIndex[_countryCode] = countryId;
_emitCountryCodeAdded(countryIndex[_countryCode], _countryCode, MAX_TOKEN_HOLDER_NUMBER);
_created = true;
}
return (countryId, _created);
}
function _getATxToken() private view returns (ATxAssetProxy) {
ServiceController _serviceController = ServiceController(serviceController);
return ATxAssetProxy(_serviceController.proxy());
}
}
/// @title Contract that will work with ERC223 tokens.
interface ERC223ReceivingInterface {
/// @notice Standard ERC223 function that will handle incoming token transfers.
/// @param _from Token sender address.
/// @param _value Amount of tokens.
/// @param _data Transaction metadata.
function tokenFallback(address _from, uint _value, bytes _data) external;
}
contract ATxProxy is ERC20 {
bytes32 public smbl;
address public platform;
function __transferWithReference(address _to, uint _value, string _reference, address _sender) public returns (bool);
function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) public returns (bool);
function __approve(address _spender, uint _value, address _sender) public returns (bool);
function getLatestVersion() public returns (address);
function init(address _bmcPlatform, string _symbol, string _name) public;
function proposeUpgrade(address _newVersion) public;
}
/// @title ATx Asset implementation contract.
///
/// Basic asset implementation contract, without any additional logic.
/// Every other asset implementation contracts should derive from this one.
/// Receives calls from the proxy, and calls back immediately without arguments modification.
///
/// Note: all the non constant functions return false instead of throwing in case if state change
/// didn't happen yet.
contract ATxAsset is BasicAsset, Owned {
uint public constant OK = 1;
using SafeMath for uint;
enum Roles {
Holder,
Service,
Other
}
ServiceController public serviceController;
DataController public dataController;
uint public lockupDate;
/// @notice Default constructor for ATxAsset.
function ATxAsset() public {
}
function() payable public {
revert();
}
/// @notice Init function for ATxAsset.
///
/// @param _proxy - atx asset proxy.
/// @param _serviceController - service controoler.
/// @param _dataController - data controller.
/// @param _lockupDate - th lockup date.
function initAtx(
address _proxy,
address _serviceController,
address _dataController,
uint _lockupDate
)
onlyContractOwner
public
returns (bool)
{
require(_serviceController != 0x0);
require(_dataController != 0x0);
require(_proxy != 0x0);
require(_lockupDate > now || _lockupDate == 0);
if (!super.init(ATxProxy(_proxy))) {
return false;
}
serviceController = ServiceController(_serviceController);
dataController = DataController(_dataController);
lockupDate = _lockupDate;
return true;
}
/// @notice Performs transfer call on the platform by the name of specified sender.
///
/// @dev Can only be called by proxy asset.
///
/// @param _to holder address to give to.
/// @param _value amount to transfer.
/// @param _reference transfer comment to be included in a platform's Transfer event.
/// @param _sender initial caller.
///
/// @return success.
function __transferWithReference(
address _to,
uint _value,
string _reference,
address _sender
)
onlyProxy
public
returns (bool)
{
var (_fromRole, _toRole) = _getParticipantRoles(_sender, _to);
if (!_checkTransferAllowance(_to, _toRole, _value, _sender, _fromRole)) {
return false;
}
if (!_isValidCountryLimits(_to, _toRole, _value, _sender, _fromRole)) {
return false;
}
if (!super.__transferWithReference(_to, _value, _reference, _sender)) {
return false;
}
_updateTransferLimits(_to, _toRole, _value, _sender, _fromRole);
_contractFallbackERC223(_sender, _to, _value);
return true;
}
/// @notice Performs allowance transfer call on the platform by the name of specified sender.
///
/// @dev Can only be called by proxy asset.
///
/// @param _from holder address to take from.
/// @param _to holder address to give to.
/// @param _value amount to transfer.
/// @param _reference transfer comment to be included in a platform's Transfer event.
/// @param _sender initial caller.
///
/// @return success.
function __transferFromWithReference(
address _from,
address _to,
uint _value,
string _reference,
address _sender
)
public
onlyProxy
returns (bool)
{
var (_fromRole, _toRole) = _getParticipantRoles(_from, _to);
// @note Special check for operational withdraw.
bool _isTransferFromHolderToContractOwner = (_fromRole == Roles.Holder) &&
(contractOwner == _to) &&
(dataController.allowance(_from) >= _value) &&
super.__transferFromWithReference(_from, _to, _value, _reference, _sender);
if (_isTransferFromHolderToContractOwner) {
return true;
}
if (!_checkTransferAllowanceFrom(_to, _toRole, _value, _from, _fromRole, _sender)) {
return false;
}
if (!_isValidCountryLimits(_to, _toRole, _value, _from, _fromRole)) {
return false;
}
if (!super.__transferFromWithReference(_from, _to, _value, _reference, _sender)) {
return false;
}
_updateTransferLimits(_to, _toRole, _value, _from, _fromRole);
_contractFallbackERC223(_from, _to, _value);
return true;
}
/* INTERNAL */
function _contractFallbackERC223(address _from, address _to, uint _value) internal {
uint _codeLength;
assembly {
_codeLength := extcodesize(_to)
}
if (_codeLength > 0) {
ERC223ReceivingInterface _receiver = ERC223ReceivingInterface(_to);
bytes memory _empty;
_receiver.tokenFallback(_from, _value, _empty);
}
}
function _isTokenActive() internal view returns (bool) {
return now > lockupDate;
}
function _checkTransferAllowance(address _to, Roles _toRole, uint _value, address _from, Roles _fromRole) internal view returns (bool) {
if (_to == proxy) {
return false;
}
bool _canTransferFromService = _fromRole == Roles.Service && ServiceAllowance(_from).isTransferAllowed(_from, _to, _from, proxy, _value);
bool _canTransferToService = _toRole == Roles.Service && ServiceAllowance(_to).isTransferAllowed(_from, _to, _from, proxy, _value);
bool _canTransferToHolder = _toRole == Roles.Holder && _couldDepositToHolder(_to, _value);
bool _canTransferFromHolder;
if (_isTokenActive()) {
_canTransferFromHolder = _fromRole == Roles.Holder && _couldWithdrawFromHolder(_from, _value);
} else {
_canTransferFromHolder = _fromRole == Roles.Holder && _couldWithdrawFromHolder(_from, _value) && _from == contractOwner;
}
return (_canTransferFromHolder || _canTransferFromService) && (_canTransferToHolder || _canTransferToService);
}
function _checkTransferAllowanceFrom(
address _to,
Roles _toRole,
uint _value,
address _from,
Roles _fromRole,
address
)
internal
view
returns (bool)
{
return _checkTransferAllowance(_to, _toRole, _value, _from, _fromRole);
}
function _isValidWithdrawLimits(uint _sendLimPerDay, uint _sendLimPerMonth, uint _value) internal pure returns (bool) {
return !(_value > _sendLimPerDay || _value > _sendLimPerMonth);
}
function _isValidDepositCountry(
uint _value,
uint _withdrawCountryCode,
uint _withdrawBalance,
uint _countryCode,
uint _balance,
uint _currentHolderCount,
uint _maxHolderNumber
)
internal
pure
returns (bool)
{
return _isNoNeedInCountryLimitChange(_value, _withdrawCountryCode, _withdrawBalance, _countryCode, _balance, _currentHolderCount, _maxHolderNumber)
? true
: _isValidDepositCountry(_balance, _currentHolderCount, _maxHolderNumber);
}
function _isNoNeedInCountryLimitChange(
uint _value,
uint _withdrawCountryCode,
uint _withdrawBalance,
uint _countryCode,
uint _balance,
uint _currentHolderCount,
uint _maxHolderNumber
)
internal
pure
returns (bool)
{
bool _needToIncrementCountryHolderCount = _balance == 0;
bool _needToDecrementCountryHolderCount = _withdrawBalance == _value;
bool _shouldOverflowCountryHolderCount = _currentHolderCount == _maxHolderNumber;
return _withdrawCountryCode == _countryCode && _needToDecrementCountryHolderCount && _needToIncrementCountryHolderCount && _shouldOverflowCountryHolderCount;
}
function _updateCountries(
uint _value,
uint _withdrawCountryCode,
uint _withdrawBalance,
uint _withdrawCurrentHolderCount,
uint _countryCode,
uint _balance,
uint _currentHolderCount,
uint _maxHolderNumber
)
internal
{
if (_isNoNeedInCountryLimitChange(_value, _withdrawCountryCode, _withdrawBalance, _countryCode, _balance, _currentHolderCount, _maxHolderNumber)) {
return;
}
_updateWithdrawCountry(_value, _withdrawCountryCode, _withdrawBalance, _withdrawCurrentHolderCount);
_updateDepositCountry(_countryCode, _balance, _currentHolderCount);
}
function _updateWithdrawCountry(
uint _value,
uint _countryCode,
uint _balance,
uint _currentHolderCount
)
internal
{
if (_value == _balance && OK != dataController.updateCountryHoldersCount(_countryCode, _currentHolderCount.sub(1))) {
revert();
}
}
function _updateDepositCountry(
uint _countryCode,
uint _balance,
uint _currentHolderCount
)
internal
{
if (_balance == 0 && OK != dataController.updateCountryHoldersCount(_countryCode, _currentHolderCount.add(1))) {
revert();
}
}
function _getParticipantRoles(address _from, address _to) private view returns (Roles _fromRole, Roles _toRole) {
_fromRole = dataController.isRegisteredAddress(_from) ? Roles.Holder : (serviceController.isService(_from) ? Roles.Service : Roles.Other);
_toRole = dataController.isRegisteredAddress(_to) ? Roles.Holder : (serviceController.isService(_to) ? Roles.Service : Roles.Other);
}
function _couldWithdrawFromHolder(address _holder, uint _value) private view returns (bool) {
bytes32 _holderId = dataController.getHolderExternalIdByAddress(_holder);
var (, _limPerDay, _limPerMonth, _operational,) = dataController.getHolderInfo(_holderId);
return _operational ? _isValidWithdrawLimits(_limPerDay, _limPerMonth, _value) : false;
}
function _couldDepositToHolder(address _holder, uint) private view returns (bool) {
bytes32 _holderId = dataController.getHolderExternalIdByAddress(_holder);
var (,,, _operational,) = dataController.getHolderInfo(_holderId);
return _operational;
}
//TODO need additional check: not clear check of country limit:
function _isValidDepositCountry(uint _balance, uint _currentHolderCount, uint _maxHolderNumber) private pure returns (bool) {
return !(_balance == 0 && _currentHolderCount == _maxHolderNumber);
}
function _getHoldersInfo(address _to, Roles _toRole, uint, address _from, Roles _fromRole)
private
view
returns (
uint _fromCountryCode,
uint _fromBalance,
uint _toCountryCode,
uint _toCountryCurrentHolderCount,
uint _toCountryMaxHolderNumber,
uint _toBalance
) {
bytes32 _holderId;
if (_toRole == Roles.Holder) {
_holderId = dataController.getHolderExternalIdByAddress(_to);
_toCountryCode = dataController.getHolderCountryCode(_holderId);
(_toCountryCurrentHolderCount, _toCountryMaxHolderNumber) = dataController.getCountryInfo(_toCountryCode);
_toBalance = ERC20Interface(proxy).balanceOf(_to);
}
if (_fromRole == Roles.Holder) {
_holderId = dataController.getHolderExternalIdByAddress(_from);
_fromCountryCode = dataController.getHolderCountryCode(_holderId);
_fromBalance = ERC20Interface(proxy).balanceOf(_from);
}
}
function _isValidCountryLimits(address _to, Roles _toRole, uint _value, address _from, Roles _fromRole) private view returns (bool) {
var (
_fromCountryCode,
_fromBalance,
_toCountryCode,
_toCountryCurrentHolderCount,
_toCountryMaxHolderNumber,
_toBalance
) = _getHoldersInfo(_to, _toRole, _value, _from, _fromRole);
//TODO not clear for which case this check
bool _isValidLimitFromHolder = _fromRole == _toRole && _fromRole == Roles.Holder && !_isValidDepositCountry(_value, _fromCountryCode, _fromBalance, _toCountryCode, _toBalance, _toCountryCurrentHolderCount, _toCountryMaxHolderNumber);
bool _isValidLimitsToHolder = _toRole == Roles.Holder && !_isValidDepositCountry(_toBalance, _toCountryCurrentHolderCount, _toCountryMaxHolderNumber);
return !(_isValidLimitFromHolder || _isValidLimitsToHolder);
}
function _updateTransferLimits(address _to, Roles _toRole, uint _value, address _from, Roles _fromRole) private {
var (
_fromCountryCode,
_fromBalance,
_toCountryCode,
_toCountryCurrentHolderCount,
_toCountryMaxHolderNumber,
_toBalance
) = _getHoldersInfo(_to, _toRole, _value, _from, _fromRole);
if (_fromRole == Roles.Holder && OK != dataController.withdrawFrom(_from, _value)) {
revert();
}
if (_toRole == Roles.Holder && OK != dataController.depositTo(_from, _value)) {
revert();
}
uint _fromCountryCurrentHolderCount;
if (_fromRole == Roles.Holder && _fromRole == _toRole) {
(_fromCountryCurrentHolderCount,) = dataController.getCountryInfo(_fromCountryCode);
_updateCountries(
_value,
_fromCountryCode,
_fromBalance,
_fromCountryCurrentHolderCount,
_toCountryCode,
_toBalance,
_toCountryCurrentHolderCount,
_toCountryMaxHolderNumber
);
} else if (_fromRole == Roles.Holder) {
(_fromCountryCurrentHolderCount,) = dataController.getCountryInfo(_fromCountryCode);
_updateWithdrawCountry(_value, _fromCountryCode, _fromBalance, _fromCountryCurrentHolderCount);
} else if (_toRole == Roles.Holder) {
_updateDepositCountry(_toCountryCode, _toBalance, _toCountryCurrentHolderCount);
}
}
}
/// @title ATx Asset implementation contract.
///
/// Basic asset implementation contract, without any additional logic.
/// Every other asset implementation contracts should derive from this one.
/// Receives calls from the proxy, and calls back immediately without arguments modification.
///
/// Note: all the non constant functions return false instead of throwing in case if state change
/// didn't happen yet.
contract Asset is ATxAsset {
} | TODO need additional check: not clear check of country limit: | function _isValidDepositCountry(uint _balance, uint _currentHolderCount, uint _maxHolderNumber) private pure returns (bool) {
return !(_balance == 0 && _currentHolderCount == _maxHolderNumber);
}
| 1,265,499 | [
1,
6241,
1608,
3312,
866,
30,
486,
2424,
866,
434,
5251,
1800,
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
] | [
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,
26810,
758,
1724,
8142,
12,
11890,
389,
12296,
16,
2254,
389,
2972,
6064,
1380,
16,
2254,
389,
1896,
6064,
1854,
13,
3238,
16618,
1135,
261,
6430,
13,
288,
203,
3639,
327,
401,
24899,
12296,
422,
374,
597,
389,
2972,
6064,
1380,
422,
389,
1896,
6064,
1854,
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
] |
pragma solidity ^0.4.25;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function balanceOf(address _owner) external view returns (uint256);
function allowance(address _owner, address spender) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner=0xE2d9b8259F74a46b5E3f74A30c7867be0a5f5185;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() internal {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Helps contracts guard against reentrancy attacks.
* @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]>
* @dev If you mark a function `nonReentrant`, you should also
* mark it `external`.
*/
contract ReentrancyGuard {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor() internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @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() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter);
}
}
contract Haltable is Ownable {
bool public halted;
modifier stopInEmergency {
if (halted) revert();
_;
}
modifier stopNonOwnersInEmergency {
if (halted && msg.sender != owner) revert();
_;
}
modifier onlyInEmergency {
if (!halted) revert();
_;
}
// called by the owner on emergency, triggers stopped state
function halt() external onlyOwner {
halted = true;
}
// called by the owner on end of emergency, returns to normal state
function unhalt() external onlyOwner onlyInEmergency {
halted = false;
}
}
contract Ubricoin is IERC20,Ownable,ReentrancyGuard,Haltable{
using SafeMath for uint256;
// UBN Token parameters
string public name = 'Ubricoin';
string public symbol = 'UBN';
string public version = '2.0';
uint256 public constant RATE = 1000; //1 ether = 1000 Ubricoins tokens
// min tokens to be a holder, 0.1
uint256 public constant MIN_HOLDER_TOKENS = 10 ** uint256(decimals - 1);
// 18 decimals is the strongly suggested default, avoid changing it
uint8 public constant decimals = 18;
uint256 public constant decimalFactor = 10 ** uint256(decimals);
uint256 public totalSupply_; // amount of tokens already sold/supply
uint256 public constant TOTAL_SUPPLY = 10000000000 * decimalFactor; // The initialSupply or totalSupply of 100% Released at Token Distribution (TD)
uint256 public constant SALES_SUPPLY = 1300000000 * decimalFactor; // 2.30% Released at Token Distribution (TD)
// Funds supply constants // tokens to be Distributed at every stage
uint256 public AVAILABLE_FOUNDER_SUPPLY = 1500000000 * decimalFactor; // 17.3% Released at TD
uint256 public AVAILABLE_AIRDROP_SUPPLY = 2000000000 * decimalFactor; // 22.9% Released at TD/Eco System Allocated
uint256 public AVAILABLE_OWNER_SUPPLY = 2000000000 * decimalFactor; // 22.9% Released at TD
uint256 public AVAILABLE_TEAMS_SUPPLY = 3000000000 * decimalFactor; // 34.5% Released at TD
uint256 public AVAILABLE_BONUS_SUPPLY = 200000000 * decimalFactor; // 0.10% Released at TD
uint256 public claimedTokens = 0;
// Funds supply addresses constants // tokens distribution
address public constant AVAILABLE_FOUNDER_SUPPLY_ADDRESS = 0xAC762012330350DDd97Cc64B133536F8E32193a8; //AVAILABLE_FOUNDER_SUPPLY_ADDRESS 1
address public constant AVAILABLE_AIRDROP_SUPPLY_ADDRESS = 0x28970854Bfa61C0d6fE56Cc9daAAe5271CEaEC09; //AVAILABLE_AIRDROP_SUPPLY_ADDRESS 2 Eco system Allocated
address public constant AVAILABLE_OWNER_SUPPLY_ADDRESS = 0xE2d9b8259F74a46b5E3f74A30c7867be0a5f5185; //AVAILABLE_OWNER_SUPPLY_ADDRESS 3
address public constant AVAILABLE_BONUS_SUPPLY_ADDRESS = 0xDE59297Bf5D1D1b9d38D8F50e55A270eb9aE136e; //AVAILABLE_BONUS1_SUPPLY_ADDRESS 4
address public constant AVAILABLE_TEAMS_SUPPLY_ADDRESS = 0x9888375f4663891770DaaaF9286d97d44FeFC82E; //AVAILABLE_RESERVE_TEAM_SUPPLY_ADDRESS 5
// Token holders
address[] public holders;
// ICO address
address public icoAddress;
mapping (address => uint256) balances; // This creates an array with all balances
mapping (address => mapping (address => uint256)) internal allowed;
// Keeps track of whether or not an Ubricoin airdrop has been made to a particular address
mapping (address => bool) public airdrops;
mapping (address => uint256) public holderNumber; // Holders number
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
event TransferredToken(address indexed to, uint256 value);
event FailedTransfer(address indexed to, uint256 value);
// This notifies clients about the amount burnt , only admin is able to burn the contract
event Burn(address from, uint256 value);
event AirDropped ( address[] _recipient, uint256 _amount, uint256 claimedTokens);
event AirDrop_many ( address[] _recipient, uint256[] _amount, uint256 claimedTokens);
/**
* @dev Constructor that gives a portion of all existing tokens to various addresses.
* @dev Distribute founder, airdrop,owner, reserve_team and bonus_supply tokens
* @dev and Ico address for the remaining tokens
*/
constructor () public {
// Allocate tokens to the available_founder_supply_address fund 1
balances[AVAILABLE_FOUNDER_SUPPLY_ADDRESS] = AVAILABLE_FOUNDER_SUPPLY;
holders.push(AVAILABLE_FOUNDER_SUPPLY_ADDRESS);
emit Transfer(0x0, AVAILABLE_FOUNDER_SUPPLY_ADDRESS, AVAILABLE_FOUNDER_SUPPLY);
// Allocate tokens to the available_airdrop_supply_address fund 2 eco system allocated
balances[AVAILABLE_AIRDROP_SUPPLY_ADDRESS] = AVAILABLE_AIRDROP_SUPPLY;
holders.push(AVAILABLE_AIRDROP_SUPPLY_ADDRESS);
emit Transfer(0x0, AVAILABLE_AIRDROP_SUPPLY_ADDRESS, AVAILABLE_AIRDROP_SUPPLY);
// Allocate tokens to the available_owner_supply_address fund 3
balances[AVAILABLE_OWNER_SUPPLY_ADDRESS] = AVAILABLE_OWNER_SUPPLY;
holders.push(AVAILABLE_OWNER_SUPPLY_ADDRESS);
emit Transfer(0x0, AVAILABLE_OWNER_SUPPLY_ADDRESS, AVAILABLE_OWNER_SUPPLY);
// Allocate tokens to the available_reserve_team_supply_address fund 4
balances[AVAILABLE_TEAMS_SUPPLY_ADDRESS] = AVAILABLE_TEAMS_SUPPLY;
holders.push(AVAILABLE_TEAMS_SUPPLY_ADDRESS);
emit Transfer(0x0, AVAILABLE_TEAMS_SUPPLY_ADDRESS, AVAILABLE_TEAMS_SUPPLY);
// Allocate tokens to the available_reserve_team_supply_address fund 5
balances[AVAILABLE_BONUS_SUPPLY_ADDRESS] = AVAILABLE_BONUS_SUPPLY;
holders.push(AVAILABLE_BONUS_SUPPLY_ADDRESS);
emit Transfer(0x0, AVAILABLE_BONUS_SUPPLY_ADDRESS, AVAILABLE_BONUS_SUPPLY);
totalSupply_ = TOTAL_SUPPLY.sub(SALES_SUPPLY);
}
/**
* @dev Function fallback/payable to buy tokens from contract by sending ether.
* @notice Buy tokens from contract by sending ether
* @dev This are the tokens allocated for sale's supply
*/
function () payable nonReentrant external {
require(msg.data.length == 0);
require(msg.value > 0);
uint256 tokens = msg.value.mul(RATE); // calculates the aamount
balances[msg.sender] = balances[msg.sender].add(tokens);
totalSupply_ = totalSupply_.add(tokens);
owner.transfer(msg.value); //make transfer
}
/**
* @dev set ICO address and allocate sale supply to it
* Tokens left for payment using ethers
*/
function setICO(address _icoAddress) public onlyOwner {
require(_icoAddress != address(0));
require(icoAddress == address(0));
require(totalSupply_ == TOTAL_SUPPLY.sub(SALES_SUPPLY));
// Allocate tokens to the ico contract
balances[_icoAddress] = SALES_SUPPLY;
emit Transfer(0x0, _icoAddress, SALES_SUPPLY);
icoAddress = _icoAddress;
totalSupply_ = TOTAL_SUPPLY;
}
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining ) {
return allowed[_owner][_spender];
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint256 _value) internal {
require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require(balances[_from] >= _value); // Check if the sender has enough
require(balances[_to] + _value >= balances[_to]); // Check for overflows
uint256 previousBalances = balances[_from] + balances[_to]; // Save this for an assertion in the future
balances[_from] -= _value; // Subtract from the sender
balances[_to] += _value; // Add the same to the recipient
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balances[_from] + balances[_to] == previousBalances);
}
/**
* Standard transfer function
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balances[msg.sender] > 0);
require(balances[msg.sender] >= _value); // Check if the sender has enough
require(_to != address(0x0)); // Prevent transfer to 0x0 address. Use burn() instead
require(_value > 0);
require(_to != msg.sender); // Check if sender and receiver is not same
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value); // Subtract value from sender
balances[_to] = balances[_to].add(_value); // Add the value to the receiver
emit Transfer(msg.sender, _to, _value); // Notify all clients about the transfer events
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_to != address(0x0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]); // Check allowance
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 success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
// get holders count
function getHoldersCount() public view returns (uint256) {
return holders.length;
}
// preserve holders list
function preserveHolders(address _from, address _to, uint256 _value) internal {
if (balances[_from].sub(_value) < MIN_HOLDER_TOKENS)
removeHolder(_from);
if (balances[_to].add(_value) >= MIN_HOLDER_TOKENS)
addHolder(_to);
}
// remove holder from the holders list
function removeHolder(address _holder) internal {
uint256 _number = holderNumber[_holder];
if (_number == 0 || holders.length == 0 || _number > holders.length)
return;
uint256 _index = _number.sub(1);
uint256 _lastIndex = holders.length.sub(1);
address _lastHolder = holders[_lastIndex];
if (_index != _lastIndex) {
holders[_index] = _lastHolder;
holderNumber[_lastHolder] = _number;
}
holderNumber[_holder] = 0;
holders.length = _lastIndex;
}
// add holder to the holders list
function addHolder(address _holder) internal {
if (holderNumber[_holder] == 0) {
holders.push(_holder);
holderNumber[_holder] = holders.length;
}
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) external onlyOwner {
require(balances[msg.sender] >= value); // Check if the sender has enough
balances[msg.sender] -= value; // Subtract from the sender
totalSupply_ -= value; // Updates totalSupply
emit Burn(msg.sender, value);
//return true;
require(account != address(0x0));
totalSupply_ = totalSupply_.sub(value);
balances[account] = balances[account].sub(value);
emit Transfer(account, address(0X0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) external onlyOwner {
require(balances[account] >= value); // Check if the targeted balance is enough
require(value <= allowed[account][msg.sender]); // Check allowance
balances[account] -= value; // Subtract from the targeted balance
allowed[account][msg.sender] -= value; // Subtract from the sender's allowance
totalSupply_ -= value; // Update totalSupply
emit Burn(account, value);
// return true;
allowed[account][msg.sender] = allowed[account][msg.sender].sub(value);
emit Burn(account, value);
emit Approval(account, msg.sender, allowed[account][msg.sender]);
}
function validPurchase() internal returns (bool) {
bool lessThanMaxInvestment = msg.value <= 1000 ether; // change the value to whatever you need
return validPurchase() && lessThanMaxInvestment;
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param target The account that will receive the created tokens.
* @param mintedAmount The amount that will be created.
* @dev perform a minting/create new UBN's for new allocations
* @param target is the address to mint tokens to
*
*/
function mintToken(address target, uint256 mintedAmount) public onlyOwner {
balances[target] += mintedAmount;
totalSupply_ += mintedAmount;
emit Transfer(0, owner, mintedAmount);
emit Transfer(owner, target, mintedAmount);
}
/**
* @dev perform a transfer of allocations
* @param _recipient is a list of recipients
*
* Below function can be used when you want to send every recipeint with different number of tokens
*
*/
function airDrop_many(address[] _recipient, uint256[] _amount) public onlyOwner {
require(msg.sender == owner);
require(_recipient.length == _amount.length);
uint256 amount = _amount[i] * uint256(decimalFactor);
uint256 airdropped;
for (uint i=0; i < _recipient.length; i++) {
if (!airdrops[_recipient[i]]) {
airdrops[_recipient[i]] = true;
require(Ubricoin.transfer(_recipient[i], _amount[i] * decimalFactor));
//Ubricoin.transfer(_recipient[i], _amount[i]);
airdropped = airdropped.add(amount );
} else{
emit FailedTransfer(_recipient[i], airdropped);
}
AVAILABLE_AIRDROP_SUPPLY = AVAILABLE_AIRDROP_SUPPLY.sub(airdropped);
//totalSupply_ = totalSupply_.sub(airdropped);
claimedTokens = claimedTokens.add(airdropped);
emit AirDrop_many(_recipient, _amount, claimedTokens);
}
}
/**
* @dev perform a transfer of allocations
* @param _recipient is a list of recipients
*
* this function can be used when you want to send same number of tokens to all the recipients
*
*/
function airDrop(address[] _recipient, uint256 _amount) public onlyOwner {
require(_amount > 0);
uint256 airdropped;
uint256 amount = _amount * uint256(decimalFactor);
for (uint256 index = 0; index < _recipient.length; index++) {
if (!airdrops[_recipient[index]]) {
airdrops[_recipient[index]] = true;
require(Ubricoin.transfer(_recipient[index], amount * decimalFactor ));
airdropped = airdropped.add(amount );
}else{
emit FailedTransfer(_recipient[index], airdropped);
}
}
AVAILABLE_AIRDROP_SUPPLY = AVAILABLE_AIRDROP_SUPPLY.sub(airdropped);
//totalSupply_ = totalSupply_.sub(airdropped);
claimedTokens = claimedTokens.add(airdropped);
emit AirDropped(_recipient, _amount, claimedTokens);
}
} | Subtract from the sender's allowance
| allowed[account][msg.sender] -= value; | 12,698,071 | [
1,
27904,
628,
326,
5793,
1807,
1699,
1359,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1377,
2935,
63,
4631,
6362,
3576,
18,
15330,
65,
3947,
460,
31,
2868,
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
] |
./full_match/61/0xfF84678ebEa9d981f3D507A4d456feA261E6D262/sources/contracts/Contract.sol | pool name address of sell token address of buy token total amount of token0 total amount of token1 the timestamp in seconds the pool will open the timestamp in seconds the pool will be closed the delay timestamp in seconds when buyers can claim after pool filled whitelist merkle root | struct CreateReq {
string name;
address token0;
address token1;
uint256 amountTotal0;
uint256 amountTotal1;
uint48 openAt;
uint48 closeAt;
uint48 claimAt;
uint256 maxAmount1PerWallet;
bytes32 whitelistRoot;
}
| 13,229,370 | [
1,
6011,
508,
1758,
434,
357,
80,
1147,
1758,
434,
30143,
1147,
2078,
3844,
434,
1147,
20,
2078,
3844,
434,
1147,
21,
326,
2858,
316,
3974,
326,
2845,
903,
1696,
326,
2858,
316,
3974,
326,
2845,
903,
506,
4375,
326,
4624,
2858,
316,
3974,
1347,
30143,
414,
848,
7516,
1839,
2845,
6300,
10734,
30235,
1365,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
1958,
1788,
6113,
288,
203,
3639,
533,
508,
31,
203,
3639,
1758,
1147,
20,
31,
203,
3639,
1758,
1147,
21,
31,
203,
3639,
2254,
5034,
3844,
5269,
20,
31,
203,
3639,
2254,
5034,
3844,
5269,
21,
31,
203,
3639,
2254,
8875,
1696,
861,
31,
203,
3639,
2254,
8875,
1746,
861,
31,
203,
3639,
2254,
8875,
7516,
861,
31,
203,
3639,
2254,
5034,
943,
6275,
21,
2173,
16936,
31,
203,
3639,
1731,
1578,
10734,
2375,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Library used to query support of an interface declared via {IERC165}.
*
* Note that these functions return the actual result of the query: they do not
* `revert` if an interface is not supported. It is up to the caller to decide
* what to do in these cases.
*/
library ERC165Checker {
// As per the EIP-165 spec, no interface should ever match 0xffffffff
bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Returns true if `account` supports the {IERC165} interface,
*/
function supportsERC165(address account) internal view returns (bool) {
// Any contract that implements ERC165 must explicitly indicate support of
// InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
return _supportsERC165Interface(account, _INTERFACE_ID_ERC165) &&
!_supportsERC165Interface(account, _INTERFACE_ID_INVALID);
}
/**
* @dev Returns true if `account` supports the interface defined by
* `interfaceId`. Support for {IERC165} itself is queried automatically.
*
* See {IERC165-supportsInterface}.
*/
function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
// query support of both ERC165 as per the spec and support of _interfaceId
return supportsERC165(account) &&
_supportsERC165Interface(account, interfaceId);
}
/**
* @dev Returns a boolean array where each value corresponds to the
* interfaces passed in and whether they're supported or not. This allows
* you to batch check interfaces for a contract where your expectation
* is that some interfaces may not be supported.
*
* See {IERC165-supportsInterface}.
*
* _Available since v3.4._
*/
function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) {
// an array of booleans corresponding to interfaceIds and whether they're supported or not
bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);
// query support of ERC165 itself
if (supportsERC165(account)) {
// query support of each interface in interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]);
}
}
return interfaceIdsSupported;
}
/**
* @dev Returns true if `account` supports all the interfaces defined in
* `interfaceIds`. Support for {IERC165} itself is queried automatically.
*
* Batch-querying can lead to gas savings by skipping repeated checks for
* {IERC165} support.
*
* See {IERC165-supportsInterface}.
*/
function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
// query support of ERC165 itself
if (!supportsERC165(account)) {
return false;
}
// query support of each interface in _interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
if (!_supportsERC165Interface(account, interfaceIds[i])) {
return false;
}
}
// all interfaces supported
return true;
}
/**
* @notice Query if a contract implements an interface, does not check ERC165 support
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return true if the contract at account indicates support of the interface with
* identifier interfaceId, false otherwise
* @dev Assumes that account contains a contract that supports ERC165, otherwise
* the behavior of this method is undefined. This precondition can be checked
* with {supportsERC165}.
* Interface identification is specified in ERC-165.
*/
function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) {
// success determines whether the staticcall succeeded and result determines
// whether the contract at account indicates support of _interfaceId
(bool success, bool result) = _callERC165SupportsInterface(account, interfaceId);
return (success && result);
}
/**
* @notice Calls the function with selector 0x01ffc9a7 (ERC165) and suppresses throw
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return success true if the STATICCALL succeeded, false otherwise
* @return result true if the STATICCALL succeeded and the contract at account
* indicates support of the interface with identifier interfaceId, false otherwise
*/
function _callERC165SupportsInterface(address account, bytes4 interfaceId)
private
view
returns (bool, bool)
{
bytes memory encodedParams = abi.encodeWithSelector(_INTERFACE_ID_ERC165, interfaceId);
(bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams);
if (result.length < 32) return (false, false);
return (success, abi.decode(result, (bool)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "./IVaultHandler.sol";
import "./Orchestrator.sol";
/**
* @title ERC-20 TCAP Vault
* @author Cryptex.finance
* @notice Contract in charge of handling the TCAP Vault and stake using a Collateral ERC20
*/
contract ERC20VaultHandler is IVaultHandler {
/**
* @notice Constructor
* @param _orchestrator address
* @param _divisor uint256
* @param _ratio uint256
* @param _burnFee uint256
* @param _liquidationPenalty uint256
* @param _tcapOracle address
* @param _tcapAddress address
* @param _collateralAddress address
* @param _collateralOracle address
* @param _ethOracle address
* @param _rewardHandler address
* @param _treasury address
*/
constructor(
Orchestrator _orchestrator,
uint256 _divisor,
uint256 _ratio,
uint256 _burnFee,
uint256 _liquidationPenalty,
address _tcapOracle,
TCAP _tcapAddress,
address _collateralAddress,
address _collateralOracle,
address _ethOracle,
address _rewardHandler,
address _treasury
)
IVaultHandler(
_orchestrator,
_divisor,
_ratio,
_burnFee,
_liquidationPenalty,
_tcapOracle,
_tcapAddress,
_collateralAddress,
_collateralOracle,
_ethOracle,
_rewardHandler,
_treasury
)
{}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/SafeCast.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/introspection/IERC165.sol";
import "./TCAP.sol";
import "./Orchestrator.sol";
import "./oracles/ChainlinkOracle.sol";
interface IRewardHandler {
function stake(address _staker, uint256 amount) external;
function withdraw(address _staker, uint256 amount) external;
function getRewardFromVault(address _staker) external;
}
/**
* @title TCAP Vault Handler Abstract Contract
* @author Cryptex.Finance
* @notice Contract in charge of handling the TCAP Token and stake
*/
abstract contract IVaultHandler is
Ownable,
AccessControl,
ReentrancyGuard,
Pausable,
IERC165
{
/// @notice Open Zeppelin libraries
using SafeMath for uint256;
using SafeCast for int256;
using Counters for Counters.Counter;
using SafeERC20 for IERC20;
/**
* @notice Vault object created to manage the mint and burns of TCAP tokens
* @param Id, unique identifier of the vault
* @param Collateral, current collateral on vault
* @param Debt, current amount of TCAP tokens minted
* @param Owner, owner of the vault
*/
struct Vault {
uint256 Id;
uint256 Collateral;
uint256 Debt;
address Owner;
}
/// @notice Vault Id counter
Counters.Counter public counter;
/// @notice TCAP Token Address
TCAP public immutable TCAPToken;
/// @notice Total Market Cap/USD Oracle Address
ChainlinkOracle public immutable tcapOracle;
/// @notice Collateral Token Address
IERC20 public immutable collateralContract;
/// @notice Collateral/USD Oracle Address
ChainlinkOracle public immutable collateralPriceOracle;
/// @notice ETH/USD Oracle Address
ChainlinkOracle public immutable ETHPriceOracle;
/// @notice Value used as divisor with the total market cap, just like the S&P 500 or any major financial index would to define the final tcap token price
uint256 public divisor;
/// @notice Minimun ratio required to prevent liquidation of vault
uint256 public ratio;
/// @notice Fee percentage of the total amount to burn charged on ETH when burning TCAP Tokens
uint256 public burnFee;
/// @notice Penalty charged to vault owner when a vault is liquidated, this value goes to the liquidator
uint256 public liquidationPenalty;
/// @notice Address of the contract that gives rewards to minters of TCAP, rewards are only given if address is set in constructor
IRewardHandler public immutable rewardHandler;
/// @notice Address of the treasury contract (usually the timelock) where the funds generated by the protocol are sent
address public treasury;
/// @notice Owner address to Vault Id
mapping(address => uint256) public userToVault;
/// @notice Id To Vault
mapping(uint256 => Vault) public vaults;
/// @notice value used to multiply chainlink oracle for handling decimals
uint256 public constant oracleDigits = 10000000000;
/// @notice Minimum value that the ratio can be set to
uint256 public constant MIN_RATIO = 150;
/// @notice Maximum value that the burn fee can be set to
uint256 public constant MAX_FEE = 10;
/**
* @dev the computed interface ID according to ERC-165. The interface ID is a XOR of interface method selectors.
* setRatio.selector ^
* setBurnFee.selector ^
* setLiquidationPenalty.selector ^
* pause.selector ^
* unpause.selector => 0x9e75ab0c
*/
bytes4 private constant _INTERFACE_ID_IVAULT = 0x9e75ab0c;
/// @dev bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/// @notice An event emitted when the ratio is updated
event NewRatio(address indexed _owner, uint256 _ratio);
/// @notice An event emitted when the burn fee is updated
event NewBurnFee(address indexed _owner, uint256 _burnFee);
/// @notice An event emitted when the liquidation penalty is updated
event NewLiquidationPenalty(
address indexed _owner,
uint256 _liquidationPenalty
);
/// @notice An event emitted when the treasury contract is updated
event NewTreasury(address indexed _owner, address _tresury);
/// @notice An event emitted when a vault is created
event VaultCreated(address indexed _owner, uint256 indexed _id);
/// @notice An event emitted when collateral is added to a vault
event CollateralAdded(
address indexed _owner,
uint256 indexed _id,
uint256 _amount
);
/// @notice An event emitted when collateral is removed from a vault
event CollateralRemoved(
address indexed _owner,
uint256 indexed _id,
uint256 _amount
);
/// @notice An event emitted when tokens are minted
event TokensMinted(
address indexed _owner,
uint256 indexed _id,
uint256 _amount
);
/// @notice An event emitted when tokens are burned
event TokensBurned(
address indexed _owner,
uint256 indexed _id,
uint256 _amount
);
/// @notice An event emitted when a vault is liquidated
event VaultLiquidated(
uint256 indexed _vaultId,
address indexed _liquidator,
uint256 _liquidationCollateral,
uint256 _reward
);
/// @notice An event emitted when a erc20 token is recovered
event Recovered(address _token, uint256 _amount);
/**
* @notice Constructor
* @param _orchestrator address
* @param _divisor uint256
* @param _ratio uint256
* @param _burnFee uint256
* @param _liquidationPenalty uint256
* @param _tcapOracle address
* @param _tcapAddress address
* @param _collateralAddress address
* @param _collateralOracle address
* @param _ethOracle address
* @param _rewardHandler address
* @param _treasury address
*/
constructor(
Orchestrator _orchestrator,
uint256 _divisor,
uint256 _ratio,
uint256 _burnFee,
uint256 _liquidationPenalty,
address _tcapOracle,
TCAP _tcapAddress,
address _collateralAddress,
address _collateralOracle,
address _ethOracle,
address _rewardHandler,
address _treasury
) {
require(
_liquidationPenalty.add(100) < _ratio,
"VaultHandler::constructor: liquidation penalty too high"
);
require(
_ratio >= MIN_RATIO,
"VaultHandler::constructor: ratio lower than MIN_RATIO"
);
require(
_burnFee <= MAX_FEE,
"VaultHandler::constructor: burn fee higher than MAX_FEE"
);
divisor = _divisor;
ratio = _ratio;
burnFee = _burnFee;
liquidationPenalty = _liquidationPenalty;
tcapOracle = ChainlinkOracle(_tcapOracle);
collateralContract = IERC20(_collateralAddress);
collateralPriceOracle = ChainlinkOracle(_collateralOracle);
ETHPriceOracle = ChainlinkOracle(_ethOracle);
TCAPToken = _tcapAddress;
rewardHandler = IRewardHandler(_rewardHandler);
treasury = _treasury;
/// @dev counter starts in 1 as 0 is reserved for empty objects
counter.increment();
/// @dev transfer ownership to orchestrator
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
transferOwnership(address(_orchestrator));
}
/// @notice Reverts if the user hasn't created a vault.
modifier vaultExists() {
require(
userToVault[msg.sender] != 0,
"VaultHandler::vaultExists: no vault created"
);
_;
}
/// @notice Reverts if value is 0.
modifier notZero(uint256 _value) {
require(_value != 0, "VaultHandler::notZero: value can't be 0");
_;
}
/**
* @notice Sets the collateral ratio needed to mint tokens
* @param _ratio uint
* @dev Only owner can call it
*/
function setRatio(uint256 _ratio) external virtual onlyOwner {
require(
_ratio >= MIN_RATIO,
"VaultHandler::setRatio: ratio lower than MIN_RATIO"
);
ratio = _ratio;
emit NewRatio(msg.sender, _ratio);
}
/**
* @notice Sets the burn fee percentage an user pays when burning tcap tokens
* @param _burnFee uint
* @dev Only owner can call it
*/
function setBurnFee(uint256 _burnFee) external virtual onlyOwner {
require(
_burnFee <= MAX_FEE,
"VaultHandler::setBurnFee: burn fee higher than MAX_FEE"
);
burnFee = _burnFee;
emit NewBurnFee(msg.sender, _burnFee);
}
/**
* @notice Sets the liquidation penalty % charged on liquidation
* @param _liquidationPenalty uint
* @dev Only owner can call it
* @dev recommended value is between 1-15% and can't be above 100%
*/
function setLiquidationPenalty(uint256 _liquidationPenalty)
external
virtual
onlyOwner
{
require(
_liquidationPenalty.add(100) < ratio,
"VaultHandler::setLiquidationPenalty: liquidation penalty too high"
);
liquidationPenalty = _liquidationPenalty;
emit NewLiquidationPenalty(msg.sender, _liquidationPenalty);
}
/**
* @notice Sets the treasury contract address where fees are transfered to
* @param _treasury address
* @dev Only owner can call it
*/
function setTreasury(address _treasury) external virtual onlyOwner {
require(
_treasury != address(0),
"VaultHandler::setTreasury: not a valid treasury"
);
treasury = _treasury;
emit NewTreasury(msg.sender, _treasury);
}
/**
* @notice Allows an user to create an unique Vault
* @dev Only one vault per address can be created
*/
function createVault() external virtual whenNotPaused {
require(
userToVault[msg.sender] == 0,
"VaultHandler::createVault: vault already created"
);
uint256 id = counter.current();
userToVault[msg.sender] = id;
Vault memory vault = Vault(id, 0, 0, msg.sender);
vaults[id] = vault;
counter.increment();
emit VaultCreated(msg.sender, id);
}
/**
* @notice Allows users to add collateral to their vaults
* @param _amount of collateral to be added
* @dev _amount should be higher than 0
* @dev ERC20 token must be approved first
*/
function addCollateral(uint256 _amount)
external
virtual
nonReentrant
vaultExists
whenNotPaused
notZero(_amount)
{
require(
collateralContract.transferFrom(msg.sender, address(this), _amount),
"VaultHandler::addCollateral: ERC20 transfer did not succeed"
);
Vault storage vault = vaults[userToVault[msg.sender]];
vault.Collateral = vault.Collateral.add(_amount);
emit CollateralAdded(msg.sender, vault.Id, _amount);
}
/**
* @notice Allows users to remove collateral currently not being used to generate TCAP tokens from their vaults
* @param _amount of collateral to remove
* @dev reverts if the resulting ratio is less than the minimun ratio
* @dev _amount should be higher than 0
* @dev transfers the collateral back to the user
*/
function removeCollateral(uint256 _amount)
external
virtual
nonReentrant
vaultExists
whenNotPaused
notZero(_amount)
{
Vault storage vault = vaults[userToVault[msg.sender]];
uint256 currentRatio = getVaultRatio(vault.Id);
require(
vault.Collateral >= _amount,
"VaultHandler::removeCollateral: retrieve amount higher than collateral"
);
vault.Collateral = vault.Collateral.sub(_amount);
if (currentRatio != 0) {
require(
getVaultRatio(vault.Id) >= ratio,
"VaultHandler::removeCollateral: collateral below min required ratio"
);
}
require(
collateralContract.transfer(msg.sender, _amount),
"VaultHandler::removeCollateral: ERC20 transfer did not succeed"
);
emit CollateralRemoved(msg.sender, vault.Id, _amount);
}
/**
* @notice Uses collateral to generate debt on TCAP Tokens which are minted and assigend to caller
* @param _amount of tokens to mint
* @dev _amount should be higher than 0
* @dev requires to have a vault ratio above the minimum ratio
* @dev if reward handler is set stake to earn rewards
*/
function mint(uint256 _amount)
external
virtual
nonReentrant
vaultExists
whenNotPaused
notZero(_amount)
{
Vault storage vault = vaults[userToVault[msg.sender]];
uint256 collateral = requiredCollateral(_amount);
require(
vault.Collateral >= collateral,
"VaultHandler::mint: not enough collateral"
);
vault.Debt = vault.Debt.add(_amount);
require(
getVaultRatio(vault.Id) >= ratio,
"VaultHandler::mint: collateral below min required ratio"
);
if (address(rewardHandler) != address(0)) {
rewardHandler.stake(msg.sender, _amount);
}
TCAPToken.mint(msg.sender, _amount);
emit TokensMinted(msg.sender, vault.Id, _amount);
}
/**
* @notice Pays the debt of TCAP tokens resulting them on burn, this releases collateral up to minimun vault ratio
* @param _amount of tokens to burn
* @dev _amount should be higher than 0
* @dev A fee of exactly burnFee must be sent as value on ETH
* @dev The fee goes to the treasury contract
* @dev if reward handler is set exit rewards
*/
function burn(uint256 _amount)
external
payable
virtual
nonReentrant
vaultExists
whenNotPaused
notZero(_amount)
{
uint256 fee = getFee(_amount);
require(
msg.value >= fee,
"VaultHandler::burn: burn fee less than required"
);
Vault memory vault = vaults[userToVault[msg.sender]];
_burn(vault.Id, _amount);
if (address(rewardHandler) != address(0)) {
rewardHandler.withdraw(msg.sender, _amount);
rewardHandler.getRewardFromVault(msg.sender);
}
safeTransferETH(treasury, fee);
//send back ETH above fee
safeTransferETH(msg.sender, msg.value.sub(fee));
emit TokensBurned(msg.sender, vault.Id, _amount);
}
/**
* @notice Allow users to burn TCAP tokens to liquidate vaults with vault collateral ratio under the minium ratio, the liquidator receives the staked collateral of the liquidated vault at a premium
* @param _vaultId to liquidate
* @param _maxTCAP max amount of TCAP the liquidator is willing to pay to liquidate vault
* @dev Resulting ratio must be above or equal minimun ratio
* @dev A fee of exactly burnFee must be sent as value on ETH
* @dev The fee goes to the treasury contract
*/
function liquidateVault(uint256 _vaultId, uint256 _maxTCAP)
external
payable
nonReentrant
whenNotPaused
{
Vault storage vault = vaults[_vaultId];
require(vault.Id != 0, "VaultHandler::liquidateVault: no vault created");
uint256 vaultRatio = getVaultRatio(vault.Id);
require(
vaultRatio < ratio,
"VaultHandler::liquidateVault: vault is not liquidable"
);
uint256 requiredTCAP = requiredLiquidationTCAP(vault.Id);
require(
_maxTCAP >= requiredTCAP,
"VaultHandler::liquidateVault: liquidation amount different than required"
);
uint256 fee = getFee(requiredTCAP);
require(
msg.value >= fee,
"VaultHandler::liquidateVault: burn fee less than required"
);
uint256 reward = liquidationReward(vault.Id);
_burn(vault.Id, requiredTCAP);
//Removes the collateral that is rewarded to liquidator
vault.Collateral = vault.Collateral.sub(reward);
// Triggers update of CTX Rewards
if (address(rewardHandler) != address(0)) {
rewardHandler.withdraw(vault.Owner, requiredTCAP);
}
require(
collateralContract.transfer(msg.sender, reward),
"VaultHandler::liquidateVault: ERC20 transfer did not succeed"
);
safeTransferETH(treasury, fee);
//send back ETH above fee
safeTransferETH(msg.sender, msg.value.sub(fee));
emit VaultLiquidated(vault.Id, msg.sender, requiredTCAP, reward);
}
/**
* @notice Allows the owner to Pause the Contract
*/
function pause() external onlyOwner {
_pause();
}
/**
* @notice Allows the owner to Unpause the Contract
*/
function unpause() external onlyOwner {
_unpause();
}
/**
* @notice Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
* @param _tokenAddress address
* @param _tokenAmount uint
* @dev Only owner can call it
*/
function recoverERC20(address _tokenAddress, uint256 _tokenAmount)
external
onlyOwner
{
// Cannot recover the collateral token
require(
_tokenAddress != address(collateralContract),
"Cannot withdraw the collateral tokens"
);
IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/**
* @notice Allows the safe transfer of ETH
* @param _to account to transfer ETH
* @param _value amount of ETH
*/
function safeTransferETH(address _to, uint256 _value) internal {
(bool success, ) = _to.call{value: _value}(new bytes(0));
require(success, "ETHVaultHandler::safeTransferETH: ETH transfer failed");
}
/**
* @notice ERC165 Standard for support of interfaces
* @param _interfaceId bytes of interface
* @return bool
*/
function supportsInterface(bytes4 _interfaceId)
external
pure
override
returns (bool)
{
return (_interfaceId == _INTERFACE_ID_IVAULT ||
_interfaceId == _INTERFACE_ID_ERC165);
}
/**
* @notice Returns the Vault information of specified identifier
* @param _id of vault
* @return Id, Collateral, Owner, Debt
*/
function getVault(uint256 _id)
external
view
virtual
returns (
uint256,
uint256,
address,
uint256
)
{
Vault memory vault = vaults[_id];
return (vault.Id, vault.Collateral, vault.Owner, vault.Debt);
}
/**
* @notice Returns the price of the chainlink oracle multiplied by the digits to get 18 decimals format
* @param _oracle to be the price called
* @return price
*/
function getOraclePrice(ChainlinkOracle _oracle)
public
view
virtual
returns (uint256 price)
{
price = _oracle.getLatestAnswer().toUint256().mul(oracleDigits);
}
/**
* @notice Returns the price of the TCAP token
* @return price of the TCAP Token
* @dev TCAP token is 18 decimals
* @dev oracle totalMarketPrice must be in wei format
* @dev P = T / d
* P = TCAP Token Price
* T = Total Crypto Market Cap
* d = Divisor
*/
function TCAPPrice() public view virtual returns (uint256 price) {
uint256 totalMarketPrice = getOraclePrice(tcapOracle);
price = totalMarketPrice.div(divisor);
}
/**
* @notice Returns the minimal required collateral to mint TCAP token
* @param _amount uint amount to mint
* @return collateral of the TCAP Token
* @dev TCAP token is 18 decimals
* @dev C = ((P * A * r) / 100) / cp
* C = Required Collateral
* P = TCAP Token Price
* A = Amount to Mint
* cp = Collateral Price
* r = Minimun Ratio for Liquidation
* Is only divided by 100 as eth price comes in wei to cancel the additional 0s
*/
function requiredCollateral(uint256 _amount)
public
view
virtual
returns (uint256 collateral)
{
uint256 tcapPrice = TCAPPrice();
uint256 collateralPrice = getOraclePrice(collateralPriceOracle);
collateral = ((tcapPrice.mul(_amount).mul(ratio)).div(100)).div(
collateralPrice
);
}
/**
* @notice Returns the minimal required TCAP to liquidate a Vault
* @param _vaultId of the vault to liquidate
* @return amount required of the TCAP Token
* @dev LT = ((((D * r) / 100) - cTcap) * 100) / (r - (p + 100))
* cTcap = ((C * cp) / P)
* LT = Required TCAP
* D = Vault Debt
* C = Required Collateral
* P = TCAP Token Price
* cp = Collateral Price
* r = Min Vault Ratio
* p = Liquidation Penalty
*/
function requiredLiquidationTCAP(uint256 _vaultId)
public
view
virtual
returns (uint256 amount)
{
Vault memory vault = vaults[_vaultId];
uint256 tcapPrice = TCAPPrice();
uint256 collateralPrice = getOraclePrice(collateralPriceOracle);
uint256 collateralTcap =
(vault.Collateral.mul(collateralPrice)).div(tcapPrice);
uint256 reqDividend =
(((vault.Debt.mul(ratio)).div(100)).sub(collateralTcap)).mul(100);
uint256 reqDivisor = ratio.sub(liquidationPenalty.add(100));
amount = reqDividend.div(reqDivisor);
}
/**
* @notice Returns the Reward for liquidating a vault
* @param _vaultId of the vault to liquidate
* @return rewardCollateral for liquidating Vault
* @dev the returned value is returned as collateral currency
* @dev R = (LT * (p + 100)) / 100
* R = Liquidation Reward
* LT = Required Liquidation TCAP
* p = liquidation penalty
*/
function liquidationReward(uint256 _vaultId)
public
view
virtual
returns (uint256 rewardCollateral)
{
uint256 req = requiredLiquidationTCAP(_vaultId);
uint256 tcapPrice = TCAPPrice();
uint256 collateralPrice = getOraclePrice(collateralPriceOracle);
uint256 reward = (req.mul(liquidationPenalty.add(100)));
rewardCollateral = (reward.mul(tcapPrice)).div(collateralPrice.mul(100));
}
/**
* @notice Returns the Collateral Ratio of the Vault
* @param _vaultId id of vault
* @return currentRatio
* @dev vr = (cp * (C * 100)) / D * P
* vr = Vault Ratio
* C = Vault Collateral
* cp = Collateral Price
* D = Vault Debt
* P = TCAP Token Price
*/
function getVaultRatio(uint256 _vaultId)
public
view
virtual
returns (uint256 currentRatio)
{
Vault memory vault = vaults[_vaultId];
if (vault.Id == 0 || vault.Debt == 0) {
currentRatio = 0;
} else {
uint256 collateralPrice = getOraclePrice(collateralPriceOracle);
currentRatio = (
(collateralPrice.mul(vault.Collateral.mul(100))).div(
vault.Debt.mul(TCAPPrice())
)
);
}
}
/**
* @notice Returns the required fee of ETH to burn the TCAP tokens
* @param _amount to burn
* @return fee
* @dev The returned value is returned in wei
* @dev f = (((P * A * b)/ 100))/ EP
* f = Burn Fee Value
* P = TCAP Token Price
* A = Amount to Burn
* b = Burn Fee %
* EP = ETH Price
*/
function getFee(uint256 _amount) public view virtual returns (uint256 fee) {
uint256 ethPrice = getOraclePrice(ETHPriceOracle);
fee = (TCAPPrice().mul(_amount).mul(burnFee)).div(100).div(ethPrice);
}
/**
* @notice Burns an amount of TCAP Tokens
* @param _vaultId vault id
* @param _amount to burn
*/
function _burn(uint256 _vaultId, uint256 _amount) internal {
Vault storage vault = vaults[_vaultId];
require(
vault.Debt >= _amount,
"VaultHandler::burn: amount greater than debt"
);
vault.Debt = vault.Debt.sub(_amount);
TCAPToken.burn(msg.sender, _amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/introspection/ERC165Checker.sol";
import "./IVaultHandler.sol";
import "./TCAP.sol";
import "./oracles/ChainlinkOracle.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title TCAP Orchestrator
* @author Cryptex.finance
* @notice Orchestrator contract in charge of managing the settings of the vaults, rewards and TCAP token. It acts as the owner of these contracts.
*/
contract Orchestrator is Ownable {
/// @dev Enum which saves the available functions to emergency call.
enum Functions {BURNFEE, LIQUIDATION, PAUSE}
/// @notice Address that can set to 0 the fees or pause the vaults in an emergency event
address public guardian;
/** @dev Interface constants*/
bytes4 private constant _INTERFACE_ID_IVAULT = 0x9e75ab0c;
bytes4 private constant _INTERFACE_ID_TCAP = 0xbd115939;
bytes4 private constant _INTERFACE_ID_CHAINLINK_ORACLE = 0x85be402b;
/// @dev tracks which vault was emergency called
mapping(IVaultHandler => mapping(Functions => bool)) private emergencyCalled;
/// @notice An event emitted when the guardian is updated
event GuardianSet(address indexed _owner, address guardian);
/// @notice An event emitted when a transaction is executed
event TransactionExecuted(
address indexed target,
uint256 value,
string signature,
bytes data
);
/**
* @notice Constructor
* @param _guardian The guardian address
*/
constructor(address _guardian) {
require(
_guardian != address(0),
"Orchestrator::constructor: guardian can't be zero"
);
guardian = _guardian;
}
/// @notice Throws if called by any account other than the guardian
modifier onlyGuardian() {
require(
msg.sender == guardian,
"Orchestrator::onlyGuardian: caller is not the guardian"
);
_;
}
/**
* @notice Throws if vault is not valid.
* @param _vault address
*/
modifier validVault(IVaultHandler _vault) {
require(
ERC165Checker.supportsInterface(address(_vault), _INTERFACE_ID_IVAULT),
"Orchestrator::validVault: not a valid vault"
);
_;
}
/**
* @notice Throws if TCAP Token is not valid
* @param _tcap address
*/
modifier validTCAP(TCAP _tcap) {
require(
ERC165Checker.supportsInterface(address(_tcap), _INTERFACE_ID_TCAP),
"Orchestrator::validTCAP: not a valid TCAP ERC20"
);
_;
}
/**
* @notice Throws if Chainlink Oracle is not valid
* @param _oracle address
*/
modifier validChainlinkOracle(address _oracle) {
require(
ERC165Checker.supportsInterface(
address(_oracle),
_INTERFACE_ID_CHAINLINK_ORACLE
),
"Orchestrator::validChainlinkOrchestrator: not a valid Chainlink Oracle"
);
_;
}
/**
* @notice Sets the guardian of the orchestrator
* @param _guardian address of the guardian
* @dev Only owner can call it
*/
function setGuardian(address _guardian) external onlyOwner {
require(
_guardian != address(0),
"Orchestrator::setGuardian: guardian can't be zero"
);
guardian = _guardian;
emit GuardianSet(msg.sender, _guardian);
}
/**
* @notice Sets the ratio of a vault
* @param _vault address
* @param _ratio value
* @dev Only owner can call it
*/
function setRatio(IVaultHandler _vault, uint256 _ratio)
external
onlyOwner
validVault(_vault)
{
_vault.setRatio(_ratio);
}
/**
* @notice Sets the burn fee of a vault
* @param _vault address
* @param _burnFee value
* @dev Only owner can call it
*/
function setBurnFee(IVaultHandler _vault, uint256 _burnFee)
external
onlyOwner
validVault(_vault)
{
_vault.setBurnFee(_burnFee);
}
/**
* @notice Sets the burn fee to 0, only used on a black swan event
* @param _vault address
* @dev Only guardian can call it
* @dev Validates if _vault is valid
*/
function setEmergencyBurnFee(IVaultHandler _vault)
external
onlyGuardian
validVault(_vault)
{
require(
emergencyCalled[_vault][Functions.BURNFEE] != true,
"Orchestrator::setEmergencyBurnFee: emergency call already used"
);
emergencyCalled[_vault][Functions.BURNFEE] = true;
_vault.setBurnFee(0);
}
/**
* @notice Sets the liquidation penalty of a vault
* @param _vault address
* @param _liquidationPenalty value
* @dev Only owner can call it
*/
function setLiquidationPenalty(
IVaultHandler _vault,
uint256 _liquidationPenalty
) external onlyOwner validVault(_vault) {
_vault.setLiquidationPenalty(_liquidationPenalty);
}
/**
* @notice Sets the liquidation penalty of a vault to 0, only used on a black swan event
* @param _vault address
* @dev Only guardian can call it
* @dev Validates if _vault is valid
*/
function setEmergencyLiquidationPenalty(IVaultHandler _vault)
external
onlyGuardian
validVault(_vault)
{
require(
emergencyCalled[_vault][Functions.LIQUIDATION] != true,
"Orchestrator::setEmergencyLiquidationPenalty: emergency call already used"
);
emergencyCalled[_vault][Functions.LIQUIDATION] = true;
_vault.setLiquidationPenalty(0);
}
/**
* @notice Pauses the Vault
* @param _vault address
* @dev Only guardian can call it
* @dev Validates if _vault is valid
*/
function pauseVault(IVaultHandler _vault)
external
onlyGuardian
validVault(_vault)
{
require(
emergencyCalled[_vault][Functions.PAUSE] != true,
"Orchestrator::pauseVault: emergency call already used"
);
emergencyCalled[_vault][Functions.PAUSE] = true;
_vault.pause();
}
/**
* @notice Unpauses the Vault
* @param _vault address
* @dev Only guardian can call it
* @dev Validates if _vault is valid
*/
function unpauseVault(IVaultHandler _vault)
external
onlyGuardian
validVault(_vault)
{
_vault.unpause();
}
/**
* @notice Enables or disables the TCAP Cap
* @param _tcap address
* @param _enable bool
* @dev Only owner can call it
* @dev Validates if _tcap is valid
*/
function enableTCAPCap(TCAP _tcap, bool _enable)
external
onlyOwner
validTCAP(_tcap)
{
_tcap.enableCap(_enable);
}
/**
* @notice Sets the TCAP maximum minting value
* @param _tcap address
* @param _cap uint value
* @dev Only owner can call it
* @dev Validates if _tcap is valid
*/
function setTCAPCap(TCAP _tcap, uint256 _cap)
external
onlyOwner
validTCAP(_tcap)
{
_tcap.setCap(_cap);
}
/**
* @notice Adds Vault to TCAP ERC20
* @param _tcap address
* @param _vault address
* @dev Only owner can call it
* @dev Validates if _tcap is valid
* @dev Validates if _vault is valid
*/
function addTCAPVault(TCAP _tcap, IVaultHandler _vault)
external
onlyOwner
validTCAP(_tcap)
validVault(_vault)
{
_tcap.addVaultHandler(address(_vault));
}
/**
* @notice Removes Vault to TCAP ERC20
* @param _tcap address
* @param _vault address
* @dev Only owner can call it
* @dev Validates if _tcap is valid
* @dev Validates if _vault is valid
*/
function removeTCAPVault(TCAP _tcap, IVaultHandler _vault)
external
onlyOwner
validTCAP(_tcap)
validVault(_vault)
{
_tcap.removeVaultHandler(address(_vault));
}
/**
* @notice Allows the owner to execute custom transactions
* @param target address
* @param value uint256
* @param signature string
* @param data bytes
* @dev Only owner can call it
*/
function executeTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data
) external payable onlyOwner returns (bytes memory) {
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
} else {
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
require(
target != address(0),
"Orchestrator::executeTransaction: target can't be zero"
);
// solium-disable-next-line security/no-call-value
(bool success, bytes memory returnData) =
target.call{value: value}(callData);
require(
success,
"Orchestrator::executeTransaction: Transaction execution reverted."
);
emit TransactionExecuted(target, value, signature, data);
(target, value, signature, data);
return returnData;
}
/**
* @notice Retrieves the eth stuck on the orchestrator
* @param _to address
* @dev Only owner can call it
*/
function retrieveETH(address _to) external onlyOwner {
require(
_to != address(0),
"Orchestrator::retrieveETH: address can't be zero"
);
uint256 amount = address(this).balance;
payable(_to).transfer(amount);
}
/// @notice Allows the contract to receive ETH
receive() external payable {}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/introspection/IERC165.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./Orchestrator.sol";
/**
* @title Total Market Cap Token
* @author Cryptex.finance
* @notice ERC20 token on the Ethereum Blockchain that provides total exposure to the cryptocurrency sector.
*/
contract TCAP is ERC20, Ownable, IERC165 {
/// @notice Open Zeppelin libraries
using SafeMath for uint256;
/// @notice if enabled TCAP can't be minted if the total supply is above or equal the cap value
bool public capEnabled = false;
/// @notice Maximum value the total supply of TCAP
uint256 public cap;
/**
* @notice Address to Vault Handler
* @dev Only vault handlers can mint and burn TCAP
*/
mapping(address => bool) public vaultHandlers;
/**
* @dev the computed interface ID according to ERC-165. The interface ID is a XOR of interface method selectors.
* mint.selector ^
* burn.selector ^
* setCap.selector ^
* enableCap.selector ^
* transfer.selector ^
* transferFrom.selector ^
* addVaultHandler.selector ^
* removeVaultHandler.selector ^
* approve.selector => 0xbd115939
*/
bytes4 private constant _INTERFACE_ID_TCAP = 0xbd115939;
/// @dev bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/// @notice An event emitted when a vault handler is added
event VaultHandlerAdded(
address indexed _owner,
address indexed _tokenHandler
);
/// @notice An event emitted when a vault handler is removed
event VaultHandlerRemoved(
address indexed _owner,
address indexed _tokenHandler
);
/// @notice An event emitted when the cap value is updated
event NewCap(address indexed _owner, uint256 _amount);
/// @notice An event emitted when the cap is enabled or disabled
event NewCapEnabled(address indexed _owner, bool _enable);
/**
* @notice Constructor
* @param _name uint256
* @param _symbol uint256
* @param _cap uint256
* @param _orchestrator address
*/
constructor(
string memory _name,
string memory _symbol,
uint256 _cap,
Orchestrator _orchestrator
) ERC20(_name, _symbol) {
cap = _cap;
/// @dev transfer ownership to orchestrator
transferOwnership(address(_orchestrator));
}
/// @notice Reverts if called by any account that is not a vault.
modifier onlyVault() {
require(
vaultHandlers[msg.sender],
"TCAP::onlyVault: caller is not a vault"
);
_;
}
/**
* @notice Adds a new address as a vault
* @param _vaultHandler address of a contract with permissions to mint and burn tokens
* @dev Only owner can call it
*/
function addVaultHandler(address _vaultHandler) external onlyOwner {
vaultHandlers[_vaultHandler] = true;
emit VaultHandlerAdded(msg.sender, _vaultHandler);
}
/**
* @notice Removes an address as a vault
* @param _vaultHandler address of the contract to be removed as vault
* @dev Only owner can call it
*/
function removeVaultHandler(address _vaultHandler) external onlyOwner {
vaultHandlers[_vaultHandler] = false;
emit VaultHandlerRemoved(msg.sender, _vaultHandler);
}
/**
* @notice Mints TCAP Tokens
* @param _account address of the receiver of tokens
* @param _amount uint of tokens to mint
* @dev Only vault can call it
*/
function mint(address _account, uint256 _amount) external onlyVault {
_mint(_account, _amount);
}
/**
* @notice Burns TCAP Tokens
* @param _account address of the account which is burning tokens.
* @param _amount uint of tokens to burn
* @dev Only vault can call it
*/
function burn(address _account, uint256 _amount) external onlyVault {
_burn(_account, _amount);
}
/**
* @notice Sets maximum value the total supply of TCAP can have
* @param _cap value
* @dev When capEnabled is true, mint is not allowed to issue tokens that would increase the total supply above or equal the specified capacity.
* @dev Only owner can call it
*/
function setCap(uint256 _cap) external onlyOwner {
cap = _cap;
emit NewCap(msg.sender, _cap);
}
/**
* @notice Enables or Disables the Total Supply Cap.
* @param _enable value
* @dev When capEnabled is true, minting will not be allowed above the max capacity. It can exist a supply above the cap, but it prevents minting above the cap.
* @dev Only owner can call it
*/
function enableCap(bool _enable) external onlyOwner {
capEnabled = _enable;
emit NewCapEnabled(msg.sender, _enable);
}
/**
* @notice ERC165 Standard for support of interfaces
* @param _interfaceId bytes of interface
* @return bool
*/
function supportsInterface(bytes4 _interfaceId)
external
pure
override
returns (bool)
{
return (_interfaceId == _INTERFACE_ID_TCAP ||
_interfaceId == _INTERFACE_ID_ERC165);
}
/**
* @notice executes before each token transfer or mint
* @param _from address
* @param _to address
* @param _amount value to transfer
* @dev See {ERC20-_beforeTokenTransfer}.
* @dev minted tokens must not cause the total supply to go over the cap.
* @dev Reverts if the to address is equal to token address
*/
function _beforeTokenTransfer(
address _from,
address _to,
uint256 _amount
) internal virtual override {
super._beforeTokenTransfer(_from, _to, _amount);
require(
_to != address(this),
"TCAP::transfer: can't transfer to TCAP contract"
);
if (_from == address(0) && capEnabled) {
// When minting tokens
require(
totalSupply().add(_amount) <= cap,
"TCAP::Transfer: TCAP cap exceeded"
);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/introspection/IERC165.sol";
/**
* @title Chainlink Oracle
* @author Cryptex.finance
* @notice Contract in charge or reading the information from a Chainlink Oracle. TCAP contracts read the price directly from this contract. More information can be found on Chainlink Documentation
*/
contract ChainlinkOracle is Ownable, IERC165 {
AggregatorV3Interface internal aggregatorContract;
/*
* setReferenceContract.selector ^
* getLatestAnswer.selector ^
* getLatestTimestamp.selector ^
* getPreviousAnswer.selector ^
* getPreviousTimestamp.selector => 0x85be402b
*/
bytes4 private constant _INTERFACE_ID_CHAINLINK_ORACLE = 0x85be402b;
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @notice Called once the contract is deployed.
* Set the Chainlink Oracle as an aggregator.
*/
constructor(address _aggregator, address _timelock) {
require(_aggregator != address(0) && _timelock != address(0), "address can't be 0");
aggregatorContract = AggregatorV3Interface(_aggregator);
transferOwnership(_timelock);
}
/**
* @notice Changes the reference contract.
* @dev Only owner can call it.
*/
function setReferenceContract(address _aggregator) public onlyOwner() {
aggregatorContract = AggregatorV3Interface(_aggregator);
}
/**
* @notice Returns the latest answer from the reference contract.
* @return price
*/
function getLatestAnswer() public view returns (int256) {
(
uint80 roundID,
int256 price,
,
uint256 timeStamp,
uint80 answeredInRound
) = aggregatorContract.latestRoundData();
require(
timeStamp != 0,
"ChainlinkOracle::getLatestAnswer: round is not complete"
);
require(
answeredInRound >= roundID,
"ChainlinkOracle::getLatestAnswer: stale data"
);
return price;
}
/**
* @notice Returns the latest round from the reference contract.
*/
function getLatestRound()
public
view
returns (
uint80,
int256,
uint256,
uint256,
uint80
)
{
(
uint80 roundID,
int256 price,
uint256 startedAt,
uint256 timeStamp,
uint80 answeredInRound
) = aggregatorContract.latestRoundData();
return (roundID, price, startedAt, timeStamp, answeredInRound);
}
/**
* @notice Returns a given round from the reference contract.
* @param _id of round
*/
function getRound(uint80 _id)
public
view
returns (
uint80,
int256,
uint256,
uint256,
uint80
)
{
(
uint80 roundID,
int256 price,
uint256 startedAt,
uint256 timeStamp,
uint80 answeredInRound
) = aggregatorContract.getRoundData(_id);
return (roundID, price, startedAt, timeStamp, answeredInRound);
}
/**
* @notice Returns the last time the Oracle was updated.
*/
function getLatestTimestamp() public view returns (uint256) {
(, , , uint256 timeStamp, ) = aggregatorContract.latestRoundData();
return timeStamp;
}
/**
* @notice Returns a previous answer updated on the Oracle.
* @param _id of round
* @return price
*/
function getPreviousAnswer(uint80 _id) public view returns (int256) {
(uint80 roundID, int256 price, , , ) = aggregatorContract.getRoundData(_id);
require(
_id <= roundID,
"ChainlinkOracle::getPreviousAnswer: not enough history"
);
return price;
}
/**
* @notice Returns a previous time the Oracle was updated.
* @param _id of round
* @return timeStamp
*/
function getPreviousTimestamp(uint80 _id) public view returns (uint256) {
(uint80 roundID, , , uint256 timeStamp, ) =
aggregatorContract.getRoundData(_id);
require(
_id <= roundID,
"ChainlinkOracle::getPreviousTimestamp: not enough history"
);
return timeStamp;
}
/**
* @notice ERC165 Standard for support of interfaces.
*/
function supportsInterface(bytes4 interfaceId)
external
pure
override
returns (bool)
{
return (interfaceId == _INTERFACE_ID_CHAINLINK_ORACLE ||
interfaceId == _INTERFACE_ID_ERC165);
}
} | * @notice Allows the safe transfer of ETH @param _to account to transfer ETH @param _value amount of ETH/ | function safeTransferETH(address _to, uint256 _value) internal {
require(success, "ETHVaultHandler::safeTransferETH: ETH transfer failed");
}
| 172,372 | [
1,
19132,
326,
4183,
7412,
434,
512,
2455,
225,
389,
869,
2236,
358,
7412,
512,
2455,
225,
389,
1132,
3844,
434,
512,
2455,
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,
225,
445,
4183,
5912,
1584,
44,
12,
2867,
389,
869,
16,
2254,
5034,
389,
1132,
13,
2713,
288,
203,
565,
2583,
12,
4768,
16,
315,
1584,
44,
12003,
1503,
2866,
4626,
5912,
1584,
44,
30,
512,
2455,
7412,
2535,
8863,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/4/0x8D91e9A6f34169E04e49a63E0215a239c98f6Baf/sources/src/PriceFeedConsumer.sol | * @title The PriceConsumerV3 contract @notice Acontract that returns latest price from Chainlink Price Feeds/ | contract PriceFeedConsumer {
AggregatorV3Interface internal immutable priceFeed;
pragma solidity ^0.8.7;
constructor(address _priceFeed) {
priceFeed = AggregatorV3Interface(_priceFeed);
}
function getLatestPrice() public view returns (int256) {
(
uint80 roundID,
int256 price,
uint256 startedAt,
uint256 timeStamp,
uint80 answeredInRound
) = priceFeed.latestRoundData();
return price;
}
function getPriceFeed() public view returns (AggregatorV3Interface) {
return priceFeed;
}
}
| 12,297,643 | [
1,
1986,
20137,
5869,
58,
23,
6835,
225,
432,
16351,
716,
1135,
4891,
6205,
628,
7824,
1232,
20137,
5782,
9765,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
20137,
8141,
5869,
288,
203,
565,
10594,
639,
58,
23,
1358,
2713,
11732,
6205,
8141,
31,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
27,
31,
203,
565,
3885,
12,
2867,
389,
8694,
8141,
13,
288,
203,
3639,
6205,
8141,
273,
10594,
639,
58,
23,
1358,
24899,
8694,
8141,
1769,
203,
565,
289,
203,
203,
565,
445,
336,
18650,
5147,
1435,
1071,
1476,
1135,
261,
474,
5034,
13,
288,
203,
3639,
261,
203,
5411,
2254,
3672,
3643,
734,
16,
203,
5411,
509,
5034,
6205,
16,
203,
5411,
2254,
5034,
5746,
861,
16,
203,
5411,
2254,
5034,
18198,
16,
203,
5411,
2254,
3672,
5803,
329,
382,
11066,
203,
3639,
262,
273,
6205,
8141,
18,
13550,
11066,
751,
5621,
203,
3639,
327,
6205,
31,
203,
565,
289,
203,
203,
565,
445,
25930,
8141,
1435,
1071,
1476,
1135,
261,
17711,
58,
23,
1358,
13,
288,
203,
3639,
327,
6205,
8141,
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
] |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.3;
import "./Storage.sol";
// This library is an assembly optimized storage library which is designed
// to track timestamp history in a struct which uses hash derived pointers.
// WARNING - Developers using it should not access the underlying storage
// directly since we break some assumptions of high level solidity. Please
// note this library also increases the risk profile of memory manipulation
// please be cautious in your usage of uninitialized memory structs and other
// anti patterns.
library History {
// The storage layout of the historical array looks like this
// [(128 bit min index)(128 bit length)] [0][0] ... [(64 bit block num)(192 bit data)] .... [(64 bit block num)(192 bit data)]
// We give the option to the invoker of the search function the ability to clear
// stale storage. To find data we binary search for the block number we need
// This library expects the blocknumber indexed data to be pushed in ascending block number
// order and if data is pushed with the same blocknumber it only retains the most recent.
// This ensures each blocknumber is unique and contains the most recent data at the end
// of whatever block it indexes [as long as that block is not the current one].
// A struct which wraps a memory pointer to a string and the pointer to storage
// derived from that name string by the storage library
// WARNING - For security purposes never directly construct this object always use load
struct HistoricalBalances {
string name;
// Note - We use bytes32 to reduce how easy this is to manipulate in high level sol
bytes32 cachedPointer;
}
/// @notice The method by which inheriting contracts init the HistoricalBalances struct
/// @param name The name of the variable. Note - these are globals, any invocations of this
/// with the same name work on the same storage.
/// @return The memory pointer to the wrapper of the storage pointer
function load(string memory name)
internal
pure
returns (HistoricalBalances memory)
{
mapping(address => uint256[]) storage storageData =
Storage.mappingAddressToUnit256ArrayPtr(name);
bytes32 pointer;
assembly {
pointer := storageData.slot
}
return HistoricalBalances(name, pointer);
}
/// @notice An unsafe method of attaching the cached ptr in a historical balance memory objects
/// @param pointer cached pointer to storage
/// @return storageData A storage array mapping pointer
/// @dev PLEASE DO NOT USE THIS METHOD WITHOUT SERIOUS REVIEW. IF AN EXTERNAL ACTOR CAN CALL THIS WITH
// ARBITRARY DATA THEY MAY BE ABLE TO OVERWRITE ANY STORAGE IN THE CONTRACT.
function _getMapping(bytes32 pointer)
private
pure
returns (mapping(address => uint256[]) storage storageData)
{
assembly {
storageData.slot := pointer
}
}
/// @notice This function adds a block stamp indexed piece of data to a historical data array
/// To prevent duplicate entries if the top of the array has the same blocknumber
/// the value is updated instead
/// @param wrapper The wrapper which hold the reference to the historical data storage pointer
/// @param who The address which indexes the array we need to push to
/// @param data The data to append, should be at most 192 bits and will revert if not
function push(
HistoricalBalances memory wrapper,
address who,
uint256 data
) internal {
// Check preconditions
// OoB = Out of Bounds, short for contract bytecode size reduction
require(data <= type(uint192).max, "OoB");
// Get the storage this is referencing
mapping(address => uint256[]) storage storageMapping =
_getMapping(wrapper.cachedPointer);
// Get the array we need to push to
uint256[] storage storageData = storageMapping[who];
// We load the block number and then shift it to be in the top 64 bits
uint256 blockNumber = block.number << 192;
// We combine it with the data, because of our require this will have a clean
// top 64 bits
uint256 packedData = blockNumber | data;
// Load the array length
(uint256 minIndex, uint256 length) = _loadBounds(storageData);
// On the first push we don't try to load
uint256 loadedBlockNumber = 0;
if (length != 0) {
(loadedBlockNumber, ) = _loadAndUnpack(storageData, length - 1);
}
// The index we push to, note - we use this pattern to not branch the assembly
uint256 index = length;
// If the caller is changing data in the same block we change the entry for this block
// instead of adding a new one. This ensures each block numb is unique in the array.
if (loadedBlockNumber == block.number) {
index = length - 1;
}
// We use assembly to write our data to the index
assembly {
// Stores packed data in the equivalent of storageData[length]
sstore(
add(
// The start of the data slots
add(storageData.slot, 1),
// index where we store
index
),
packedData
)
}
// Reset the boundaries if they changed
if (loadedBlockNumber != block.number) {
_setBounds(storageData, minIndex, length + 1);
}
}
/// @notice Loads the most recent timestamp of delegation power
/// @param wrapper The memory struct which we want to search for historical data
/// @param who The user who's balance we want to load
/// @return the top slot of the array
function loadTop(HistoricalBalances memory wrapper, address who)
internal
view
returns (uint256)
{
// Load the storage pointer
uint256[] storage userData = _getMapping(wrapper.cachedPointer)[who];
// Load the length
(, uint256 length) = _loadBounds(userData);
// If it's zero no data has ever been pushed so we return zero
if (length == 0) {
return 0;
}
// Load the current top
(, uint256 storedData) = _loadAndUnpack(userData, length - 1);
// and return it
return (storedData);
}
/// @notice Finds the data stored with the highest block number which is less than or equal to a provided
/// blocknumber.
/// @param wrapper The memory struct which we want to search for historical data
/// @param who The address which indexes the array to be searched
/// @param blocknumber The blocknumber we want to load the historical data of
/// @return The loaded unpacked data at this point in time.
function find(
HistoricalBalances memory wrapper,
address who,
uint256 blocknumber
) internal view returns (uint256) {
// Get the storage this is referencing
mapping(address => uint256[]) storage storageMapping =
_getMapping(wrapper.cachedPointer);
// Get the array we need to push to
uint256[] storage storageData = storageMapping[who];
// Pre load the bounds
(uint256 minIndex, uint256 length) = _loadBounds(storageData);
// Search for the blocknumber
(, uint256 loadedData) =
_find(storageData, blocknumber, 0, minIndex, length);
// In this function we don't have to change the stored length data
return (loadedData);
}
/// @notice Finds the data stored with the highest blocknumber which is less than or equal to a provided block number
/// Opportunistically clears any data older than staleBlock which is possible to clear.
/// @param wrapper The memory struct which points to the storage we want to search
/// @param who The address which indexes the historical data we want to search
/// @param blocknumber The blocknumber we want to load the historical state of
/// @param staleBlock A block number which we can [but are not obligated to] delete history older than
/// @return The found data
function findAndClear(
HistoricalBalances memory wrapper,
address who,
uint256 blocknumber,
uint256 staleBlock
) internal returns (uint256) {
// Get the storage this is referencing
mapping(address => uint256[]) storage storageMapping =
_getMapping(wrapper.cachedPointer);
// Get the array we need to push to
uint256[] storage storageData = storageMapping[who];
// Pre load the bounds
(uint256 minIndex, uint256 length) = _loadBounds(storageData);
// Search for the blocknumber
(uint256 staleIndex, uint256 loadedData) =
_find(storageData, blocknumber, staleBlock, minIndex, length);
// We clear any data in the stale region
// Note - Since find returns 0 if no stale data is found and we use > instead of >=
// this won't trigger if no stale data is found. Plus it won't trigger on minIndex == staleIndex
// == maxIndex and clear the whole array.
if (staleIndex > minIndex) {
// Delete the outdated stored info
_clear(minIndex, staleIndex, storageData);
// Reset the array info with stale index as the new minIndex
_setBounds(storageData, staleIndex, length);
}
return (loadedData);
}
/// @notice Searches for the data stored at the largest blocknumber index less than a provided parameter.
/// Allows specification of a expiration stamp and returns the greatest examined index which is
/// found to be older than that stamp.
/// @param data The stored data
/// @param blocknumber the blocknumber we want to load the historical data for.
/// @param staleBlock The oldest block that we care about the data stored for, all previous data can be deleted
/// @param startingMinIndex The smallest filled index in the array
/// @param length the length of the array
/// @return Returns the largest stale data index seen or 0 for no seen stale data and the stored data
function _find(
uint256[] storage data,
uint256 blocknumber,
uint256 staleBlock,
uint256 startingMinIndex,
uint256 length
) private view returns (uint256, uint256) {
// We explicitly revert on the reading of memory which is uninitialized
require(length != 0, "uninitialized");
// Do some correctness checks
require(staleBlock <= blocknumber);
require(startingMinIndex < length);
// Load the bounds of our binary search
uint256 maxIndex = length - 1;
uint256 minIndex = startingMinIndex;
uint256 staleIndex = 0;
// We run a binary search on the block number fields in the array between
// the minIndex and maxIndex. If we find indexes with blocknumber < staleBlock
// we set staleIndex to them and return that data for an optional clearing step
// in the calling function.
while (minIndex != maxIndex) {
// We use the ceil instead of the floor because this guarantees that
// we pick the highest blocknumber less than or equal the requested one
uint256 mid = (minIndex + maxIndex + 1) / 2;
// Load and unpack the data in the midpoint index
(uint256 pastBlock, uint256 loadedData) = _loadAndUnpack(data, mid);
// If we've found the exact block we are looking for
if (pastBlock == blocknumber) {
// Then we just return the data
return (staleIndex, loadedData);
// Otherwise if the loaded block is smaller than the block number
} else if (pastBlock < blocknumber) {
// Then we first check if this is possibly a stale block
if (pastBlock < staleBlock) {
// If it is we mark it for clearing
staleIndex = mid;
}
// We then repeat the search logic on the indices greater than the midpoint
minIndex = mid;
// In this case the pastBlock > blocknumber
} else {
// We then repeat the search on the indices below the midpoint
maxIndex = mid - 1;
}
}
// We load at the final index of the search
(uint256 _pastBlock, uint256 _loadedData) =
_loadAndUnpack(data, minIndex);
// This will only be hit if a user has misconfigured the stale index and then
// tried to load father into the past than has been preserved
require(_pastBlock <= blocknumber, "Search Failure");
return (staleIndex, _loadedData);
}
/// @notice Clears storage between two bounds in array
/// @param oldMin The first index to set to zero
/// @param newMin The new minimum filled index, ie clears to index < newMin
/// @param data The storage array pointer
function _clear(
uint256 oldMin,
uint256 newMin,
uint256[] storage data
) private {
// Correctness checks on this call
require(oldMin <= newMin);
// This function is private and trusted and should be only called by functions which ensure
// that oldMin < newMin < length
assembly {
// The layout of arrays in solidity is [length][data]....[data] so this pointer is the
// slot to write to data
let dataLocation := add(data.slot, 1)
// Loop through each index which is below new min and clear the storage
// Note - Uses strict min so if given an input like oldMin = 5 newMin = 5 will be a no op
for {
let i := oldMin
} lt(i, newMin) {
i := add(i, 1)
} {
// store at the starting data pointer + i 256 bits of zero
sstore(add(dataLocation, i), 0)
}
}
}
/// @notice Loads and unpacks the block number index and stored data from a data array
/// @param data the storage array
/// @param i the index to load and unpack
/// @return (block number, stored data)
function _loadAndUnpack(uint256[] storage data, uint256 i)
private
view
returns (uint256, uint256)
{
// This function is trusted and should only be called after checking data lengths
// we use assembly for the sload to avoid reloading length.
uint256 loaded;
assembly {
loaded := sload(add(add(data.slot, 1), i))
}
// Unpack the packed 64 bit block number and 192 bit data field
return (
loaded >> 192,
loaded &
0x0000000000000000ffffffffffffffffffffffffffffffffffffffffffffffff
);
}
/// @notice This function sets our non standard bounds data field where a normal array
/// would have length
/// @param data the pointer to the storage array
/// @param minIndex The minimum non stale index
/// @param length The length of the storage array
function _setBounds(
uint256[] storage data,
uint256 minIndex,
uint256 length
) private {
// Correctness check
require(minIndex < length);
assembly {
// Ensure data cleanliness
let clearedLength := and(
length,
0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff
)
// We move the min index into the top 128 bits by shifting it left by 128 bits
let minInd := shl(128, minIndex)
// We pack the data using binary or
let packed := or(minInd, clearedLength)
// We store in the packed data in the length field of this storage array
sstore(data.slot, packed)
}
}
/// @notice This function loads and unpacks our packed min index and length for our custom storage array
/// @param data The pointer to the storage location
/// @return minInd the first filled index in the array
/// @return length the length of the array
function _loadBounds(uint256[] storage data)
private
view
returns (uint256 minInd, uint256 length)
{
// Use assembly to manually load the length storage field
uint256 packedData;
assembly {
packedData := sload(data.slot)
}
// We use a shift right to clear out the low order bits of the data field
minInd = packedData >> 128;
// We use a binary and to extract only the bottom 128 bits
length =
packedData &
0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff;
}
}
| The index we push to, note - we use this pattern to not branch the assembly | uint256 index = length;
| 5,506,027 | [
1,
1986,
770,
732,
1817,
358,
16,
4721,
300,
732,
999,
333,
1936,
358,
486,
3803,
326,
19931,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
5034,
770,
273,
769,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2020-10-17
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @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;
}
}
interface ITokenInterface {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function burn(uint amount) external;
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IValueLiquidPool {
function swapExactAmountIn(address tokenIn, uint tokenAmountIn, address tokenOut, uint minAmountOut, uint maxPrice) external returns (uint tokenAmountOut, uint spotPriceAfter);
}
interface IUniswapRouter {
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}
// This class implements IValueLiquidPool to support Value Vault's strategies
// Will implement UniswapRouter.swapExactTokensForTokensSupportingFeeOnTransferTokens for some rare cases which takes fee for token transfer (eg. Dego.finance)
contract UniswapRouterSupportingFeeOnTransferTokens is IValueLiquidPool, IUniswapRouter {
using SafeMath for uint256;
address public governance;
IUniswapRouter public unirouter = IUniswapRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uint256 public constant FEE_DENOMINATOR = 10000;
uint256 public performanceFee = 0; // 0% at start and can be set by governance decision
mapping(address => mapping(address => address[])) public uniswapPaths; // [input -> output] => uniswap_path
mapping(address => bool) public hasTransferFee; // token_address => has_transfer_fee
constructor(address _tokenHasTransferFee) public {
hasTransferFee[_tokenHasTransferFee] = true;
governance = msg.sender;
}
function setGovernance(address _governance) external {
require(msg.sender == governance, "!governance");
governance = _governance;
}
function approveForSpender(ITokenInterface _token, address _spender, uint256 _amount) external {
require(msg.sender == governance, "!governance");
_token.approve(_spender, _amount);
}
function setUnirouter(IUniswapRouter _unirouter) external {
require(msg.sender == governance, "!governance");
unirouter = _unirouter;
}
function setPerformanceFee(uint256 _performanceFee) public {
require(msg.sender == governance, "!governance");
performanceFee = _performanceFee;
}
function setHasTransferFee(address _token, bool _hasFee) public {
require(msg.sender == governance, "!governance");
hasTransferFee[_token] = _hasFee;
}
function setUnirouterPath(address _input, address _output, address [] memory _path) public {
require(msg.sender == governance, "!governance");
uniswapPaths[_input][_output] = _path;
}
function swapExactAmountIn(address _tokenIn, uint _tokenAmountIn, address _tokenOut, uint _minAmountOut, uint) external override returns (uint _tokenAmountOut, uint) {
address[] memory path = uniswapPaths[_tokenIn][_tokenOut];
if (block.timestamp == 0) { //injected CONTRACT AFFECTED BY MINERS
// path: _input -> _output
path = new address[](2);
path[0] = _tokenIn;
path[1] = _tokenOut;
}
ITokenInterface input = ITokenInterface(_tokenIn);
ITokenInterface output = ITokenInterface(_tokenOut);
input.transferFrom(msg.sender, address(this), _tokenAmountIn);
if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS
uint256 performanceFeeAmount = _tokenAmountIn.mul(performanceFee).div(FEE_DENOMINATOR);
_tokenAmountIn = _tokenAmountIn.sub(performanceFeeAmount);
input.transfer(governance, performanceFeeAmount);
}
if (hasTransferFee[_tokenIn] || hasTransferFee[_tokenOut]) {
// swapExactTokensForTokensSupportingFeeOnTransferTokens(amountIn, amountOutMin, path, to, deadline)
unirouter.swapExactTokensForTokensSupportingFeeOnTransferTokens(_tokenAmountIn, _minAmountOut, path, msg.sender, now.add(1800));
} else {
// swapExactTokensForTokens(amountIn, amountOutMin, path, to, deadline)
unirouter.swapExactTokensForTokens(_tokenAmountIn, _minAmountOut, path, msg.sender, now.add(1800));
}
_tokenAmountOut = output.balanceOf(address(this));
output.transfer(msg.sender, _tokenAmountOut);
}
function swapExactTokensForTokens(uint256 _amountIn, uint256 _amountOutMin, address[] calldata _path, address _to, uint256 _deadline) external override returns (uint256[] memory amounts) {
ITokenInterface input = ITokenInterface(_path[0]);
input.transferFrom(msg.sender, address(this), _amountIn);
if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS
uint256 performanceFeeAmount = _amountIn.mul(performanceFee).div(FEE_DENOMINATOR);
_amountIn = _amountIn.sub(performanceFeeAmount);
input.transfer(governance, performanceFeeAmount);
}
amounts = unirouter.swapExactTokensForTokens(_amountIn, _amountOutMin, _path, _to, _deadline);
}
function swapExactTokensForTokensSupportingFeeOnTransferTokens(uint256 _amountIn, uint256 _amountOutMin, address[] calldata _path, address _to, uint256 _deadline) external override returns (uint256[] memory amounts) {
ITokenInterface input = ITokenInterface(_path[0]);
input.transferFrom(msg.sender, address(this), _amountIn);
if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS
uint256 performanceFeeAmount = _amountIn.mul(performanceFee).div(FEE_DENOMINATOR);
_amountIn = _amountIn.sub(performanceFeeAmount);
input.transfer(governance, performanceFeeAmount);
}
amounts = unirouter.swapExactTokensForTokensSupportingFeeOnTransferTokens(_amountIn, _amountOutMin, _path, _to, _deadline);
}
/**
* This function allows governance to take unsupported tokens out of the contract.
* This is in an effort to make someone whole, should they seriously mess up.
* There is no guarantee governance will vote to return these.
* It also allows for removal of airdropped tokens.
*/
function governanceRecoverUnsupported(ITokenInterface _token, uint256 amount, address to) external {
require(msg.sender == governance, "!governance");
_token.transfer(to, amount);
}
} | This class implements IValueLiquidPool to support Value Vault's strategies Will implement UniswapRouter.swapExactTokensForTokensSupportingFeeOnTransferTokens for some rare cases which takes fee for token transfer (eg. Dego.finance) | contract UniswapRouterSupportingFeeOnTransferTokens is IValueLiquidPool, IUniswapRouter {
using SafeMath for uint256;
address public governance;
IUniswapRouter public unirouter = IUniswapRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uint256 public constant FEE_DENOMINATOR = 10000;
constructor(address _tokenHasTransferFee) public {
hasTransferFee[_tokenHasTransferFee] = true;
governance = msg.sender;
}
function setGovernance(address _governance) external {
require(msg.sender == governance, "!governance");
governance = _governance;
}
function approveForSpender(ITokenInterface _token, address _spender, uint256 _amount) external {
require(msg.sender == governance, "!governance");
_token.approve(_spender, _amount);
}
function setUnirouter(IUniswapRouter _unirouter) external {
require(msg.sender == governance, "!governance");
unirouter = _unirouter;
}
function setPerformanceFee(uint256 _performanceFee) public {
require(msg.sender == governance, "!governance");
performanceFee = _performanceFee;
}
function setHasTransferFee(address _token, bool _hasFee) public {
require(msg.sender == governance, "!governance");
hasTransferFee[_token] = _hasFee;
}
function setUnirouterPath(address _input, address _output, address [] memory _path) public {
require(msg.sender == governance, "!governance");
uniswapPaths[_input][_output] = _path;
}
function swapExactAmountIn(address _tokenIn, uint _tokenAmountIn, address _tokenOut, uint _minAmountOut, uint) external override returns (uint _tokenAmountOut, uint) {
address[] memory path = uniswapPaths[_tokenIn][_tokenOut];
path = new address[](2);
path[0] = _tokenIn;
path[1] = _tokenOut;
}
ITokenInterface input = ITokenInterface(_tokenIn);
ITokenInterface output = ITokenInterface(_tokenOut);
input.transferFrom(msg.sender, address(this), _tokenAmountIn);
uint256 performanceFeeAmount = _tokenAmountIn.mul(performanceFee).div(FEE_DENOMINATOR);
_tokenAmountIn = _tokenAmountIn.sub(performanceFeeAmount);
input.transfer(governance, performanceFeeAmount);
}
| 885,778 | [
1,
2503,
667,
4792,
467,
620,
48,
18988,
350,
2864,
358,
2865,
1445,
17329,
1807,
20417,
9980,
2348,
1351,
291,
91,
438,
8259,
18,
22270,
14332,
5157,
1290,
5157,
6289,
310,
14667,
1398,
5912,
5157,
364,
2690,
25671,
6088,
1492,
5530,
14036,
364,
1147,
7412,
261,
1332,
18,
463,
1332,
83,
18,
926,
1359,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
16351,
1351,
291,
91,
438,
8259,
6289,
310,
14667,
1398,
5912,
5157,
353,
467,
620,
48,
18988,
350,
2864,
16,
467,
984,
291,
91,
438,
8259,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
1758,
1071,
314,
1643,
82,
1359,
31,
203,
203,
565,
467,
984,
291,
91,
438,
8259,
1071,
7738,
10717,
273,
467,
984,
291,
91,
438,
8259,
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,
203,
565,
2254,
5034,
1071,
5381,
478,
9383,
67,
13296,
1872,
706,
3575,
273,
12619,
31,
203,
203,
203,
565,
3885,
12,
2867,
389,
2316,
5582,
5912,
14667,
13,
1071,
288,
203,
3639,
711,
5912,
14667,
63,
67,
2316,
5582,
5912,
14667,
65,
273,
638,
31,
203,
3639,
314,
1643,
82,
1359,
273,
1234,
18,
15330,
31,
203,
565,
289,
203,
203,
565,
445,
26770,
1643,
82,
1359,
12,
2867,
389,
75,
1643,
82,
1359,
13,
3903,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
314,
1643,
82,
1359,
16,
17528,
75,
1643,
82,
1359,
8863,
203,
3639,
314,
1643,
82,
1359,
273,
389,
75,
1643,
82,
1359,
31,
203,
565,
289,
203,
203,
565,
445,
6617,
537,
1290,
27223,
264,
12,
1285,
969,
1358,
389,
2316,
16,
1758,
389,
87,
1302,
264,
16,
2254,
5034,
389,
8949,
13,
3903,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
314,
1643,
82,
1359,
2
] |
./full_match/5/0x21517abae577dDC59Ac6945C501F36AF085d97A7/sources/contracts/CrowdFunding.sol | we want to get a campaign from the storage named item and put it in campaign i .
| Campaign storage item = campaigns[i]; | 1,856,076 | [
1,
1814,
2545,
358,
336,
279,
8965,
628,
326,
2502,
4141,
761,
471,
1378,
518,
316,
8965,
277,
263,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
13432,
2502,
761,
273,
8965,
87,
63,
77,
15533,
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
] |
pragma solidity ^0.4.18;
import './deps/MintableToken.sol';
import './deps/ERC20Interface.sol';
import './deps/Ownable.sol';
import './deps/ApproveAndCallFallBack.sol';
contract Fr8NetworkToken is ERC20Interface, Ownable {
using SafeMath for uint;
// standard ERC20 stuff
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
bool public mintable;
// contract version
uint public version;
mapping(address => uint) internal balances;
mapping(address => mapping(address => uint)) internal allowed;
event MintingDisabled();
function Fr8NetworkToken() public {
version = 10;
// initial erc20 settings
symbol = "FR8";
name = "Fr8 Network Test Token";
decimals = 18;
mintable = true;
_totalSupply = 1000000000 * 10**uint(decimals);
balances[owner] = _totalSupply;
Transfer(address(0), owner, _totalSupply);
}
function totalSupply() public view returns (uint) {
return _totalSupply - balances[address(0)];
}
function disableMinting() public onlyOwner {
require(mintable);
mintable = false;
MintingDisabled();
}
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(msg.sender, to, tokens);
return true;
}
/**
* Token owner can approve for `spender` to transferFrom(...) `tokens`
* from the token owner's account
*
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
* recommends that there are no checks for the approval double-spend attack
* as this should be implemented in user interfaces
*/
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
/**
* Transfer `tokens` from the `from` account to the `to` account
*
* The calling account must already have sufficient tokens approve(...)-d
* for spending from the `from` account and
* - From account must have sufficient balance to transfer
* - Spender must have sufficient allowance to transfer
* - 0 value transfers are allowed
*/
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(from, to, tokens);
return true;
}
/**
* Returns the amount of tokens approved by the owner that can be
* transferred to the spender's account
*/
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
/**
* Token owner can approve for `spender` to transferFrom(...) `tokens`
* from the token owner's account. The `spender` contract function
* `receiveApproval(...)` is then executed
*/
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
/**
* Mint tokens
*/
function mint(address tokenOwner, uint tokens) public onlyOwner returns (bool success) {
require(mintable);
balances[tokenOwner] = balances[tokenOwner].add(tokens);
_totalSupply = _totalSupply.add(tokens);
Transfer(address(0), tokenOwner, tokens);
return true;
}
/**
* [Deprecated] Owner can transfer out any accidentally sent ERC20 tokens
* Ensure cannot send self token
*/
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
}
| * Transfer `tokens` from the `from` account to the `to` account The calling account must already have sufficient tokens approve(...)-d for spending from the `from` account and - From account must have sufficient balance to transfer - Spender must have sufficient allowance to transfer - 0 value transfers are allowed/ | function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(from, to, tokens);
return true;
}
| 13,017,472 | [
1,
5912,
1375,
7860,
68,
628,
326,
1375,
2080,
68,
2236,
358,
326,
1375,
869,
68,
2236,
1021,
4440,
2236,
1297,
1818,
1240,
18662,
2430,
6617,
537,
5825,
24950,
72,
364,
272,
9561,
628,
326,
1375,
2080,
68,
2236,
471,
300,
6338,
2236,
1297,
1240,
18662,
11013,
358,
7412,
300,
348,
1302,
264,
1297,
1240,
18662,
1699,
1359,
358,
7412,
300,
374,
460,
29375,
854,
2935,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
225,
445,
7412,
1265,
12,
2867,
628,
16,
1758,
358,
16,
2254,
2430,
13,
1071,
1135,
261,
6430,
2216,
13,
288,
203,
565,
324,
26488,
63,
2080,
65,
273,
324,
26488,
63,
2080,
8009,
1717,
12,
7860,
1769,
203,
565,
2935,
63,
2080,
6362,
3576,
18,
15330,
65,
273,
2935,
63,
2080,
6362,
3576,
18,
15330,
8009,
1717,
12,
7860,
1769,
203,
565,
324,
26488,
63,
869,
65,
273,
324,
26488,
63,
869,
8009,
1289,
12,
7860,
1769,
203,
565,
12279,
12,
2080,
16,
358,
16,
2430,
1769,
203,
565,
327,
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
] |
./partial_match/1/0x8d371f713A9126C89211F1006E38b9e2665c140A/sources/LAIKAGF.sol | Create a uniswap pair for this new token exclude from paying fees or having max transaction amount | constructor(address _owner) ERC20("LAIKA GF", "LAIKA GF") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = _uniswapV2Pair;
excludeFromFees(_owner, true);
excludeFromFees(marketingWallet, true);
excludeFromFees(address(this), true);
an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_createSupply(_owner, 1000000000 * (10**18));
| 4,067,503 | [
1,
1684,
279,
640,
291,
91,
438,
3082,
364,
333,
394,
1147,
4433,
628,
8843,
310,
1656,
281,
578,
7999,
943,
2492,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
12,
2867,
389,
8443,
13,
4232,
39,
3462,
2932,
2534,
45,
47,
37,
611,
42,
3113,
315,
2534,
45,
47,
37,
611,
42,
7923,
288,
203,
377,
202,
45,
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,
1758,
389,
318,
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,
3639,
640,
291,
91,
438,
58,
22,
4154,
273,
389,
318,
291,
91,
438,
58,
22,
4154,
31,
203,
203,
3639,
4433,
1265,
2954,
281,
24899,
8443,
16,
638,
1769,
203,
3639,
4433,
1265,
2954,
281,
12,
3355,
21747,
16936,
16,
638,
1769,
203,
3639,
4433,
1265,
2954,
281,
12,
2867,
12,
2211,
3631,
638,
1769,
203,
540,
203,
5411,
392,
2713,
445,
316,
4232,
39,
3462,
18,
18281,
716,
353,
1338,
2566,
2674,
16,
203,
5411,
471,
385,
16791,
506,
2566,
14103,
3382,
203,
3639,
389,
2640,
2
] |
// Author: Alex Roan
pragma solidity ^0.5.5;
import "@openzeppelin/contracts/token/ERC721/ERC721Enumerable.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/SafeCast.sol";
// TennisPlayer ERC721 Token
contract TennisPlayerBase is ERC721Enumerable, Ownable {
using SafeMath for uint;
using SafeCast for uint;
// Player information
struct Player {
// game details
uint xp;
// personal details
string name;
uint8 age;
uint8 height;
uint8 condition;
// attributes
uint8 agility;
uint8 power;
uint8 stamina;
uint8 technique;
}
// List of all players
Player[] public players;
// Create new player on behalf of manager
function newPlayer(
uint _xp,
string memory _name,
uint8 _age,
uint8 _height,
uint8 _condition,
uint8 _agility,
uint8 _power,
uint8 _stamina,
uint8 _technique,
address _to
) public onlyOwner returns (uint)
{
uint id = players.length;
players.push(
Player(_xp, _name, _age, _height, _condition,
_agility, _power, _stamina, _technique)
);
_safeMint(_to, id);
return id;
}
// Cast and add a uint8 to a uint8
function castAdd8(uint8 _a, uint8 _b) internal pure returns (uint8) {
return uint(_a).add(uint(_b)).toUint8();
}
// Cast and subtract a uint8 from uint8
function castSubtract8(uint8 _a, uint8 _b) internal pure returns (uint8) {
return uint(_a).sub(uint(_b)).toUint8();
}
// Cast and subtract a uint8 from a uint
function castSubtract256(uint _a, uint8 _b) internal pure returns (uint) {
return _a.sub(uint(_b));
}
}
| List of all players | Player[] public players;
| 12,573,212 | [
1,
682,
434,
777,
18115,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
12148,
8526,
1071,
18115,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
/* Internal Imports */
import {DataTypes as dt} from "./libraries/DataTypes.sol";
import {Transitions as tn} from "./libraries/Transitions.sol";
import "./libraries/ErrMsg.sol";
import "./libraries/MerkleTree.sol";
import "./Registry.sol";
import "./PriorityOperations.sol";
import "./TransitionDisputer.sol";
import "./strategies/interfaces/IStrategy.sol";
import "./interfaces/IWETH.sol";
contract RollupChain is Ownable, Pausable {
using SafeERC20 for IERC20;
// All intents in a block have been executed.
uint32 public constant BLOCK_EXEC_COUNT_DONE = 2**32 - 1;
/* Fields */
// The state transition disputer
TransitionDisputer public immutable transitionDisputer;
// Asset and strategy registry
Registry public immutable registry;
// Pending queues
PriorityOperations public immutable priorityOperations;
// All the blocks (prepared and/or executed).
dt.Block[] public blocks;
uint256 public countExecuted;
// Track pending withdraws arriving from L2 then done on L1 across 2 phases.
// A separate mapping is used for each phase:
// (1) pendingWithdrawCommits: commitBlock() --> executeBlock(), per blockId
// (2) pendingWithdraws: executeBlock() --> L1-withdraw, per user account address
//
// - commitBlock() creates pendingWithdrawCommits entries for the blockId.
// - executeBlock() aggregates them into per-account pendingWithdraws entries and
// deletes the pendingWithdrawCommits entries.
// - fraudulent block deletes the pendingWithdrawCommits during the blockId rollback.
// - L1 withdraw() gives the funds and deletes the account's pendingWithdraws entries.
struct PendingWithdrawCommit {
address account;
uint32 assetId;
uint256 amount;
}
mapping(uint256 => PendingWithdrawCommit[]) public pendingWithdrawCommits;
// Mapping of account => assetId => pendingWithdrawAmount
mapping(address => mapping(uint32 => uint256)) public pendingWithdraws;
// per-asset (total deposit - total withdrawal) amount
mapping(address => uint256) public netDeposits;
// per-asset (total deposit - total withdrawal) limit
mapping(address => uint256) public netDepositLimits;
uint256 public blockChallengePeriod; // delay (in # of ETH blocks) to challenge a rollup block
uint256 public maxPriorityTxDelay; // delay (in # of rollup blocks) to reflect an L1-initiated tx in a rollup block
address public operator;
/* Events */
event RollupBlockCommitted(uint256 blockId);
event RollupBlockExecuted(uint256 blockId, uint32 execLen);
event RollupBlockReverted(uint256 blockId, string reason);
event AssetDeposited(address account, uint32 assetId, uint256 amount, uint64 depositId);
event AssetWithdrawn(address account, uint32 assetId, uint256 amount);
event AggregationExecuted(
uint32 strategyId,
uint64 aggregateId,
bool success,
uint256 sharesFromBuy,
uint256 amountFromSell
);
event OperatorChanged(address previousOperator, address newOperator);
event EpochUpdate(uint64 epoch, uint64 epochId);
constructor(
uint256 _blockChallengePeriod,
uint256 _maxPriorityTxDelay,
address _transitionDisputerAddress,
address _registryAddress,
address _priorityOperationsAddress,
address _operator
) {
blockChallengePeriod = _blockChallengePeriod;
maxPriorityTxDelay = _maxPriorityTxDelay;
transitionDisputer = TransitionDisputer(_transitionDisputerAddress);
registry = Registry(_registryAddress);
priorityOperations = PriorityOperations(_priorityOperationsAddress);
operator = _operator;
}
modifier onlyOperator() {
require(msg.sender == operator, ErrMsg.REQ_NOT_OPER);
_;
}
receive() external payable {}
/**********************
* External Functions *
**********************/
/**
* @notice Deposits ERC20 asset.
*
* @param _asset The asset address;
* @param _amount The amount;
*/
function deposit(address _asset, uint256 _amount) external whenNotPaused {
_deposit(_asset, _amount, msg.sender);
IERC20(_asset).safeTransferFrom(msg.sender, address(this), _amount);
}
/**
* @notice Deposits ETH.
*
* @param _amount The amount;
* @param _weth The address for WETH.
*/
function depositETH(address _weth, uint256 _amount) external payable whenNotPaused {
require(msg.value == _amount, ErrMsg.REQ_BAD_AMOUNT);
_deposit(_weth, _amount, msg.sender);
IWETH(_weth).deposit{value: _amount}();
}
/**
* @notice Deposits ERC20 asset for staking reward.
*
* @param _asset The asset address;
* @param _amount The amount;
*/
function depositReward(address _asset, uint256 _amount) external whenNotPaused {
_deposit(_asset, _amount, address(0));
IERC20(_asset).safeTransferFrom(msg.sender, address(this), _amount);
}
/**
* @notice Executes pending withdraw of an asset to an account.
*
* @param _account The destination account.
* @param _asset The asset address;
*/
function withdraw(address _account, address _asset) external whenNotPaused {
uint256 amount = _withdraw(_account, _asset);
IERC20(_asset).safeTransfer(_account, amount);
}
/**
* @notice Executes pending withdraw of ETH to an account.
*
* @param _account The destination account.
* @param _weth The address for WETH.
*/
function withdrawETH(address _account, address _weth) external whenNotPaused {
uint256 amount = _withdraw(_account, _weth);
IWETH(_weth).withdraw(amount);
(bool sent, ) = _account.call{value: amount}("");
require(sent, ErrMsg.REQ_NO_WITHDRAW);
}
/**
* @notice Submit a prepared batch as a new rollup block.
*
* @param _blockId Rollup block id
* @param _transitions List of layer-2 transitions
*/
function commitBlock(uint256 _blockId, bytes[] calldata _transitions) external whenNotPaused onlyOperator {
require(_blockId == blocks.length, ErrMsg.REQ_BAD_BLOCKID);
bytes32[] memory leafs = new bytes32[](_transitions.length);
for (uint256 i = 0; i < _transitions.length; i++) {
leafs[i] = keccak256(_transitions[i]);
}
bytes32 root = MerkleTree.getMerkleRoot(leafs);
// Loop over transition and handle these cases:
// 1. deposit: update the pending deposit record
// 2. withdraw: create a pending withdraw-commit record
// 3. aggregate-orders: fill the "intents" array for future executeBlock()
// 4. execution-result: update the pending execution result record
bytes32 intentHash;
for (uint256 i = 0; i < _transitions.length; i++) {
uint8 tnType = tn.extractTransitionType(_transitions[i]);
if (
tnType == tn.TN_TYPE_BUY ||
tnType == tn.TN_TYPE_SELL ||
tnType == tn.TN_TYPE_XFER_ASSET ||
tnType == tn.TN_TYPE_XFER_SHARE ||
tnType == tn.TN_TYPE_SETTLE
) {
continue;
} else if (tnType == tn.TN_TYPE_DEPOSIT) {
// Update the pending deposit record.
dt.DepositTransition memory dp = tn.decodePackedDepositTransition(_transitions[i]);
priorityOperations.checkPendingDeposit(dp.account, dp.assetId, dp.amount, _blockId);
} else if (tnType == tn.TN_TYPE_WITHDRAW) {
// Append the pending withdraw-commit record for this blockId.
dt.WithdrawTransition memory wd = tn.decodePackedWithdrawTransition(_transitions[i]);
pendingWithdrawCommits[_blockId].push(
PendingWithdrawCommit({account: wd.account, assetId: wd.assetId, amount: wd.amount - wd.fee})
);
} else if (tnType == tn.TN_TYPE_AGGREGATE_ORDER) {
intentHash = keccak256(abi.encodePacked(intentHash, _transitions[i]));
} else if (tnType == tn.TN_TYPE_EXEC_RESULT) {
// Update the pending execution result record.
priorityOperations.checkPendingExecutionResult(_transitions[i], _blockId);
} else if (tnType == tn.TN_TYPE_WITHDRAW_PROTO_FEE) {
dt.WithdrawProtocolFeeTransition memory wf = tn.decodeWithdrawProtocolFeeTransition(_transitions[i]);
pendingWithdrawCommits[_blockId].push(
PendingWithdrawCommit({account: owner(), assetId: wf.assetId, amount: wf.amount})
);
} else if (tnType == tn.TN_TYPE_DEPOSIT_REWARD) {
// Update the pending deposit record.
dt.DepositRewardTransition memory dp = tn.decodeDepositRewardTransition(_transitions[i]);
priorityOperations.checkPendingDeposit(address(0), dp.assetId, dp.amount, _blockId);
} else if (tnType == tn.TN_TYPE_UPDATE_EPOCH) {
dt.UpdateEpochTransition memory ep = tn.decodeUpdateEpochTransition(_transitions[i]);
priorityOperations.checkPendingEpochUpdate(ep.epoch, _blockId);
}
}
blocks.push(
dt.Block({
rootHash: root,
intentHash: intentHash,
intentExecCount: 0,
blockTime: uint64(block.number),
blockSize: uint32(_transitions.length)
})
);
emit RollupBlockCommitted(_blockId);
}
/**
* @notice Execute a rollup block after it passes the challenge period.
* @dev Note: only the "intent" transitions (AggregateOrders) are given to executeBlock() instead of
* re-sending the whole rollup block. This includes the case of a rollup block with zero intents.
* @dev Note: this supports partial incremental block execution using the "_execLen" parameter.
*
* @param _blockId Rollup block id
* @param _intents List of AggregateOrders transitions of the rollup block
* @param _execLen The next number of AggregateOrders transitions to execute from the full list.
*/
function executeBlock(
uint256 _blockId,
bytes[] calldata _intents,
uint32 _execLen
) external whenNotPaused {
require(_blockId == countExecuted, ErrMsg.REQ_BAD_BLOCKID);
require(blocks[_blockId].blockTime + blockChallengePeriod < block.number, ErrMsg.REQ_BAD_CHALLENGE);
uint32 intentExecCount = blocks[_blockId].intentExecCount;
// Validate the input intent transitions.
bytes32 intentHash;
if (_intents.length > 0) {
for (uint256 i = 0; i < _intents.length; i++) {
intentHash = keccak256(abi.encodePacked(intentHash, _intents[i]));
}
}
require(intentHash == blocks[_blockId].intentHash, ErrMsg.REQ_BAD_HASH);
uint32 newIntentExecCount = intentExecCount + _execLen;
require(newIntentExecCount <= _intents.length, ErrMsg.REQ_BAD_LEN);
// In the first execution of any parts of this block, handle the pending deposit & withdraw records.
if (intentExecCount == 0) {
priorityOperations.cleanupPendingQueue(_blockId);
_cleanupPendingWithdrawCommits(_blockId);
}
// Decode the intent transitions and execute the strategy updates for the requested incremental batch.
for (uint256 i = intentExecCount; i < newIntentExecCount; i++) {
dt.AggregateOrdersTransition memory aggregation = tn.decodePackedAggregateOrdersTransition(_intents[i]);
_executeAggregation(aggregation, _blockId);
}
if (newIntentExecCount == _intents.length) {
blocks[_blockId].intentExecCount = BLOCK_EXEC_COUNT_DONE;
countExecuted++;
} else {
blocks[_blockId].intentExecCount = newIntentExecCount;
}
emit RollupBlockExecuted(_blockId, newIntentExecCount);
}
/**
* @notice Dispute a transition in a block.
* @dev Provide the transition proofs of the previous (valid) transition and the disputed transition,
* the account proof(s), the strategy proof, the staking pool proof, and the global info. The account proof(s),
* strategy proof, staking pool proof and global info are always needed even if the disputed transition only updates
* an account (or two) or only updates the strategy because the transition stateRoot is computed as:
*
* stateRoot = hash(accountStateRoot, strategyStateRoot, stakingPoolStateRoot, globalInfoHash)
*
* Thus all 4 components of the hash are needed to validate the input data.
* If the transition is invalid, prune the chain from that invalid block.
*
* @param _prevTransitionProof The inclusion proof of the transition immediately before the fraudulent transition.
* @param _invalidTransitionProof The inclusion proof of the fraudulent transition.
* @param _accountProofs The inclusion proofs of one or two accounts involved.
* @param _strategyProof The inclusion proof of the strategy involved.
* @param _stakingPoolProof The inclusion proof of the staking pool involved.
* @param _globalInfo The global info.
*/
function disputeTransition(
dt.TransitionProof calldata _prevTransitionProof,
dt.TransitionProof calldata _invalidTransitionProof,
dt.AccountProof[] calldata _accountProofs,
dt.StrategyProof calldata _strategyProof,
dt.StakingPoolProof calldata _stakingPoolProof,
dt.GlobalInfo calldata _globalInfo
) external {
dt.Block memory prevTransitionBlock = blocks[_prevTransitionProof.blockId];
dt.Block memory invalidTransitionBlock = blocks[_invalidTransitionProof.blockId];
require(invalidTransitionBlock.blockTime + blockChallengePeriod > block.number, ErrMsg.REQ_BAD_CHALLENGE);
bool success;
bytes memory returnData;
(success, returnData) = address(transitionDisputer).call(
abi.encodeWithSelector(
transitionDisputer.disputeTransition.selector,
_prevTransitionProof,
_invalidTransitionProof,
_accountProofs,
_strategyProof,
_stakingPoolProof,
_globalInfo,
prevTransitionBlock,
invalidTransitionBlock,
registry
)
);
if (success) {
string memory reason = abi.decode((returnData), (string));
_revertBlock(_invalidTransitionProof.blockId, reason);
} else {
revert("Failed to dispute");
}
}
/**
* @notice Dispute if operator failed to reflect an L1-initiated priority tx
* in a rollup block within the maxPriorityTxDelay
*/
function disputePriorityTxDelay() external {
if (priorityOperations.isPriorityTxDelayViolated(blocks.length, maxPriorityTxDelay)) {
_pause();
return;
}
revert("Not exceed max priority tx delay");
}
/**
* @notice Update mining epoch to current block number
*/
function updateEpoch() external {
(uint64 epoch, uint64 epochId) = priorityOperations.addPendingEpochUpdate(blocks.length);
emit EpochUpdate(epoch, epochId);
}
/**
* @notice Called by the owner to pause contract
* @dev emergency use only
*/
function pause() external onlyOwner {
_pause();
}
/**
* @notice Called by the owner to unpause contract
* @dev emergency use only
*/
function unpause() external onlyOwner {
_unpause();
}
/**
* @notice Owner drains one type of tokens when the contract is paused
* @dev emergency use only
*
* @param _asset drained asset address
* @param _amount drained asset amount
*/
function drainToken(address _asset, uint256 _amount) external whenPaused onlyOwner {
IERC20(_asset).safeTransfer(msg.sender, _amount);
}
/**
* @notice Owner drains ETH when the contract is paused
* @dev This is for emergency situations.
*
* @param _amount drained ETH amount
*/
function drainETH(uint256 _amount) external whenPaused onlyOwner {
(bool sent, ) = msg.sender.call{value: _amount}("");
require(sent, ErrMsg.REQ_NO_DRAIN);
}
/**
* @notice Called by the owner to set blockChallengePeriod
* @param _blockChallengePeriod delay (in # of ETH blocks) to challenge a rollup block
*/
function setBlockChallengePeriod(uint256 _blockChallengePeriod) external onlyOwner {
blockChallengePeriod = _blockChallengePeriod;
}
/**
* @notice Called by the owner to set maxPriorityTxDelay
* @param _maxPriorityTxDelay delay (in # of rollup blocks) to reflect an L1-initiated tx in a rollup block
*/
function setMaxPriorityTxDelay(uint256 _maxPriorityTxDelay) external onlyOwner {
maxPriorityTxDelay = _maxPriorityTxDelay;
}
/**
* @notice Called by the owner to set operator account address
* @param _operator operator's ETH address
*/
function setOperator(address _operator) external onlyOwner {
emit OperatorChanged(operator, _operator);
operator = _operator;
}
/**
* @notice Called by the owner to set net deposit limit
* @param _asset asset token address
* @param _limit asset net deposit limit amount
*/
function setNetDepositLimit(address _asset, uint256 _limit) external onlyOwner {
uint32 assetId = registry.assetAddressToIndex(_asset);
require(assetId != 0, ErrMsg.REQ_BAD_ASSET);
netDepositLimits[_asset] = _limit;
}
/**
* @notice Get count of rollup blocks.
* @return count of rollup blocks
*/
function getCountBlocks() public view returns (uint256) {
return blocks.length;
}
/*********************
* Private Functions *
*********************/
/**
* @notice internal deposit processing without actual token transfer.
*
* @param _asset The asset token address.
* @param _amount The asset token amount.
* @param _account The account who owns the deposit (zero for reward).
*/
function _deposit(
address _asset,
uint256 _amount,
address _account
) private {
uint32 assetId = registry.assetAddressToIndex(_asset);
require(assetId > 0, ErrMsg.REQ_BAD_ASSET);
uint256 netDeposit = netDeposits[_asset] + _amount;
require(netDeposit <= netDepositLimits[_asset], ErrMsg.REQ_OVER_LIMIT);
netDeposits[_asset] = netDeposit;
uint64 depositId = priorityOperations.addPendingDeposit(_account, assetId, _amount, blocks.length);
emit AssetDeposited(_account, assetId, _amount, depositId);
}
/**
* @notice internal withdrawal processing without actual token transfer.
*
* @param _account The destination account.
* @param _asset The asset token address.
* @return amount to withdraw
*/
function _withdraw(address _account, address _asset) private returns (uint256) {
uint32 assetId = registry.assetAddressToIndex(_asset);
require(assetId > 0, ErrMsg.REQ_BAD_ASSET);
uint256 amount = pendingWithdraws[_account][assetId];
require(amount > 0, ErrMsg.REQ_BAD_AMOUNT);
if (netDeposits[_asset] < amount) {
netDeposits[_asset] = 0;
} else {
netDeposits[_asset] -= amount;
}
pendingWithdraws[_account][assetId] = 0;
emit AssetWithdrawn(_account, assetId, amount);
return amount;
}
/**
* @notice execute aggregated order.
* @param _aggregation The AggregateOrders transition.
* @param _blockId Executed block Id.
*/
function _executeAggregation(dt.AggregateOrdersTransition memory _aggregation, uint256 _blockId) private {
uint32 strategyId = _aggregation.strategyId;
address strategyAddr = registry.strategyIndexToAddress(strategyId);
require(strategyAddr != address(0), ErrMsg.REQ_BAD_ST);
IStrategy strategy = IStrategy(strategyAddr);
// TODO: reset allowance to zero after strategy interaction?
IERC20(strategy.getAssetAddress()).safeIncreaseAllowance(strategyAddr, _aggregation.buyAmount);
(bool success, bytes memory returnData) = strategyAddr.call(
abi.encodeWithSelector(
IStrategy.aggregateOrders.selector,
_aggregation.buyAmount,
_aggregation.sellShares,
_aggregation.minSharesFromBuy,
_aggregation.minAmountFromSell
)
);
uint256 sharesFromBuy;
uint256 amountFromSell;
if (success) {
(sharesFromBuy, amountFromSell) = abi.decode((returnData), (uint256, uint256));
}
uint64 aggregateId = priorityOperations.addPendingExecutionResult(
PriorityOperations.ExecResultInfo(
strategyId,
success,
sharesFromBuy,
amountFromSell,
blocks.length,
_blockId
)
);
emit AggregationExecuted(strategyId, aggregateId, success, sharesFromBuy, amountFromSell);
}
/**
* @notice Aggregate the pending withdraw-commit records for this blockId into the final
* pending withdraw records per account (for later L1 withdraw), and delete them.
* @param _blockId Executed block Id.
*/
function _cleanupPendingWithdrawCommits(uint256 _blockId) private {
PendingWithdrawCommit[] memory pwc = pendingWithdrawCommits[_blockId];
for (uint256 i = 0; i < pwc.length; i++) {
// Find and increment this account's assetId total amount
pendingWithdraws[pwc[i].account][pwc[i].assetId] += pwc[i].amount;
}
delete pendingWithdrawCommits[_blockId];
}
/**
* @notice Revert rollup block on dispute success
*
* @param _blockId Rollup block id
* @param _reason Revert reason
*/
function _revertBlock(uint256 _blockId, string memory _reason) private {
// pause contract
_pause();
// revert blocks and pending states
while (blocks.length > _blockId) {
delete pendingWithdrawCommits[blocks.length - 1];
blocks.pop();
}
priorityOperations.revertBlock(_blockId);
emit RollupBlockReverted(_blockId, _reason);
}
}
| All intents in a block have been executed. The state transition disputer Asset and strategy registry Pending queues All the blocks (prepared and/or executed). Track pending withdraws arriving from L2 then done on L1 across 2 phases. A separate mapping is used for each phase: (1) pendingWithdrawCommits: commitBlock() --> executeBlock(), per blockId (2) pendingWithdraws: executeBlock() --> L1-withdraw, per user account address - commitBlock() creates pendingWithdrawCommits entries for the blockId. - executeBlock() aggregates them into per-account pendingWithdraws entries and deletes the pendingWithdrawCommits entries. - fraudulent block deletes the pendingWithdrawCommits during the blockId rollback. - L1 withdraw() gives the funds and deletes the account's pendingWithdraws entries. | contract RollupChain is Ownable, Pausable {
using SafeERC20 for IERC20;
uint32 public constant BLOCK_EXEC_COUNT_DONE = 2**32 - 1;
TransitionDisputer public immutable transitionDisputer;
Registry public immutable registry;
PriorityOperations public immutable priorityOperations;
dt.Block[] public blocks;
uint256 public countExecuted;
import {DataTypes as dt} from "./libraries/DataTypes.sol";
import {Transitions as tn} from "./libraries/Transitions.sol";
struct PendingWithdrawCommit {
address account;
uint32 assetId;
uint256 amount;
}
mapping(uint256 => PendingWithdrawCommit[]) public pendingWithdrawCommits;
address public operator;
event RollupBlockExecuted(uint256 blockId, uint32 execLen);
event RollupBlockReverted(uint256 blockId, string reason);
event AssetDeposited(address account, uint32 assetId, uint256 amount, uint64 depositId);
event AssetWithdrawn(address account, uint32 assetId, uint256 amount);
event AggregationExecuted(
uint32 strategyId,
uint64 aggregateId,
bool success,
uint256 sharesFromBuy,
uint256 amountFromSell
);
event OperatorChanged(address previousOperator, address newOperator);
event EpochUpdate(uint64 epoch, uint64 epochId);
constructor(
uint256 _blockChallengePeriod,
uint256 _maxPriorityTxDelay,
address _transitionDisputerAddress,
address _registryAddress,
address _priorityOperationsAddress,
address _operator
mapping(address => mapping(uint32 => uint256)) public pendingWithdraws;
mapping(address => uint256) public netDeposits;
mapping(address => uint256) public netDepositLimits;
event RollupBlockCommitted(uint256 blockId);
) {
blockChallengePeriod = _blockChallengePeriod;
maxPriorityTxDelay = _maxPriorityTxDelay;
transitionDisputer = TransitionDisputer(_transitionDisputerAddress);
registry = Registry(_registryAddress);
priorityOperations = PriorityOperations(_priorityOperationsAddress);
operator = _operator;
}
modifier onlyOperator() {
require(msg.sender == operator, ErrMsg.REQ_NOT_OPER);
_;
}
receive() external payable {}
function deposit(address _asset, uint256 _amount) external whenNotPaused {
_deposit(_asset, _amount, msg.sender);
IERC20(_asset).safeTransferFrom(msg.sender, address(this), _amount);
}
function depositETH(address _weth, uint256 _amount) external payable whenNotPaused {
require(msg.value == _amount, ErrMsg.REQ_BAD_AMOUNT);
_deposit(_weth, _amount, msg.sender);
}
IWETH(_weth).deposit{value: _amount}();
function depositReward(address _asset, uint256 _amount) external whenNotPaused {
_deposit(_asset, _amount, address(0));
IERC20(_asset).safeTransferFrom(msg.sender, address(this), _amount);
}
function withdraw(address _account, address _asset) external whenNotPaused {
uint256 amount = _withdraw(_account, _asset);
IERC20(_asset).safeTransfer(_account, amount);
}
function withdrawETH(address _account, address _weth) external whenNotPaused {
uint256 amount = _withdraw(_account, _weth);
IWETH(_weth).withdraw(amount);
require(sent, ErrMsg.REQ_NO_WITHDRAW);
}
(bool sent, ) = _account.call{value: amount}("");
function commitBlock(uint256 _blockId, bytes[] calldata _transitions) external whenNotPaused onlyOperator {
require(_blockId == blocks.length, ErrMsg.REQ_BAD_BLOCKID);
bytes32[] memory leafs = new bytes32[](_transitions.length);
for (uint256 i = 0; i < _transitions.length; i++) {
leafs[i] = keccak256(_transitions[i]);
}
bytes32 root = MerkleTree.getMerkleRoot(leafs);
for (uint256 i = 0; i < _transitions.length; i++) {
uint8 tnType = tn.extractTransitionType(_transitions[i]);
if (
tnType == tn.TN_TYPE_BUY ||
tnType == tn.TN_TYPE_SELL ||
tnType == tn.TN_TYPE_XFER_ASSET ||
tnType == tn.TN_TYPE_XFER_SHARE ||
tnType == tn.TN_TYPE_SETTLE
) {
continue;
dt.DepositTransition memory dp = tn.decodePackedDepositTransition(_transitions[i]);
priorityOperations.checkPendingDeposit(dp.account, dp.assetId, dp.amount, _blockId);
dt.WithdrawTransition memory wd = tn.decodePackedWithdrawTransition(_transitions[i]);
pendingWithdrawCommits[_blockId].push(
);
intentHash = keccak256(abi.encodePacked(intentHash, _transitions[i]));
priorityOperations.checkPendingExecutionResult(_transitions[i], _blockId);
dt.WithdrawProtocolFeeTransition memory wf = tn.decodeWithdrawProtocolFeeTransition(_transitions[i]);
pendingWithdrawCommits[_blockId].push(
);
dt.DepositRewardTransition memory dp = tn.decodeDepositRewardTransition(_transitions[i]);
priorityOperations.checkPendingDeposit(address(0), dp.assetId, dp.amount, _blockId);
dt.UpdateEpochTransition memory ep = tn.decodeUpdateEpochTransition(_transitions[i]);
priorityOperations.checkPendingEpochUpdate(ep.epoch, _blockId);
}
}
blocks.push(
dt.Block({
rootHash: root,
intentHash: intentHash,
intentExecCount: 0,
blockTime: uint64(block.number),
blockSize: uint32(_transitions.length)
})
);
emit RollupBlockCommitted(_blockId);
}
function commitBlock(uint256 _blockId, bytes[] calldata _transitions) external whenNotPaused onlyOperator {
require(_blockId == blocks.length, ErrMsg.REQ_BAD_BLOCKID);
bytes32[] memory leafs = new bytes32[](_transitions.length);
for (uint256 i = 0; i < _transitions.length; i++) {
leafs[i] = keccak256(_transitions[i]);
}
bytes32 root = MerkleTree.getMerkleRoot(leafs);
for (uint256 i = 0; i < _transitions.length; i++) {
uint8 tnType = tn.extractTransitionType(_transitions[i]);
if (
tnType == tn.TN_TYPE_BUY ||
tnType == tn.TN_TYPE_SELL ||
tnType == tn.TN_TYPE_XFER_ASSET ||
tnType == tn.TN_TYPE_XFER_SHARE ||
tnType == tn.TN_TYPE_SETTLE
) {
continue;
dt.DepositTransition memory dp = tn.decodePackedDepositTransition(_transitions[i]);
priorityOperations.checkPendingDeposit(dp.account, dp.assetId, dp.amount, _blockId);
dt.WithdrawTransition memory wd = tn.decodePackedWithdrawTransition(_transitions[i]);
pendingWithdrawCommits[_blockId].push(
);
intentHash = keccak256(abi.encodePacked(intentHash, _transitions[i]));
priorityOperations.checkPendingExecutionResult(_transitions[i], _blockId);
dt.WithdrawProtocolFeeTransition memory wf = tn.decodeWithdrawProtocolFeeTransition(_transitions[i]);
pendingWithdrawCommits[_blockId].push(
);
dt.DepositRewardTransition memory dp = tn.decodeDepositRewardTransition(_transitions[i]);
priorityOperations.checkPendingDeposit(address(0), dp.assetId, dp.amount, _blockId);
dt.UpdateEpochTransition memory ep = tn.decodeUpdateEpochTransition(_transitions[i]);
priorityOperations.checkPendingEpochUpdate(ep.epoch, _blockId);
}
}
blocks.push(
dt.Block({
rootHash: root,
intentHash: intentHash,
intentExecCount: 0,
blockTime: uint64(block.number),
blockSize: uint32(_transitions.length)
})
);
emit RollupBlockCommitted(_blockId);
}
bytes32 intentHash;
function commitBlock(uint256 _blockId, bytes[] calldata _transitions) external whenNotPaused onlyOperator {
require(_blockId == blocks.length, ErrMsg.REQ_BAD_BLOCKID);
bytes32[] memory leafs = new bytes32[](_transitions.length);
for (uint256 i = 0; i < _transitions.length; i++) {
leafs[i] = keccak256(_transitions[i]);
}
bytes32 root = MerkleTree.getMerkleRoot(leafs);
for (uint256 i = 0; i < _transitions.length; i++) {
uint8 tnType = tn.extractTransitionType(_transitions[i]);
if (
tnType == tn.TN_TYPE_BUY ||
tnType == tn.TN_TYPE_SELL ||
tnType == tn.TN_TYPE_XFER_ASSET ||
tnType == tn.TN_TYPE_XFER_SHARE ||
tnType == tn.TN_TYPE_SETTLE
) {
continue;
dt.DepositTransition memory dp = tn.decodePackedDepositTransition(_transitions[i]);
priorityOperations.checkPendingDeposit(dp.account, dp.assetId, dp.amount, _blockId);
dt.WithdrawTransition memory wd = tn.decodePackedWithdrawTransition(_transitions[i]);
pendingWithdrawCommits[_blockId].push(
);
intentHash = keccak256(abi.encodePacked(intentHash, _transitions[i]));
priorityOperations.checkPendingExecutionResult(_transitions[i], _blockId);
dt.WithdrawProtocolFeeTransition memory wf = tn.decodeWithdrawProtocolFeeTransition(_transitions[i]);
pendingWithdrawCommits[_blockId].push(
);
dt.DepositRewardTransition memory dp = tn.decodeDepositRewardTransition(_transitions[i]);
priorityOperations.checkPendingDeposit(address(0), dp.assetId, dp.amount, _blockId);
dt.UpdateEpochTransition memory ep = tn.decodeUpdateEpochTransition(_transitions[i]);
priorityOperations.checkPendingEpochUpdate(ep.epoch, _blockId);
}
}
blocks.push(
dt.Block({
rootHash: root,
intentHash: intentHash,
intentExecCount: 0,
blockTime: uint64(block.number),
blockSize: uint32(_transitions.length)
})
);
emit RollupBlockCommitted(_blockId);
}
function commitBlock(uint256 _blockId, bytes[] calldata _transitions) external whenNotPaused onlyOperator {
require(_blockId == blocks.length, ErrMsg.REQ_BAD_BLOCKID);
bytes32[] memory leafs = new bytes32[](_transitions.length);
for (uint256 i = 0; i < _transitions.length; i++) {
leafs[i] = keccak256(_transitions[i]);
}
bytes32 root = MerkleTree.getMerkleRoot(leafs);
for (uint256 i = 0; i < _transitions.length; i++) {
uint8 tnType = tn.extractTransitionType(_transitions[i]);
if (
tnType == tn.TN_TYPE_BUY ||
tnType == tn.TN_TYPE_SELL ||
tnType == tn.TN_TYPE_XFER_ASSET ||
tnType == tn.TN_TYPE_XFER_SHARE ||
tnType == tn.TN_TYPE_SETTLE
) {
continue;
dt.DepositTransition memory dp = tn.decodePackedDepositTransition(_transitions[i]);
priorityOperations.checkPendingDeposit(dp.account, dp.assetId, dp.amount, _blockId);
dt.WithdrawTransition memory wd = tn.decodePackedWithdrawTransition(_transitions[i]);
pendingWithdrawCommits[_blockId].push(
);
intentHash = keccak256(abi.encodePacked(intentHash, _transitions[i]));
priorityOperations.checkPendingExecutionResult(_transitions[i], _blockId);
dt.WithdrawProtocolFeeTransition memory wf = tn.decodeWithdrawProtocolFeeTransition(_transitions[i]);
pendingWithdrawCommits[_blockId].push(
);
dt.DepositRewardTransition memory dp = tn.decodeDepositRewardTransition(_transitions[i]);
priorityOperations.checkPendingDeposit(address(0), dp.assetId, dp.amount, _blockId);
dt.UpdateEpochTransition memory ep = tn.decodeUpdateEpochTransition(_transitions[i]);
priorityOperations.checkPendingEpochUpdate(ep.epoch, _blockId);
}
}
blocks.push(
dt.Block({
rootHash: root,
intentHash: intentHash,
intentExecCount: 0,
blockTime: uint64(block.number),
blockSize: uint32(_transitions.length)
})
);
emit RollupBlockCommitted(_blockId);
}
} else if (tnType == tn.TN_TYPE_DEPOSIT) {
} else if (tnType == tn.TN_TYPE_WITHDRAW) {
PendingWithdrawCommit({account: wd.account, assetId: wd.assetId, amount: wd.amount - wd.fee})
} else if (tnType == tn.TN_TYPE_AGGREGATE_ORDER) {
} else if (tnType == tn.TN_TYPE_EXEC_RESULT) {
} else if (tnType == tn.TN_TYPE_WITHDRAW_PROTO_FEE) {
PendingWithdrawCommit({account: owner(), assetId: wf.assetId, amount: wf.amount})
} else if (tnType == tn.TN_TYPE_DEPOSIT_REWARD) {
} else if (tnType == tn.TN_TYPE_UPDATE_EPOCH) {
function commitBlock(uint256 _blockId, bytes[] calldata _transitions) external whenNotPaused onlyOperator {
require(_blockId == blocks.length, ErrMsg.REQ_BAD_BLOCKID);
bytes32[] memory leafs = new bytes32[](_transitions.length);
for (uint256 i = 0; i < _transitions.length; i++) {
leafs[i] = keccak256(_transitions[i]);
}
bytes32 root = MerkleTree.getMerkleRoot(leafs);
for (uint256 i = 0; i < _transitions.length; i++) {
uint8 tnType = tn.extractTransitionType(_transitions[i]);
if (
tnType == tn.TN_TYPE_BUY ||
tnType == tn.TN_TYPE_SELL ||
tnType == tn.TN_TYPE_XFER_ASSET ||
tnType == tn.TN_TYPE_XFER_SHARE ||
tnType == tn.TN_TYPE_SETTLE
) {
continue;
dt.DepositTransition memory dp = tn.decodePackedDepositTransition(_transitions[i]);
priorityOperations.checkPendingDeposit(dp.account, dp.assetId, dp.amount, _blockId);
dt.WithdrawTransition memory wd = tn.decodePackedWithdrawTransition(_transitions[i]);
pendingWithdrawCommits[_blockId].push(
);
intentHash = keccak256(abi.encodePacked(intentHash, _transitions[i]));
priorityOperations.checkPendingExecutionResult(_transitions[i], _blockId);
dt.WithdrawProtocolFeeTransition memory wf = tn.decodeWithdrawProtocolFeeTransition(_transitions[i]);
pendingWithdrawCommits[_blockId].push(
);
dt.DepositRewardTransition memory dp = tn.decodeDepositRewardTransition(_transitions[i]);
priorityOperations.checkPendingDeposit(address(0), dp.assetId, dp.amount, _blockId);
dt.UpdateEpochTransition memory ep = tn.decodeUpdateEpochTransition(_transitions[i]);
priorityOperations.checkPendingEpochUpdate(ep.epoch, _blockId);
}
}
blocks.push(
dt.Block({
rootHash: root,
intentHash: intentHash,
intentExecCount: 0,
blockTime: uint64(block.number),
blockSize: uint32(_transitions.length)
})
);
emit RollupBlockCommitted(_blockId);
}
function executeBlock(
uint256 _blockId,
bytes[] calldata _intents,
uint32 _execLen
) external whenNotPaused {
require(_blockId == countExecuted, ErrMsg.REQ_BAD_BLOCKID);
require(blocks[_blockId].blockTime + blockChallengePeriod < block.number, ErrMsg.REQ_BAD_CHALLENGE);
uint32 intentExecCount = blocks[_blockId].intentExecCount;
bytes32 intentHash;
if (_intents.length > 0) {
for (uint256 i = 0; i < _intents.length; i++) {
intentHash = keccak256(abi.encodePacked(intentHash, _intents[i]));
}
}
require(intentHash == blocks[_blockId].intentHash, ErrMsg.REQ_BAD_HASH);
uint32 newIntentExecCount = intentExecCount + _execLen;
require(newIntentExecCount <= _intents.length, ErrMsg.REQ_BAD_LEN);
if (intentExecCount == 0) {
priorityOperations.cleanupPendingQueue(_blockId);
_cleanupPendingWithdrawCommits(_blockId);
}
for (uint256 i = intentExecCount; i < newIntentExecCount; i++) {
dt.AggregateOrdersTransition memory aggregation = tn.decodePackedAggregateOrdersTransition(_intents[i]);
_executeAggregation(aggregation, _blockId);
}
if (newIntentExecCount == _intents.length) {
blocks[_blockId].intentExecCount = BLOCK_EXEC_COUNT_DONE;
countExecuted++;
blocks[_blockId].intentExecCount = newIntentExecCount;
}
emit RollupBlockExecuted(_blockId, newIntentExecCount);
}
function executeBlock(
uint256 _blockId,
bytes[] calldata _intents,
uint32 _execLen
) external whenNotPaused {
require(_blockId == countExecuted, ErrMsg.REQ_BAD_BLOCKID);
require(blocks[_blockId].blockTime + blockChallengePeriod < block.number, ErrMsg.REQ_BAD_CHALLENGE);
uint32 intentExecCount = blocks[_blockId].intentExecCount;
bytes32 intentHash;
if (_intents.length > 0) {
for (uint256 i = 0; i < _intents.length; i++) {
intentHash = keccak256(abi.encodePacked(intentHash, _intents[i]));
}
}
require(intentHash == blocks[_blockId].intentHash, ErrMsg.REQ_BAD_HASH);
uint32 newIntentExecCount = intentExecCount + _execLen;
require(newIntentExecCount <= _intents.length, ErrMsg.REQ_BAD_LEN);
if (intentExecCount == 0) {
priorityOperations.cleanupPendingQueue(_blockId);
_cleanupPendingWithdrawCommits(_blockId);
}
for (uint256 i = intentExecCount; i < newIntentExecCount; i++) {
dt.AggregateOrdersTransition memory aggregation = tn.decodePackedAggregateOrdersTransition(_intents[i]);
_executeAggregation(aggregation, _blockId);
}
if (newIntentExecCount == _intents.length) {
blocks[_blockId].intentExecCount = BLOCK_EXEC_COUNT_DONE;
countExecuted++;
blocks[_blockId].intentExecCount = newIntentExecCount;
}
emit RollupBlockExecuted(_blockId, newIntentExecCount);
}
function executeBlock(
uint256 _blockId,
bytes[] calldata _intents,
uint32 _execLen
) external whenNotPaused {
require(_blockId == countExecuted, ErrMsg.REQ_BAD_BLOCKID);
require(blocks[_blockId].blockTime + blockChallengePeriod < block.number, ErrMsg.REQ_BAD_CHALLENGE);
uint32 intentExecCount = blocks[_blockId].intentExecCount;
bytes32 intentHash;
if (_intents.length > 0) {
for (uint256 i = 0; i < _intents.length; i++) {
intentHash = keccak256(abi.encodePacked(intentHash, _intents[i]));
}
}
require(intentHash == blocks[_blockId].intentHash, ErrMsg.REQ_BAD_HASH);
uint32 newIntentExecCount = intentExecCount + _execLen;
require(newIntentExecCount <= _intents.length, ErrMsg.REQ_BAD_LEN);
if (intentExecCount == 0) {
priorityOperations.cleanupPendingQueue(_blockId);
_cleanupPendingWithdrawCommits(_blockId);
}
for (uint256 i = intentExecCount; i < newIntentExecCount; i++) {
dt.AggregateOrdersTransition memory aggregation = tn.decodePackedAggregateOrdersTransition(_intents[i]);
_executeAggregation(aggregation, _blockId);
}
if (newIntentExecCount == _intents.length) {
blocks[_blockId].intentExecCount = BLOCK_EXEC_COUNT_DONE;
countExecuted++;
blocks[_blockId].intentExecCount = newIntentExecCount;
}
emit RollupBlockExecuted(_blockId, newIntentExecCount);
}
function executeBlock(
uint256 _blockId,
bytes[] calldata _intents,
uint32 _execLen
) external whenNotPaused {
require(_blockId == countExecuted, ErrMsg.REQ_BAD_BLOCKID);
require(blocks[_blockId].blockTime + blockChallengePeriod < block.number, ErrMsg.REQ_BAD_CHALLENGE);
uint32 intentExecCount = blocks[_blockId].intentExecCount;
bytes32 intentHash;
if (_intents.length > 0) {
for (uint256 i = 0; i < _intents.length; i++) {
intentHash = keccak256(abi.encodePacked(intentHash, _intents[i]));
}
}
require(intentHash == blocks[_blockId].intentHash, ErrMsg.REQ_BAD_HASH);
uint32 newIntentExecCount = intentExecCount + _execLen;
require(newIntentExecCount <= _intents.length, ErrMsg.REQ_BAD_LEN);
if (intentExecCount == 0) {
priorityOperations.cleanupPendingQueue(_blockId);
_cleanupPendingWithdrawCommits(_blockId);
}
for (uint256 i = intentExecCount; i < newIntentExecCount; i++) {
dt.AggregateOrdersTransition memory aggregation = tn.decodePackedAggregateOrdersTransition(_intents[i]);
_executeAggregation(aggregation, _blockId);
}
if (newIntentExecCount == _intents.length) {
blocks[_blockId].intentExecCount = BLOCK_EXEC_COUNT_DONE;
countExecuted++;
blocks[_blockId].intentExecCount = newIntentExecCount;
}
emit RollupBlockExecuted(_blockId, newIntentExecCount);
}
function executeBlock(
uint256 _blockId,
bytes[] calldata _intents,
uint32 _execLen
) external whenNotPaused {
require(_blockId == countExecuted, ErrMsg.REQ_BAD_BLOCKID);
require(blocks[_blockId].blockTime + blockChallengePeriod < block.number, ErrMsg.REQ_BAD_CHALLENGE);
uint32 intentExecCount = blocks[_blockId].intentExecCount;
bytes32 intentHash;
if (_intents.length > 0) {
for (uint256 i = 0; i < _intents.length; i++) {
intentHash = keccak256(abi.encodePacked(intentHash, _intents[i]));
}
}
require(intentHash == blocks[_blockId].intentHash, ErrMsg.REQ_BAD_HASH);
uint32 newIntentExecCount = intentExecCount + _execLen;
require(newIntentExecCount <= _intents.length, ErrMsg.REQ_BAD_LEN);
if (intentExecCount == 0) {
priorityOperations.cleanupPendingQueue(_blockId);
_cleanupPendingWithdrawCommits(_blockId);
}
for (uint256 i = intentExecCount; i < newIntentExecCount; i++) {
dt.AggregateOrdersTransition memory aggregation = tn.decodePackedAggregateOrdersTransition(_intents[i]);
_executeAggregation(aggregation, _blockId);
}
if (newIntentExecCount == _intents.length) {
blocks[_blockId].intentExecCount = BLOCK_EXEC_COUNT_DONE;
countExecuted++;
blocks[_blockId].intentExecCount = newIntentExecCount;
}
emit RollupBlockExecuted(_blockId, newIntentExecCount);
}
function executeBlock(
uint256 _blockId,
bytes[] calldata _intents,
uint32 _execLen
) external whenNotPaused {
require(_blockId == countExecuted, ErrMsg.REQ_BAD_BLOCKID);
require(blocks[_blockId].blockTime + blockChallengePeriod < block.number, ErrMsg.REQ_BAD_CHALLENGE);
uint32 intentExecCount = blocks[_blockId].intentExecCount;
bytes32 intentHash;
if (_intents.length > 0) {
for (uint256 i = 0; i < _intents.length; i++) {
intentHash = keccak256(abi.encodePacked(intentHash, _intents[i]));
}
}
require(intentHash == blocks[_blockId].intentHash, ErrMsg.REQ_BAD_HASH);
uint32 newIntentExecCount = intentExecCount + _execLen;
require(newIntentExecCount <= _intents.length, ErrMsg.REQ_BAD_LEN);
if (intentExecCount == 0) {
priorityOperations.cleanupPendingQueue(_blockId);
_cleanupPendingWithdrawCommits(_blockId);
}
for (uint256 i = intentExecCount; i < newIntentExecCount; i++) {
dt.AggregateOrdersTransition memory aggregation = tn.decodePackedAggregateOrdersTransition(_intents[i]);
_executeAggregation(aggregation, _blockId);
}
if (newIntentExecCount == _intents.length) {
blocks[_blockId].intentExecCount = BLOCK_EXEC_COUNT_DONE;
countExecuted++;
blocks[_blockId].intentExecCount = newIntentExecCount;
}
emit RollupBlockExecuted(_blockId, newIntentExecCount);
}
} else {
function disputeTransition(
dt.TransitionProof calldata _prevTransitionProof,
dt.TransitionProof calldata _invalidTransitionProof,
dt.AccountProof[] calldata _accountProofs,
dt.StrategyProof calldata _strategyProof,
dt.StakingPoolProof calldata _stakingPoolProof,
dt.GlobalInfo calldata _globalInfo
) external {
dt.Block memory prevTransitionBlock = blocks[_prevTransitionProof.blockId];
dt.Block memory invalidTransitionBlock = blocks[_invalidTransitionProof.blockId];
require(invalidTransitionBlock.blockTime + blockChallengePeriod > block.number, ErrMsg.REQ_BAD_CHALLENGE);
bool success;
bytes memory returnData;
(success, returnData) = address(transitionDisputer).call(
abi.encodeWithSelector(
transitionDisputer.disputeTransition.selector,
_prevTransitionProof,
_invalidTransitionProof,
_accountProofs,
_strategyProof,
_stakingPoolProof,
_globalInfo,
prevTransitionBlock,
invalidTransitionBlock,
registry
)
);
if (success) {
string memory reason = abi.decode((returnData), (string));
_revertBlock(_invalidTransitionProof.blockId, reason);
revert("Failed to dispute");
}
}
function disputeTransition(
dt.TransitionProof calldata _prevTransitionProof,
dt.TransitionProof calldata _invalidTransitionProof,
dt.AccountProof[] calldata _accountProofs,
dt.StrategyProof calldata _strategyProof,
dt.StakingPoolProof calldata _stakingPoolProof,
dt.GlobalInfo calldata _globalInfo
) external {
dt.Block memory prevTransitionBlock = blocks[_prevTransitionProof.blockId];
dt.Block memory invalidTransitionBlock = blocks[_invalidTransitionProof.blockId];
require(invalidTransitionBlock.blockTime + blockChallengePeriod > block.number, ErrMsg.REQ_BAD_CHALLENGE);
bool success;
bytes memory returnData;
(success, returnData) = address(transitionDisputer).call(
abi.encodeWithSelector(
transitionDisputer.disputeTransition.selector,
_prevTransitionProof,
_invalidTransitionProof,
_accountProofs,
_strategyProof,
_stakingPoolProof,
_globalInfo,
prevTransitionBlock,
invalidTransitionBlock,
registry
)
);
if (success) {
string memory reason = abi.decode((returnData), (string));
_revertBlock(_invalidTransitionProof.blockId, reason);
revert("Failed to dispute");
}
}
} else {
function disputePriorityTxDelay() external {
if (priorityOperations.isPriorityTxDelayViolated(blocks.length, maxPriorityTxDelay)) {
_pause();
return;
}
revert("Not exceed max priority tx delay");
}
function disputePriorityTxDelay() external {
if (priorityOperations.isPriorityTxDelayViolated(blocks.length, maxPriorityTxDelay)) {
_pause();
return;
}
revert("Not exceed max priority tx delay");
}
function updateEpoch() external {
(uint64 epoch, uint64 epochId) = priorityOperations.addPendingEpochUpdate(blocks.length);
emit EpochUpdate(epoch, epochId);
}
function pause() external onlyOwner {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
function drainToken(address _asset, uint256 _amount) external whenPaused onlyOwner {
IERC20(_asset).safeTransfer(msg.sender, _amount);
}
function drainETH(uint256 _amount) external whenPaused onlyOwner {
require(sent, ErrMsg.REQ_NO_DRAIN);
}
(bool sent, ) = msg.sender.call{value: _amount}("");
function setBlockChallengePeriod(uint256 _blockChallengePeriod) external onlyOwner {
blockChallengePeriod = _blockChallengePeriod;
}
function setMaxPriorityTxDelay(uint256 _maxPriorityTxDelay) external onlyOwner {
maxPriorityTxDelay = _maxPriorityTxDelay;
}
function setOperator(address _operator) external onlyOwner {
emit OperatorChanged(operator, _operator);
operator = _operator;
}
function setNetDepositLimit(address _asset, uint256 _limit) external onlyOwner {
uint32 assetId = registry.assetAddressToIndex(_asset);
require(assetId != 0, ErrMsg.REQ_BAD_ASSET);
netDepositLimits[_asset] = _limit;
}
function getCountBlocks() public view returns (uint256) {
return blocks.length;
}
function _deposit(
address _asset,
uint256 _amount,
address _account
) private {
uint32 assetId = registry.assetAddressToIndex(_asset);
require(assetId > 0, ErrMsg.REQ_BAD_ASSET);
uint256 netDeposit = netDeposits[_asset] + _amount;
require(netDeposit <= netDepositLimits[_asset], ErrMsg.REQ_OVER_LIMIT);
netDeposits[_asset] = netDeposit;
uint64 depositId = priorityOperations.addPendingDeposit(_account, assetId, _amount, blocks.length);
emit AssetDeposited(_account, assetId, _amount, depositId);
}
function _withdraw(address _account, address _asset) private returns (uint256) {
uint32 assetId = registry.assetAddressToIndex(_asset);
require(assetId > 0, ErrMsg.REQ_BAD_ASSET);
uint256 amount = pendingWithdraws[_account][assetId];
require(amount > 0, ErrMsg.REQ_BAD_AMOUNT);
if (netDeposits[_asset] < amount) {
netDeposits[_asset] = 0;
netDeposits[_asset] -= amount;
}
pendingWithdraws[_account][assetId] = 0;
emit AssetWithdrawn(_account, assetId, amount);
return amount;
}
function _withdraw(address _account, address _asset) private returns (uint256) {
uint32 assetId = registry.assetAddressToIndex(_asset);
require(assetId > 0, ErrMsg.REQ_BAD_ASSET);
uint256 amount = pendingWithdraws[_account][assetId];
require(amount > 0, ErrMsg.REQ_BAD_AMOUNT);
if (netDeposits[_asset] < amount) {
netDeposits[_asset] = 0;
netDeposits[_asset] -= amount;
}
pendingWithdraws[_account][assetId] = 0;
emit AssetWithdrawn(_account, assetId, amount);
return amount;
}
} else {
function _executeAggregation(dt.AggregateOrdersTransition memory _aggregation, uint256 _blockId) private {
uint32 strategyId = _aggregation.strategyId;
address strategyAddr = registry.strategyIndexToAddress(strategyId);
require(strategyAddr != address(0), ErrMsg.REQ_BAD_ST);
IStrategy strategy = IStrategy(strategyAddr);
IERC20(strategy.getAssetAddress()).safeIncreaseAllowance(strategyAddr, _aggregation.buyAmount);
(bool success, bytes memory returnData) = strategyAddr.call(
abi.encodeWithSelector(
IStrategy.aggregateOrders.selector,
_aggregation.buyAmount,
_aggregation.sellShares,
_aggregation.minSharesFromBuy,
_aggregation.minAmountFromSell
)
);
uint256 sharesFromBuy;
uint256 amountFromSell;
if (success) {
(sharesFromBuy, amountFromSell) = abi.decode((returnData), (uint256, uint256));
}
uint64 aggregateId = priorityOperations.addPendingExecutionResult(
PriorityOperations.ExecResultInfo(
strategyId,
success,
sharesFromBuy,
amountFromSell,
blocks.length,
_blockId
)
);
emit AggregationExecuted(strategyId, aggregateId, success, sharesFromBuy, amountFromSell);
}
function _executeAggregation(dt.AggregateOrdersTransition memory _aggregation, uint256 _blockId) private {
uint32 strategyId = _aggregation.strategyId;
address strategyAddr = registry.strategyIndexToAddress(strategyId);
require(strategyAddr != address(0), ErrMsg.REQ_BAD_ST);
IStrategy strategy = IStrategy(strategyAddr);
IERC20(strategy.getAssetAddress()).safeIncreaseAllowance(strategyAddr, _aggregation.buyAmount);
(bool success, bytes memory returnData) = strategyAddr.call(
abi.encodeWithSelector(
IStrategy.aggregateOrders.selector,
_aggregation.buyAmount,
_aggregation.sellShares,
_aggregation.minSharesFromBuy,
_aggregation.minAmountFromSell
)
);
uint256 sharesFromBuy;
uint256 amountFromSell;
if (success) {
(sharesFromBuy, amountFromSell) = abi.decode((returnData), (uint256, uint256));
}
uint64 aggregateId = priorityOperations.addPendingExecutionResult(
PriorityOperations.ExecResultInfo(
strategyId,
success,
sharesFromBuy,
amountFromSell,
blocks.length,
_blockId
)
);
emit AggregationExecuted(strategyId, aggregateId, success, sharesFromBuy, amountFromSell);
}
function _cleanupPendingWithdrawCommits(uint256 _blockId) private {
PendingWithdrawCommit[] memory pwc = pendingWithdrawCommits[_blockId];
for (uint256 i = 0; i < pwc.length; i++) {
pendingWithdraws[pwc[i].account][pwc[i].assetId] += pwc[i].amount;
}
delete pendingWithdrawCommits[_blockId];
}
function _cleanupPendingWithdrawCommits(uint256 _blockId) private {
PendingWithdrawCommit[] memory pwc = pendingWithdrawCommits[_blockId];
for (uint256 i = 0; i < pwc.length; i++) {
pendingWithdraws[pwc[i].account][pwc[i].assetId] += pwc[i].amount;
}
delete pendingWithdrawCommits[_blockId];
}
function _revertBlock(uint256 _blockId, string memory _reason) private {
_pause();
while (blocks.length > _blockId) {
delete pendingWithdrawCommits[blocks.length - 1];
blocks.pop();
}
priorityOperations.revertBlock(_blockId);
emit RollupBlockReverted(_blockId, _reason);
}
function _revertBlock(uint256 _blockId, string memory _reason) private {
_pause();
while (blocks.length > _blockId) {
delete pendingWithdrawCommits[blocks.length - 1];
blocks.pop();
}
priorityOperations.revertBlock(_blockId);
emit RollupBlockReverted(_blockId, _reason);
}
}
| 15,856,699 | [
1,
1595,
509,
4877,
316,
279,
1203,
1240,
2118,
7120,
18,
1021,
919,
6007,
1015,
458,
264,
10494,
471,
6252,
4023,
16034,
11897,
4826,
326,
4398,
261,
9366,
72,
471,
19,
280,
7120,
2934,
11065,
4634,
598,
9446,
87,
2454,
9288,
628,
511,
22,
1508,
2731,
603,
511,
21,
10279,
576,
24642,
18,
432,
9004,
2874,
353,
1399,
364,
1517,
6855,
30,
261,
21,
13,
4634,
1190,
9446,
23072,
30,
3294,
1768,
1435,
15431,
1836,
1768,
9334,
1534,
25980,
261,
22,
13,
4634,
1190,
9446,
87,
30,
1836,
1768,
1435,
15431,
511,
21,
17,
1918,
9446,
16,
1534,
729,
2236,
1758,
300,
3294,
1768,
1435,
3414,
4634,
1190,
9446,
23072,
3222,
364,
326,
25980,
18,
300,
1836,
1768,
1435,
29389,
2182,
1368,
1534,
17,
4631,
4634,
1190,
9446,
87,
3222,
471,
282,
9792,
326,
4634,
1190,
9446,
23072,
3222,
18,
300,
284,
354,
1100,
332,
319,
1203,
9792,
326,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
16351,
31291,
416,
3893,
353,
14223,
6914,
16,
21800,
16665,
288,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
203,
565,
2254,
1578,
1071,
5381,
14073,
67,
15271,
67,
7240,
67,
26875,
273,
576,
636,
1578,
300,
404,
31,
203,
203,
565,
16515,
1669,
458,
264,
1071,
11732,
6007,
1669,
458,
264,
31,
203,
565,
5438,
1071,
11732,
4023,
31,
203,
565,
13354,
9343,
1071,
11732,
4394,
9343,
31,
203,
203,
565,
3681,
18,
1768,
8526,
1071,
4398,
31,
203,
565,
2254,
5034,
1071,
1056,
23839,
31,
203,
203,
203,
5666,
288,
751,
2016,
487,
3681,
97,
628,
25165,
31417,
19,
751,
2016,
18,
18281,
14432,
203,
5666,
288,
23299,
487,
16002,
97,
628,
25165,
31417,
19,
23299,
18,
18281,
14432,
203,
565,
1958,
16034,
1190,
9446,
5580,
288,
203,
3639,
1758,
2236,
31,
203,
3639,
2254,
1578,
3310,
548,
31,
203,
3639,
2254,
5034,
3844,
31,
203,
565,
289,
203,
565,
2874,
12,
11890,
5034,
516,
16034,
1190,
9446,
5580,
63,
5717,
1071,
4634,
1190,
9446,
23072,
31,
203,
203,
203,
203,
203,
565,
1758,
1071,
3726,
31,
203,
203,
565,
871,
31291,
416,
1768,
23839,
12,
11890,
5034,
25980,
16,
2254,
1578,
1196,
2891,
1769,
203,
565,
871,
31291,
416,
1768,
426,
25631,
12,
11890,
5034,
25980,
16,
533,
3971,
1769,
203,
565,
871,
10494,
758,
1724,
329,
12,
2867,
2236,
16,
2254,
1578,
3310,
548,
16,
2254,
5034,
3844,
16,
2254,
1105,
443,
1724,
548,
1769,
203,
565,
871,
10494,
1190,
9446,
82,
12,
2867,
2
] |
./full_match/4/0xc91810B7F984213857717fd1894be374f982bbc3/sources/sampleNFT.sol | Adding Furniture Token Coin | contract PicpleRewardToken is ERC20PresetMinterPauser {
using Counters for Counters.Counter;
Counters.Counter private _tokenCounter;
mapping(string => uint256) tokenID;
pragma solidity ^0.8.0;
constructor() ERC20PresetMinterPauser("PicpleRewardToken", "PRT"){}
function addToken(uint256 init_amount) external {
require(hasRole(MINTER_ROLE, _msgSender()), "PicpleRewardToken: must have minter role to mint");
require(totalSupply() <= 1000000000, "PicpleRewardToken: maximum supply exceeded");
_mint(msg.sender, init_amount);
}
function decimals() public pure override returns(uint8){
return 0;
}
function showTokenID(string memory furniture) external view returns(uint256){
return tokenID[furniture];
}
} | 12,280,956 | [
1,
13962,
478,
321,
305,
594,
3155,
28932,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16351,
453,
335,
1802,
17631,
1060,
1345,
353,
4232,
39,
3462,
18385,
49,
2761,
16507,
1355,
288,
203,
565,
1450,
9354,
87,
364,
9354,
87,
18,
4789,
31,
203,
565,
9354,
87,
18,
4789,
3238,
389,
2316,
4789,
31,
203,
203,
565,
2874,
12,
1080,
516,
2254,
5034,
13,
1147,
734,
31,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
565,
3885,
1435,
4232,
39,
3462,
18385,
49,
2761,
16507,
1355,
2932,
52,
335,
1802,
17631,
1060,
1345,
3113,
315,
8025,
56,
7923,
2916,
203,
565,
445,
527,
1345,
12,
11890,
5034,
1208,
67,
8949,
13,
3903,
288,
203,
3639,
2583,
12,
5332,
2996,
12,
6236,
2560,
67,
16256,
16,
389,
3576,
12021,
1435,
3631,
315,
52,
335,
1802,
17631,
1060,
1345,
30,
1297,
1240,
1131,
387,
2478,
358,
312,
474,
8863,
203,
3639,
2583,
12,
4963,
3088,
1283,
1435,
1648,
15088,
3784,
16,
315,
52,
335,
1802,
17631,
1060,
1345,
30,
4207,
14467,
12428,
8863,
203,
3639,
389,
81,
474,
12,
3576,
18,
15330,
16,
1208,
67,
8949,
1769,
203,
565,
289,
203,
377,
203,
565,
445,
15105,
1435,
1071,
16618,
3849,
1135,
12,
11890,
28,
15329,
203,
3639,
327,
374,
31,
203,
565,
289,
203,
377,
203,
565,
445,
2405,
1345,
734,
12,
1080,
3778,
284,
321,
305,
594,
13,
3903,
1476,
1135,
12,
11890,
5034,
15329,
203,
3639,
327,
1147,
734,
63,
74,
321,
305,
594,
15533,
203,
565,
289,
203,
377,
203,
97,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.0;
contract Game {
struct Player{
address payable addressOfPlayer;
uint8 serialNo;
bytes32[100] choiceHash;
uint8[100] choice;
uint8 bet;
}
Player public player1;
Player public player2;
bool bothHaveLockedChoices = false;
uint8 countForLockingChoice = 0;
uint8 public turnVariable;
event bothHaveLockedChoiceEvent(bool value);
event hitTileEvent(uint tileNumber, address hitAddress);
event TestEvent(address who); // declaring event
event PlayerEvent(address addressOfPlayer, bytes32[100] choiceHash, uint8 serialNo);
event consoleEvent(string consolevalue);
event uintconsoleEvent(uint8 consolevalue);
event bytesConsoleEvent(bytes consolevalue);
event bytes32ConsoleEvent(bytes32 consolevalue);
event bytes32ArrayConsoleEvent(bytes32[100] consolevalue,address who);
event revealTitleEvent(uint8 value , address revealToAddress,bool isHit);
constructor() public {
}
function register() public {
if (player1.addressOfPlayer == address(0)){
player1.addressOfPlayer = msg.sender;
player1.serialNo = 1;
}
else if (player2.addressOfPlayer == address(0)){
player2.addressOfPlayer = msg.sender;
player2.serialNo = 2;
}
// Both have to register and then only play
countForLockingChoice = 0;
}
function setShips(bytes32[100] memory choiceHash) public {
if (msg.sender == player1.addressOfPlayer ){
player1.choiceHash = choiceHash;
countForLockingChoice += 1;
}
else if (msg.sender == player2.addressOfPlayer){
player2.choiceHash = choiceHash;
countForLockingChoice += 1;
}
if(countForLockingChoice == 2){
bothHaveLockedChoices = true;
turnVariable = 1;
emit bothHaveLockedChoiceEvent(true);
}
}
function whoAmI() public view returns (uint8){
if (player1.addressOfPlayer == msg.sender){
return 1;
}
else if (player2.addressOfPlayer == msg.sender){
return 2;
}
}
function getLength() public view returns (uint) {
return player1.choiceHash.length;
}
function hitTile(uint tileNumber) public {
if (player1.addressOfPlayer == msg.sender && turnVariable==1) {
emit hitTileEvent(tileNumber,player2.addressOfPlayer);
}
else if (player2.addressOfPlayer == msg.sender && turnVariable == 2) {
emit hitTileEvent(tileNumber,player1.addressOfPlayer);
}
}
// Taking randomKey as number, but can change to string
// Should use event emit?
function revealTile(uint8 pos, uint8 randomKey, uint8 value) public {
if (msg.sender == player1.addressOfPlayer){
if( keccak256(abi.encodePacked(randomKey,value)) == player1.choiceHash[pos] ){
player1.choice[pos] = value;
emit revealTitleEvent(value, player2.addressOfPlayer, true);
}else{
emit revealTitleEvent(value, player2.addressOfPlayer, false);
}
turnVariable = 1;
}
else if (msg.sender == player2.addressOfPlayer){
if( keccak256(abi.encodePacked(randomKey,value)) == player2.choiceHash[pos] ){
player1.choice[pos] = value;
emit revealTitleEvent(value, player1.addressOfPlayer, true);
}else{
emit revealTitleEvent(value, player1.addressOfPlayer, true);
}
turnVariable = 2;
}
}
}
| Both have to register and then only play | countForLockingChoice = 0;
| 12,923,662 | [
1,
20240,
1240,
358,
1744,
471,
1508,
1338,
6599,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1056,
1290,
2531,
310,
10538,
273,
374,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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: Base.sol
ver: 0.2.1
updated:18-Nov-2016
author: Darryl Morris (o0ragman0o)
email: o0ragman0o AT gmail.com
An basic contract furnishing inheriting contracts with ownership, reentry
protection and safe sending functions.
This software 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 lesser General Public License for more details.
<http://www.gnu.org/licenses/>.
*/
pragma solidity ^0.4.0;
contract Base
{
/* Constants */
string constant VERSION = "Base 0.1.1 \n";
/* State Variables */
bool mutex;
address public owner;
/* Events */
event Log(string message);
event ChangedOwner(address indexed oldOwner, address indexed newOwner);
/* Modifiers */
// To throw call not made by owner
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}
// This modifier can be used on functions with external calls to
// prevent reentry attacks.
// Constraints:
// Protected functions must have only one point of exit.
// Protected functions cannot use the `return` keyword
// Protected functions return values must be through return parameters.
modifier preventReentry() {
if (mutex) throw;
else mutex = true;
_;
delete mutex;
return;
}
// This modifier can be applied to pulic access state mutation functions
// to protect against reentry if a `mutextProtect` function is already
// on the call stack.
modifier noReentry() {
if (mutex) throw;
_;
}
// Same as noReentry() but intended to be overloaded
modifier canEnter() {
if (mutex) throw;
_;
}
/* Functions */
function Base() { owner = msg.sender; }
function version() public constant returns (string) {
return VERSION;
}
function contractBalance() public constant returns(uint) {
return this.balance;
}
// Change the owner of a contract
function changeOwner(address _newOwner)
public onlyOwner returns (bool)
{
owner = _newOwner;
ChangedOwner(msg.sender, owner);
return true;
}
function safeSend(address _recipient, uint _ether)
internal
preventReentry()
returns (bool success_)
{
if(!_recipient.call.value(_ether)()) throw;
success_ = true;
}
}
/* End of Base */
/*
file: Math.sol
ver: 0.2.0
updated:18-Nov-2016
author: Darryl Morris
email: o0ragman0o AT gmail.com
An inheritable contract containing math functions and comparitors.
This software 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 lesser General Public License for more details.
<http://www.gnu.org/licenses/>.
*/
pragma solidity ^0.4.0;
contract Math
{
/* Constants */
string constant VERSION = "Math 0.0.1 \n";
uint constant NULL = 0;
bool constant LT = false;
bool constant GT = true;
// No type bool <-> int type converstion in solidity :~(
uint constant iTRUE = 1;
uint constant iFALSE = 0;
uint constant iPOS = 1;
uint constant iZERO = 0;
uint constant iNEG = uint(-1);
/* Modifiers */
/* Functions */
function version() public constant returns (string)
{
return VERSION;
}
function assert(bool assertion) internal constant
{
if (!assertion) throw;
}
// @dev Parametric comparitor for > or <
// !_sym returns a < b
// _sym returns a > b
function cmp (uint a, uint b, bool _sym) internal constant returns (bool)
{
return (a!=b) && ((a < b) != _sym);
}
/// @dev Parametric comparitor for >= or <=
/// !_sym returns a <= b
/// _sym returns a >= b
function cmpEq (uint a, uint b, bool _sym) internal constant returns (bool)
{
return (a==b) || ((a < b) != _sym);
}
/// Trichotomous comparitor
/// a < b returns -1
/// a == b returns 0
/// a > b returns 1
/* function triCmp(uint a, uint b) internal constant returns (bool)
{
uint c = a - b;
return c & c & (0 - 1);
}
function nSign(uint a) internal returns (uint)
{
return a & 2^255;
}
function neg(uint a) internal returns (uint) {
return 0 - a;
}
*/
function safeMul(uint a, uint b) internal constant returns (uint)
{
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeSub(uint a, uint b) internal constant returns (uint)
{
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal constant returns (uint)
{
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
}
/* End of Math */
/*
file: ERC20.sol
ver: 0.2.3
updated:18-Nov-2016
author: Darryl Morris
email: o0ragman0o AT gmail.com
An ERC20 compliant token.
This software 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 lesser General Public License for more details.
<http://www.gnu.org/licenses/>.
*/
//pragma solidity ^0.4.0;
//import "Math.sol";
//import "Base.sol";
// ERC20 Standard Token Interface with safe maths and reentry protection
contract ERC20Interface
{
/* Structs */
/* Constants */
string constant VERSION = "ERC20 0.2.3-o0ragman0o\nMath 0.0.1\nBase 0.1.1\n";
/* State Valiables */
uint public totalSupply;
uint8 public decimalPlaces;
string public name;
string public symbol;
// Token ownership mapping
// mapping (address => uint) public balanceOf;
mapping (address => uint) balance;
// Transfer allowances mapping
mapping (address => mapping (address => uint)) public allowance;
/* Events */
// Triggered when tokens are transferred.
event Transfer(
address indexed _from,
address indexed _to,
uint256 _value);
// Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value);
/* Modifiers */
/* Function Abstracts */
/* State variable Accessor Functions (for reference - leave commented) */
// Returns the allowable transfer of tokens by a proxy
// function allowance (address tokenHolders, address proxy, uint allowance) public constant returns (uint);
// Get the total token supply
// function totalSupply() public constant returns (uint);
// Returns token symbol
// function symbol() public constant returns(string);
// Returns token symbol
// function name() public constant returns(string);
// Returns decimal places designated for unit of token.
// function decimalPlaces() public returns(uint);
// Send _value amount of tokens to address _to
// function transfer(address _to, uint256 _value) public returns (bool success);
// Send _value amount of tokens from address _from to address _to
// function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
// Allow _spender to withdraw from your account, multiple times, up to the
// _value amount.
// function approve(address _spender, uint256 _value) public returns (bool success);
}
contract ERC20Token is Base, Math, ERC20Interface
{
/* Events */
/* Structs */
/* Constants */
/* State Valiables */
/* Modifiers */
modifier isAvailable(uint _amount) {
if (_amount > balance[msg.sender]) throw;
_;
}
modifier isAllowed(address _from, uint _amount) {
if (_amount > allowance[_from][msg.sender] ||
_amount > balance[_from]) throw;
_;
}
/* Funtions Public */
function ERC20Token(
uint _supply,
uint8 _decimalPlaces,
string _symbol,
string _name)
{
totalSupply = _supply;
decimalPlaces = _decimalPlaces;
symbol = _symbol;
name = _name;
balance[msg.sender] = totalSupply;
}
function version() public constant returns(string) {
return VERSION;
}
function balanceOf(address _addr)
public
constant
returns (uint)
{
return balance[_addr];
}
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
external
canEnter
isAvailable(_value)
returns (bool)
{
balance[msg.sender] = safeSub(balance[msg.sender], _value);
balance[_to] = safeAdd(balance[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
// Send _value amount of tokens from address _from to address _to
function transferFrom(address _from, address _to, uint256 _value)
external
canEnter
isAllowed(_from, _value)
returns (bool)
{
balance[_from] = safeSub(balance[_from], _value);
balance[_to] = safeAdd(balance[_to], _value);
allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender], _value);
Transfer(msg.sender, _to, _value);
return true;
}
// Allow _spender to withdraw from your account, multiple times, up to the
// _value amount. If this function is called again it overwrites the current
// allowance with _value.
function approve(address _spender, uint256 _value)
external
canEnter
returns (bool success)
{
if (balance[msg.sender] == 0) throw;
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
}
/* End of ERC20 */
/*
file: LibCLL.sol
ver: 0.3.1
updated:21-Sep-2016
author: Darryl Morris
email: o0ragman0o AT gmail.com
A Solidity library for implementing a data indexing regime using
a circular linked list.
This library provisions lookup, navigation and key/index storage
functionality which can be used in conjunction with an array or mapping.
NOTICE: This library uses internal functions only and so cannot be compiled
and deployed independently from its calling contract.
This library 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 lesser General Public License for more details.
<http://www.gnu.org/licenses/>.
*/
//pragma solidity ^0.4.0;
// LibCLL using `uint` keys
library LibCLLu {
string constant VERSION = "LibCLLu 0.3.1";
uint constant NULL = 0;
uint constant HEAD = NULL;
bool constant PREV = false;
bool constant NEXT = true;
struct CLL{
mapping (uint => mapping (bool => uint)) cll;
}
// n: node id d: direction r: return node id
function version() internal constant returns (string) {
return VERSION;
}
// Return existential state of a list.
function exists(CLL storage self)
internal
constant returns (bool)
{
if (self.cll[HEAD][PREV] != HEAD || self.cll[HEAD][NEXT] != HEAD)
return true;
}
// Returns the number of elements in the list
function sizeOf(CLL storage self) internal constant returns (uint r) {
uint i = step(self, HEAD, NEXT);
while (i != HEAD) {
i = step(self, i, NEXT);
r++;
}
return;
}
// Returns the links of a node as and array
function getNode(CLL storage self, uint n)
internal constant returns (uint[2])
{
return [self.cll[n][PREV], self.cll[n][NEXT]];
}
// Returns the link of a node `n` in direction `d`.
function step(CLL storage self, uint n, bool d)
internal constant returns (uint)
{
return self.cll[n][d];
}
// Can be used before `insert` to build an ordered list
// `a` an existing node to search from, e.g. HEAD.
// `b` value to seek
// `r` first node beyond `b` in direction `d`
function seek(CLL storage self, uint a, uint b, bool d)
internal constant returns (uint r)
{
r = step(self, a, d);
while ((b!=r) && ((b < r) != d)) r = self.cll[r][d];
return;
}
// Creates a bidirectional link between two nodes on direction `d`
function stitch(CLL storage self, uint a, uint b, bool d) internal {
self.cll[b][!d] = a;
self.cll[a][d] = b;
}
// Insert node `b` beside and existing node `a` in direction `d`.
function insert (CLL storage self, uint a, uint b, bool d) internal {
uint c = self.cll[a][d];
stitch (self, a, b, d);
stitch (self, b, c, d);
}
function remove(CLL storage self, uint n) internal returns (uint) {
if (n == NULL) return;
stitch(self, self.cll[n][PREV], self.cll[n][NEXT], NEXT);
delete self.cll[n][PREV];
delete self.cll[n][NEXT];
return n;
}
function push(CLL storage self, uint n, bool d) internal {
insert(self, HEAD, n, d);
}
function pop(CLL storage self, bool d) internal returns (uint) {
return remove(self, step(self, HEAD, d));
}
}
// LibCLL using `int` keys
library LibCLLi {
string constant VERSION = "LibCLLi 0.3.1";
int constant NULL = 0;
int constant HEAD = NULL;
bool constant PREV = false;
bool constant NEXT = true;
struct CLL{
mapping (int => mapping (bool => int)) cll;
}
// n: node id d: direction r: return node id
function version() internal constant returns (string) {
return VERSION;
}
// Return existential state of a node. n == HEAD returns list existence.
function exists(CLL storage self, int n) internal constant returns (bool) {
if (self.cll[HEAD][PREV] != HEAD || self.cll[HEAD][NEXT] != HEAD)
return true;
}
// Returns the number of elements in the list
function sizeOf(CLL storage self) internal constant returns (uint r) {
int i = step(self, HEAD, NEXT);
while (i != HEAD) {
i = step(self, i, NEXT);
r++;
}
return;
}
// Returns the links of a node as and array
function getNode(CLL storage self, int n)
internal constant returns (int[2])
{
return [self.cll[n][PREV], self.cll[n][NEXT]];
}
// Returns the link of a node `n` in direction `d`.
function step(CLL storage self, int n, bool d)
internal constant returns (int)
{
return self.cll[n][d];
}
// Can be used before `insert` to build an ordered list
// `a` an existing node to search from, e.g. HEAD.
// `b` value to seek
// `r` first node beyond `b` in direction `d`
function seek(CLL storage self, int a, int b, bool d)
internal constant returns (int r)
{
r = step(self, a, d);
while ((b!=r) && ((b < r) != d)) r = self.cll[r][d];
return;
}
// Creates a bidirectional link between two nodes on direction `d`
function stitch(CLL storage self, int a, int b, bool d) internal {
self.cll[b][!d] = a;
self.cll[a][d] = b;
}
// Insert node `b` beside existing node `a` in direction `d`.
function insert (CLL storage self, int a, int b, bool d) internal {
int c = self.cll[a][d];
stitch (self, a, b, d);
stitch (self, b, c, d);
}
function remove(CLL storage self, int n) internal returns (int) {
if (n == NULL) return;
stitch(self, self.cll[n][PREV], self.cll[n][NEXT], NEXT);
delete self.cll[n][PREV];
delete self.cll[n][NEXT];
return n;
}
function push(CLL storage self, int n, bool d) internal {
insert(self, HEAD, n, d);
}
function pop(CLL storage self, bool d) internal returns (int) {
return remove(self, step(self, HEAD, d));
}
}
/* End of LibCLLi */
/*
file: ITT.sol
ver: 0.3.6
updated:18-Nov-2016
author: Darryl Morris (o0ragman0o)
email: o0ragman0o AT gmail.com
An ERC20 compliant token with currency
exchange functionality here called an 'Intrinsically Tradable
Token' (ITT).
This software 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 lesser General Public License for more details.
<http://www.gnu.org/licenses/>.
*/
//pragma solidity ^0.4.0;
//import "Base.sol";
//import "Math.sol";
//import "ERC20.sol";
//import "LibCLL.sol";
contract ITTInterface
{
using LibCLLu for LibCLLu.CLL;
/* Constants */
string constant VERSION = "ITT 0.3.6\nERC20 0.2.3-o0ragman0o\nMath 0.0.1\nBase 0.1.1\n";
uint constant HEAD = 0;
uint constant MINNUM = uint(1);
// use only 128 bits of uint to prevent mul overflows.
uint constant MAXNUM = 2**128;
uint constant MINPRICE = uint(1);
uint constant NEG = uint(-1); //2**256 - 1
bool constant PREV = false;
bool constant NEXT = true;
bool constant BID = false;
bool constant ASK = true;
// minimum gas required to prevent out of gas on 'take' loop
uint constant MINGAS = 100000;
// For staging and commiting trade details. This saves unneccessary state
// change gas usage during multi order takes but does increase logic
// complexity when encountering 'trade with self' orders
struct TradeMessage {
bool make;
bool side;
uint price;
uint tradeAmount;
uint balance;
uint etherBalance;
}
/* State Valiables */
// To allow for trade halting by owner.
bool public trading;
// Mapping for ether ownership of accumulated deposits, sales and refunds.
mapping (address => uint) etherBalance;
// Orders are stored in circular linked list FIFO's which are mappings with
// price as key and value as trader address. A trader can have only one
// order open at each price. Reordering at that price will cancel the first
// order and push the new one onto the back of the queue.
mapping (uint => LibCLLu.CLL) orderFIFOs;
// Order amounts are stored in a seperate lookup. The keys of this mapping
// are `sha3` hashes of the price and trader address.
// This mapping prevents more than one order at a particular price.
mapping (bytes32 => uint) amounts;
// The pricebook is a linked list holding keys to lookup the price FIFO's
LibCLLu.CLL priceBook = orderFIFOs[0];
/* Events */
// Triggered on a make sell order
event Ask (uint indexed price, uint amount, address indexed trader);
// Triggered on a make buy order
event Bid (uint indexed price, uint amount, address indexed trader);
// Triggered on a filled order
event Sale (uint indexed price, uint amount, address indexed buyer, address indexed seller);
// Triggered when trading is started or halted
event Trading(bool trading);
/* Functions Public constant */
/// @notice Returns best bid or ask price.
function spread(bool _side) public constant returns(uint);
/// @notice Returns the order amount for trader `_trader` at '_price'
/// @param _trader Address of trader
/// @param _price Price of order
function getAmount(uint _price, address _trader)
public constant returns(uint);
/// @notice Returns the collective order volume at a `_price`.
/// @param _price FIFO for price.
function getPriceVolume(uint _price) public constant returns (uint);
/// @notice Returns an array of all prices and their volumes.
/// @dev [even] indecies are the price. [odd] are the volume. [0] is the
/// index of the spread.
function getBook() public constant returns (uint[]);
/* Functions Public non-constant*/
/// @notice Will buy `_amount` tokens at or below `_price` each.
/// @param _bidPrice Highest price to bid.
/// @param _amount The requested amount of tokens to buy.
/// @param _make Value of true will make order if not filled.
function buy (uint _bidPrice, uint _amount, bool _make)
payable returns (bool);
/// @notice Will sell `_amount` tokens at or above `_price` each.
/// @param _askPrice Lowest price to ask.
/// @param _amount The requested amount of tokens to buy.
/// @param _make A value of true will make an order if not market filled.
function sell (uint _askPrice, uint _amount, bool _make)
external returns (bool);
/// @notice Will withdraw `_ether` to your account.
/// @param _ether The amount to withdraw
function withdraw(uint _ether)
external returns (bool success_);
/// @notice Cancel order at `_price`
/// @param _price The price at which the order was placed.
function cancel(uint _price)
external returns (bool);
/// @notice Will set trading state to `_trading`
/// @param _trading State to set trading to.
function setTrading(bool _trading)
external returns (bool);
}
/* Intrinsically Tradable Token code */
contract ITT is ERC20Token, ITTInterface
{
/* Structs */
/* Modifiers */
/// @dev Passes if token is currently trading
modifier isTrading() {
if (!trading) throw;
_;
}
/// @dev Validate buy parameters
modifier isValidBuy(uint _bidPrice, uint _amount) {
if ((etherBalance[msg.sender] + msg.value) < (_amount * _bidPrice) ||
_amount == 0 || _amount > totalSupply ||
_bidPrice <= MINPRICE || _bidPrice >= MAXNUM) throw; // has insufficient ether.
_;
}
/// @dev Validates sell parameters. Price must be larger than 1.
modifier isValidSell(uint _askPrice, uint _amount) {
if (_amount > balance[msg.sender] || _amount == 0 ||
_askPrice < MINPRICE || _askPrice > MAXNUM) throw;
_;
}
/// @dev Validates ether balance
modifier hasEther(address _member, uint _ether) {
if (etherBalance[_member] < _ether) throw;
_;
}
/// @dev Validates token balance
modifier hasBalance(address _member, uint _amount) {
if (balance[_member] < _amount) throw;
_;
}
/* Functions */
function ITT(
uint _totalSupply,
uint8 _decimalPlaces,
string _symbol,
string _name
)
ERC20Token(
_totalSupply,
_decimalPlaces,
_symbol,
_name
)
{
// setup pricebook and maximum spread.
priceBook.cll[HEAD][PREV] = MINPRICE;
priceBook.cll[MINPRICE][PREV] = MAXNUM;
priceBook.cll[HEAD][NEXT] = MAXNUM;
priceBook.cll[MAXNUM][NEXT] = MINPRICE;
trading = true;
balance[owner] = totalSupply;
}
/* Functions Getters */
function version() public constant returns(string) {
return VERSION;
}
function etherBalanceOf(address _addr) public constant returns (uint) {
return etherBalance[_addr];
}
function spread(bool _side) public constant returns(uint) {
return priceBook.step(HEAD, _side);
}
function getAmount(uint _price, address _trader)
public constant returns(uint) {
return amounts[sha3(_price, _trader)];
}
function sizeOf(uint l) constant returns (uint s) {
if(l == 0) return priceBook.sizeOf();
return orderFIFOs[l].sizeOf();
}
function getPriceVolume(uint _price) public constant returns (uint v_)
{
uint n = orderFIFOs[_price].step(HEAD,NEXT);
while (n != HEAD) {
v_ += amounts[sha3(_price, address(n))];
n = orderFIFOs[_price].step(n, NEXT);
}
return;
}
function getBook() public constant returns (uint[])
{
uint i;
uint p = priceBook.step(MINNUM, NEXT);
uint[] memory volumes = new uint[](priceBook.sizeOf() * 2 - 2);
while (p < MAXNUM) {
volumes[i++] = p;
volumes[i++] = getPriceVolume(p);
p = priceBook.step(p, NEXT);
}
return volumes;
}
function numOrdersOf(address _addr) public constant returns (uint)
{
uint c;
uint p = MINNUM;
while (p < MAXNUM) {
if (amounts[sha3(p, _addr)] > 0) c++;
p = priceBook.step(p, NEXT);
}
return c;
}
function getOpenOrdersOf(address _addr) public constant returns (uint[])
{
uint i;
uint c;
uint p = MINNUM;
uint[] memory open = new uint[](numOrdersOf(_addr)*2);
p = MINNUM;
while (p < MAXNUM) {
if (amounts[sha3(p, _addr)] > 0) {
open[i++] = p;
open[i++] = amounts[sha3(p, _addr)];
}
p = priceBook.step(p, NEXT);
}
return open;
}
function getNode(uint _list, uint _node) public constant returns(uint[2])
{
return [orderFIFOs[_list].cll[_node][PREV],
orderFIFOs[_list].cll[_node][NEXT]];
}
/* Functions Public */
// Here non-constant public functions act as a security layer. They are re-entry
// protected so cannot call each other. For this reason, they
// are being used for parameter and enterance validation, while internal
// functions manage the logic. This also allows for deriving contracts to
// overload the public function with customised validations and not have to
// worry about rewritting the logic.
function buy (uint _bidPrice, uint _amount, bool _make)
payable
canEnter
isTrading
isValidBuy(_bidPrice, _amount)
returns (bool)
{
trade(_bidPrice, _amount, BID, _make);
return true;
}
function sell (uint _askPrice, uint _amount, bool _make)
external
canEnter
isTrading
isValidSell(_askPrice, _amount)
returns (bool)
{
trade(_askPrice, _amount, ASK, _make);
return true;
}
function withdraw(uint _ether)
external
canEnter
hasEther(msg.sender, _ether)
returns (bool success_)
{
etherBalance[msg.sender] -= _ether;
safeSend(msg.sender, _ether);
success_ = true;
}
function cancel(uint _price)
external
canEnter
returns (bool)
{
TradeMessage memory tmsg;
tmsg.price = _price;
tmsg.balance = balance[msg.sender];
tmsg.etherBalance = etherBalance[msg.sender];
cancelIntl(tmsg);
balance[msg.sender] = tmsg.balance;
etherBalance[msg.sender] = tmsg.etherBalance;
return true;
}
function setTrading(bool _trading)
external
onlyOwner
canEnter
returns (bool)
{
trading = _trading;
Trading(true);
return true;
}
/* Functions Internal */
// Internal functions handle this contract's logic.
function trade (uint _price, uint _amount, bool _side, bool _make) internal {
TradeMessage memory tmsg;
tmsg.price = _price;
tmsg.tradeAmount = _amount;
tmsg.side = _side;
tmsg.make = _make;
// Cache state balances to memory and commit to storage only once after trade.
tmsg.balance = balance[msg.sender];
tmsg.etherBalance = etherBalance[msg.sender] + msg.value;
take(tmsg);
make(tmsg);
balance[msg.sender] = tmsg.balance;
etherBalance[msg.sender] = tmsg.etherBalance;
}
function take (TradeMessage tmsg)
internal
{
address maker;
bytes32 orderHash;
uint takeAmount;
uint takeEther;
// use of signed math on unsigned ints is intentional
uint sign = tmsg.side ? uint(1) : uint(-1);
uint bestPrice = spread(!tmsg.side);
// Loop with available gas to take orders
while (
tmsg.tradeAmount > 0 &&
cmpEq(tmsg.price, bestPrice, !tmsg.side) &&
msg.gas > MINGAS
)
{
maker = address(orderFIFOs[bestPrice].step(HEAD, NEXT));
orderHash = sha3(bestPrice, maker);
if (tmsg.tradeAmount < amounts[orderHash]) {
// Prepare to take partial order
amounts[orderHash] = safeSub(amounts[orderHash], tmsg.tradeAmount);
takeAmount = tmsg.tradeAmount;
tmsg.tradeAmount = 0;
} else {
// Prepare to take full order
takeAmount = amounts[orderHash];
tmsg.tradeAmount = safeSub(tmsg.tradeAmount, takeAmount);
closeOrder(bestPrice, maker);
}
takeEther = safeMul(bestPrice, takeAmount);
// signed multiply on uints is intentional and so safeMaths will
// break here. Valid range for exit balances are 0..2**128
tmsg.etherBalance += takeEther * sign;
tmsg.balance -= takeAmount * sign;
if (tmsg.side) {
// Sell to bidder
if (msg.sender == maker) {
// bidder is self
tmsg.balance += takeAmount;
} else {
balance[maker] += takeAmount;
}
} else {
// Buy from asker;
if (msg.sender == maker) {
// asker is self
tmsg.etherBalance += takeEther;
} else {
etherBalance[maker] += takeEther;
}
}
// prep for next order
bestPrice = spread(!tmsg.side);
Sale (bestPrice, takeAmount, msg.sender, maker);
}
}
function make(TradeMessage tmsg)
internal
{
bytes32 orderHash;
if (tmsg.tradeAmount == 0 || !tmsg.make || msg.gas < MINGAS) return;
orderHash = sha3(tmsg.price, msg.sender);
if (amounts[orderHash] != 0) {
// Cancel any pre-existing owned order at this price
cancelIntl(tmsg);
}
if (!orderFIFOs[tmsg.price].exists()) {
// Register price in pricebook
priceBook.insert(
priceBook.seek(HEAD, tmsg.price, tmsg.side),
tmsg.price, !tmsg.side);
}
amounts[orderHash] = tmsg.tradeAmount;
orderFIFOs[tmsg.price].push(uint(msg.sender), PREV);
if (tmsg.side) {
tmsg.balance -= tmsg.tradeAmount;
Ask (tmsg.price, tmsg.tradeAmount, msg.sender);
} else {
tmsg.etherBalance -= tmsg.tradeAmount * tmsg.price;
Bid (tmsg.price, tmsg.tradeAmount, msg.sender);
}
}
function cancelIntl(TradeMessage tmsg) internal {
uint amount = amounts[sha3(tmsg.price, msg.sender)];
if (amount == 0) return;
if (tmsg.price > spread(BID)) tmsg.balance += amount; // was ask
else tmsg.etherBalance += tmsg.price * amount; // was bid
closeOrder(tmsg.price, msg.sender);
}
function closeOrder(uint _price, address _trader) internal {
orderFIFOs[_price].remove(uint(_trader));
if (!orderFIFOs[_price].exists()) {
priceBook.remove(_price);
}
delete amounts[sha3(_price, _trader)];
}
} | Returns the link of a node `n` in direction `d`. | function step(CLL storage self, int n, bool d)
internal constant returns (int)
{
return self.cll[n][d];
}
| 1,055,317 | [
1,
1356,
326,
1692,
434,
279,
756,
1375,
82,
68,
316,
4068,
1375,
72,
8338,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2235,
12,
39,
4503,
2502,
365,
16,
509,
290,
16,
1426,
302,
13,
203,
3639,
2713,
225,
5381,
1135,
261,
474,
13,
203,
565,
288,
203,
3639,
327,
365,
18,
830,
80,
63,
82,
6362,
72,
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
] |
/**
*Submitted for verification at Etherscan.io on 2020-03-04
*/
pragma solidity 0.5.10;
/**
* Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*/
library SafeMath {
/**
* Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
//require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
/**
* @title Roles
* Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
*Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner, "Ownable: the caller must be owner");
_;
}
/**
* Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see `ERC20Detailed`.
*/
interface IERC20 {
/**
* Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through `transferFrom`. This is
* zero by default.
*
* This value changes when `approve` or `transferFrom` are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* > Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an `Approval` event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* Emitted when the allowance of a `spender` for an `owner` is set by
* a call to `approve`. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* Implementation of the `IERC20` interface.
*
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) internal _allowances;
uint256 internal _totalSupply;
/**
* See `IERC20.totalSupply`.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* See `IERC20.balanceOf`.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* See `IERC20.transfer`.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* See `IERC20.allowance`.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* See `IERC20.approve`.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* See `IERC20.transferFrom`.
*
* Emits an `Approval` event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of `ERC20`;
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `value`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount));
return true;
}
/**
* Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to `approve` that can be used as a mitigation for
* problems described in `IERC20.approve`.
*
* Emits an `Approval` event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseApproval(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
/**
* Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to `approve` that can be used as a mitigation for
* problems described in `IERC20.approve`.
*
* Emits an `Approval` event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseApproval(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to `transfer`, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a `Transfer` event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
}
/**
* Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* Set the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* Return the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* Return the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* Return 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`).
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
/**
* Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*/
contract Pausable is Ownable {
/**
* Emitted when the pause is triggered by a pauser (`account`).
*/
event Paused(address account);
/**
* Emitted when the pause is lifted by a pauser (`account`).
*/
event Unpaused(address account);
bool private _paused;
/**
* Initialize the contract in unpaused state. Assigns the Pauser role
* to the deployer.
*/
constructor () internal {
_paused = false;
}
/**
* Return true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* Called by a pauser to pause, triggers stopped state.
*/
function pause() public onlyOwner whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* Called by a pauser to unpause, returns to normal state.
*/
function unpause() public onlyOwner whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
/**
* @title Pausable token
* ERC20 modified with pausable transfers.
*/
contract ERC20Pausable is ERC20, Pausable {
function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) {
return super.transferFrom(from, to, value);
}
function approve(address spender, uint256 value) public whenNotPaused returns (bool) {
return super.approve(spender, value);
}
function increaseApproval(address spender, uint addedValue) public whenNotPaused returns (bool) {
return super.increaseApproval(spender, addedValue);
}
function decreaseApproval(address spender, uint subtractedValue) public whenNotPaused returns (bool) {
return super.decreaseApproval(spender, subtractedValue);
}
}
contract MinterRole is Ownable {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
modifier onlyMinter() {
require(isMinter(msg.sender) || msg.sender == owner, "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyOwner {
_addMinter(account);
}
function removeMinter(address account) public onlyOwner {
_removeMinter(account);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
/**
* Extension of `ERC20` that adds a set of accounts with the `MinterRole`,
* which have permission to mint (create) new tokens as they see fit.
*
* At construction, the deployer of the contract is the only minter.
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* See `ERC20._mint`.
*
* Requirements:
* - the caller must have the `MinterRole`.
*/
function mint(address account, uint256 amount) public onlyMinter returns (bool) {
_mint(account, amount);
return true;
}
}
/**
* Extension of `ERC20Mintable` that adds a cap to the supply of tokens.
*/
contract ERC20Capped is ERC20Mintable {
uint256 internal _cap;
bool public isFinishMint;
/**
* Returns the cap on the token's total supply.
*/
function cap() public view returns (uint256) {
return _cap;
}
/**
* See `ERC20Mintable.mint`.
*
* Requirements:
*
* - `value` must not cause the total supply to go over the cap.
*/
function _mint(address account, uint256 value) internal {
require(!isFinishMint, "ERC20Capped: minting has been finished");
require(totalSupply().add(value) <= _cap, "ERC20Capped: cap exceeded");
if(totalSupply().add(value) == _cap) {
isFinishMint = true;
}
super._mint(account, value);
}
function finishMint() public onlyOwner {
require(!isFinishMint, "ERC20Capped: minting has been finished");
isFinishMint = true;
}
}
/**
* @title ERC20Burnable
* Implement the function of ERC20 token burning.
*/
contract ERC20Burnable is ERC20, Ownable {
event Burn(address indexed owner, uint256 amount);
/**
* @dev Burn a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public onlyOwner {
require(_value <= _balances[msg.sender], "ERC20Burnable: not enough token balance");
// 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[msg.sender] = _balances[msg.sender].sub(_value); //injected INTEGER OVERFLOW OR UNDERFLOW
_totalSupply = _totalSupply.sub(_value); //injected INTEGER OVERFLOW OR UNDERFLOW
emit Burn(msg.sender, _value);
emit Transfer(msg.sender, address(0), _value);
}
}
/**
* Implementation of the TigerCash.
*/
contract overflow is ERC20Detailed, ERC20Pausable, ERC20Capped, ERC20Burnable {
// The total amount of locks at the specified address.
mapping (address => uint256) public totalLockAmount;
// The amount of released addresses of the specified address.
mapping (address => uint256) public releasedAmount;
mapping (address => uint256) public lockedAmount;
mapping (address => allocation[]) public allocations;
struct allocation {
uint256 releaseTime;
uint256 releaseAmount;
}
event LockToken(address indexed beneficiary, uint256[] releaseAmounts, uint256[] releaseTimes);
event ReleaseToken(address indexed user, uint256 releaseAmount, uint256 releaseTime);
/**
* Initialize token basic information.
*/
constructor(string memory token_name, string memory token_symbol, uint8 token_decimals, uint256 token_cap) public
ERC20Detailed(token_name, token_symbol, token_decimals) {
_cap = token_cap * 10 ** uint256(token_decimals);
}
/**
* Send the token to the beneficiary and lock it, and the timestamp and quantity of locks can be set by owner.
* @param _beneficiary A specified address.
* @param _releaseTimes Array,the timesamp of release token.
* @param _releaseAmounts Array,the amount of release token.
*/
function lockToken(address _beneficiary, uint256[] memory _releaseTimes, uint256[] memory _releaseAmounts) public onlyOwner returns(bool) {
require(_beneficiary != address(0), "Token: the target address cannot be a zero address");
require(_releaseTimes.length == _releaseAmounts.length, "Token: the array length must be equal");
uint256 _lockedAmount;
for (uint256 i = 0; i < _releaseTimes.length; i++) {
_lockedAmount = _lockedAmount.add(_releaseAmounts[i]);
require(_releaseAmounts[i] > 0, "Token: the amount must be greater than 0");
require(_releaseTimes[i] >= now, "Token: the time must be greater than current time");
//Save the locktoken information
allocations[_beneficiary].push(allocation(_releaseTimes[i], _releaseAmounts[i]));
}
lockedAmount[_beneficiary] = lockedAmount[_beneficiary].add(_lockedAmount);
totalLockAmount[_beneficiary] = totalLockAmount[_beneficiary].add(_lockedAmount);
_balances[owner] = _balances[owner].sub(_lockedAmount); //Remove this part of the locked token from the owner.
_balances[_beneficiary] = _balances[_beneficiary].add(_lockedAmount);
emit Transfer(owner, _beneficiary, _lockedAmount);
emit LockToken(_beneficiary, _releaseAmounts, _releaseTimes);
return true;
}
/**
* Rewrite the transfer function to automatically unlock the locked token.
*/
function transfer(address to, uint256 value) public returns (bool) {
if(releasableAmount(msg.sender) > 0) {
_releaseToken(msg.sender);
}
require(_balances[msg.sender].sub(lockedAmount[msg.sender]) >= value, "Token: not enough token balance");
super.transfer(to, value);
return true;
}
/**
* Rewrite the transferFrom function to automatically unlock the locked token.
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
if(releasableAmount(from) > 0) {
_releaseToken(from);
}
require(_balances[from].sub(lockedAmount[from]) >= value, "Token: not enough token balance");
super.transferFrom(from, to, value);
return true;
}
/**
* Get the amount of current timestamps that can be released.
* @param addr A specified address.
*/
function releasableAmount(address addr) public view returns(uint256) {
uint256 num = 0;
for (uint256 i = 0; i < allocations[addr].length; i++) {
if (now >= allocations[addr][i].releaseTime) {
num = num.add(allocations[addr][i].releaseAmount);
}
}
return num.sub(releasedAmount[addr]);
}
/**
* Internal function, implement the basic functions of releasing tokens.
*/
function _releaseToken(address _owner) internal returns(bool) {
//Get the amount of release and update the lock-plans data.
uint256 amount = releasableAmount(_owner);
require(amount > 0, "Token: no releasable tokens");
lockedAmount[_owner] = lockedAmount[_owner].sub(amount);
releasedAmount[_owner] = releasedAmount[_owner].add(amount);
// If the token on this address has been completely released, the address lock record and the total amount of locks and the released amount are cleared.
if (releasedAmount[_owner] == totalLockAmount[_owner]) {
delete allocations[_owner]; // Clear the address history data.
totalLockAmount[_owner] = 0;
releasedAmount[_owner] = 0;
lockedAmount[_owner] = 0;
}
emit ReleaseToken(_owner, amount, now);
return true;
}
} | * @title Pausable token ERC20 modified with pausable transfers./ | contract ERC20Pausable is ERC20, Pausable {
function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) {
return super.transferFrom(from, to, value);
}
function approve(address spender, uint256 value) public whenNotPaused returns (bool) {
return super.approve(spender, value);
}
function increaseApproval(address spender, uint addedValue) public whenNotPaused returns (bool) {
return super.increaseApproval(spender, addedValue);
}
function decreaseApproval(address spender, uint subtractedValue) public whenNotPaused returns (bool) {
return super.decreaseApproval(spender, subtractedValue);
}
}
| 5,467,839 | [
1,
16507,
16665,
1147,
225,
4232,
39,
3462,
4358,
598,
6790,
16665,
29375,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
4232,
39,
3462,
16507,
16665,
353,
4232,
39,
3462,
16,
21800,
16665,
288,
203,
565,
445,
7412,
12,
2867,
358,
16,
2254,
5034,
460,
13,
1071,
1347,
1248,
28590,
1135,
261,
6430,
13,
288,
203,
3639,
327,
2240,
18,
13866,
12,
869,
16,
460,
1769,
203,
565,
289,
203,
203,
565,
445,
7412,
1265,
12,
2867,
628,
16,
1758,
358,
16,
2254,
5034,
460,
13,
1071,
1347,
1248,
28590,
1135,
261,
6430,
13,
288,
203,
3639,
327,
2240,
18,
13866,
1265,
12,
2080,
16,
358,
16,
460,
1769,
203,
565,
289,
203,
203,
565,
445,
6617,
537,
12,
2867,
17571,
264,
16,
2254,
5034,
460,
13,
1071,
1347,
1248,
28590,
1135,
261,
6430,
13,
288,
203,
3639,
327,
2240,
18,
12908,
537,
12,
87,
1302,
264,
16,
460,
1769,
203,
565,
289,
203,
203,
565,
445,
10929,
23461,
12,
2867,
17571,
264,
16,
2254,
3096,
620,
13,
1071,
1347,
1248,
28590,
1135,
261,
6430,
13,
288,
203,
3639,
327,
2240,
18,
267,
11908,
23461,
12,
87,
1302,
264,
16,
3096,
620,
1769,
203,
565,
289,
203,
203,
565,
445,
20467,
23461,
12,
2867,
17571,
264,
16,
2254,
10418,
329,
620,
13,
1071,
1347,
1248,
28590,
1135,
261,
6430,
13,
288,
203,
3639,
327,
2240,
18,
323,
11908,
23461,
12,
87,
1302,
264,
16,
10418,
329,
620,
1769,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.16;
//Slightly modified SafeMath library - includes a min and max function, removes useless div function
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function add(int256 a, int256 b) internal pure returns (int256 c) {
if (b > 0) {
c = a + b;
assert(c >= a);
} else {
c = a + b;
assert(c <= a);
}
}
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
function max(int256 a, int256 b) internal pure returns (uint256) {
return a > b ? uint256(a) : uint256(b);
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function sub(int256 a, int256 b) internal pure returns (int256 c) {
if (b > 0) {
c = a - b;
assert(c <= a);
} else {
c = a - b;
assert(c >= a);
}
}
}
pragma solidity ^0.5.0;
/**
* @title Tellor Oracle Storage Library
* @dev Contains all the variables/structs used by Tellor
*/
library TellorStorage {
//Internal struct for use in proof-of-work submission
struct Details {
uint256 value;
address miner;
}
struct Dispute {
bytes32 hash; //unique hash of dispute: keccak256(_miner,_requestId,_timestamp)
int256 tally; //current tally of votes for - against measure
bool executed; //is the dispute settled
bool disputeVotePassed; //did the vote pass?
bool isPropFork; //true for fork proposal NEW
address reportedMiner; //miner who alledgedly submitted the 'bad value' will get disputeFee if dispute vote fails
address reportingParty; //miner reporting the 'bad value'-pay disputeFee will get reportedMiner's stake if dispute vote passes
address proposedForkAddress; //new fork address (if fork proposal)
mapping(bytes32 => uint256) disputeUintVars;
//Each of the variables below is saved in the mapping disputeUintVars for each disputeID
//e.g. TellorStorageStruct.DisputeById[disputeID].disputeUintVars[keccak256("requestId")]
//These are the variables saved in this mapping:
// uint keccak256("requestId");//apiID of disputed value
// uint keccak256("timestamp");//timestamp of distputed value
// uint keccak256("value"); //the value being disputed
// uint keccak256("minExecutionDate");//7 days from when dispute initialized
// uint keccak256("numberOfVotes");//the number of parties who have voted on the measure
// uint keccak256("blockNumber");// the blocknumber for which votes will be calculated from
// uint keccak256("minerSlot"); //index in dispute array
// uint keccak256("fee"); //fee paid corresponding to dispute
mapping(address => bool) voted; //mapping of address to whether or not they voted
}
struct StakeInfo {
uint256 currentStatus; //0-not Staked, 1=Staked, 2=LockedForWithdraw 3= OnDispute 4=ReadyForUnlocking 5=Unlocked
uint256 startDate; //stake start date
}
//Internal struct to allow balances to be queried by blocknumber for voting purposes
struct Checkpoint {
uint128 fromBlock; // fromBlock is the block number that the value was generated from
uint128 value; // value is the amount of tokens at a specific block number
}
struct Request {
string queryString; //id to string api
string dataSymbol; //short name for api request
bytes32 queryHash; //hash of api string and granularity e.g. keccak256(abi.encodePacked(_sapi,_granularity))
uint256[] requestTimestamps; //array of all newValueTimestamps requested
mapping(bytes32 => uint256) apiUintVars;
//Each of the variables below is saved in the mapping apiUintVars for each api request
//e.g. requestDetails[_requestId].apiUintVars[keccak256("totalTip")]
//These are the variables saved in this mapping:
// uint keccak256("granularity"); //multiplier for miners
// uint keccak256("requestQPosition"); //index in requestQ
// uint keccak256("totalTip");//bonus portion of payout
mapping(uint256 => uint256) minedBlockNum; //[apiId][minedTimestamp]=>block.number
//This the time series of finalValues stored by the contract where uint UNIX timestamp is mapped to value
mapping(uint256 => uint256) finalValues;
mapping(uint256 => bool) inDispute; //checks if API id is in dispute or finalized.
mapping(uint256 => address[5]) minersByValue;
mapping(uint256 => uint256[5]) valuesByTimestamp;
}
struct TellorStorageStruct {
bytes32 currentChallenge; //current challenge to be solved
uint256[51] requestQ; //uint50 array of the top50 requests by payment amount
uint256[] newValueTimestamps; //array of all timestamps requested
Details[5] currentMiners; //This struct is for organizing the five mined values to find the median
mapping(bytes32 => address) addressVars;
//Address fields in the Tellor contract are saved the addressVars mapping
//e.g. addressVars[keccak256("tellorContract")] = address
//These are the variables saved in this mapping:
// address keccak256("tellorContract");//Tellor address
// address keccak256("_owner");//Tellor Owner address
// address keccak256("_deity");//Tellor Owner that can do things at will
// address keccak256("pending_owner"); // The proposed new owner
mapping(bytes32 => uint256) uintVars;
//uint fields in the Tellor contract are saved the uintVars mapping
//e.g. uintVars[keccak256("decimals")] = uint
//These are the variables saved in this mapping:
// keccak256("decimals"); //18 decimal standard ERC20
// keccak256("disputeFee");//cost to dispute a mined value
// keccak256("disputeCount");//totalHistoricalDisputes
// keccak256("total_supply"); //total_supply of the token in circulation
// keccak256("stakeAmount");//stakeAmount for miners (we can cut gas if we just hardcode it in...or should it be variable?)
// keccak256("stakerCount"); //number of parties currently staked
// keccak256("timeOfLastNewValue"); // time of last challenge solved
// keccak256("difficulty"); // Difficulty of current block
// keccak256("currentTotalTips"); //value of highest api/timestamp PayoutPool
// keccak256("currentRequestId"); //API being mined--updates with the ApiOnQ Id
// keccak256("requestCount"); // total number of requests through the system
// keccak256("slotProgress");//Number of miners who have mined this value so far
// keccak256("miningReward");//Mining Reward in PoWo tokens given to all miners per value
// keccak256("timeTarget"); //The time between blocks (mined Oracle values)
// keccak256("_tblock"); //
// keccak256("runningTips"); // VAriable to track running tips
// keccak256("currentReward"); // The current reward
// keccak256("devShare"); // The amount directed towards th devShare
// keccak256("currentTotalTips"); //
//This is a boolean that tells you if a given challenge has been completed by a given miner
mapping(bytes32 => mapping(address => bool)) minersByChallenge;
mapping(uint256 => uint256) requestIdByTimestamp; //minedTimestamp to apiId
mapping(uint256 => uint256) requestIdByRequestQIndex; //link from payoutPoolIndex (position in payout pool array) to apiId
mapping(uint256 => Dispute) disputesById; //disputeId=> Dispute details
mapping(address => Checkpoint[]) balances; //balances of a party given blocks
mapping(address => mapping(address => uint256)) allowed; //allowance for a given party and approver
mapping(address => StakeInfo) stakerDetails; //mapping from a persons address to their staking info
mapping(uint256 => Request) requestDetails; //mapping of apiID to details
mapping(bytes32 => uint256) requestIdByQueryHash; // api bytes32 gets an id = to count of requests array
mapping(bytes32 => uint256) disputeIdByDisputeHash; //maps a hash to an ID for each dispute
}
}
pragma solidity ^0.5.16;
/**
* @title Tellor Transfer
* @dev Contains the methods related to transfers and ERC20. Tellor.sol and TellorGetters.sol
* reference this library for function's logic.
*/
library TellorTransfer {
using SafeMath for uint256;
event Approval(address indexed _owner, address indexed _spender, uint256 _value); //ERC20 Approval event
event Transfer(address indexed _from, address indexed _to, uint256 _value); //ERC20 Transfer Event
bytes32 public constant stakeAmount = 0x7be108969d31a3f0b261465c71f2b0ba9301cd914d55d9091c3b36a49d4d41b2; //keccak256("stakeAmount")
/*Functions*/
/**
* @dev Allows for a transfer of tokens to _to
* @param _to The address to send tokens to
* @param _amount The amount of tokens to send
* @return true if transfer is successful
*/
function transfer(TellorStorage.TellorStorageStruct storage self, address _to, uint256 _amount) public returns (bool success) {
doTransfer(self, msg.sender, _to, _amount);
return true;
}
/**
* @notice Send _amount tokens to _to from _from on the condition it
* is approved by _from
* @param _from The address holding the tokens being transferred
* @param _to The address of the recipient
* @param _amount The amount of tokens to be transferred
* @return True if the transfer was successful
*/
function transferFrom(TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint256 _amount)
public
returns (bool success)
{
require(self.allowed[_from][msg.sender] >= _amount, "Allowance is wrong");
self.allowed[_from][msg.sender] -= _amount;
doTransfer(self, _from, _to, _amount);
return true;
}
/**
* @dev This function approves a _spender an _amount of tokens to use
* @param _spender address
* @param _amount amount the spender is being approved for
* @return true if spender appproved successfully
*/
function approve(TellorStorage.TellorStorageStruct storage self, address _spender, uint256 _amount) public returns (bool) {
require(_spender != address(0), "Spender is 0-address");
require(self.allowed[msg.sender][_spender] == 0 || _amount == 0, "Spender is already approved");
self.allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
/**
* @param _user address of party with the balance
* @param _spender address of spender of parties said balance
* @return Returns the remaining allowance of tokens granted to the _spender from the _user
*/
function allowance(TellorStorage.TellorStorageStruct storage self, address _user, address _spender) public view returns (uint256) {
return self.allowed[_user][_spender];
}
/**
* @dev Completes POWO transfers by updating the balances on the current block number
* @param _from address to transfer from
* @param _to addres to transfer to
* @param _amount to transfer
*/
function doTransfer(TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint256 _amount) public {
require(_amount != 0, "Tried to send non-positive amount");
require(_to != address(0), "Receiver is 0 address");
require(allowedToTrade(self, _from, _amount), "Should have sufficient balance to trade");
uint256 previousBalance = balanceOf(self, _from);
updateBalanceAtNow(self.balances[_from], previousBalance - _amount);
previousBalance = balanceOf(self,_to);
require(previousBalance + _amount >= previousBalance, "Overflow happened"); // Check for overflow
updateBalanceAtNow(self.balances[_to], previousBalance + _amount);
emit Transfer(_from, _to, _amount);
}
/**
* @dev Gets balance of owner specified
* @param _user is the owner address used to look up the balance
* @return Returns the balance associated with the passed in _user
*/
function balanceOf(TellorStorage.TellorStorageStruct storage self, address _user) public view returns (uint256) {
return balanceOfAt(self, _user, block.number);
}
/**
* @dev Queries the balance of _user at a specific _blockNumber
* @param _user The address from which the balance will be retrieved
* @param _blockNumber The block number when the balance is queried
* @return The balance at _blockNumber specified
*/
function balanceOfAt(TellorStorage.TellorStorageStruct storage self, address _user, uint256 _blockNumber) public view returns (uint256) {
TellorStorage.Checkpoint[] storage checkpoints = self.balances[_user];
if (checkpoints.length == 0|| checkpoints[0].fromBlock > _blockNumber) {
return 0;
} else {
if (_blockNumber >= checkpoints[checkpoints.length - 1].fromBlock) return checkpoints[checkpoints.length - 1].value;
// Binary search of the value in the array
uint256 min = 0;
uint256 max = checkpoints.length - 2;
while (max > min) {
uint256 mid = (max + min + 1) / 2;
if (checkpoints[mid].fromBlock ==_blockNumber){
return checkpoints[mid].value;
}else if(checkpoints[mid].fromBlock < _blockNumber) {
min = mid;
} else {
max = mid - 1;
}
}
return checkpoints[min].value;
}
}
/**
* @dev This function returns whether or not a given user is allowed to trade a given amount
* and removing the staked amount from their balance if they are staked
* @param _user address of user
* @param _amount to check if the user can spend
* @return true if they are allowed to spend the amount being checked
*/
function allowedToTrade(TellorStorage.TellorStorageStruct storage self, address _user, uint256 _amount) public view returns (bool) {
if (self.stakerDetails[_user].currentStatus != 0 && self.stakerDetails[_user].currentStatus < 5) {
//Subtracts the stakeAmount from balance if the _user is staked
if (balanceOf(self, _user)- self.uintVars[stakeAmount] >= _amount) {
return true;
}
return false;
}
return (balanceOf(self, _user) >= _amount);
}
/**
* @dev Updates balance for from and to on the current block number via doTransfer
* @param checkpoints gets the mapping for the balances[owner]
* @param _value is the new balance
*/
function updateBalanceAtNow(TellorStorage.Checkpoint[] storage checkpoints, uint256 _value) public {
if (checkpoints.length == 0 || checkpoints[checkpoints.length - 1].fromBlock != block.number) {
checkpoints.push(TellorStorage.Checkpoint({
fromBlock : uint128(block.number),
value : uint128(_value)
}));
} else {
TellorStorage.Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1];
oldCheckPoint.value = uint128(_value);
}
}
}
pragma solidity ^0.5.16;
/**
* @title Tellor Dispute
* @dev Contains the methods related to disputes. Tellor.sol references this library for function's logic.
*/
library TellorDispute {
using SafeMath for uint256;
using SafeMath for int256;
//emitted when a new dispute is initialized
event NewDispute(uint256 indexed _disputeId, uint256 indexed _requestId, uint256 _timestamp, address _miner);
//emitted when a new vote happens
event Voted(uint256 indexed _disputeID, bool _position, address indexed _voter, uint256 indexed _voteWeight);
//emitted upon dispute tally
event DisputeVoteTallied(uint256 indexed _disputeID, int256 _result, address indexed _reportedMiner, address _reportingParty, bool _active);
event NewTellorAddress(address _newTellor); //emmited when a proposed fork is voted true
/*Functions*/
/**
* @dev Helps initialize a dispute by assigning it a disputeId
* when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the
* invalidated value information to POS voting
* @param _requestId being disputed
* @param _timestamp being disputed
* @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value
* requires 5 miners to submit a value.
*/
function beginDispute(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp, uint256 _minerIndex) public {
TellorStorage.Request storage _request = self.requestDetails[_requestId];
require(_request.minedBlockNum[_timestamp] != 0, "Mined block is 0");
require(_minerIndex < 5, "Miner index is wrong");
//_miner is the miner being disputed. For every mined value 5 miners are saved in an array and the _minerIndex
//provided by the party initiating the dispute
address _miner = _request.minersByValue[_timestamp][_minerIndex];
bytes32 _hash = keccak256(abi.encodePacked(_miner, _requestId, _timestamp));
//Increase the dispute count by 1
uint256 disputeId = self.uintVars[keccak256("disputeCount")] + 1;
self.uintVars[keccak256("disputeCount")] = disputeId;
//Sets the new disputeCount as the disputeId
//Ensures that a dispute is not already open for the that miner, requestId and timestamp
uint256 hashId = self.disputeIdByDisputeHash[_hash];
if(hashId != 0){
self.disputesById[disputeId].disputeUintVars[keccak256("origID")] = hashId;
}
else{
self.disputeIdByDisputeHash[_hash] = disputeId;
hashId = disputeId;
}
uint256 origID = hashId;
uint256 dispRounds = self.disputesById[origID].disputeUintVars[keccak256("disputeRounds")] + 1;
self.disputesById[origID].disputeUintVars[keccak256("disputeRounds")] = dispRounds;
self.disputesById[origID].disputeUintVars[keccak256(abi.encode(dispRounds))] = disputeId;
if(disputeId != origID){
uint256 lastID = self.disputesById[origID].disputeUintVars[keccak256(abi.encode(dispRounds-1))];
require(self.disputesById[lastID].disputeUintVars[keccak256("minExecutionDate")] <= now, "Dispute is already open");
if(self.disputesById[lastID].executed){
require(now - self.disputesById[lastID].disputeUintVars[keccak256("tallyDate")] <= 1 days, "Time for voting haven't elapsed");
}
}
uint256 _fee;
if (_minerIndex == 2) {
self.requestDetails[_requestId].apiUintVars[keccak256("disputeCount")] = self.requestDetails[_requestId].apiUintVars[keccak256("disputeCount")] +1;
//update dispute fee for this case
_fee = self.uintVars[keccak256("stakeAmount")]*self.requestDetails[_requestId].apiUintVars[keccak256("disputeCount")];
} else {
_fee = self.uintVars[keccak256("disputeFee")] * dispRounds;
}
//maps the dispute to the Dispute struct
self.disputesById[disputeId] = TellorStorage.Dispute({
hash: _hash,
isPropFork: false,
reportedMiner: _miner,
reportingParty: msg.sender,
proposedForkAddress: address(0),
executed: false,
disputeVotePassed: false,
tally: 0
});
//Saves all the dispute variables for the disputeId
self.disputesById[disputeId].disputeUintVars[keccak256("requestId")] = _requestId;
self.disputesById[disputeId].disputeUintVars[keccak256("timestamp")] = _timestamp;
self.disputesById[disputeId].disputeUintVars[keccak256("value")] = _request.valuesByTimestamp[_timestamp][_minerIndex];
self.disputesById[disputeId].disputeUintVars[keccak256("minExecutionDate")] = now + 2 days * dispRounds;
self.disputesById[disputeId].disputeUintVars[keccak256("blockNumber")] = block.number;
self.disputesById[disputeId].disputeUintVars[keccak256("minerSlot")] = _minerIndex;
self.disputesById[disputeId].disputeUintVars[keccak256("fee")] = _fee;
TellorTransfer.doTransfer(self, msg.sender, address(this),_fee);
//Values are sorted as they come in and the official value is the median of the first five
//So the "official value" miner is always minerIndex==2. If the official value is being
//disputed, it sets its status to inDispute(currentStatus = 3) so that users are made aware it is under dispute
if (_minerIndex == 2) {
_request.inDispute[_timestamp] = true;
_request.finalValues[_timestamp] = 0;
}
self.stakerDetails[_miner].currentStatus = 3;
emit NewDispute(disputeId, _requestId, _timestamp, _miner);
}
/**
* @dev Allows token holders to vote
* @param _disputeId is the dispute id
* @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute)
*/
function vote(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId, bool _supportsDispute) public {
TellorStorage.Dispute storage disp = self.disputesById[_disputeId];
//Get the voteWeight or the balance of the user at the time/blockNumber the disupte began
uint256 voteWeight = TellorTransfer.balanceOfAt(self, msg.sender, disp.disputeUintVars[keccak256("blockNumber")]);
//Require that the msg.sender has not voted
require(disp.voted[msg.sender] != true, "Sender has already voted");
//Requre that the user had a balance >0 at time/blockNumber the disupte began
require(voteWeight != 0, "User balance is 0");
//ensures miners that are under dispute cannot vote
require(self.stakerDetails[msg.sender].currentStatus != 3, "Miner is under dispute");
//Update user voting status to true
disp.voted[msg.sender] = true;
//Update the number of votes for the dispute
disp.disputeUintVars[keccak256("numberOfVotes")] += 1;
//If the user supports the dispute increase the tally for the dispute by the voteWeight
//otherwise decrease it
if (_supportsDispute) {
disp.tally = disp.tally.add(int256(voteWeight));
} else {
disp.tally = disp.tally.sub(int256(voteWeight));
}
//Let the network know the user has voted on the dispute and their casted vote
emit Voted(_disputeId, _supportsDispute, msg.sender, voteWeight);
}
/**
* @dev tallies the votes and locks the stake disbursement(currentStatus = 4) if the vote passes
* @param _disputeId is the dispute id
*/
function tallyVotes(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId) public {
TellorStorage.Dispute storage disp = self.disputesById[_disputeId];
//Ensure this has not already been executed/tallied
require(disp.executed == false, "Dispute has been already executed");
require(now >= disp.disputeUintVars[keccak256("minExecutionDate")], "Time for voting haven't elapsed");
require(disp.reportingParty != address(0), "reporting Party is address 0");
int256 _tally = disp.tally;
if (_tally > 0) {
//Set the dispute state to passed/true
disp.disputeVotePassed = true;
}
//If the vote is not a proposed fork
if (disp.isPropFork == false) {
//Ensure the time for voting has elapsed
TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner];
//If the vote for disputing a value is succesful(disp.tally >0) then unstake the reported
// miner and transfer the stakeAmount and dispute fee to the reporting party
if(stakes.currentStatus == 3){
stakes.currentStatus = 4;
}
} else if (uint(_tally) >= ((self.uintVars[keccak256("total_supply")] * 10) / 100)) {
emit NewTellorAddress(disp.proposedForkAddress);
}
disp.disputeUintVars[keccak256("tallyDate")] = now;
disp.executed = true;
emit DisputeVoteTallied(_disputeId, _tally, disp.reportedMiner, disp.reportingParty, disp.disputeVotePassed);
}
/**
* @dev Allows for a fork to be proposed
* @param _propNewTellorAddress address for new proposed Tellor
*/
function proposeFork(TellorStorage.TellorStorageStruct storage self, address _propNewTellorAddress) public {
bytes32 _hash = keccak256(abi.encode(_propNewTellorAddress));
TellorTransfer.doTransfer(self, msg.sender, address(this), 100e18); //This is the fork fee (just 100 tokens flat, no refunds)
self.uintVars[keccak256("disputeCount")]++;
uint256 disputeId = self.uintVars[keccak256("disputeCount")];
if(self.disputeIdByDisputeHash[_hash] != 0){
self.disputesById[disputeId].disputeUintVars[keccak256("origID")] = self.disputeIdByDisputeHash[_hash];
}
else{
self.disputeIdByDisputeHash[_hash] = disputeId;
}
uint256 origID = self.disputeIdByDisputeHash[_hash];
self.disputesById[origID].disputeUintVars[keccak256("disputeRounds")]++;
uint256 dispRounds = self.disputesById[origID].disputeUintVars[keccak256("disputeRounds")];
self.disputesById[origID].disputeUintVars[keccak256(abi.encode(dispRounds))] = disputeId;
if(disputeId != origID){
uint256 lastID = self.disputesById[origID].disputeUintVars[keccak256(abi.encode(dispRounds-1))];
require(self.disputesById[lastID].disputeUintVars[keccak256("minExecutionDate")] <= now, "Dispute is already open");
if(self.disputesById[lastID].executed){
require(now - self.disputesById[lastID].disputeUintVars[keccak256("tallyDate")] <= 1 days, "Time for voting haven't elapsed");
}
}
self.disputesById[disputeId] = TellorStorage.Dispute({
hash: _hash,
isPropFork: true,
reportedMiner: msg.sender,
reportingParty: msg.sender,
proposedForkAddress: _propNewTellorAddress,
executed: false,
disputeVotePassed: false,
tally: 0
});
self.disputesById[disputeId].disputeUintVars[keccak256("blockNumber")] = block.number;
self.disputesById[disputeId].disputeUintVars[keccak256("minExecutionDate")] = now + 7 days;
}
/**
* @dev Updates the Tellor address after a proposed fork has
* passed the vote and day has gone by without a dispute
* @param _disputeId the disputeId for the proposed fork
*/
function updateTellor(TellorStorage.TellorStorageStruct storage self, uint _disputeId) public {
bytes32 _hash = self.disputesById[_disputeId].hash;
uint256 origID = self.disputeIdByDisputeHash[_hash];
uint256 lastID = self.disputesById[origID].disputeUintVars[keccak256(abi.encode(self.disputesById[origID].disputeUintVars[keccak256("disputeRounds")]))];
TellorStorage.Dispute storage disp = self.disputesById[lastID];
require(disp.disputeVotePassed == true, "vote needs to pass");
require(now - disp.disputeUintVars[keccak256("tallyDate")] > 1 days, "Time for voting for further disputes has not passed");
self.addressVars[keccak256("tellorContract")] = disp.proposedForkAddress;
}
/**
* @dev Allows disputer to unlock the dispute fee
* @param _disputeId to unlock fee from
*/
function unlockDisputeFee (TellorStorage.TellorStorageStruct storage self, uint _disputeId) public {
uint256 origID = self.disputeIdByDisputeHash[self.disputesById[_disputeId].hash];
uint256 lastID = self.disputesById[origID].disputeUintVars[keccak256(abi.encode(self.disputesById[origID].disputeUintVars[keccak256("disputeRounds")]))];
if(lastID == 0){
lastID = origID;
}
TellorStorage.Dispute storage disp = self.disputesById[origID];
TellorStorage.Dispute storage last = self.disputesById[lastID];
//disputeRounds is increased by 1 so that the _id is not a negative number when it is the first time a dispute is initiated
uint256 dispRounds = disp.disputeUintVars[keccak256("disputeRounds")];
if(dispRounds == 0){
dispRounds = 1;
}
uint256 _id;
require(disp.disputeUintVars[keccak256("paid")] == 0,"already paid out");
require(now - last.disputeUintVars[keccak256("tallyDate")] > 1 days, "Time for voting haven't elapsed");
TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner];
disp.disputeUintVars[keccak256("paid")] = 1;
if (last.disputeVotePassed == true){
//Changing the currentStatus and startDate unstakes the reported miner and transfers the stakeAmount
stakes.startDate = now - (now % 86400);
//Reduce the staker count
self.uintVars[keccak256("stakerCount")] -= 1;
//Update the minimum dispute fee that is based on the number of stakers
updateMinDisputeFee(self);
//Decreases the stakerCount since the miner's stake is being slashed
if(stakes.currentStatus == 4){
stakes.currentStatus = 5;
TellorTransfer.doTransfer(self,disp.reportedMiner,disp.reportingParty,self.uintVars[keccak256("stakeAmount")]);
stakes.currentStatus =0 ;
}
for(uint i = 0; i < dispRounds;i++){
_id = disp.disputeUintVars[keccak256(abi.encode(dispRounds-i))];
if(_id == 0){
_id = origID;
}
TellorStorage.Dispute storage disp2 = self.disputesById[_id];
//transfer fee adjusted based on number of miners if the minerIndex is not 2(official value)
TellorTransfer.doTransfer(self,address(this), disp2.reportingParty, disp2.disputeUintVars[keccak256("fee")]);
}
}
else {
stakes.currentStatus = 1;
TellorStorage.Request storage _request = self.requestDetails[disp.disputeUintVars[keccak256("requestId")]];
if(disp.disputeUintVars[keccak256("minerSlot")] == 2) {
//note we still don't put timestamp back into array (is this an issue? (shouldn't be))
_request.finalValues[disp.disputeUintVars[keccak256("timestamp")]] = disp.disputeUintVars[keccak256("value")];
}
if (_request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] == true) {
_request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] = false;
}
for(uint i = 0; i < dispRounds;i++){
_id = disp.disputeUintVars[keccak256(abi.encode(dispRounds-i))];
if(_id != 0){
last = self.disputesById[_id];//handling if happens during an upgrade
}
TellorTransfer.doTransfer(self,address(this),last.reportedMiner,self.disputesById[_id].disputeUintVars[keccak256("fee")]);
}
}
if (disp.disputeUintVars[keccak256("minerSlot")] == 2) {
self.requestDetails[disp.disputeUintVars[keccak256("requestId")]].apiUintVars[keccak256("disputeCount")]--;
}
}
/**
* @dev This function upates the minimun dispute fee as a function of the amount
* of staked miners
*/
function updateMinDisputeFee(TellorStorage.TellorStorageStruct storage self) public {
uint256 stakeAmount = self.uintVars[keccak256("stakeAmount")];
uint256 targetMiners = self.uintVars[keccak256("targetMiners")];
self.uintVars[keccak256("disputeFee")] = SafeMath.max(15e18,
(stakeAmount-(stakeAmount*(SafeMath.min(targetMiners,self.uintVars[keccak256("stakerCount")])*1000)/
targetMiners)/1000));
}
}
pragma solidity ^0.5.16;
//Functions for retrieving min and Max in 51 length array (requestQ)
//Taken partly from: https://github.com/modular-network/ethereum-libraries-array-utils/blob/master/contracts/Array256Lib.sol
library Utilities {
/**
* @dev Returns the max value in an array.
* The zero position here is ignored. It's because
* there's no null in solidity and we map each address
* to an index in this array. So when we get 51 parties,
* and one person is kicked out of the top 50, we
* assign them a 0, and when you get mined and pulled
* out of the top 50, also a 0. So then lot's of parties
* will have zero as the index so we made the array run
* from 1-51 with zero as nothing.
* @param data is the array to calculate max from
* @return max amount and its index within the array
*/
function getMax(uint256[51] memory data) internal pure returns (uint256 max, uint256 maxIndex) {
maxIndex = 1;
max = data[maxIndex];
for (uint256 i = 2; i < data.length; i++) {
if (data[i] > max) {
max = data[i];
maxIndex = i;
}
}
}
/**
* @dev Returns the minimum value in an array.
* @param data is the array to calculate min from
* @return min amount and its index within the array
*/
function getMin(uint256[51] memory data) internal pure returns (uint256 min, uint256 minIndex) {
minIndex = data.length - 1;
min = data[minIndex];
for (uint256 i = data.length - 2; i > 0; i--) {
if (data[i] < min) {
min = data[i];
minIndex = i;
}
}
}
/**
* @dev Returns the 5 requestsId's with the top payouts in an array.
* @param data is the array to get the top 5 from
* @return to 5 max amounts and their respective index within the array
*/
function getMax5(uint256[51] memory data) internal pure returns (uint256[5] memory max, uint256[5] memory maxIndex) {
uint256 min5 = data[1];
uint256 minI = 0;
for(uint256 j=0;j<5;j++){
max[j]= data[j+1];//max[0]=data[1]
maxIndex[j] = j+1;//maxIndex[0]= 1
if(max[j] < min5){
min5 = max[j];
minI = j;
}
}
for(uint256 i = 6; i < data.length; i++) {
if (data[i] > min5) {
max[minI] = data[i];
maxIndex[minI] = i;
min5 = data[i];
for(uint256 j=0;j<5;j++){
if(max[j] < min5){
min5 = max[j];
minI = j;
}
}
}
}
}
}
pragma solidity ^0.5.16;
/**
* itle Tellor Stake
* @dev Contains the methods related to miners staking and unstaking. Tellor.sol
* references this library for function's logic.
*/
library TellorStake {
event NewStake(address indexed _sender); //Emits upon new staker
event StakeWithdrawn(address indexed _sender); //Emits when a staker is now no longer staked
event StakeWithdrawRequested(address indexed _sender); //Emits when a staker begins the 7 day withdraw period
/*Functions*/
/**
* @dev This function allows stakers to request to withdraw their stake (no longer stake)
* once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they
* can withdraw the deposit
*/
function requestStakingWithdraw(TellorStorage.TellorStorageStruct storage self) public {
TellorStorage.StakeInfo storage stakes = self.stakerDetails[msg.sender];
//Require that the miner is staked
require(stakes.currentStatus == 1, "Miner is not staked");
//Change the miner staked to locked to be withdrawStake
stakes.currentStatus = 2;
//Change the startDate to now since the lock up period begins now
//and the miner can only withdraw 7 days later from now(check the withdraw function)
stakes.startDate = now - (now % 86400);
//Reduce the staker count
self.uintVars[keccak256("stakerCount")] -= 1;
//Update the minimum dispute fee that is based on the number of stakers
TellorDispute.updateMinDisputeFee(self);
emit StakeWithdrawRequested(msg.sender);
}
/**
* @dev This function allows users to withdraw their stake after a 7 day waiting period from request
*/
function withdrawStake(TellorStorage.TellorStorageStruct storage self) public {
TellorStorage.StakeInfo storage stakes = self.stakerDetails[msg.sender];
//Require the staker has locked for withdraw(currentStatus ==2) and that 7 days have
//passed by since they locked for withdraw
require(now - (now % 86400) - stakes.startDate >= 7 days, "7 days didn't pass");
require(stakes.currentStatus == 2, "Miner was not locked for withdrawal");
stakes.currentStatus = 0;
emit StakeWithdrawn(msg.sender);
}
/**
* @dev This function allows miners to deposit their stake.
*/
function depositStake(TellorStorage.TellorStorageStruct storage self) public {
newStake(self, msg.sender);
//self adjusting disputeFee
TellorDispute.updateMinDisputeFee(self);
}
/**
* @dev This function is used by the init function to succesfully stake the initial 5 miners.
* The function updates their status/state and status start date so they are locked it so they can't withdraw
* and updates the number of stakers in the system.
*/
function newStake(TellorStorage.TellorStorageStruct storage self, address staker) internal {
require(TellorTransfer.balanceOf(self, staker) >= self.uintVars[keccak256("stakeAmount")], "Balance is lower than stake amount");
//Ensure they can only stake if they are not currrently staked or if their stake time frame has ended
//and they are currently locked for witdhraw
require(self.stakerDetails[staker].currentStatus == 0 || self.stakerDetails[staker].currentStatus == 2, "Miner is in the wrong state");
self.uintVars[keccak256("stakerCount")] += 1;
self.stakerDetails[staker] = TellorStorage.StakeInfo({
currentStatus: 1, //this resets their stake start date to today
startDate: now - (now % 86400)
});
emit NewStake(staker);
}
/**
* @dev Getter function for the requestId being mined
* @return variables for the current minin event: Challenge, 5 RequestId, difficulty and Totaltips
*/
function getNewCurrentVariables(TellorStorage.TellorStorageStruct storage self) internal view returns(bytes32 _challenge,uint[5] memory _requestIds,uint256 _difficulty, uint256 _tip){
for(uint i=0;i<5;i++){
_requestIds[i] = self.currentMiners[i].value;
}
return (self.currentChallenge,_requestIds,self.uintVars[keccak256("difficulty")],self.uintVars[keccak256("currentTotalTips")]);
}
/**
* @dev Getter function for next requestId on queue/request with highest payout at time the function is called
* @return onDeck/info on top 5 requests(highest payout)-- RequestId, Totaltips
*/
function getNewVariablesOnDeck(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck) {
idsOnDeck = getTopRequestIDs(self);
for(uint i = 0;i<5;i++){
tipsOnDeck[i] = self.requestDetails[idsOnDeck[i]].apiUintVars[keccak256("totalTip")];
}
}
/**
* @dev Getter function for the top 5 requests with highest payouts. This function is used within the getNewVariablesOnDeck function
* @return uint256[5] is an array with the top 5(highest payout) _requestIds at the time the function is called
*/
function getTopRequestIDs(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256[5] memory _requestIds) {
uint256[5] memory _max;
uint256[5] memory _index;
(_max, _index) = Utilities.getMax5(self.requestQ);
for(uint i=0;i<5;i++){
if(_max[i] != 0){
_requestIds[i] = self.requestIdByRequestQIndex[_index[i]];
}
else{
_requestIds[i] = self.currentMiners[4-i].value;
}
}
}
}
pragma solidity ^0.5.0;
/**
* @title Tellor Getters Library
* @dev This is the getter library for all variables in the Tellor Tributes system. TellorGetters references this
* libary for the getters logic
*/
library TellorGettersLibrary {
using SafeMath for uint256;
event NewTellorAddress(address _newTellor); //emmited when a proposed fork is voted true
/*Functions*/
//The next two functions are onlyOwner functions. For Tellor to be truly decentralized, we will need to transfer the Deity to the 0 address.
//Only needs to be in library
/**
* @dev This function allows us to set a new Deity (or remove it)
* @param _newDeity address of the new Deity of the tellor system
*/
function changeDeity(TellorStorage.TellorStorageStruct storage self, address _newDeity) internal {
require(self.addressVars[keccak256("_deity")] == msg.sender, "Sender is not deity");
self.addressVars[keccak256("_deity")] = _newDeity;
}
//Only needs to be in library
/**
* @dev This function allows the deity to upgrade the Tellor System
* @param _tellorContract address of new updated TellorCore contract
*/
function changeTellorContract(TellorStorage.TellorStorageStruct storage self, address _tellorContract) internal {
require(self.addressVars[keccak256("_deity")] == msg.sender, "Sender is not deity");
self.addressVars[keccak256("tellorContract")] = _tellorContract;
emit NewTellorAddress(_tellorContract);
}
/*Tellor Getters*/
/**
* @dev This function tells you if a given challenge has been completed by a given miner
* @param _challenge the challenge to search for
* @param _miner address that you want to know if they solved the challenge
* @return true if the _miner address provided solved the
*/
function didMine(TellorStorage.TellorStorageStruct storage self, bytes32 _challenge, address _miner) public view returns (bool) {
return self.minersByChallenge[_challenge][_miner];
}
/**
* @dev Checks if an address voted in a dispute
* @param _disputeId to look up
* @param _address of voting party to look up
* @return bool of whether or not party voted
*/
function didVote(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId, address _address) internal view returns (bool) {
return self.disputesById[_disputeId].voted[_address];
}
/**
* @dev allows Tellor to read data from the addressVars mapping
* @param _data is the keccak256("variable_name") of the variable that is being accessed.
* These are examples of how the variables are saved within other functions:
* addressVars[keccak256("_owner")]
* addressVars[keccak256("tellorContract")]
* @return address requested
*/
function getAddressVars(TellorStorage.TellorStorageStruct storage self, bytes32 _data) internal view returns (address) {
return self.addressVars[_data];
}
/**
* @dev Gets all dispute variables
* @param _disputeId to look up
* @return bytes32 hash of dispute
* @return bool executed where true if it has been voted on
* @return bool disputeVotePassed
* @return bool isPropFork true if the dispute is a proposed fork
* @return address of reportedMiner
* @return address of reportingParty
* @return address of proposedForkAddress
* @return uint of requestId
* @return uint of timestamp
* @return uint of value
* @return uint of minExecutionDate
* @return uint of numberOfVotes
* @return uint of blocknumber
* @return uint of minerSlot
* @return uint of quorum
* @return uint of fee
* @return int count of the current tally
*/
function getAllDisputeVars(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId)
internal
view
returns (bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256)
{
TellorStorage.Dispute storage disp = self.disputesById[_disputeId];
return (
disp.hash,
disp.executed,
disp.disputeVotePassed,
disp.isPropFork,
disp.reportedMiner,
disp.reportingParty,
disp.proposedForkAddress,
[
disp.disputeUintVars[keccak256("requestId")],
disp.disputeUintVars[keccak256("timestamp")],
disp.disputeUintVars[keccak256("value")],
disp.disputeUintVars[keccak256("minExecutionDate")],
disp.disputeUintVars[keccak256("numberOfVotes")],
disp.disputeUintVars[keccak256("blockNumber")],
disp.disputeUintVars[keccak256("minerSlot")],
disp.disputeUintVars[keccak256("quorum")],
disp.disputeUintVars[keccak256("fee")]
],
disp.tally
);
}
/**
* @dev Getter function for variables for the requestId being currently mined(currentRequestId)
* @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request
*/
function getCurrentVariables(TellorStorage.TellorStorageStruct storage self)
internal
view
returns (bytes32, uint256, uint256, string memory, uint256, uint256)
{
return (
self.currentChallenge,
self.uintVars[keccak256("currentRequestId")],
self.uintVars[keccak256("difficulty")],
self.requestDetails[self.uintVars[keccak256("currentRequestId")]].queryString,
self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("granularity")],
self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("totalTip")]
);
}
/**
* @dev Checks if a given hash of miner,requestId has been disputed
* @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId));
* @return uint disputeId
*/
function getDisputeIdByDisputeHash(TellorStorage.TellorStorageStruct storage self, bytes32 _hash) internal view returns (uint256) {
return self.disputeIdByDisputeHash[_hash];
}
/**
* @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId
* @param _disputeId is the dispute id;
* @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
* the variables/strings used to save the data in the mapping. The variables names are
* commented out under the disputeUintVars under the Dispute struct
* @return uint value for the bytes32 data submitted
*/
function getDisputeUintVars(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId, bytes32 _data)
internal
view
returns (uint256)
{
return self.disputesById[_disputeId].disputeUintVars[_data];
}
/**
* @dev Gets the a value for the latest timestamp available
* @return value for timestamp of last proof of work submited
* @return true if the is a timestamp for the lastNewValue
*/
function getLastNewValue(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256, bool) {
return (
retrieveData(
self,
self.requestIdByTimestamp[self.uintVars[keccak256("timeOfLastNewValue")]],
self.uintVars[keccak256("timeOfLastNewValue")]
),
true
);
}
/**
* @dev Gets the a value for the latest timestamp available
* @param _requestId being requested
* @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't
*/
function getLastNewValueById(TellorStorage.TellorStorageStruct storage self, uint256 _requestId) internal view returns (uint256, bool) {
TellorStorage.Request storage _request = self.requestDetails[_requestId];
if (_request.requestTimestamps.length != 0) {
return (retrieveData(self, _requestId, _request.requestTimestamps[_request.requestTimestamps.length - 1]), true);
} else {
return (0, false);
}
}
/**
* @dev Gets blocknumber for mined timestamp
* @param _requestId to look up
* @param _timestamp is the timestamp to look up blocknumber
* @return uint of the blocknumber which the dispute was mined
*/
function getMinedBlockNum(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp)
internal
view
returns (uint256)
{
return self.requestDetails[_requestId].minedBlockNum[_timestamp];
}
/**
* @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
* @param _requestId to look up
* @param _timestamp is the timestamp to look up miners for
* @return the 5 miners' addresses
*/
function getMinersByRequestIdAndTimestamp(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp)
internal
view
returns (address[5] memory)
{
return self.requestDetails[_requestId].minersByValue[_timestamp];
}
/**
* @dev Counts the number of values that have been submited for the request
* if called for the currentRequest being mined it can tell you how many miners have submitted a value for that
* request so far
* @param _requestId the requestId to look up
* @return uint count of the number of values received for the requestId
*/
function getNewValueCountbyRequestId(TellorStorage.TellorStorageStruct storage self, uint256 _requestId) internal view returns (uint256) {
return self.requestDetails[_requestId].requestTimestamps.length;
}
/**
* @dev Getter function for the specified requestQ index
* @param _index to look up in the requestQ array
* @return uint of reqeuestId
*/
function getRequestIdByRequestQIndex(TellorStorage.TellorStorageStruct storage self, uint256 _index) internal view returns (uint256) {
require(_index <= 50, "RequestQ index is above 50");
return self.requestIdByRequestQIndex[_index];
}
/**
* @dev Getter function for requestId based on timestamp
* @param _timestamp to check requestId
* @return uint of reqeuestId
*/
function getRequestIdByTimestamp(TellorStorage.TellorStorageStruct storage self, uint256 _timestamp) internal view returns (uint256) {
return self.requestIdByTimestamp[_timestamp];
}
/**
* @dev Getter function for requestId based on the qeuaryHash
* @param _queryHash hash(of string api and granularity) to check if a request already exists
* @return uint requestId
*/
function getRequestIdByQueryHash(TellorStorage.TellorStorageStruct storage self, bytes32 _queryHash) internal view returns (uint256) {
return self.requestIdByQueryHash[_queryHash];
}
/**
* @dev Getter function for the requestQ array
* @return the requestQ arrray
*/
function getRequestQ(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256[51] memory) {
return self.requestQ;
}
/**
* @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct
* for the requestId specified
* @param _requestId to look up
* @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
* the variables/strings used to save the data in the mapping. The variables names are
* commented out under the apiUintVars under the requestDetails struct
* @return uint value of the apiUintVars specified in _data for the requestId specified
*/
function getRequestUintVars(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, bytes32 _data)
internal
view
returns (uint256)
{
return self.requestDetails[_requestId].apiUintVars[_data];
}
/**
* @dev Gets the API struct variables that are not mappings
* @param _requestId to look up
* @return string of api to query
* @return string of symbol of api to query
* @return bytes32 hash of string
* @return bytes32 of the granularity(decimal places) requested
* @return uint of index in requestQ array
* @return uint of current payout/tip for this requestId
*/
function getRequestVars(TellorStorage.TellorStorageStruct storage self, uint256 _requestId)
internal
view
returns (string memory, string memory, bytes32, uint256, uint256, uint256)
{
TellorStorage.Request storage _request = self.requestDetails[_requestId];
return (
_request.queryString,
_request.dataSymbol,
_request.queryHash,
_request.apiUintVars[keccak256("granularity")],
_request.apiUintVars[keccak256("requestQPosition")],
_request.apiUintVars[keccak256("totalTip")]
);
}
/**
* @dev This function allows users to retireve all information about a staker
* @param _staker address of staker inquiring about
* @return uint current state of staker
* @return uint startDate of staking
*/
function getStakerInfo(TellorStorage.TellorStorageStruct storage self, address _staker) internal view returns (uint256, uint256) {
return (self.stakerDetails[_staker].currentStatus, self.stakerDetails[_staker].startDate);
}
/**
* @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
* @param _requestId to look up
* @param _timestamp is the timestampt to look up miners for
* @return address[5] array of 5 addresses ofminers that mined the requestId
*/
function getSubmissionsByTimestamp(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp)
internal
view
returns (uint256[5] memory)
{
return self.requestDetails[_requestId].valuesByTimestamp[_timestamp];
}
/**
* @dev Gets the timestamp for the value based on their index
* @param _requestID is the requestId to look up
* @param _index is the value index to look up
* @return uint timestamp
*/
function getTimestampbyRequestIDandIndex(TellorStorage.TellorStorageStruct storage self, uint256 _requestID, uint256 _index)
internal
view
returns (uint256)
{
return self.requestDetails[_requestID].requestTimestamps[_index];
}
/**
* @dev Getter for the variables saved under the TellorStorageStruct uintVars variable
* @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
* the variables/strings used to save the data in the mapping. The variables names are
* commented out under the uintVars under the TellorStorageStruct struct
* This is an example of how data is saved into the mapping within other functions:
* self.uintVars[keccak256("stakerCount")]
* @return uint of specified variable
*/
function getUintVar(TellorStorage.TellorStorageStruct storage self, bytes32 _data) internal view returns (uint256) {
return self.uintVars[_data];
}
/**
* @dev Getter function for next requestId on queue/request with highest payout at time the function is called
* @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string
*/
function getVariablesOnDeck(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256, uint256, string memory) {
uint256 newRequestId = getTopRequestID(self);
return (
newRequestId,
self.requestDetails[newRequestId].apiUintVars[keccak256("totalTip")],
self.requestDetails[newRequestId].queryString
);
}
/**
* @dev Getter function for the request with highest payout. This function is used within the getVariablesOnDeck function
* @return uint _requestId of request with highest payout at the time the function is called
*/
function getTopRequestID(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256 _requestId) {
uint256 _max;
uint256 _index;
(_max, _index) = Utilities.getMax(self.requestQ);
_requestId = self.requestIdByRequestQIndex[_index];
}
/**
* @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
* @param _requestId to looku p
* @param _timestamp is the timestamp to look up miners for
* @return bool true if requestId/timestamp is under dispute
*/
function isInDispute(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp) internal view returns (bool) {
return self.requestDetails[_requestId].inDispute[_timestamp];
}
/**
* @dev Retreive value from oracle based on requestId/timestamp
* @param _requestId being requested
* @param _timestamp to retreive data/value from
* @return uint value for requestId/timestamp submitted
*/
function retrieveData(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp)
internal
view
returns (uint256)
{
return self.requestDetails[_requestId].finalValues[_timestamp];
}
/**
* @dev Getter for the total_supply of oracle tokens
* @return uint total supply
*/
function totalSupply(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256) {
return self.uintVars[keccak256("total_supply")];
}
}
pragma solidity ^0.5.16;
/**
* @title Tellor Oracle System Library
* @dev Contains the functions' logic for the Tellor contract where miners can submit the proof of work
* along with the value and smart contracts can requestData and tip miners.
*/
library TellorLibrary {
using SafeMath for uint256;
bytes32 public constant requestCount = 0x05de9147d05477c0a5dc675aeea733157f5092f82add148cf39d579cafe3dc98; //keccak256("requestCount")
bytes32 public constant totalTip = 0x2a9e355a92978430eca9c1aa3a9ba590094bac282594bccf82de16b83046e2c3; //keccak256("totalTip")
bytes32 public constant _tBlock = 0x969ea04b74d02bb4d9e6e8e57236e1b9ca31627139ae9f0e465249932e824502; //keccak256("_tBlock")
bytes32 public constant timeOfLastNewValue = 0x97e6eb29f6a85471f7cc9b57f9e4c3deaf398cfc9798673160d7798baf0b13a4; //keccak256("timeOfLastNewValue")
bytes32 public constant difficulty = 0xb12aff7664b16cb99339be399b863feecd64d14817be7e1f042f97e3f358e64e; //keccak256("difficulty")
bytes32 public constant timeTarget = 0xad16221efc80aaf1b7e69bd3ecb61ba5ffa539adf129c3b4ffff769c9b5bbc33; //keccak256("timeTarget")
bytes32 public constant runningTips = 0xdb21f0c4accc4f2f5f1045353763a9ffe7091ceaf0fcceb5831858d96cf84631; //keccak256("runningTips")
bytes32 public constant currentReward = 0x9b6853911475b07474368644a0d922ee13bc76a15cd3e97d3e334326424a47d4; //keccak256("currentReward")
bytes32 public constant total_supply = 0xb1557182e4359a1f0c6301278e8f5b35a776ab58d39892581e357578fb287836; //keccak256("total_supply")
bytes32 public constant devShare = 0x8fe9ded8d7c08f720cf0340699024f83522ea66b2bbfb8f557851cb9ee63b54c; //keccak256("devShare")
bytes32 public constant _owner = 0x9dbc393ddc18fd27b1d9b1b129059925688d2f2d5818a5ec3ebb750b7c286ea6; //keccak256("_owner")
bytes32 public constant requestQPosition = 0x1e344bd070f05f1c5b3f0b1266f4f20d837a0a8190a3a2da8b0375eac2ba86ea; //keccak256("requestQPosition")
bytes32 public constant currentTotalTips = 0xd26d9834adf5a73309c4974bf654850bb699df8505e70d4cfde365c417b19dfc; //keccak256("currentTotalTips")
bytes32 public constant slotProgress =0x6c505cb2db6644f57b42d87bd9407b0f66788b07d0617a2bc1356a0e69e66f9a; //keccak256("slotProgress")
bytes32 public constant pending_owner = 0x44b2657a0f8a90ed8e62f4c4cceca06eacaa9b4b25751ae1ebca9280a70abd68; //keccak256("pending_owner")
bytes32 public constant currentRequestId = 0x7584d7d8701714da9c117f5bf30af73b0b88aca5338a84a21eb28de2fe0d93b8; //keccak256("currentRequestId")
event TipAdded(address indexed _sender, uint256 indexed _requestId, uint256 _tip, uint256 _totalTips);
//emits when a new challenge is created (either on mined block or when a new request is pushed forward on waiting system)
event NewChallenge(
bytes32 indexed _currentChallenge,
uint256[5] _currentRequestId,
uint256 _difficulty,
uint256 _totalTips
);
//Emits upon a successful Mine, indicates the blocktime at point of the mine and the value mined
event NewValue(uint256[5] _requestId, uint256 _time, uint256[5] _value, uint256 _totalTips, bytes32 indexed _currentChallenge);
//Emits upon each mine (5 total) and shows the miner, nonce, and value submitted
event NonceSubmitted(address indexed _miner, string _nonce, uint256[5] _requestId, uint256[5] _value, bytes32 indexed _currentChallenge);
event OwnershipTransferred(address indexed _previousOwner, address indexed _newOwner);
event OwnershipProposed(address indexed _previousOwner, address indexed _newOwner);
/*Functions*/
/**
* @dev Add tip to Request value from oracle
* @param _requestId being requested to be mined
* @param _tip amount the requester is willing to pay to be get on queue. Miners
* mine the onDeckQueryHash, or the api with the highest payout pool
*/
function addTip(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _tip) public {
require(_requestId != 0, "RequestId is 0");
require(_tip != 0, "Tip should be greater than 0");
uint256 _count =self.uintVars[requestCount] + 1;
if(_requestId == _count){
self.uintVars[requestCount] = _count;
}
else{
require(_requestId < _count, "RequestId is not less than count");
}
TellorTransfer.doTransfer(self, msg.sender, address(this), _tip);
//Update the information for the request that should be mined next based on the tip submitted
updateOnDeck(self, _requestId, _tip);
emit TipAdded(msg.sender, _requestId, _tip, self.requestDetails[_requestId].apiUintVars[totalTip]);
}
/**
* @dev This function is called by submitMiningSolution and adjusts the difficulty, sorts and stores the first
* 5 values received, pays the miners, the dev share and assigns a new challenge
* @param _nonce or solution for the PoW for the requestId
* @param _requestId for the current request being mined
*/
function newBlock(TellorStorage.TellorStorageStruct storage self, string memory _nonce, uint256[5] memory _requestId) public {
TellorStorage.Request storage _tblock = self.requestDetails[self.uintVars[_tBlock]];
// If the difference between the timeTarget and how long it takes to solve the challenge this updates the challenge
//difficulty up or donw by the difference between the target time and how long it took to solve the previous challenge
//otherwise it sets it to 1
uint timeDiff = now - self.uintVars[timeOfLastNewValue];
int256 _change = int256(SafeMath.min(1200, timeDiff));
int256 _diff = int256(self.uintVars[difficulty]);
_change = (_diff * (int256(self.uintVars[timeTarget]) - _change)) / 4000;
if (_change == 0) {
_change = 1;
}
self.uintVars[difficulty] = uint256(SafeMath.max(_diff + _change,1));
//Sets time of value submission rounded to 1 minute
bytes32 _currChallenge = self.currentChallenge;
uint256 _timeOfLastNewValue = now - (now % 1 minutes);
self.uintVars[timeOfLastNewValue] = _timeOfLastNewValue;
uint[5] memory a;
for (uint k = 0; k < 5; k++) {
for (uint i = 1; i < 5; i++) {
uint256 temp = _tblock.valuesByTimestamp[k][i];
address temp2 = _tblock.minersByValue[k][i];
uint256 j = i;
while (j > 0 && temp < _tblock.valuesByTimestamp[k][j - 1]) {
_tblock.valuesByTimestamp[k][j] = _tblock.valuesByTimestamp[k][j - 1];
_tblock.minersByValue[k][j] = _tblock.minersByValue[k][j - 1];
j--;
}
if (j < i) {
_tblock.valuesByTimestamp[k][j] = temp;
_tblock.minersByValue[k][j] = temp2;
}
}
TellorStorage.Request storage _request = self.requestDetails[_requestId[k]];
//Save the official(finalValue), timestamp of it, 5 miners and their submitted values for it, and its block number
a = _tblock.valuesByTimestamp[k];
_request.finalValues[_timeOfLastNewValue] = a[2];
_request.minersByValue[_timeOfLastNewValue] = _tblock.minersByValue[k];
_request.valuesByTimestamp[_timeOfLastNewValue] = _tblock.valuesByTimestamp[k];
delete _tblock.minersByValue[k];
delete _tblock.valuesByTimestamp[k];
_request.requestTimestamps.push(_timeOfLastNewValue);
_request.minedBlockNum[_timeOfLastNewValue] = block.number;
_request.apiUintVars[totalTip] = 0;
}
emit NewValue(
_requestId,
_timeOfLastNewValue,
a,
self.uintVars[runningTips],
_currChallenge
);
//map the timeOfLastValue to the requestId that was just mined
self.requestIdByTimestamp[_timeOfLastNewValue] = _requestId[0];
//add timeOfLastValue to the newValueTimestamps array
self.newValueTimestamps.push(_timeOfLastNewValue);
address[5] memory miners = self.requestDetails[_requestId[0]].minersByValue[_timeOfLastNewValue];
//payMinersRewards
_payReward(self, timeDiff, miners);
self.uintVars[_tBlock] ++;
uint256[5] memory _topId = TellorStake.getTopRequestIDs(self);
for(uint i = 0; i< 5;i++){
self.currentMiners[i].value = _topId[i];
self.requestQ[self.requestDetails[_topId[i]].apiUintVars[requestQPosition]] = 0;
self.uintVars[currentTotalTips] += self.requestDetails[_topId[i]].apiUintVars[totalTip];
}
//Issue the the next challenge
_currChallenge = keccak256(abi.encode(_nonce, _currChallenge, blockhash(block.number - 1)));
self.currentChallenge = _currChallenge; // Save hash for next proof
emit NewChallenge(
_currChallenge,
_topId,
self.uintVars[difficulty],
self.uintVars[currentTotalTips]
);
}
/**
* @dev Proof of work is called by the miner when they submit the solution (proof of work and value)
* @param _nonce uint submitted by miner
* @param _requestId is the array of the 5 PSR's being mined
* @param _value is an array of 5 values
*/
function submitMiningSolution(TellorStorage.TellorStorageStruct storage self, string calldata _nonce,uint256[5] calldata _requestId, uint256[5] calldata _value)
external
{
_verifyNonce(self, _nonce);
_submitMiningSolution(self, _nonce, _requestId, _value);
}
function _submitMiningSolution(TellorStorage.TellorStorageStruct storage self, string memory _nonce,uint256[5] memory _requestId, uint256[5] memory _value)
internal
{
//Verifying Miner Eligibility
bytes32 _hashMsgSender = keccak256(abi.encode(msg.sender));
require(self.stakerDetails[msg.sender].currentStatus == 1, "Miner status is not staker");
require(now - self.uintVars[_hashMsgSender] > 15 minutes, "Miner can only win rewards once per 15 min");
require(_requestId[0] == self.currentMiners[0].value,"Request ID is wrong");
require(_requestId[1] == self.currentMiners[1].value,"Request ID is wrong");
require(_requestId[2] == self.currentMiners[2].value,"Request ID is wrong");
require(_requestId[3] == self.currentMiners[3].value,"Request ID is wrong");
require(_requestId[4] == self.currentMiners[4].value,"Request ID is wrong");
self.uintVars[_hashMsgSender] = now;
bytes32 _currChallenge = self.currentChallenge;
uint256 _slotProgress = self.uintVars[slotProgress];
//Saving the challenge information as unique by using the msg.sender
//Checking and updating Miner Status
require(self.minersByChallenge[_currChallenge][msg.sender] == false, "Miner already submitted the value");
//Update the miner status to true once they submit a value so they don't submit more than once
self.minersByChallenge[_currChallenge][msg.sender] = true;
//Updating Request
TellorStorage.Request storage _tblock = self.requestDetails[self.uintVars[_tBlock]];
_tblock.minersByValue[1][_slotProgress]= msg.sender;
//Assigng directly is cheaper than using a for loop
_tblock.valuesByTimestamp[0][_slotProgress] = _value[0];
_tblock.valuesByTimestamp[1][_slotProgress] = _value[1];
_tblock.valuesByTimestamp[2][_slotProgress] = _value[2];
_tblock.valuesByTimestamp[3][_slotProgress] = _value[3];
_tblock.valuesByTimestamp[4][_slotProgress] = _value[4];
_tblock.minersByValue[0][_slotProgress]= msg.sender;
_tblock.minersByValue[1][_slotProgress]= msg.sender;
_tblock.minersByValue[2][_slotProgress]= msg.sender;
_tblock.minersByValue[3][_slotProgress]= msg.sender;
_tblock.minersByValue[4][_slotProgress]= msg.sender;
//If 5 values have been received, adjust the difficulty otherwise sort the values until 5 are received
if (_slotProgress + 1 == 5) { //slotProgress has been incremented, but we're using the variable on stack to save gas
newBlock(self, _nonce, _requestId);
self.uintVars[slotProgress] = 0;
}
else{
self.uintVars[slotProgress]++;
}
emit NonceSubmitted(msg.sender, _nonce, _requestId, _value, _currChallenge);
}
function _verifyNonce(TellorStorage.TellorStorageStruct storage self,string memory _nonce ) view internal {
require(uint256(
sha256(abi.encodePacked(ripemd160(abi.encodePacked(keccak256(abi.encodePacked(self.currentChallenge, msg.sender, _nonce))))))
) %
self.uintVars[difficulty] == 0
|| (now - (now % 1 minutes)) - self.uintVars[timeOfLastNewValue] >= 15 minutes,
"Incorrect nonce for current challenge"
);
}
/**
* @dev Internal function to calculate and pay rewards to miners
*
*/
function _payReward(TellorStorage.TellorStorageStruct storage self, uint _timeDiff, address[5] memory miners) internal {
//_timeDiff is how many minutes passed since last block
uint _currReward = 1e18;
uint reward = _timeDiff* _currReward / 300; //each miner get's
uint _tip = self.uintVars[currentTotalTips] / 10;
uint _devShare = reward / 2;
TellorTransfer.doTransfer(self, address(this), miners[0], reward + _tip);
TellorTransfer.doTransfer(self, address(this), miners[1], reward + _tip);
TellorTransfer.doTransfer(self, address(this), miners[2], reward + _tip);
TellorTransfer.doTransfer(self, address(this), miners[3], reward + _tip);
TellorTransfer.doTransfer(self, address(this), miners[4], reward + _tip);
//update the total supply
self.uintVars[total_supply] += _devShare + reward * 5 - (self.uintVars[currentTotalTips] / 2);
TellorTransfer.doTransfer(self, address(this), self.addressVars[_owner], _devShare);
self.uintVars[currentTotalTips] = 0;
}
/**
* @dev Allows the current owner to propose transfer control of the contract to a
* newOwner and the ownership is pending until the new owner calls the claimOwnership
* function
* @param _pendingOwner The address to transfer ownership to.
*/
function proposeOwnership(TellorStorage.TellorStorageStruct storage self, address payable _pendingOwner) public {
require(msg.sender == self.addressVars[_owner], "Sender is not owner");
emit OwnershipProposed(self.addressVars[_owner], _pendingOwner);
self.addressVars[pending_owner] = _pendingOwner;
}
/**
* @dev Allows the new owner to claim control of the contract
*/
function claimOwnership(TellorStorage.TellorStorageStruct storage self) public {
require(msg.sender == self.addressVars[pending_owner], "Sender is not pending owner");
emit OwnershipTransferred(self.addressVars[_owner], self.addressVars[pending_owner]);
self.addressVars[_owner] = self.addressVars[pending_owner];
}
/**
* @dev This function updates APIonQ and the requestQ when requestData or addTip are ran
* @param _requestId being requested
* @param _tip is the tip to add
*/
function updateOnDeck(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _tip) public {
TellorStorage.Request storage _request = self.requestDetails[_requestId];
_request.apiUintVars[totalTip] = _request.apiUintVars[totalTip].add(_tip);
if(self.currentMiners[0].value == _requestId || self.currentMiners[1].value== _requestId ||self.currentMiners[2].value == _requestId||self.currentMiners[3].value== _requestId || self.currentMiners[4].value== _requestId ){
self.uintVars[currentTotalTips] += _tip;
}
else {
//if the request is not part of the requestQ[51] array
//then add to the requestQ[51] only if the _payout/tip is greater than the minimum(tip) in the requestQ[51] array
if (_request.apiUintVars[requestQPosition] == 0) {
uint256 _min;
uint256 _index;
(_min, _index) = Utilities.getMin(self.requestQ);
//we have to zero out the oldOne
//if the _payout is greater than the current minimum payout in the requestQ[51] or if the minimum is zero
//then add it to the requestQ array aand map its index information to the requestId and the apiUintvars
if (_request.apiUintVars[totalTip] > _min || _min == 0) {
self.requestQ[_index] = _request.apiUintVars[totalTip];
self.requestDetails[self.requestIdByRequestQIndex[_index]].apiUintVars[requestQPosition] = 0;
self.requestIdByRequestQIndex[_index] = _requestId;
_request.apiUintVars[requestQPosition] = _index;
}
// else if the requestid is part of the requestQ[51] then update the tip for it
} else{
self.requestQ[_request.apiUintVars[requestQPosition]] += _tip;
}
}
}
}
pragma solidity ^0.5.16;
/**
* @title Tellor Oracle System
* @dev Oracle contract where miners can submit the proof of work along with the value.
* The logic for this contract is in TellorLibrary.sol, TellorDispute.sol, TellorStake.sol,
* and TellorTransfer.sol
*/
contract Tellor {
using SafeMath for uint256;
using TellorDispute for TellorStorage.TellorStorageStruct;
using TellorLibrary for TellorStorage.TellorStorageStruct;
using TellorStake for TellorStorage.TellorStorageStruct;
using TellorTransfer for TellorStorage.TellorStorageStruct;
TellorStorage.TellorStorageStruct tellor;
/*Functions*/
/**
* @dev Helps initialize a dispute by assigning it a disputeId
* when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the
* invalidated value information to POS voting
* @param _requestId being disputed
* @param _timestamp being disputed
* @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value
* requires 5 miners to submit a value.
*/
function beginDispute(uint256 _requestId, uint256 _timestamp, uint256 _minerIndex) external {
tellor.beginDispute(_requestId, _timestamp, _minerIndex);
}
/**
* @dev Allows token holders to vote
* @param _disputeId is the dispute id
* @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute)
*/
function vote(uint256 _disputeId, bool _supportsDispute) external {
tellor.vote(_disputeId, _supportsDispute);
}
/**
* @dev tallies the votes.
* @param _disputeId is the dispute id
*/
function tallyVotes(uint256 _disputeId) external {
tellor.tallyVotes(_disputeId);
}
/**
* @dev Allows for a fork to be proposed
* @param _propNewTellorAddress address for new proposed Tellor
*/
function proposeFork(address _propNewTellorAddress) external {
tellor.proposeFork(_propNewTellorAddress);
}
/**
* @dev Add tip to Request value from oracle
* @param _requestId being requested to be mined
* @param _tip amount the requester is willing to pay to be get on queue. Miners
* mine the onDeckQueryHash, or the api with the highest payout pool
*/
function addTip(uint256 _requestId, uint256 _tip) external {
tellor.addTip(_requestId, _tip);
}
/**
* @dev This is called by the miner when they submit the PoW solution (proof of work and value)
* @param _nonce uint submitted by miner
* @param _requestId is the array of the 5 PSR's being mined
* @param _value is an array of 5 values
*/
function submitMiningSolution(string calldata _nonce,uint256[5] calldata _requestId, uint256[5] calldata _value) external {
tellor.submitMiningSolution(_nonce,_requestId, _value);
}
/**
* @dev Allows the current owner to propose transfer control of the contract to a
* newOwner and the ownership is pending until the new owner calls the claimOwnership
* function
* @param _pendingOwner The address to transfer ownership to.
*/
function proposeOwnership(address payable _pendingOwner) external {
tellor.proposeOwnership(_pendingOwner);
}
/**
* @dev Allows the new owner to claim control of the contract
*/
function claimOwnership() external {
tellor.claimOwnership();
}
/**
* @dev This function allows miners to deposit their stake.
*/
function depositStake() external {
tellor.depositStake();
}
/**
* @dev This function allows stakers to request to withdraw their stake (no longer stake)
* once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they
* can withdraw the stake
*/
function requestStakingWithdraw() external {
tellor.requestStakingWithdraw();
}
/**
* @dev This function allows users to withdraw their stake after a 7 day waiting period from request
*/
function withdrawStake() external {
tellor.withdrawStake();
}
/**
* @dev This function approves a _spender an _amount of tokens to use
* @param _spender address
* @param _amount amount the spender is being approved for
* @return true if spender appproved successfully
*/
function approve(address _spender, uint256 _amount) external returns (bool) {
return tellor.approve(_spender, _amount);
}
/**
* @dev Allows for a transfer of tokens to _to
* @param _to The address to send tokens to
* @param _amount The amount of tokens to send
* @return true if transfer is successful
*/
function transfer(address _to, uint256 _amount) external returns (bool) {
return tellor.transfer(_to, _amount);
}
/**
* @dev Sends _amount tokens to _to from _from on the condition it
* is approved by _from
* @param _from The address holding the tokens being transferred
* @param _to The address of the recipient
* @param _amount The amount of tokens to be transferred
* @return True if the transfer was successful
*/
function transferFrom(address _from, address _to, uint256 _amount) external returns (bool) {
return tellor.transferFrom(_from, _to, _amount);
}
/**
* @dev Allows users to access the token's name
*/
function name() external pure returns (string memory) {
return "Tellor Tributes";
}
/**
* @dev Allows users to access the token's symbol
*/
function symbol() external pure returns (string memory) {
return "TRB";
}
/**
* @dev Allows users to access the number of decimals
*/
function decimals() external pure returns (uint8) {
return 18;
}
/**
* @dev Getter for the current variables that include the 5 requests Id's
* @return the challenge, 5 requestsId, difficulty and tip
*/
function getNewCurrentVariables() external view returns(bytes32 _challenge,uint[5] memory _requestIds,uint256 _difficutly, uint256 _tip){
return tellor.getNewCurrentVariables();
}
/**
* @dev Getter for the top tipped 5 requests Id's
* @return the 5 requestsId
*/
function getTopRequestIDs() external view returns(uint256[5] memory _requestIds){
return tellor.getTopRequestIDs();
}
/**
* @dev Getter for the 5 requests Id's next in line to get mined
* @return the 5 requestsId
*/
function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck) {
return tellor.getNewVariablesOnDeck();
}
/**
* @dev Updates the Tellor address after a proposed fork has
* passed the vote and day has gone by without a dispute
* @param _disputeId the disputeId for the proposed fork
*/
function updateTellor(uint _disputeId) external{
return tellor.updateTellor(_disputeId);
}
/**
* @dev Allows disputer to unlock the dispute fee
* @param _disputeId to unlock fee from
*/
function unlockDisputeFee (uint _disputeId) external{
return tellor.unlockDisputeFee(_disputeId);
}
/*******************TEST Functions NOT INCLUDED ON PRODUCTION/MAINNET/RINKEBY******/
// /*This is a cheat for demo purposes, will delete upon actual launch*/
// function theLazyCoon(address _address, uint _amount) external {
// tellor.theLazyCoon(_address,_amount);
// }
// // function testSubmitMiningSolution(string calldata _nonce, uint256 _requestId, uint256 _value) external {
// // tellor.testSubmitMiningSolution(_nonce, _requestId, _value);
// // }
// function testSubmitMiningSolution(string calldata _nonce,uint256[5] calldata _requestId, uint256[5] calldata _value) external {
// tellor.testSubmitMiningSolution(_nonce,_requestId, _value);
// }
/***************END TEST Functions NOT INCLUDED ON PRODUCTION/MAINNET/RINKEBY******/
} | * @dev Updates balance for from and to on the current block number via doTransfer @param checkpoints gets the mapping for the balances[owner] @param _value is the new balance/ | function updateBalanceAtNow(TellorStorage.Checkpoint[] storage checkpoints, uint256 _value) public {
if (checkpoints.length == 0 || checkpoints[checkpoints.length - 1].fromBlock != block.number) {
checkpoints.push(TellorStorage.Checkpoint({
fromBlock : uint128(block.number),
value : uint128(_value)
}));
TellorStorage.Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1];
oldCheckPoint.value = uint128(_value);
}
}
| 1,434,061 | [
1,
5121,
11013,
364,
628,
471,
358,
603,
326,
783,
1203,
1300,
3970,
741,
5912,
225,
26402,
5571,
326,
2874,
364,
326,
324,
26488,
63,
8443,
65,
225,
389,
1132,
353,
326,
394,
11013,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1089,
13937,
861,
8674,
12,
21009,
280,
3245,
18,
14431,
8526,
2502,
26402,
16,
2254,
5034,
389,
1132,
13,
1071,
288,
203,
3639,
309,
261,
1893,
4139,
18,
2469,
422,
374,
747,
26402,
63,
1893,
4139,
18,
2469,
300,
404,
8009,
2080,
1768,
480,
1203,
18,
2696,
13,
288,
203,
6647,
26402,
18,
6206,
12,
21009,
280,
3245,
18,
14431,
12590,
203,
7734,
628,
1768,
294,
2254,
10392,
12,
2629,
18,
2696,
3631,
203,
7734,
460,
294,
2254,
10392,
24899,
1132,
13,
203,
5411,
289,
10019,
203,
5411,
29860,
280,
3245,
18,
14431,
2502,
1592,
1564,
2148,
273,
26402,
63,
1893,
4139,
18,
2469,
300,
404,
15533,
203,
5411,
1592,
1564,
2148,
18,
1132,
273,
2254,
10392,
24899,
1132,
1769,
203,
3639,
289,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x3362229de7d2C1AF21BCa907626CE9ED84AE2928/sources/contracts/common/ERC2981.sol | * @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information. Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first. Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the fee is specified in basis points by default. IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See voluntarily pay royalties together with sales, but note that this standard is not yet widely supported. _Available since v4.5._/ | abstract contract ERC2981 is IERC2981, ERC165, Math {
struct RoyaltyInfo {
address receiver;
uint96 royaltyFraction;
}
RoyaltyInfo private _defaultRoyaltyInfo;
mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo;
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {
return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId);
}
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) public view override returns (address, uint256) {
RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId];
if (royalty.receiver == address(0)) {
royalty = _defaultRoyaltyInfo;
}
uint256 royaltyAmount = mulDiv(_salePrice, royalty.royaltyFraction, _feeDenominator());
return (royalty.receiver, royaltyAmount);
}
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) public view override returns (address, uint256) {
RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId];
if (royalty.receiver == address(0)) {
royalty = _defaultRoyaltyInfo;
}
uint256 royaltyAmount = mulDiv(_salePrice, royalty.royaltyFraction, _feeDenominator());
return (royalty.receiver, royaltyAmount);
}
function _feeDenominator() internal pure returns (uint96) {
return 10000;
}
function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal {
require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
require(receiver != address(0), "ERC2981: invalid receiver");
_defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator);
}
}
| 9,635,898 | [
1,
13621,
434,
326,
423,
4464,
534,
13372,
15006,
8263,
16,
279,
4529,
1235,
4031,
358,
4614,
721,
93,
15006,
5184,
1779,
18,
534,
13372,
15006,
1779,
848,
506,
1269,
25654,
364,
777,
1147,
3258,
3970,
288,
67,
542,
1868,
54,
13372,
15006,
5779,
471,
19,
280,
28558,
364,
2923,
1147,
3258,
3970,
288,
67,
542,
1345,
54,
13372,
15006,
5496,
1021,
23740,
5530,
14172,
1879,
326,
1122,
18,
534,
13372,
15006,
353,
1269,
487,
279,
8330,
434,
272,
5349,
6205,
18,
288,
67,
21386,
8517,
26721,
97,
353,
5713,
27621,
1496,
3467,
358,
12619,
16,
12256,
326,
14036,
353,
1269,
316,
10853,
3143,
635,
805,
18,
21840,
6856,
30,
4232,
39,
17,
5540,
11861,
1338,
11470,
279,
4031,
358,
4277,
721,
93,
15006,
1779,
471,
1552,
486,
12980,
2097,
5184,
18,
2164,
6626,
10032,
10243,
8843,
721,
93,
2390,
606,
9475,
598,
272,
5408,
16,
1496,
4721,
716,
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,
4232,
39,
5540,
11861,
353,
467,
654,
39,
5540,
11861,
16,
4232,
39,
28275,
16,
2361,
288,
203,
203,
565,
1958,
534,
13372,
15006,
966,
288,
203,
3639,
1758,
5971,
31,
203,
3639,
2254,
10525,
721,
93,
15006,
13724,
31,
203,
565,
289,
203,
203,
565,
534,
13372,
15006,
966,
3238,
389,
1886,
54,
13372,
15006,
966,
31,
203,
565,
2874,
12,
11890,
5034,
516,
534,
13372,
15006,
966,
13,
3238,
389,
2316,
54,
13372,
15006,
966,
31,
203,
203,
565,
445,
6146,
1358,
12,
3890,
24,
1560,
548,
13,
1071,
1476,
5024,
3849,
12,
45,
654,
39,
28275,
16,
4232,
39,
28275,
13,
1135,
261,
6430,
13,
288,
203,
3639,
327,
1560,
548,
422,
618,
12,
45,
654,
39,
5540,
11861,
2934,
5831,
548,
747,
2240,
18,
28064,
1358,
12,
5831,
548,
1769,
203,
565,
289,
203,
203,
565,
445,
721,
93,
15006,
966,
12,
11890,
5034,
389,
2316,
548,
16,
2254,
5034,
389,
87,
5349,
5147,
13,
1071,
1476,
3849,
1135,
261,
2867,
16,
2254,
5034,
13,
288,
203,
3639,
534,
13372,
15006,
966,
3778,
721,
93,
15006,
273,
389,
2316,
54,
13372,
15006,
966,
63,
67,
2316,
548,
15533,
203,
203,
3639,
309,
261,
3800,
15006,
18,
24454,
422,
1758,
12,
20,
3719,
288,
203,
5411,
721,
93,
15006,
273,
389,
1886,
54,
13372,
15006,
966,
31,
203,
3639,
289,
203,
3639,
2254,
5034,
721,
93,
15006,
6275,
273,
14064,
7244,
24899,
87,
5349,
5147,
16,
721,
93,
15006,
18,
3800,
15006,
13724,
16,
389,
21386,
8517,
26721,
10663,
2
] |
/*
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.5.9;
import "../src/ReentrancyGuard.sol";
contract TestReentrancyGuard is
ReentrancyGuard
{
/// @dev Exposes the nonReentrant modifier publicly.
/// @param shouldBeAttacked True if the contract should be attacked.
/// @return True if successful.
function guarded(bool shouldBeAttacked)
external
nonReentrant
returns (bool)
{
if (shouldBeAttacked) {
return this.exploitive();
} else {
return this.nonExploitive();
}
}
/// @dev This is a function that will reenter the current contract.
/// @return True if successful.
function exploitive()
external
returns (bool)
{
return this.guarded(true);
}
/// @dev This is a function that will not reenter the current contract.
/// @return True if successful.
function nonExploitive()
external
pure
returns (bool)
{
return true;
}
}
| @dev This is a function that will reenter the current contract. @return True if successful. | function exploitive()
external
returns (bool)
{
return this.guarded(true);
}
| 15,804,028 | [
1,
2503,
353,
279,
445,
716,
903,
283,
2328,
326,
783,
6835,
18,
327,
1053,
309,
6873,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
15233,
3720,
1435,
203,
3639,
3903,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
327,
333,
18,
6891,
17212,
12,
3767,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.21;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract KahnAirDrop2{
using SafeMath for uint256;
struct User{
address user_address;
uint signup_time;
uint256 reward_amount;
bool blacklisted;
uint paid_time;
uint256 paid_token;
bool status;
}
/* @dev Contract creator address */
address public owner;
/* @dev Assigned wallet where the remaining unclaim tokens to be return */
address public wallet;
/* @dev bounty address */
address[] public bountyaddress;
/* @dev admin address */
address[] public adminaddress;
/* @dev Total Signup count */
uint public userSignupCount = 0;
/* @dev Total tokens claimed */
uint256 public userClaimAmt = 0;
/* @dev The token being distribute */
ERC20 public token;
/* @dev To record the different reward amount for each bounty */
mapping(address => User) public bounties;
/* @dev to include the bounty in the list */
mapping(address => bool) public signups;
/* @dev Admin with permission to manage the signed up bounty */
mapping (address => bool) public admins;
/**
* @param _token Token smart contract address
* @param _wallet ETH address to reclaim unclaim tokens
*/
function KahnAirDrop2(ERC20 _token, address _wallet) public {
require(_token != address(0));
token = _token;
admins[msg.sender] = true;
adminaddress.push(msg.sender) -1;
owner = msg.sender;
wallet = _wallet;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier onlyAdmin {
require(admins[msg.sender]);
_;
}
/*******************/
/* Owner Function **/
/*******************/
/* @dev Update Contract Configuration */
function ownerUpdateToken(ERC20 _token, address _wallet) public onlyOwner{
token = _token;
wallet = _wallet;
}
/*******************/
/* Admin Function **/
/*******************/
/* @dev Add admin to whitelist */
function addAdminWhitelist(address[] _userlist) public onlyOwner onlyAdmin{
require(_userlist.length > 0);
for (uint256 i = 0; i < _userlist.length; i++) {
address baddr = _userlist[i];
if(baddr != address(0)){
if(!admins[baddr]){
admins[baddr] = true;
adminaddress.push(baddr) -1;
}
}
}
}
/* @dev Remove admin from whitelist */
function removeAdminWhitelist(address[] _userlist) public onlyAdmin{
require(_userlist.length > 0);
for (uint256 i = 0; i < _userlist.length; i++) {
address baddr = _userlist[i];
if(baddr != address(0)){
if(admins[baddr]){
admins[baddr] = false;
}
}
}
}
/* @dev Allow Admin to reclaim all unclaim tokens back to the specified wallet */
function reClaimBalance() public onlyAdmin{
uint256 taBal = token.balanceOf(this);
token.transfer(wallet, taBal);
}
function adminUpdateWallet(address _wallet) public onlyAdmin{
require(_wallet != address(0));
wallet = _wallet;
}
/***************************/
/* Admin & Staff Function **/
/***************************/
/* @dev Admin/Staffs Update Contract Configuration */
/* @dev Add user to whitelist */
function signupUserWhitelist(address[] _userlist, uint256[] _amount) public onlyAdmin{
require(_userlist.length > 0);
require(_amount.length > 0);
for (uint256 i = 0; i < _userlist.length; i++) {
address baddr = _userlist[i];
uint256 bval = _amount[i];
if(baddr != address(0)){
if(bounties[baddr].user_address != baddr){
bounties[baddr] = User(baddr,now,0,false,now,bval,true);
token.transfer(baddr, bval);
}
}
}
}
/* @dev Return list of bounty addresses */
function getBountyAddress() view public onlyAdmin returns(address[]){
return bountyaddress;
}
function chkUserDetails(address _address) view public onlyAdmin returns(address,uint,uint256,bool,uint,uint256,bool){
require(_address != address(0));
return(bounties[_address].user_address, bounties[_address].signup_time, bounties[_address].reward_amount, bounties[_address].blacklisted, bounties[_address].paid_time, bounties[_address].paid_token, bounties[_address].status);
}
function () external payable {
revert();
}
} | ******************/ Owner Function **/******************/ @dev Update Contract Configuration */ | function ownerUpdateToken(ERC20 _token, address _wallet) public onlyOwner{
token = _token;
wallet = _wallet;
}
| 10,810,211 | [
1,
19,
16837,
4284,
368,
225,
2315,
13456,
4659,
225,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
3410,
1891,
1345,
12,
654,
39,
3462,
389,
2316,
16,
1758,
389,
19177,
13,
1071,
1338,
5541,
95,
203,
3639,
1147,
273,
389,
2316,
31,
203,
3639,
9230,
273,
389,
19177,
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
] |
/**
* Copyright 2017-2021, bZeroX, LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
import "../PriceFeeds.sol";
/**
* @title Price Feeds Local contract.
*
* @notice This contract code comes from bZx. bZx is a protocol for tokenized
* margin trading and lending https://bzx.network similar to the dYdX protocol.
*
* This contract contains the logic of setting and getting rates between two tokens.
* */
contract PriceFeedsLocal is PriceFeeds {
mapping(address => mapping(address => uint256)) public rates;
/// uint256 public slippageMultiplier = 100 ether;
/**
* @notice Deploy local price feed contract.
*
* @param _wrbtcTokenAddress The address of the wrBTC instance.
* @param _protocolTokenAddress The address of the protocol token instance.
* */
constructor(address _wrbtcTokenAddress, address _protocolTokenAddress)
public
PriceFeeds(_wrbtcTokenAddress, _protocolTokenAddress, _wrbtcTokenAddress)
{}
/**
* @notice Calculate the price ratio between two tokens.
*
* @param sourceToken The address of the source tokens.
* @param destToken The address of the destiny tokens.
*
* @return rate The price ratio source/dest.
* @return precision The ratio precision.
* */
function _queryRate(address sourceToken, address destToken)
internal
view
returns (uint256 rate, uint256 precision)
{
require(!globalPricingPaused, "pricing is paused");
if (sourceToken == destToken) {
rate = 10**18;
precision = 10**18;
} else {
if (sourceToken == protocolTokenAddress) {
/// Hack for testnet; only returns price in rBTC.
rate = protocolTokenEthPrice;
} else if (destToken == protocolTokenAddress) {
/// Hack for testnet; only returns price in rBTC.
rate = SafeMath.div(10**36, protocolTokenEthPrice);
} else {
if (rates[sourceToken][destToken] != 0) {
rate = rates[sourceToken][destToken];
} else {
uint256 sourceToEther =
rates[sourceToken][address(wrbtcToken)] != 0
? rates[sourceToken][address(wrbtcToken)]
: 10**18;
uint256 etherToDest =
rates[address(wrbtcToken)][destToken] != 0
? rates[address(wrbtcToken)][destToken]
: 10**18;
rate = sourceToEther.mul(etherToDest).div(10**18);
}
}
precision = _getDecimalPrecision(sourceToken, destToken);
}
}
/**
* @notice Owner set price ratio between two tokens.
*
* @param sourceToken The address of the source tokens.
* @param destToken The address of the destiny tokens.
* @param rate The price ratio source/dest.
* */
function setRates(
address sourceToken,
address destToken,
uint256 rate
) public onlyOwner {
if (sourceToken != destToken) {
rates[sourceToken][destToken] = rate;
rates[destToken][sourceToken] = SafeMath.div(10**36, rate);
}
}
/*function setSlippageMultiplier(
uint256 _slippageMultiplier)
public
onlyOwner
{
require (slippageMultiplier != _slippageMultiplier && _slippageMultiplier <= 100 ether);
slippageMultiplier = _slippageMultiplier;
}*/
}
| Hack for testnet; only returns price in rBTC. | } else if (destToken == protocolTokenAddress) {
| 5,537,644 | [
1,
44,
484,
364,
1842,
2758,
31,
1338,
1135,
6205,
316,
436,
38,
15988,
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
] | [
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,
5411,
289,
469,
309,
261,
10488,
1345,
422,
1771,
1345,
1887,
13,
288,
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
] |
/**
*Submitted for verification at Etherscan.io on 2021-12-15
*/
// SPDX-License-Identifier: No License (None)
pragma solidity ^0.8.0;
interface IBEP20TokenCloned {
// initialize cloned token just for BEP20TokenCloned
function initialize(address newOwner, string calldata name, string calldata symbol, uint8 decimals) external;
function mint(address user, uint256 amount) external;
function burnFrom(address account, uint256 amount) external returns(bool);
function burn(uint256 amount) external returns(bool);
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);
}
/**
* @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
* deploying minimal proxy contracts, also known as "clones".
*
* > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
* > a minimal bytecode implementation that delegates all calls to a known, fixed address.
*
* The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
* (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
* deterministic method.
*
* _Available since v3.4._
*/
library Clones {
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create opcode, which should never revert.
*/
function clone(address implementation) internal returns (address instance) {
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create(0, ptr, 0x37)
}
require(instance != address(0), "ERC1167: create failed");
}
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `implementation` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create2(0, ptr, 0x37, salt)
}
require(instance != address(0), "ERC1167: create2 failed");
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(
address implementation,
bytes32 salt,
address deployer
) internal pure returns (address predicted) {
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000)
mstore(add(ptr, 0x38), shl(0x60, deployer))
mstore(add(ptr, 0x4c), salt)
mstore(add(ptr, 0x6c), keccak256(ptr, 0x37))
predicted := keccak256(add(ptr, 0x37), 0x55)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address implementation, bytes32 salt)
internal
view
returns (address predicted)
{
return predictDeterministicAddress(implementation, salt, address(this));
}
}
// 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');
}
}
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
struct AddressSet {
// Storage of set values
address[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (address => 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(AddressSet storage set, address value) internal returns (bool) {
if (!contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
address 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(AddressSet storage set, address value) internal view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns 1-based index of value in the set. O(1).
*/
function indexOf(AddressSet storage set, address value) internal view returns (uint256) {
return set._indexes[value];
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
}
abstract contract Ownable {
address internal _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
/* will use initialize instead
constructor () {
_owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
*/
/**
* @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() == msg.sender, "Ownable: caller is not the owner");
_;
}
}
contract CallistoBridge is Ownable {
using TransferHelper for address;
using EnumerableSet for EnumerableSet.AddressSet;
EnumerableSet.AddressSet authorities; // authority has to sign claim transaction (message)
address constant MAX_NATIVE_COINS = address(31); // addresses from address(1) to MAX_NATIVE_COINS are considered as native coins
// CLO = address(1)
struct Token {
address token; // foreign token address
bool isWrapped; // is native token wrapped of foreign
}
struct Upgrade {
address newContract;
uint64 validFrom;
}
uint256 public threshold; // minimum number of signatures required to approve swap
address public tokenImplementation; // implementation of wrapped token
address public feeTo; // send fee to this address
bool public frozen; // if frozen - swap will not work
uint256 public wrapNonce; // the last nonce used to create wrapped token address begin with 0xCC....
mapping(uint256 => mapping(bytes32 => bool)) public isTxProcessed; // chainID => txID => isProcessed
mapping(uint256 => mapping(address => Token)) public tokenPair; // chainID => native token address => Token struct
mapping(uint256 => mapping(address => address)) public tokenForeign; // chainID => foreign token address => native token
mapping(address => uint256) public tokenDeposits; // amount of tokens were deposited by users
mapping(address => bool) public isFreezer; // addresses that have right to freeze contract
uint256 public setupMode; // time when setup mode will start, 0 if disable
Upgrade public upgradeData;
address public founders;
address public requiredAuthority; // authority address that MUST sign swap transaction
event SetAuthority(address authority, bool isEnable);
event SetFeeTo(address previousFeeTo, address newFeeTo);
event SetThreshold(uint256 threshold);
event Deposit(address indexed token, address indexed sender, uint256 value, uint256 toChainId, address toToken);
event Claim(address indexed token, address indexed to, uint256 value, bytes32 txId, uint256 fromChainId, address fromToken);
event Fee(address indexed sender, uint256 fee);
event CreatePair(address toToken, bool isWrapped, address fromToken, uint256 fromChainId);
event Frozen(bool status);
event RescuedERC20(address token, address to, uint256 value);
event SetFreezer(address freezer, bool isActive);
event SetupMode(uint time);
event UpgradeRequest(address newContract, uint256 validFrom);
event BridgeToContract(address indexed token, address indexed sender, uint256 value, uint256 toChainId, address toToken, address toContract, bytes data);
event ClaimToContract(address indexed token, address indexed to, uint256 value, bytes32 txId, uint256 fromChainId, address fromToken, address toContract);
// run only once from proxy
function initialize(address newOwner, address newFounders, address _tokenImplementation) external {
require(newOwner != address(0) && newFounders != address(0) && founders == address(0)); // run only once
_owner = newOwner;
founders = newFounders;
emit OwnershipTransferred(address(0), msg.sender);
require(_tokenImplementation != address(0), "Wrong tokenImplementation");
tokenImplementation = _tokenImplementation;
feeTo = msg.sender;
threshold = 1;
setupMode = 1; // allow setup after deployment
}
/*
constructor (address _tokenImplementation) {
require(_tokenImplementation != address(0), "Wrong tokenImplementation");
tokenImplementation = _tokenImplementation;
feeTo = msg.sender;
threshold = 1;
}
*/
modifier notFrozen() {
require(!frozen, "Bridge is frozen");
_;
}
// allowed only in setup mode
modifier onlySetup() {
uint256 mode = setupMode; //use local variable to save gas
require(mode != 0 && mode < block.timestamp, "Not in setup mode");
_;
}
function upgradeTo() external view returns(address newContract) {
Upgrade memory upg = upgradeData;
require(upg.validFrom < block.timestamp && upg.newContract != address(0), "Upgrade not allowed");
newContract = upg.newContract;
}
function requestUpgrade(address newContract) external onlyOwner {
require(newContract != address(0), "Zero address");
uint256 validFrom = block.timestamp + 3 days;
upgradeData = Upgrade(newContract, uint64(validFrom));
emit UpgradeRequest(newContract, validFrom);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public {
require(founders == msg.sender, "Ownable: caller is not the founders");
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
function ChangeFounder(address newFounders) public {
require(founders == msg.sender, "caller is not the founders");
require(newFounders != address(0), "new owner is the zero address");
emit OwnershipTransferred(founders, newFounders);
founders = newFounders;
}
// get number of authorities
function getAuthoritiesNumber() external view returns(uint256) {
return authorities.length();
}
// returns list of authorities addresses
function getAuthorities() external view returns(address[] memory) {
return authorities._values;
}
// Owner or Authority may freeze bridge in case of anomaly detection
function freeze() external {
require(msg.sender == owner() || authorities.contains(msg.sender) || isFreezer[msg.sender]);
frozen = true;
emit Frozen(true);
}
// Only owner can manually unfreeze contract
function unfreeze() external onlyOwner onlySetup {
frozen = false;
emit Frozen(false);
}
// add authority
function setFreezer(address freezer, bool isActive) external onlyOwner {
require(freezer != address(0), "Zero address");
isFreezer[freezer] = isActive;
emit SetFreezer(freezer, isActive);
}
// add authority
function addAuthority(address authority) external onlyOwner onlySetup {
require(authority != address(0), "Zero address");
require(authorities.length() < 255, "Too many authorities");
require(authorities.add(authority), "Authority already added");
emit SetAuthority(authority, true);
}
// remove authority
function removeAuthority(address authority) external onlyOwner {
require(authorities.remove(authority), "Authority does not exist");
emit SetAuthority(authority, false);
}
// set authority address that MUST sign claim request
function setRequiredAuthority(address authority) external onlyOwner onlySetup {
requiredAuthority = authority;
}
// set fee receiver address
function setFeeTo(address newFeeTo) external onlyOwner onlySetup {
require(newFeeTo != address(0), "Zero address");
address previousFeeTo = feeTo;
feeTo = newFeeTo;
emit SetFeeTo(previousFeeTo, newFeeTo);
}
// set threshold - minimum number of signatures required to approve swap
function setThreshold(uint256 _threshold) external onlyOwner onlySetup {
require(threshold != 0 && threshold <= authorities.length(), "Wrong threshold");
threshold = _threshold;
emit SetThreshold(threshold);
}
function disableSetupMode() external onlyOwner {
setupMode = 0;
emit SetupMode(0);
}
function enableSetupMode() external onlyOwner {
setupMode = block.timestamp + 1 days;
emit SetupMode(setupMode);
}
// returns `nonce` to use in `createWrappedToken()` to create address starting with 0xCC.....
function calculateNonce() external view returns(uint256 nonce, address addr) {
nonce = wrapNonce;
address implementation = tokenImplementation;
while (true) {
nonce++;
addr = Clones.predictDeterministicAddress(implementation, bytes32(nonce));
if (uint160(addr) & uint160(0xfF00000000000000000000000000000000000000) == uint160(0xCc00000000000000000000000000000000000000))
break;
}
}
function rescueERC20(address token, address to) external onlyOwner {
uint256 value = IBEP20TokenCloned(token).balanceOf(address(this)) - tokenDeposits[token];
token.safeTransfer(to, value);
emit RescuedERC20(token, to, value);
}
// Create wrapped token for foreign token
function createWrappedToken(
address fromToken, // foreign token address
uint256 fromChainId, // foreign chain ID where token deployed
string memory name, // wrapped token name
string memory symbol, // wrapped token symbol
uint8 decimals, // wrapped token decimals (should be the same as in original token)
uint256 nonce // nonce to create wrapped token address begin with 0xCC....
)
external
onlyOwner
onlySetup
{
require(fromToken != address(0), "Wrong token address");
require(tokenForeign[fromChainId][fromToken] == address(0), "This token already wrapped");
require(nonce > wrapNonce, "Nonce must be higher then wrapNonce");
wrapNonce = nonce;
address wrappedToken = Clones.cloneDeterministic(tokenImplementation, bytes32(nonce));
IBEP20TokenCloned(wrappedToken).initialize(owner(), name, symbol, decimals);
tokenPair[fromChainId][wrappedToken] = Token(fromToken, true);
tokenForeign[fromChainId][fromToken] = wrappedToken;
emit CreatePair(wrappedToken, true, fromToken, fromChainId); //wrappedToken - wrapped token contract address
}
/**
* @dev Create pair between existing tokens on native and foreign chains
* @param toToken token address on native chain
* @param fromToken token address on foreign chain
* @param fromChainId foreign chain ID
* @param isWrapped `true` if `toToken` is our wrapped token otherwise `false`
*/
function createPair(address toToken, address fromToken, uint256 fromChainId, bool isWrapped) external onlyOwner onlySetup {
require(tokenPair[fromChainId][toToken].token == address(0), "Pair already exist");
tokenPair[fromChainId][toToken] = Token(fromToken, isWrapped);
tokenForeign[fromChainId][fromToken] = toToken;
emit CreatePair(toToken, isWrapped, fromToken, fromChainId);
}
/**
* @dev Delete unused pair
* @param toToken token address on native chain
* @param fromChainId foreign chain ID
*/
function deletePair(address toToken, uint256 fromChainId) external onlyOwner onlySetup {
delete tokenPair[fromChainId][toToken];
}
// Move tokens through the bridge and call the contract with 'data' parameters on the destination chain
function bridgeToContract(
address receiver, // address of token receiver on destination chain
address token, // token that user send (if token address < 32, then send native coin)
uint256 value, // tokens value
uint256 toChainId, // destination chain Id where will be claimed tokens
address toContract, // this contract will be called on destination chain
bytes memory data // this data will be passed to contract call (ABI encoded parameters)
)
external
payable
notFrozen
{
require(receiver != address(0), "Incorrect receiver address");
address pair_token = _deposit(token, value, toChainId);
emit BridgeToContract(token, receiver, value, toChainId, pair_token, toContract, data);
}
// Claim tokens from the bridge and call the contract with 'data' parameters
function claimToContract(
address token, // token to receive
bytes32 txId, // deposit transaction hash on fromChain
address to, // user address
uint256 value, // value of tokens
uint256 fromChainId, // chain ID where user deposited
address toContract, // this contract will be called on destination chain
bytes memory data, // this data will be passed to contract call (ABI encoded parameters)
bytes[] memory sig // authority signatures
)
external
notFrozen
{
require(!isTxProcessed[fromChainId][txId], "Transaction already processed");
Token memory pair = tokenPair[fromChainId][token];
require(pair.token != address(0), "There is no pair");
isTxProcessed[fromChainId][txId] = true;
// Check signature
address must = requiredAuthority;
bytes32 messageHash = keccak256(abi.encodePacked(token, to, value, txId, fromChainId, block.chainid, toContract, data));
messageHash = prefixed(messageHash);
uint256 uniqSig;
uint256 set; // maximum number of authorities is 255
for (uint i = 0; i < sig.length; i++) {
address authority = recoverSigner(messageHash, sig[i]);
if (authority == must) must = address(0);
uint256 index = authorities.indexOf(authority);
uint256 mask = 1 << index;
if (index != 0 && (set & mask) == 0 ) {
set |= mask;
uniqSig++;
}
}
require(threshold <= uniqSig, "Require more signatures");
require(must == address(0), "The required authority does not sign");
// Call toContract
if(isContract(toContract) && toContract != address(this)) {
if (token <= MAX_NATIVE_COINS) {
uint balance = address(this).balance;
(bool success,) = toContract.call{value: value}(data); // transfer coin back to sender (to address(this)) is not supported
if (!success && balance == address(this).balance) { // double check the coin was not spent
to.safeTransferETH(value); // send coin to user
}
} else {
if(pair.isWrapped) {
IBEP20TokenCloned(token).mint(address(this), value);
} else {
tokenDeposits[token] -= value;
}
if (IBEP20TokenCloned(token).allowance(address(this), toContract) == 0) { // should be zero
IBEP20TokenCloned(token).approve(toContract, value);
(bool success,) = toContract.call{value: 0}(data);
value = IBEP20TokenCloned(token).allowance(address(this), toContract); // unused amount (the rest) = allowance
}
if (value != 0) { // if not all value used reset approvement
IBEP20TokenCloned(token).approve(toContract, 0);
token.safeTransfer(to, value); // send to user rest of tokens
}
}
} else { // if not contract
if (token <= MAX_NATIVE_COINS) {
to.safeTransferETH(value);
} else {
if(pair.isWrapped) {
IBEP20TokenCloned(token).mint(to, value);
} else {
tokenDeposits[token] -= value;
token.safeTransfer(to, value);
}
}
}
emit ClaimToContract(token, to, value, txId, fromChainId, pair.token, toContract);
}
function depositTokens(
address receiver, // address of token receiver on destination chain
address token, // token that user send (if token address < 32, then send native coin)
uint256 value, // tokens value
uint256 toChainId // destination chain Id where will be claimed tokens
)
external
payable
notFrozen
{
require(receiver != address(0), "Incorrect receiver address");
address pair_token = _deposit(token, value, toChainId);
emit Deposit(token, receiver, value, toChainId, pair_token);
}
function depositTokens(
address token, // token that user send (if token address < 32, then send native coin)
uint256 value, // tokens value
uint256 toChainId // destination chain Id where will be claimed tokens
)
external
payable
notFrozen
{
address pair_token = _deposit(token, value, toChainId);
emit Deposit(token, msg.sender, value, toChainId, pair_token);
}
function _deposit(
address token, // token that user send (if token address < 32, then send native coin)
uint256 value, // tokens value
uint256 toChainId // destination chain Id where will be claimed tokens
)
internal
returns (address pair_token)
{
Token memory pair = tokenPair[toChainId][token];
require(pair.token != address(0), "There is no pair");
pair_token = pair.token;
uint256 fee = msg.value;
if (token <= MAX_NATIVE_COINS) {
require(value <= msg.value, "Wrong value");
fee -= value;
} else {
if(pair.isWrapped) {
IBEP20TokenCloned(token).burnFrom(msg.sender, value);
} else {
tokenDeposits[token] += value;
token.safeTransferFrom(msg.sender, address(this), value);
}
}
if (fee != 0) {
feeTo.safeTransferETH(fee);
emit Fee(msg.sender, fee);
}
}
// claim
function claim(
address token, // token to receive
bytes32 txId, // deposit transaction hash on fromChain
address to, // user address
uint256 value, // value of tokens
uint256 fromChainId, // chain ID where user deposited
bytes[] memory sig // authority signatures
)
external
notFrozen
{
require(!isTxProcessed[fromChainId][txId], "Transaction already processed");
Token memory pair = tokenPair[fromChainId][token];
require(pair.token != address(0), "There is no pair");
isTxProcessed[fromChainId][txId] = true;
address must = requiredAuthority;
bytes32 messageHash = keccak256(abi.encodePacked(token, to, value, txId, fromChainId, block.chainid));
messageHash = prefixed(messageHash);
uint256 uniqSig;
uint256 set; // maximum number of authorities is 255
for (uint i = 0; i < sig.length; i++) {
address authority = recoverSigner(messageHash, sig[i]);
if (authority == must) must = address(0);
uint256 index = authorities.indexOf(authority);
uint256 mask = 1 << index;
if (index != 0 && (set & mask) == 0 ) {
set |= mask;
uniqSig++;
}
}
require(threshold <= uniqSig, "Require more signatures");
require(must == address(0), "The required authority does not sign");
if (token <= MAX_NATIVE_COINS) {
to.safeTransferETH(value);
} else {
if(pair.isWrapped) {
IBEP20TokenCloned(token).mint(to, value);
} else {
tokenDeposits[token] -= value;
token.safeTransfer(to, value);
}
}
emit Claim(token, to, value, txId, fromChainId, pair.token);
}
// Signature methods
function splitSignature(bytes memory sig)
internal
pure
returns (uint8 v, bytes32 r, bytes32 s)
{
require(sig.length == 65);
assembly {
// first 32 bytes, after the length prefix
r := mload(add(sig, 32))
// second 32 bytes
s := mload(add(sig, 64))
// final byte (first byte of the next 32 bytes)
v := byte(0, mload(add(sig, 96)))
}
}
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);
}
// 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 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;
}
} | Only owner can manually unfreeze contract | function unfreeze() external onlyOwner onlySetup {
frozen = false;
emit Frozen(false);
}
| 2,141,372 | [
1,
3386,
3410,
848,
10036,
640,
29631,
6835,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
640,
29631,
1435,
3903,
1338,
5541,
1338,
7365,
288,
203,
3639,
12810,
273,
629,
31,
203,
3639,
3626,
478,
9808,
12,
5743,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.18;
// File: zeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: zeppelin-solidity/contracts/lifecycle/Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
// File: zeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @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);
}
// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
// File: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: contracts/BasketToken.sol
library AddressArrayUtils {
/// @return Returns index and ok of the first occurrence starting from index 0
function index(address[] addresses, address a) internal pure returns (uint, bool) {
for (uint i = 0; i < addresses.length; i++) {
if (addresses[i] == a) {
return (i, true);
}
}
return (0, false);
}
}
/// @title A decentralized Basket-like ERC20 which gives the owner a claim to the
/// underlying assets
/// @notice Basket Tokens are transferable, and can be created and redeemed by
/// anyone. To create, a user must approve the contract to move the underlying
/// tokens, then call `create()`.
/// @author Daniel Que and Quan Pham
contract BasketToken is StandardToken, Pausable {
using SafeMath for uint256;
using AddressArrayUtils for address[];
string constant public name = "ERC20 TWENTY";
string constant public symbol = "ETW";
uint8 constant public decimals = 18;
struct TokenInfo {
address addr;
uint256 tokenUnits;
}
uint256 private creationQuantity_;
TokenInfo[] public tokens;
event Mint(address indexed to, uint256 amount);
event Burn(address indexed from, uint256 amount);
/// @notice Requires value to be divisible by creationQuantity
/// @param value Number to be checked
modifier requireMultiple(uint256 value) {
require((value % creationQuantity_) == 0);
_;
}
/// @notice Requires value to be non-zero
/// @param value Number to be checked
modifier requireNonZero(uint256 value) {
require(value > 0);
_;
}
/// @notice Initializes contract with a list of ERC20 token addresses and
/// corresponding minimum number of units required for a creation unit
/// @param addresses Addresses of the underlying ERC20 token contracts
/// @param tokenUnits Number of token base units required per creation unit
/// @param _creationQuantity Number of base units per creation unit
function BasketToken(
address[] addresses,
uint256[] tokenUnits,
uint256 _creationQuantity
) public {
require(0 < addresses.length && addresses.length < 256);
require(addresses.length == tokenUnits.length);
require(_creationQuantity >= 1);
creationQuantity_ = _creationQuantity;
for (uint8 i = 0; i < addresses.length; i++) { // Using uint8 because we expect maximum of 256 underlying tokens
tokens.push(TokenInfo({
addr: addresses[i],
tokenUnits: tokenUnits[i]
}));
}
}
/// @notice Returns the creationQuantity
/// @dev Creation quantity concept is similar but not identical to the one
/// described by EIP777
/// @return creationQuantity_ Creation quantity of the Basket token
function creationQuantity() external view returns(uint256) {
return creationQuantity_;
}
/// @notice Creates Basket tokens in exchange for underlying tokens. Before
/// calling, underlying tokens must be approved to be moved by the Basket Token
/// contract. The number of approved tokens required depends on
/// baseUnits.
/// @dev If any underlying tokens' `transferFrom` fails (eg. the token is
/// frozen), create will no longer work. At this point a token upgrade will
/// be necessary.
/// @param baseUnits Number of base units to create. Must be a multiple of
/// creationQuantity.
function create(uint256 baseUnits)
external
whenNotPaused()
requireNonZero(baseUnits)
requireMultiple(baseUnits)
{
// Check overflow
require((totalSupply_ + baseUnits) > totalSupply_);
for (uint8 i = 0; i < tokens.length; i++) {
TokenInfo memory tokenInfo = tokens[i];
ERC20 erc20 = ERC20(tokenInfo.addr);
uint256 amount = baseUnits.div(creationQuantity_).mul(tokenInfo.tokenUnits);
require(erc20.transferFrom(msg.sender, address(this), amount));
}
mint(msg.sender, baseUnits);
}
/// @notice Redeems Basket Token in return for underlying tokens
/// @param baseUnits Number of base units to redeem. Must be a multiple of
/// creationQuantity.
/// @param tokensToSkip Underlying token addresses to skip redemption for.
/// Intended to be used to skip frozen or broken tokens which would prevent
/// all underlying tokens from being withdrawn due to a revert. Skipped
/// tokens will be left in the Basket Token contract and will be unclaimable.
function redeem(uint256 baseUnits, address[] tokensToSkip)
external
whenNotPaused()
requireNonZero(baseUnits)
requireMultiple(baseUnits)
{
require((totalSupply_ >= baseUnits));
require((balances[msg.sender] >= baseUnits));
require(tokensToSkip.length <= tokens.length);
// Burn before to prevent re-entrancy
burn(msg.sender, baseUnits);
for (uint8 i = 0; i < tokens.length; i++) {
TokenInfo memory tokenInfo = tokens[i];
ERC20 erc20 = ERC20(tokenInfo.addr);
uint256 index;
bool ok;
(index, ok) = tokensToSkip.index(tokenInfo.addr);
if (ok) {
continue;
}
uint256 amount = baseUnits.div(creationQuantity_).mul(tokenInfo.tokenUnits);
require(erc20.transfer(msg.sender, amount));
}
}
/// @return tokenAddresses Underlying token addresses
function tokenAddresses() external view returns (address[]){
address[] memory tokenAddresses = new address[](tokens.length);
for (uint8 i = 0; i < tokens.length; i++) {
tokenAddresses[i] = tokens[i].addr;
}
return tokenAddresses;
}
/// @return tokenUnits Number of token base units required per creation unit
function tokenUnits() external view returns (uint256[]){
uint256[] memory tokenUnits = new uint256[](tokens.length);
for (uint8 i = 0; i < tokens.length; i++) {
tokenUnits[i] = tokens[i].tokenUnits;
}
return tokenUnits;
}
// @dev Mints new Basket tokens
// @param to
// @param amount
// @return ok
function mint(address to, uint256 amount) internal returns (bool) {
totalSupply_ = totalSupply_.add(amount);
balances[to] = balances[to].add(amount);
Mint(to, amount);
Transfer(address(0), to, amount);
return true;
}
// @dev Burns Basket tokens
// @param from
// @param amount
// @return ok
function burn(address from, uint256 amount) internal returns (bool) {
totalSupply_ = totalSupply_.sub(amount);
balances[from] = balances[from].sub(amount);
Burn(from, amount);
Transfer(from, address(0), amount);
return true;
}
// @notice Look up token info
// @param token Token address to look up
// @return (tokenUnits, ok) Units of underlying token, and whether the
// operation was successful
function getTokenUnits(address token) internal view returns (uint256, bool) {
for (uint8 i = 0; i < tokens.length; i++) {
if (tokens[i].addr == token) {
return (tokens[i].tokenUnits, true);
}
}
return (0, false);
}
/// @notice Owner: Withdraw excess funds which don't belong to Basket Token
/// holders
/// @param token ERC20 token address to withdraw
function withdrawExcessToken(address token)
external
onlyOwner
{
ERC20 erc20 = ERC20(token);
uint256 withdrawAmount;
uint256 amountOwned = erc20.balanceOf(address(this));
uint256 tokenUnits;
bool ok;
(tokenUnits, ok) = getTokenUnits(token);
if (ok) {
withdrawAmount = amountOwned.sub(totalSupply_.div(creationQuantity_).mul(tokenUnits));
} else {
withdrawAmount = amountOwned;
}
require(erc20.transfer(owner, withdrawAmount));
}
/// @notice Owner: Withdraw Ether
function withdrawEther()
external
onlyOwner
{
owner.transfer(this.balance);
}
/// @notice Fallback function
function() external payable {
}
} | @return tokenAddresses Underlying token addresses | function tokenAddresses() external view returns (address[]){
address[] memory tokenAddresses = new address[](tokens.length);
for (uint8 i = 0; i < tokens.length; i++) {
tokenAddresses[i] = tokens[i].addr;
}
return tokenAddresses;
}
| 10,974,428 | [
1,
2463,
1147,
7148,
21140,
6291,
1147,
6138,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1147,
7148,
1435,
3903,
1476,
1135,
261,
2867,
63,
5717,
95,
203,
3639,
1758,
8526,
3778,
1147,
7148,
273,
394,
1758,
8526,
12,
7860,
18,
2469,
1769,
203,
3639,
364,
261,
11890,
28,
277,
273,
374,
31,
277,
411,
2430,
18,
2469,
31,
277,
27245,
288,
203,
5411,
1147,
7148,
63,
77,
65,
273,
2430,
63,
77,
8009,
4793,
31,
203,
3639,
289,
203,
3639,
327,
1147,
7148,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x929aE527A74a0C6927b46A9747190FfE2c38D0a1/sources/BANKOFMEMES.sol | set as Marketing wallet
| marketingWallet = address(0xd5c9Ad8bf1D30AFCF7fB5a5954FDcd6368c1481B); | 16,054,851 | [
1,
542,
487,
6622,
21747,
9230,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
377,
202,
3355,
21747,
16936,
273,
1758,
12,
20,
7669,
25,
71,
29,
1871,
28,
17156,
21,
40,
5082,
37,
4488,
42,
27,
74,
38,
25,
69,
6162,
6564,
16894,
4315,
4449,
9470,
71,
3461,
11861,
38,
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
] |
pragma solidity ^0.6.0;
import "../interface/ITokenDelegate.sol";
import "./STransferData.sol";
import "../TokenStorage.sol";
import "../TokenProxy.sol";
/**
* @title Base Token Delegate
* @dev Base Token Delegate
*
* @author Cyril Lapinte - <[email protected]>
* SPDX-License-Identifier: MIT
*
* Error messages
* TD01: Recipient must not be null
* TD02: Not enougth tokens
* TD03: Transfer event must be generated
* TD04: Allowance limit reached
*/
contract BaseTokenDelegate is ITokenDelegate, TokenStorage {
function decimals() virtual override public view returns (uint256) {
return tokens[msg.sender].decimals;
}
function totalSupply() virtual override public view returns (uint256) {
return tokens[msg.sender].totalSupply;
}
function balanceOf(address _owner) virtual override public view returns (uint256) {
return tokens[msg.sender].balances[_owner];
}
function allowance(address _owner, address _spender)
virtual override public view returns (uint256)
{
return tokens[msg.sender].allowances[_owner][_spender];
}
/**
* @dev Overriden transfer function
*/
function transfer(address _sender, address _receiver, uint256 _value)
virtual override public returns (bool)
{
return transferInternal(
transferData(msg.sender, address(0), _sender, _receiver, _value));
}
/**
* @dev Overriden transferFrom function
*/
function transferFrom(
address _caller, address _sender, address _receiver, uint256 _value)
virtual override public returns (bool)
{
return transferInternal(
transferData(msg.sender, _caller, _sender, _receiver, _value));
}
/**
* @dev can transfer
*/
function canTransfer(
address _sender,
address _receiver,
uint256 _value) virtual override public view returns (TransferCode)
{
return canTransferInternal(
transferData(msg.sender, address(0), _sender, _receiver, _value));
}
/**
* @dev approve
*/
function approve(address _sender, address _spender, uint256 _value)
virtual override public returns (bool)
{
TokenData storage token = tokens[msg.sender];
token.allowances[_sender][_spender] = _value;
require(
TokenProxy(msg.sender).emitApproval(_sender, _spender, _value),
"TD03");
return true;
}
/**
* @dev increase approval
*/
function increaseApproval(address _sender, address _spender, uint _addedValue)
virtual override public returns (bool)
{
TokenData storage token = tokens[msg.sender];
token.allowances[_sender][_spender] = (
token.allowances[_sender][_spender].add(_addedValue));
require(
TokenProxy(msg.sender).emitApproval(_sender, _spender, token.allowances[_sender][_spender]),
"TD03");
return true;
}
/**
* @dev decrease approval
*/
function decreaseApproval(address _sender, address _spender, uint _subtractedValue)
virtual override public returns (bool)
{
TokenData storage token = tokens[msg.sender];
uint oldValue = token.allowances[_sender][_spender];
if (_subtractedValue > oldValue) {
token.allowances[_sender][_spender] = 0;
} else {
token.allowances[_sender][_spender] = oldValue.sub(_subtractedValue);
}
require(
TokenProxy(msg.sender).emitApproval(_sender, _spender, token.allowances[_sender][_spender]),
"TD03");
return true;
}
/**
* @dev check configuration
**/
function checkConfigurations(uint256[] memory) virtual override public returns (bool) {
return true;
}
/**
* @dev transfer
*/
function transferInternal(STransferData memory _transferData)
virtual internal returns (bool)
{
TokenData storage token = tokens[_transferData.token];
address caller = _transferData.caller;
address sender = _transferData.sender;
address receiver = _transferData.receiver;
uint256 value = _transferData.value;
require(receiver != address(0), "TD01");
require(value <= token.balances[sender], "TD02");
if (caller != address(0)
&& (selfManaged[sender]
|| !hasProxyPrivilege(caller, _transferData.token, msg.sig)))
{
require(value <= token.allowances[sender][caller], "TD04");
token.allowances[sender][caller] = token.allowances[sender][caller].sub(value);
}
token.balances[sender] = token.balances[sender].sub(value);
token.balances[receiver] = token.balances[receiver].add(value);
require(
TokenProxy(msg.sender).emitTransfer(sender, receiver, value),
"TD03");
return true;
}
/**
* @dev can transfer
*/
function canTransferInternal(STransferData memory _transferData)
virtual internal view returns (TransferCode)
{
TokenData storage token = tokens[_transferData.token];
address sender = _transferData.sender;
address receiver = _transferData.receiver;
uint256 value = _transferData.value;
if (sender == address(0)) {
return TransferCode.INVALID_SENDER;
}
if (receiver == address(0)) {
return TransferCode.NO_RECIPIENT;
}
if (value > token.balances[sender]) {
return TransferCode.INSUFFICIENT_TOKENS;
}
return TransferCode.OK;
}
/**
* @dev transferData
*/
function transferData(
address _token, address _caller,
address _sender, address _receiver, uint256 _value)
internal pure returns (STransferData memory)
{
uint256[] memory emptyArray = new uint256[](1);
return STransferData(
_token,
_caller,
_sender,
_receiver,
0,
emptyArray,
false,
0,
emptyArray,
false,
_value,
0
);
}
}
| * @dev decrease approval/ | function decreaseApproval(address _sender, address _spender, uint _subtractedValue)
virtual override public returns (bool)
{
TokenData storage token = tokens[msg.sender];
uint oldValue = token.allowances[_sender][_spender];
if (_subtractedValue > oldValue) {
token.allowances[_sender][_spender] = 0;
token.allowances[_sender][_spender] = oldValue.sub(_subtractedValue);
}
require(
TokenProxy(msg.sender).emitApproval(_sender, _spender, token.allowances[_sender][_spender]),
"TD03");
return true;
}
| 12,773,578 | [
1,
323,
11908,
23556,
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,
225,
445,
20467,
23461,
12,
2867,
389,
15330,
16,
1758,
389,
87,
1302,
264,
16,
2254,
389,
1717,
1575,
329,
620,
13,
203,
565,
5024,
3849,
1071,
1135,
261,
6430,
13,
203,
225,
288,
203,
565,
3155,
751,
2502,
1147,
273,
2430,
63,
3576,
18,
15330,
15533,
203,
565,
2254,
11144,
273,
1147,
18,
5965,
6872,
63,
67,
15330,
6362,
67,
87,
1302,
264,
15533,
203,
565,
309,
261,
67,
1717,
1575,
329,
620,
405,
11144,
13,
288,
203,
1377,
1147,
18,
5965,
6872,
63,
67,
15330,
6362,
67,
87,
1302,
264,
65,
273,
374,
31,
203,
1377,
1147,
18,
5965,
6872,
63,
67,
15330,
6362,
67,
87,
1302,
264,
65,
273,
11144,
18,
1717,
24899,
1717,
1575,
329,
620,
1769,
203,
565,
289,
203,
565,
2583,
12,
203,
1377,
3155,
3886,
12,
3576,
18,
15330,
2934,
18356,
23461,
24899,
15330,
16,
389,
87,
1302,
264,
16,
1147,
18,
5965,
6872,
63,
67,
15330,
6362,
67,
87,
1302,
264,
65,
3631,
203,
1377,
315,
23409,
4630,
8863,
203,
565,
327,
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
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.