file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
|---|---|---|---|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./owner/Operator.sol";
// Note: This pool has no minter key of CHIPs (rewards). Instead, the governance will call
// CHIPs distributeReward method and send reward to this pool at the beginning.
contract ChipRewardPool is Operator, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address public DAO = 0x1C3dF661182c1f9cc8afE226915e5f91E93d1A6f;
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt.
}
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. CHIPs to distribute per block.
uint256 lastRewardBlock; // Last block number that CHIPs distribution occurs.
uint256 accChipsPerShare; // Accumulated CHIPs per share, times 1e18.
bool isStarted; // Has lastRewardBlock passed?
}
IERC20 public CHIPS;
PoolInfo[] public poolInfo;
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
uint256 public totalAllocPoint = 0; // Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public startBlock; // The block number when CHIPS minting starts.
uint256 public endBlock; // The block number when CHIPS minting ends.
uint256 public timeLockBlock;
uint256 public constant BLOCKS_PER_DAY = 28800; // 86400 / 3;
uint256 public rewardDuration = 10; // Days.
uint256 public totalRewards = 50 ether;
uint256 public rewardPerBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event RewardPaid(address indexed user, uint256 amount);
constructor(address _CHIPS, uint256 _startBlock) {
require(block.number < _startBlock, "ChipRewardPool.constructor(): The current block is after the specified start block.");
if (_CHIPS != address(0)) CHIPS = IERC20(_CHIPS);
startBlock = _startBlock;
endBlock = startBlock.add(BLOCKS_PER_DAY.mul(rewardDuration));
rewardPerBlock = totalRewards.div(endBlock.sub(startBlock));
timeLockBlock = startBlock.add(BLOCKS_PER_DAY.mul(rewardDuration.add(1)));
}
function checkPoolDuplicate(IERC20 _lpToken) internal view {
uint256 length = poolInfo.length;
require(length < 6, "ChipRewardPool.checkPoolDuplicate(): Pool size exceeded.");
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].lpToken != _lpToken, "ChipRewardPool.checkPoolDuplicate(): Found duplicate token in pool.");
}
}
// Add a new lp token to the pool. Can only be called by the owner. can add only 5 lp token.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, uint256 _lastRewardBlock) external onlyOperator {
require(poolInfo.length < 5, "ChipRewardPool: can't add pool anymore");
checkPoolDuplicate(_lpToken);
if (_withUpdate) {
massUpdatePools();
}
if (block.number < startBlock) {
// The chef is sleeping.
if (_lastRewardBlock == 0) {
_lastRewardBlock = startBlock;
} else {
if (_lastRewardBlock < startBlock) {
_lastRewardBlock = startBlock;
}
}
} else {
// The chef is cooking.
if (_lastRewardBlock == 0 || _lastRewardBlock < block.number) {
_lastRewardBlock = block.number;
}
}
bool _isStarted =
(_lastRewardBlock <= startBlock) ||
(_lastRewardBlock <= block.number);
poolInfo.push(PoolInfo({
lpToken : _lpToken,
allocPoint : _allocPoint,
lastRewardBlock : _lastRewardBlock,
accChipsPerShare : 0,
isStarted : _isStarted
}));
if (_isStarted) {
totalAllocPoint = totalAllocPoint.add(_allocPoint);
}
}
// Update the given pool's CHIPs allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint) public onlyOperator {
require(block.number > timeLockBlock, "ChipRewardPool: Locked");
massUpdatePools();
PoolInfo storage pool = poolInfo[_pid];
if (pool.isStarted) {
totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add(
_allocPoint
);
}
pool.allocPoint = _allocPoint;
}
// Return accumulate rewards over the given _from to _to block.
function getGeneratedReward(uint256 _from, uint256 _to) public view returns (uint256) {
if (_from >= _to) return 0;
if (_to <= startBlock) {
return 0;
} else if (_to >= endBlock) {
if (_from >= endBlock) {
return 0;
} else if (_from <= startBlock) {
return rewardPerBlock.mul(endBlock.sub(startBlock));
} else {
return rewardPerBlock.mul(endBlock.sub(_from));
}
} else {
if (_from <= startBlock) {
return rewardPerBlock.mul(_to.sub(startBlock));
} else {
return rewardPerBlock.mul(_to.sub(_from));
}
}
}
// View function to see pending CHIPs.
function pendingReward(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accChipsPerShare = pool.accChipsPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 _generatedReward = getGeneratedReward(pool.lastRewardBlock, block.number);
uint256 _CHIPSReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint);
accChipsPerShare = accChipsPerShare.add(_CHIPSReward.mul(1e18).div(lpSupply));
}
return user.amount.mul(accChipsPerShare).div(1e18).sub(user.rewardDebt);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() internal {
uint256 length = poolInfo.length;
require(length < 6, "ChipRewardPool.massUpdatePools(): Pool size exceeded.");
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) internal {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
if (!pool.isStarted) {
pool.isStarted = true;
totalAllocPoint = totalAllocPoint.add(pool.allocPoint);
}
if (totalAllocPoint > 0) {
uint256 _generatedReward = getGeneratedReward(pool.lastRewardBlock, block.number);
uint256 _CHIPSReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint);
pool.accChipsPerShare = pool.accChipsPerShare.add(_CHIPSReward.mul(1e18).div(lpSupply));
}
pool.lastRewardBlock = block.number;
}
// Deposit tokens.
function deposit(uint256 _pid, uint256 _amount) external nonReentrant {
address _sender = msg.sender;
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 _pending = user.amount.mul(pool.accChipsPerShare).div(1e18).sub(user.rewardDebt);
if (_pending > 0) {
safeChipsTransfer(_sender, _pending);
emit RewardPaid(_sender, _pending);
}
}
if (_amount > 0) {
uint256 FeeToDAO = 0;
if(_pid != 4){
// In case of BNB, BUSD, BTD, BTS pool, users have to pay 1% fee when they deposit.
FeeToDAO = _amount.div(100);
}
if(FeeToDAO > 0) pool.lpToken.safeTransferFrom(_sender, DAO, FeeToDAO);
pool.lpToken.safeTransferFrom(_sender, address(this), _amount.sub(FeeToDAO));
user.amount = user.amount.add(_amount.sub(FeeToDAO));
}
user.rewardDebt = user.amount.mul(pool.accChipsPerShare).div(1e18);
emit Deposit(_sender, _pid, _amount);
}
// Withdraw tokens.
function withdraw(uint256 _pid, uint256 _amount) external nonReentrant {
address _sender = msg.sender;
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_sender];
require(user.amount >= _amount, "ChipRewardPool.withdraw(): User amount less than withdrawal amount.");
updatePool(_pid);
uint256 _pending = user.amount.mul(pool.accChipsPerShare).div(1e18).sub(user.rewardDebt);
if (_pending > 0) {
safeChipsTransfer(_sender, _pending);
emit RewardPaid(_sender, _pending);
}
if (_amount > 0) {
uint256 FeeToDAO = 0;
if(_pid == 4){
// In case of CHIP/BNB pool, users have to pay 3% fee when they withdraw.
FeeToDAO = _amount.mul(3).div(100);
}
if(FeeToDAO > 0) pool.lpToken.safeTransfer(DAO, FeeToDAO);
pool.lpToken.safeTransfer(_sender, _amount.sub(FeeToDAO));
user.amount = user.amount.sub(_amount);
}
user.rewardDebt = user.amount.mul(pool.accChipsPerShare).div(1e18);
emit Withdraw(_sender, _pid, _amount);
}
// Withdraw without caring about rewards. Emergency only.
function emergencyWithdraw(uint256 _pid) external {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 _amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(msg.sender, _amount);
emit EmergencyWithdraw(msg.sender, _pid, _amount);
}
// Safe CHIPs transfer function, just in case if rounding error causes pool to not have enough CHIPs.
function safeChipsTransfer(address _to, uint256 _amount) internal {
uint256 _CHIPSBal = CHIPS.balanceOf(address(this));
if (_CHIPSBal > 0) {
if (_amount > _CHIPSBal) {
CHIPS.safeTransfer(_to, _CHIPSBal);
} else {
CHIPS.safeTransfer(_to, _amount);
}
}
}
function governanceRecoverUnsupported(IERC20 _token, uint256 amount, address to) external onlyOperator {
require(block.number > timeLockBlock, "ChipRewardPool: locked");
if (block.number < endBlock + BLOCKS_PER_DAY * 180) {
// Do not allow to drain lpToken if less than 180 days after farming.
require(_token != CHIPS, "ChipRewardPool.governanceRecoverUnsupported(): Not a chip token.");
uint256 length = poolInfo.length;
require(length < 6, "ChipRewardPool.governanceRecoverUnsupported(): Pool size exceeded.");
for (uint256 pid = 0; pid < length; ++pid) {
PoolInfo storage pool = poolInfo[pid];
require(_token != pool.lpToken, "ChipRewardPool.governanceRecoverUnsupported(): Skipping liquidity provider token.");
}
}
_token.safeTransfer(to, amount);
}
function getPoolStatus() external view returns(uint256) {
uint256 status;
if(block.number <= startBlock) status = 0;
else if(block.number > endBlock) status = 2;
else status = 1;
return status;
}
}
|
Update reward variables for all pools. Be careful of gas spending!
|
function massUpdatePools() internal {
uint256 length = poolInfo.length;
require(length < 6, "ChipRewardPool.massUpdatePools(): Pool size exceeded.");
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
| 1,773,189
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
contract Owned {
address payable internal owner;
event feePaid(address to, uint256 amount);
// creator is owner
constructor() {
owner = payable(msg.sender);
}
// only owner is allowed to call restricted function
modifier restrict {
require(msg.sender == owner, "access denied, you are not the contract owner");
_;
}
// requires a fee for the owner
modifier fee(uint256 amount) {
require(msg.value >= amount, "not enough payment for the fee");
_;
owner.transfer(amount);
emit feePaid(owner, amount);
}
function getOwner() public view returns (address payable) {
return owner;
}
// allow update of the owner
function changeOwner(address payable newOwner) public restrict {
owner = newOwner;
}
// move whole balance to the owner
function withdraw() public restrict {
owner.transfer(address(this).balance);
}
}
|
allow update of the owner
|
function changeOwner(address payable newOwner) public restrict {
owner = newOwner;
}
| 7,272,158
|
pragma solidity ^0.5.0;
contract Voting {
struct Proposal {
string title;
uint256 voteCountPos;
uint256 voteCountNeg;
uint256 voteCountAbs;
mapping(address => Voter) voters;
address[] votersAddress;
}
struct Voter {
uint256 value;
bool voted;
}
Proposal[] public proposals;
event CreatedProposalEvent();
event CreatedVoteEvent();
function getNumProposals() public view returns (uint256) {
return proposals.length;
}
function getProposal(uint256 proposalInt)
public
view
returns (
uint256,
string memory,
uint256,
uint256,
uint256,
address[] memory
)
{
if (proposals.length > 0) {
Proposal storage p = proposals[proposalInt]; // Get the proposal
return (
proposalInt,
p.title,
p.voteCountPos,
p.voteCountNeg,
p.voteCountAbs,
p.votersAddress
);
}
}
function addProposal(string memory title) public returns (bool) {
Proposal memory proposal;
emit CreatedProposalEvent();
proposal.title = title;
proposals.push(proposal);
return true;
}
function vote(uint256 proposalInt, uint256 voteValue)
public
returns (bool)
{
if (proposals[proposalInt].voters[msg.sender].voted == false) {
// check duplicate key
require(voteValue == 1 || voteValue == 2 || voteValue == 3); // check voteValue
Proposal storage p = proposals[proposalInt]; // Get the proposal
if (voteValue == 1) {
p.voteCountPos += 1;
} else if (voteValue == 2) {
p.voteCountNeg += 1;
} else {
p.voteCountAbs += 1;
}
p.voters[msg.sender].value = voteValue;
p.voters[msg.sender].voted = true;
p.votersAddress.push(msg.sender);
emit CreatedVoteEvent();
return true;
} else {
return false;
}
}
}
|
check duplicate key
|
function vote(uint256 proposalInt, uint256 voteValue)
public
returns (bool)
{
if (proposals[proposalInt].voters[msg.sender].voted == false) {
if (voteValue == 1) {
p.voteCountPos += 1;
p.voteCountNeg += 1;
p.voteCountAbs += 1;
}
p.voters[msg.sender].value = voteValue;
p.voters[msg.sender].voted = true;
p.votersAddress.push(msg.sender);
emit CreatedVoteEvent();
return true;
return false;
}
}
| 12,604,856
|
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./TradingAction.sol";
import "./ActionGuards.sol";
import "./nTokenMintAction.sol";
import "./nTokenRedeemAction.sol";
import "../SettleAssetsExternal.sol";
import "../FreeCollateralExternal.sol";
import "../../math/SafeInt256.sol";
import "../../global/StorageLayoutV1.sol";
import "../../internal/balances/BalanceHandler.sol";
import "../../internal/portfolio/PortfolioHandler.sol";
import "../../internal/AccountContextHandler.sol";
import "../../../interfaces/notional/NotionalCallback.sol";
contract BatchAction is StorageLayoutV1, ActionGuards {
using BalanceHandler for BalanceState;
using PortfolioHandler for PortfolioState;
using AccountContextHandler for AccountContext;
using SafeInt256 for int256;
/// @notice Executes a batch of balance transfers including minting and redeeming nTokens.
/// @param account the account for the action
/// @param actions array of balance actions to take, must be sorted by currency id
/// @dev emit:CashBalanceChange, emit:nTokenSupplyChange
/// @dev auth:msg.sender auth:ERC1155
function batchBalanceAction(address account, BalanceAction[] calldata actions)
external
payable
nonReentrant
{
require(account == msg.sender || msg.sender == address(this), "Unauthorized");
requireValidAccount(account);
// Return any settle amounts here to reduce the number of storage writes to balances
AccountContext memory accountContext = _settleAccountIfRequired(account);
BalanceState memory balanceState;
for (uint256 i = 0; i < actions.length; i++) {
BalanceAction calldata action = actions[i];
// msg.value will only be used when currency id == 1, referencing ETH. The requirement
// to sort actions by increasing id enforces that msg.value will only be used once.
if (i > 0) {
require(action.currencyId > actions[i - 1].currencyId, "Unsorted actions");
}
// Loads the currencyId into balance state
balanceState.loadBalanceState(account, action.currencyId, accountContext);
_executeDepositAction(
account,
balanceState,
action.actionType,
action.depositActionAmount
);
_calculateWithdrawActionAndFinalize(
account,
accountContext,
balanceState,
action.withdrawAmountInternalPrecision,
action.withdrawEntireCashBalance,
action.redeemToUnderlying
);
}
_finalizeAccountContext(account, accountContext);
}
/// @notice Executes a batch of balance transfers and trading actions
/// @param account the account for the action
/// @param actions array of balance actions with trades to take, must be sorted by currency id
/// @dev emit:CashBalanceChange, emit:nTokenSupplyChange, emit:LendBorrowTrade, emit:AddRemoveLiquidity,
/// @dev emit:SettledCashDebt, emit:nTokenResidualPurchase, emit:ReserveFeeAccrued
/// @dev auth:msg.sender auth:ERC1155
function batchBalanceAndTradeAction(address account, BalanceActionWithTrades[] calldata actions)
external
payable
nonReentrant
{
require(account == msg.sender || msg.sender == address(this), "Unauthorized");
requireValidAccount(account);
AccountContext memory accountContext = _batchBalanceAndTradeAction(account, actions);
_finalizeAccountContext(account, accountContext);
}
/// @notice Executes a batch of balance transfers and trading actions via an authorized callback contract. This
/// can be used as a "flash loan" facility for special contracts that migrate assets between protocols or perform
/// other actions on behalf of the user.
/// Contracts can borrow from Notional and receive a callback prior to an FC check, this can be useful if the contract
/// needs to perform a trade or repay a debt on a different protocol before depositing collateral. Since Notional's AMM
/// will never be as capital efficient or gas efficient as other flash loan facilities, this method requires whitelisting
/// and will mainly be used for contracts that make migrating assets a better user experience.
/// @param account the account that will take all the actions
/// @param actions array of balance actions with trades to take, must be sorted by currency id
/// @param callbackData arbitrary bytes to be passed backed to the caller in the callback
/// @dev emit:CashBalanceChange, emit:nTokenSupplyChange, emit:LendBorrowTrade, emit:AddRemoveLiquidity,
/// @dev emit:SettledCashDebt, emit:nTokenResidualPurchase, emit:ReserveFeeAccrued
/// @dev auth:authorizedCallbackContract
function batchBalanceAndTradeActionWithCallback(
address account,
BalanceActionWithTrades[] calldata actions,
bytes calldata callbackData
) external payable {
// NOTE: Re-entrancy is allowed for authorized callback functions.
require(authorizedCallbackContract[msg.sender], "Unauthorized");
requireValidAccount(account);
AccountContext memory accountContext = _batchBalanceAndTradeAction(account, actions);
accountContext.setAccountContext(account);
// Be sure to set the account context before initiating the callback, all stateful updates
// have been finalized at this point so we are safe to issue a callback. This callback may
// re-enter Notional safely to deposit or take other actions.
NotionalCallback(msg.sender).notionalCallback(msg.sender, account, callbackData);
if (accountContext.hasDebt != 0x00) {
// NOTE: this method may update the account context to turn off the hasDebt flag, this
// is ok because the worst case would be causing an extra free collateral check when it
// is not required. This check will be entered if the account hasDebt prior to the callback
// being triggered above, so it will happen regardless of what the callback function does.
FreeCollateralExternal.checkFreeCollateralAndRevert(account);
}
}
function _batchBalanceAndTradeAction(
address account,
BalanceActionWithTrades[] calldata actions
) internal returns (AccountContext memory) {
AccountContext memory accountContext = _settleAccountIfRequired(account);
BalanceState memory balanceState;
// NOTE: loading the portfolio state must happen after settle account to get the
// correct portfolio, it will have changed if the account is settled.
PortfolioState memory portfolioState = PortfolioHandler.buildPortfolioState(
account,
accountContext.assetArrayLength,
0
);
for (uint256 i = 0; i < actions.length; i++) {
BalanceActionWithTrades calldata action = actions[i];
// msg.value will only be used when currency id == 1, referencing ETH. The requirement
// to sort actions by increasing id enforces that msg.value will only be used once.
if (i > 0) {
require(action.currencyId > actions[i - 1].currencyId, "Unsorted actions");
}
// Loads the currencyId into balance state
balanceState.loadBalanceState(account, action.currencyId, accountContext);
// Does not revert on invalid action types here, they also have no effect.
_executeDepositAction(
account,
balanceState,
action.actionType,
action.depositActionAmount
);
if (action.trades.length > 0) {
int256 netCash;
if (accountContext.isBitmapEnabled()) {
require(
accountContext.bitmapCurrencyId == action.currencyId,
"Invalid trades for account"
);
bool didIncurDebt;
(netCash, didIncurDebt) = TradingAction.executeTradesBitmapBatch(
account,
accountContext.bitmapCurrencyId,
accountContext.nextSettleTime,
action.trades
);
if (didIncurDebt) {
accountContext.hasDebt = Constants.HAS_ASSET_DEBT | accountContext.hasDebt;
}
} else {
// NOTE: we return portfolio state here instead of setting it inside executeTradesArrayBatch
// because we want to only write to storage once after all trades are completed
(portfolioState, netCash) = TradingAction.executeTradesArrayBatch(
account,
action.currencyId,
portfolioState,
action.trades
);
}
// If the account owes cash after trading, ensure that it has enough
if (netCash < 0) _checkSufficientCash(balanceState, netCash.neg());
balanceState.netCashChange = balanceState.netCashChange.add(netCash);
}
_calculateWithdrawActionAndFinalize(
account,
accountContext,
balanceState,
action.withdrawAmountInternalPrecision,
action.withdrawEntireCashBalance,
action.redeemToUnderlying
);
}
// Update the portfolio state if bitmap is not enabled. If bitmap is already enabled
// then all the assets have already been updated in in storage.
if (!accountContext.isBitmapEnabled()) {
// NOTE: account context is updated in memory inside this method call.
accountContext.storeAssetsAndUpdateContext(account, portfolioState, false);
}
// NOTE: free collateral and account context will be set outside of this method call.
return accountContext;
}
/// @dev Executes deposits
function _executeDepositAction(
address account,
BalanceState memory balanceState,
DepositActionType depositType,
uint256 depositActionAmount_
) private {
int256 depositActionAmount = SafeInt256.toInt(depositActionAmount_);
int256 assetInternalAmount;
require(depositActionAmount >= 0);
if (depositType == DepositActionType.None) {
return;
} else if (
depositType == DepositActionType.DepositAsset ||
depositType == DepositActionType.DepositAssetAndMintNToken
) {
// NOTE: this deposit will NOT revert on a failed transfer unless there is a
// transfer fee. The actual transfer will take effect later in balanceState.finalize
assetInternalAmount = balanceState.depositAssetToken(
account,
depositActionAmount,
false // no force transfer
);
} else if (
depositType == DepositActionType.DepositUnderlying ||
depositType == DepositActionType.DepositUnderlyingAndMintNToken
) {
// NOTE: this deposit will revert on a failed transfer immediately
assetInternalAmount = balanceState.depositUnderlyingToken(account, depositActionAmount);
} else if (depositType == DepositActionType.ConvertCashToNToken) {
// _executeNTokenAction will check if the account has sufficient cash
assetInternalAmount = depositActionAmount;
}
_executeNTokenAction(
balanceState,
depositType,
depositActionAmount,
assetInternalAmount
);
}
/// @dev Executes nToken actions
function _executeNTokenAction(
BalanceState memory balanceState,
DepositActionType depositType,
int256 depositActionAmount,
int256 assetInternalAmount
) private {
// After deposits have occurred, check if we are minting nTokens
if (
depositType == DepositActionType.DepositAssetAndMintNToken ||
depositType == DepositActionType.DepositUnderlyingAndMintNToken ||
depositType == DepositActionType.ConvertCashToNToken
) {
// Will revert if trying to mint ntokens and results in a negative cash balance
_checkSufficientCash(balanceState, assetInternalAmount);
balanceState.netCashChange = balanceState.netCashChange.sub(assetInternalAmount);
// Converts a given amount of cash (denominated in internal precision) into nTokens
int256 tokensMinted = nTokenMintAction.nTokenMint(
balanceState.currencyId,
assetInternalAmount
);
balanceState.netNTokenSupplyChange = balanceState.netNTokenSupplyChange.add(
tokensMinted
);
} else if (depositType == DepositActionType.RedeemNToken) {
require(
// prettier-ignore
balanceState
.storedNTokenBalance
.add(balanceState.netNTokenTransfer) // transfers would not occur at this point
.add(balanceState.netNTokenSupplyChange) >= depositActionAmount,
"Insufficient token balance"
);
balanceState.netNTokenSupplyChange = balanceState.netNTokenSupplyChange.sub(
depositActionAmount
);
int256 assetCash = nTokenRedeemAction.nTokenRedeemViaBatch(
balanceState.currencyId,
depositActionAmount
);
balanceState.netCashChange = balanceState.netCashChange.add(assetCash);
}
}
/// @dev Calculations any withdraws and finalizes balances
function _calculateWithdrawActionAndFinalize(
address account,
AccountContext memory accountContext,
BalanceState memory balanceState,
uint256 withdrawAmountInternalPrecision,
bool withdrawEntireCashBalance,
bool redeemToUnderlying
) private {
int256 withdrawAmount = SafeInt256.toInt(withdrawAmountInternalPrecision);
require(withdrawAmount >= 0); // dev: withdraw action overflow
// NOTE: if withdrawEntireCashBalance is set it will override the withdrawAmountInternalPrecision input
if (withdrawEntireCashBalance) {
// This option is here so that accounts do not end up with dust after lending since we generally
// cannot calculate exact cash amounts from the liquidity curve.
withdrawAmount = balanceState.storedCashBalance
.add(balanceState.netCashChange)
.add(balanceState.netAssetTransferInternalPrecision);
// If the account has a negative cash balance then cannot withdraw
if (withdrawAmount < 0) withdrawAmount = 0;
}
// prettier-ignore
balanceState.netAssetTransferInternalPrecision = balanceState
.netAssetTransferInternalPrecision
.sub(withdrawAmount);
balanceState.finalize(account, accountContext, redeemToUnderlying);
}
function _finalizeAccountContext(address account, AccountContext memory accountContext)
private
{
// At this point all balances, market states and portfolio states should be finalized. Just need to check free
// collateral if required.
accountContext.setAccountContext(account);
if (accountContext.hasDebt != 0x00) {
FreeCollateralExternal.checkFreeCollateralAndRevert(account);
}
}
/// @notice When lending, adding liquidity or minting nTokens the account must have a sufficient cash balance
/// to do so.
function _checkSufficientCash(BalanceState memory balanceState, int256 amountInternalPrecision)
private
pure
{
// The total cash position at this point is: storedCashBalance + netCashChange + netAssetTransferInternalPrecision
require(
amountInternalPrecision >= 0 &&
balanceState.storedCashBalance
.add(balanceState.netCashChange)
.add(balanceState.netAssetTransferInternalPrecision) >= amountInternalPrecision,
"Insufficient cash"
);
}
function _settleAccountIfRequired(address account)
private
returns (AccountContext memory)
{
AccountContext memory accountContext = AccountContextHandler.getAccountContext(account);
if (accountContext.mustSettleAssets()) {
// Returns a new memory reference to account context
return SettleAssetsExternal.settleAccount(account, accountContext);
} else {
return accountContext;
}
}
/// @notice Get a list of deployed library addresses (sorted by library name)
function getLibInfo() external view returns (address, address, address, address, address, address) {
return (
address(FreeCollateralExternal),
address(MigrateIncentives),
address(SettleAssetsExternal),
address(TradingAction),
address(nTokenMintAction),
address(nTokenRedeemAction)
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../FreeCollateralExternal.sol";
import "../SettleAssetsExternal.sol";
import "../../internal/markets/Market.sol";
import "../../internal/markets/CashGroup.sol";
import "../../internal/markets/AssetRate.sol";
import "../../internal/balances/BalanceHandler.sol";
import "../../internal/portfolio/PortfolioHandler.sol";
import "../../internal/portfolio/TransferAssets.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library TradingAction {
using PortfolioHandler for PortfolioState;
using AccountContextHandler for AccountContext;
using Market for MarketParameters;
using CashGroup for CashGroupParameters;
using AssetRate for AssetRateParameters;
using SafeInt256 for int256;
using SafeMath for uint256;
event LendBorrowTrade(
address indexed account,
uint16 indexed currencyId,
uint40 maturity,
int256 netAssetCash,
int256 netfCash
);
event AddRemoveLiquidity(
address indexed account,
uint16 indexed currencyId,
uint40 maturity,
int256 netAssetCash,
int256 netfCash,
int256 netLiquidityTokens
);
event SettledCashDebt(
address indexed settledAccount,
uint16 indexed currencyId,
address indexed settler,
int256 amountToSettleAsset,
int256 fCashAmount
);
event nTokenResidualPurchase(
uint16 indexed currencyId,
uint40 indexed maturity,
address indexed purchaser,
int256 fCashAmountToPurchase,
int256 netAssetCashNToken
);
/// @dev Used internally to manage stack issues
struct TradeContext {
int256 cash;
int256 fCashAmount;
int256 fee;
int256 netCash;
int256 totalFee;
uint256 blockTime;
}
/// @notice Executes trades for a bitmapped portfolio, cannot be called directly
/// @param account account to put fCash assets in
/// @param bitmapCurrencyId currency id of the bitmap
/// @param nextSettleTime used to calculate the relative positions in the bitmap
/// @param trades tightly packed array of trades, schema is defined in global/Types.sol
/// @return netCash generated by trading
/// @return didIncurDebt if the bitmap had an fCash position go negative
function executeTradesBitmapBatch(
address account,
uint16 bitmapCurrencyId,
uint40 nextSettleTime,
bytes32[] calldata trades
) external returns (int256, bool) {
CashGroupParameters memory cashGroup = CashGroup.buildCashGroupStateful(bitmapCurrencyId);
MarketParameters memory market;
bool didIncurDebt;
TradeContext memory c;
c.blockTime = block.timestamp;
for (uint256 i = 0; i < trades.length; i++) {
uint256 maturity;
(maturity, c.cash, c.fCashAmount) = _executeTrade(
account,
cashGroup,
market,
trades[i],
c.blockTime
);
c.fCashAmount = BitmapAssetsHandler.addifCashAsset(
account,
bitmapCurrencyId,
maturity,
nextSettleTime,
c.fCashAmount
);
didIncurDebt = didIncurDebt || (c.fCashAmount < 0);
c.netCash = c.netCash.add(c.cash);
}
return (c.netCash, didIncurDebt);
}
/// @notice Executes trades for a bitmapped portfolio, cannot be called directly
/// @param account account to put fCash assets in
/// @param currencyId currency id to trade
/// @param portfolioState used to update the positions in the portfolio
/// @param trades tightly packed array of trades, schema is defined in global/Types.sol
/// @return resulting portfolio state
/// @return netCash generated by trading
function executeTradesArrayBatch(
address account,
uint16 currencyId,
PortfolioState memory portfolioState,
bytes32[] calldata trades
) external returns (PortfolioState memory, int256) {
CashGroupParameters memory cashGroup = CashGroup.buildCashGroupStateful(currencyId);
MarketParameters memory market;
TradeContext memory c;
c.blockTime = block.timestamp;
for (uint256 i = 0; i < trades.length; i++) {
TradeActionType tradeType = TradeActionType(uint256(uint8(bytes1(trades[i]))));
if (
tradeType == TradeActionType.AddLiquidity ||
tradeType == TradeActionType.RemoveLiquidity
) {
revert("Disabled");
/**
* Manual adding and removing of liquidity is currently disabled.
*
* // Liquidity tokens can only be added by array portfolio
* c.cash = _executeLiquidityTrade(
* account,
* cashGroup,
* market,
* tradeType,
* trades[i],
* portfolioState,
* c.netCash
* );
*/
} else {
uint256 maturity;
(maturity, c.cash, c.fCashAmount) = _executeTrade(
account,
cashGroup,
market,
trades[i],
c.blockTime
);
portfolioState.addAsset(
currencyId,
maturity,
Constants.FCASH_ASSET_TYPE,
c.fCashAmount
);
}
c.netCash = c.netCash.add(c.cash);
}
return (portfolioState, c.netCash);
}
/// @notice Executes a non-liquidity token trade
/// @param account the initiator of the trade
/// @param cashGroup parameters for the trade
/// @param market market memory location to use
/// @param trade bytes32 encoding of the particular trade
/// @param blockTime the current block time
/// @return maturity of the asset that was traded
/// @return cashAmount - a positive or negative cash amount accrued to the account
/// @return fCashAmount - a positive or negative fCash amount accrued to the account
function _executeTrade(
address account,
CashGroupParameters memory cashGroup,
MarketParameters memory market,
bytes32 trade,
uint256 blockTime
)
private
returns (
uint256 maturity,
int256 cashAmount,
int256 fCashAmount
)
{
TradeActionType tradeType = TradeActionType(uint256(uint8(bytes1(trade))));
if (tradeType == TradeActionType.PurchaseNTokenResidual) {
(maturity, cashAmount, fCashAmount) = _purchaseNTokenResidual(
account,
cashGroup,
blockTime,
trade
);
} else if (tradeType == TradeActionType.SettleCashDebt) {
(maturity, cashAmount, fCashAmount) = _settleCashDebt(account, cashGroup, blockTime, trade);
} else if (tradeType == TradeActionType.Lend || tradeType == TradeActionType.Borrow) {
(cashAmount, fCashAmount) = _executeLendBorrowTrade(
cashGroup,
market,
tradeType,
blockTime,
trade
);
// This is a little ugly but required to deal with stack issues. We know the market is loaded
// with the proper maturity inside _executeLendBorrowTrade
maturity = market.maturity;
emit LendBorrowTrade(
account,
uint16(cashGroup.currencyId),
uint40(maturity),
cashAmount,
fCashAmount
);
} else {
revert("Invalid trade type");
}
}
/// @notice Executes a liquidity token trade, no fees incurred and only array portfolios may hold
/// liquidity tokens.
/// @param account the initiator of the trade
/// @param cashGroup parameters for the trade
/// @param market market memory location to use
/// @param tradeType whether this is add or remove liquidity
/// @param trade bytes32 encoding of the particular trade
/// @param portfolioState the current account's portfolio state
/// @param netCash the current net cash accrued in this batch of trades, can be
// used for adding liquidity
/// @return cashAmount: a positive or negative cash amount accrued to the account
function _executeLiquidityTrade(
address account,
CashGroupParameters memory cashGroup,
MarketParameters memory market,
TradeActionType tradeType,
bytes32 trade,
PortfolioState memory portfolioState,
int256 netCash
) private returns (int256) {
uint256 marketIndex = uint8(bytes1(trade << 8));
// NOTE: this loads the market in memory
cashGroup.loadMarket(market, marketIndex, true, block.timestamp);
int256 cashAmount;
int256 fCashAmount;
int256 tokens;
if (tradeType == TradeActionType.AddLiquidity) {
cashAmount = int256((uint256(trade) >> 152) & type(uint88).max);
// Setting cash amount to zero will deposit all net cash accumulated in this trade into
// liquidity. This feature allows accounts to borrow in one maturity to provide liquidity
// in another in a single transaction without dust. It also allows liquidity providers to
// sell off the net cash residuals and use the cash amount in the new market without dust
if (cashAmount == 0) cashAmount = netCash;
// Add liquidity will check cash amount is positive
(tokens, fCashAmount) = market.addLiquidity(cashAmount);
cashAmount = cashAmount.neg(); // Report a negative cash amount in the event
} else {
tokens = int256((uint256(trade) >> 152) & type(uint88).max);
(cashAmount, fCashAmount) = market.removeLiquidity(tokens);
tokens = tokens.neg(); // Report a negative amount tokens in the event
}
{
uint256 minImpliedRate = uint32(uint256(trade) >> 120);
uint256 maxImpliedRate = uint32(uint256(trade) >> 88);
// If minImpliedRate is not set then it will be zero
require(market.lastImpliedRate >= minImpliedRate, "Trade failed, slippage");
if (maxImpliedRate != 0)
require(market.lastImpliedRate <= maxImpliedRate, "Trade failed, slippage");
}
// Add the assets in this order so they are sorted
portfolioState.addAsset(
cashGroup.currencyId,
market.maturity,
Constants.FCASH_ASSET_TYPE,
fCashAmount
);
// Adds the liquidity token asset
portfolioState.addAsset(
cashGroup.currencyId,
market.maturity,
marketIndex + 1,
tokens
);
emit AddRemoveLiquidity(
account,
cashGroup.currencyId,
// This will not overflow for a long time
uint40(market.maturity),
cashAmount,
fCashAmount,
tokens
);
return cashAmount;
}
/// @notice Executes a lend or borrow trade
/// @param cashGroup parameters for the trade
/// @param market market memory location to use
/// @param tradeType whether this is add or remove liquidity
/// @param blockTime the current block time
/// @param trade bytes32 encoding of the particular trade
/// @return cashAmount - a positive or negative cash amount accrued to the account
/// @return fCashAmount - a positive or negative fCash amount accrued to the account
function _executeLendBorrowTrade(
CashGroupParameters memory cashGroup,
MarketParameters memory market,
TradeActionType tradeType,
uint256 blockTime,
bytes32 trade
)
private
returns (
int256 cashAmount,
int256 fCashAmount
)
{
uint256 marketIndex = uint256(uint8(bytes1(trade << 8)));
// NOTE: this updates the market in memory
cashGroup.loadMarket(market, marketIndex, false, blockTime);
fCashAmount = int256(uint88(bytes11(trade << 16)));
// fCash to account will be negative here
if (tradeType == TradeActionType.Borrow) fCashAmount = fCashAmount.neg();
cashAmount = market.executeTrade(
cashGroup,
fCashAmount,
market.maturity.sub(blockTime),
marketIndex
);
require(cashAmount != 0, "Trade failed, liquidity");
uint256 rateLimit = uint256(uint32(bytes4(trade << 104)));
if (rateLimit != 0) {
if (tradeType == TradeActionType.Borrow) {
// Do not allow borrows over the rate limit
require(market.lastImpliedRate <= rateLimit, "Trade failed, slippage");
} else {
// Do not allow lends under the rate limit
require(market.lastImpliedRate >= rateLimit, "Trade failed, slippage");
}
}
}
/// @notice If an account has a negative cash balance we allow anyone to lend to to that account at a penalty
/// rate to the 3 month market.
/// @param account the account initiating the trade, used to check that self settlement is not possible
/// @param cashGroup parameters for the trade
/// @param blockTime the current block time
/// @param trade bytes32 encoding of the particular trade
/// @return maturity: the date of the three month maturity where fCash will be exchanged
/// @return cashAmount: a negative cash amount that the account must pay to the settled account
/// @return fCashAmount: a positive fCash amount that the account will receive
function _settleCashDebt(
address account,
CashGroupParameters memory cashGroup,
uint256 blockTime,
bytes32 trade
)
internal
returns (
uint256,
int256,
int256
)
{
address counterparty = address(uint256(trade) >> 88);
// Allowing an account to settle itself would result in strange outcomes
require(account != counterparty, "Cannot settle self");
int256 amountToSettleAsset = int256(uint88(uint256(trade)));
AccountContext memory counterpartyContext =
AccountContextHandler.getAccountContext(counterparty);
if (counterpartyContext.mustSettleAssets()) {
counterpartyContext = SettleAssetsExternal.settleAccount(counterparty, counterpartyContext);
}
// This will check if the amountToSettleAsset is valid and revert if it is not. Amount to settle is a positive
// number denominated in asset terms. If amountToSettleAsset is set equal to zero on the input, will return the
// max amount to settle. This will update the balance storage on the counterparty.
amountToSettleAsset = BalanceHandler.setBalanceStorageForSettleCashDebt(
counterparty,
cashGroup,
amountToSettleAsset,
counterpartyContext
);
// Settled account must borrow from the 3 month market at a penalty rate. This will fail if the market
// is not initialized.
uint256 threeMonthMaturity = DateTime.getReferenceTime(blockTime) + Constants.QUARTER;
int256 fCashAmount =
_getfCashSettleAmount(cashGroup, threeMonthMaturity, blockTime, amountToSettleAsset);
// Defensive check to ensure that we can't inadvertently cause the settler to lose fCash.
require(fCashAmount >= 0);
// It's possible that this action will put an account into negative free collateral. In this case they
// will immediately become eligible for liquidation and the account settling the debt can also liquidate
// them in the same transaction. Do not run a free collateral check here to allow this to happen.
{
PortfolioAsset[] memory assets = new PortfolioAsset[](1);
assets[0].currencyId = cashGroup.currencyId;
assets[0].maturity = threeMonthMaturity;
assets[0].notional = fCashAmount.neg(); // This is the debt the settled account will incur
assets[0].assetType = Constants.FCASH_ASSET_TYPE;
// Can transfer assets, we have settled above
counterpartyContext = TransferAssets.placeAssetsInAccount(
counterparty,
counterpartyContext,
assets
);
}
counterpartyContext.setAccountContext(counterparty);
emit SettledCashDebt(
counterparty,
uint16(cashGroup.currencyId),
account,
amountToSettleAsset,
fCashAmount.neg()
);
return (threeMonthMaturity, amountToSettleAsset.neg(), fCashAmount);
}
/// @dev Helper method to calculate the fCashAmount from the penalty settlement rate
function _getfCashSettleAmount(
CashGroupParameters memory cashGroup,
uint256 threeMonthMaturity,
uint256 blockTime,
int256 amountToSettleAsset
) private view returns (int256) {
uint256 oracleRate = cashGroup.calculateOracleRate(threeMonthMaturity, blockTime);
int256 exchangeRate =
Market.getExchangeRateFromImpliedRate(
oracleRate.add(cashGroup.getSettlementPenalty()),
threeMonthMaturity.sub(blockTime)
);
// Amount to settle is positive, this returns the fCashAmount that the settler will
// receive as a positive number
return
cashGroup.assetRate
.convertToUnderlying(amountToSettleAsset)
// Exchange rate converts from cash to fCash when multiplying
.mulInRatePrecision(exchangeRate);
}
/// @notice Allows an account to purchase ntoken residuals
/// @param purchaser account that is purchasing the residuals
/// @param cashGroup parameters for the trade
/// @param blockTime the current block time
/// @param trade bytes32 encoding of the particular trade
/// @return maturity: the date of the idiosyncratic maturity where fCash will be exchanged
/// @return cashAmount: a positive or negative cash amount that the account will receive or pay
/// @return fCashAmount: a positive or negative fCash amount that the account will receive
function _purchaseNTokenResidual(
address purchaser,
CashGroupParameters memory cashGroup,
uint256 blockTime,
bytes32 trade
)
internal
returns (
uint256,
int256,
int256
)
{
uint256 maturity = uint256(uint32(uint256(trade) >> 216));
int256 fCashAmountToPurchase = int88(uint88(uint256(trade) >> 128));
require(maturity > blockTime, "Invalid maturity");
// Require that the residual to purchase does not fall on an existing maturity (i.e.
// it is an idiosyncratic maturity)
require(
!DateTime.isValidMarketMaturity(cashGroup.maxMarketIndex, maturity, blockTime),
"Non idiosyncratic maturity"
);
address nTokenAddress = nTokenHandler.nTokenAddress(cashGroup.currencyId);
// prettier-ignore
(
/* currencyId */,
/* incentiveRate */,
uint256 lastInitializedTime,
/* assetArrayLength */,
bytes5 parameters
) = nTokenHandler.getNTokenContext(nTokenAddress);
// Restrict purchasing until some amount of time after the last initialized time to ensure that arbitrage
// opportunities are not available (by generating residuals and then immediately purchasing them at a discount)
// This is always relative to the last initialized time which is set at utc0 when initialized, not the
// reference time. Therefore we will always restrict residual purchase relative to initialization, not reference.
// This is safer, prevents an attack if someone forces residuals and then somehow prevents market initialization
// until the residual time buffer passes.
require(
blockTime >
lastInitializedTime.add(
uint256(uint8(parameters[Constants.RESIDUAL_PURCHASE_TIME_BUFFER])) * 1 hours
),
"Insufficient block time"
);
int256 notional =
BitmapAssetsHandler.getifCashNotional(nTokenAddress, cashGroup.currencyId, maturity);
// Check if amounts are valid and set them to the max available if necessary
if (notional < 0 && fCashAmountToPurchase < 0) {
// Does not allow purchasing more negative notional than available
if (fCashAmountToPurchase < notional) fCashAmountToPurchase = notional;
} else if (notional > 0 && fCashAmountToPurchase > 0) {
// Does not allow purchasing more positive notional than available
if (fCashAmountToPurchase > notional) fCashAmountToPurchase = notional;
} else {
// Does not allow moving notional in the opposite direction
revert("Invalid amount");
}
// If fCashAmount > 0 then this will return netAssetCash > 0, if fCashAmount < 0 this will return
// netAssetCash < 0. fCashAmount will go to the purchaser and netAssetCash will go to the nToken.
int256 netAssetCashNToken =
_getResidualPriceAssetCash(
cashGroup,
maturity,
blockTime,
fCashAmountToPurchase,
parameters
);
_updateNTokenPortfolio(
nTokenAddress,
cashGroup.currencyId,
maturity,
lastInitializedTime,
fCashAmountToPurchase,
netAssetCashNToken
);
emit nTokenResidualPurchase(
uint16(cashGroup.currencyId),
uint40(maturity),
purchaser,
fCashAmountToPurchase,
netAssetCashNToken
);
return (maturity, netAssetCashNToken.neg(), fCashAmountToPurchase);
}
/// @notice Returns the amount of asset cash required to purchase the nToken residual
function _getResidualPriceAssetCash(
CashGroupParameters memory cashGroup,
uint256 maturity,
uint256 blockTime,
int256 fCashAmount,
bytes6 parameters
) internal view returns (int256) {
uint256 oracleRate = cashGroup.calculateOracleRate(maturity, blockTime);
// Residual purchase incentive is specified in ten basis point increments
uint256 purchaseIncentive =
uint256(uint8(parameters[Constants.RESIDUAL_PURCHASE_INCENTIVE])) *
Constants.TEN_BASIS_POINTS;
if (fCashAmount > 0) {
// When fCash is positive then we add the purchase incentive, the purchaser
// can pay less cash for the fCash relative to the oracle rate
oracleRate = oracleRate.add(purchaseIncentive);
} else if (oracleRate > purchaseIncentive) {
// When fCash is negative, we reduce the interest rate that the purchaser will
// borrow at, we do this check to ensure that we floor the oracle rate at zero.
oracleRate = oracleRate.sub(purchaseIncentive);
} else {
// If the oracle rate is less than the purchase incentive floor the interest rate at zero
oracleRate = 0;
}
int256 exchangeRate =
Market.getExchangeRateFromImpliedRate(oracleRate, maturity.sub(blockTime));
// Returns the net asset cash from the nToken perspective, which is the same sign as the fCash amount
return
cashGroup.assetRate.convertFromUnderlying(fCashAmount.divInRatePrecision(exchangeRate));
}
function _updateNTokenPortfolio(
address nTokenAddress,
uint256 currencyId,
uint256 maturity,
uint256 lastInitializedTime,
int256 fCashAmountToPurchase,
int256 netAssetCashNToken
) private {
int256 finalNotional = BitmapAssetsHandler.addifCashAsset(
nTokenAddress,
currencyId,
maturity,
lastInitializedTime,
fCashAmountToPurchase.neg() // the nToken takes on the negative position
);
// Defensive check to ensure that fCash amounts do not flip signs
require(
(fCashAmountToPurchase > 0 && finalNotional >= 0) ||
(fCashAmountToPurchase < 0 && finalNotional <= 0)
);
// prettier-ignore
(
int256 nTokenCashBalance,
/* storedNTokenBalance */,
/* lastClaimTime */,
/* accountIncentiveDebt */
) = BalanceHandler.getBalanceStorage(nTokenAddress, currencyId);
nTokenCashBalance = nTokenCashBalance.add(netAssetCashNToken);
// This will ensure that the cash balance is not negative
BalanceHandler.setBalanceStorageForNToken(nTokenAddress, currencyId, nTokenCashBalance);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/StorageLayoutV1.sol";
import "../../internal/nToken/nTokenHandler.sol";
abstract contract ActionGuards is StorageLayoutV1 {
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
function initializeReentrancyGuard() internal {
require(reentrancyStatus == 0);
// Initialize the guard to a non-zero value, see the OZ reentrancy guard
// description for why this is more gas efficient:
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol
reentrancyStatus = _NOT_ENTERED;
}
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(reentrancyStatus != _ENTERED, "Reentrant call");
// Any calls to nonReentrant after this point will fail
reentrancyStatus = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
reentrancyStatus = _NOT_ENTERED;
}
// These accounts cannot receive deposits, transfers, fCash or any other
// types of value transfers.
function requireValidAccount(address account) internal view {
require(account != Constants.RESERVE); // Reserve address is address(0)
require(account != address(this));
(
uint256 isNToken,
/* incentiveAnnualEmissionRate */,
/* lastInitializedTime */,
/* assetArrayLength */,
/* parameters */
) = nTokenHandler.getNTokenContext(account);
require(isNToken == 0);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/Constants.sol";
import "../../internal/nToken/nTokenHandler.sol";
import "../../internal/nToken/nTokenCalculations.sol";
import "../../internal/markets/Market.sol";
import "../../internal/markets/CashGroup.sol";
import "../../internal/markets/AssetRate.sol";
import "../../internal/balances/BalanceHandler.sol";
import "../../internal/portfolio/PortfolioHandler.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library nTokenMintAction {
using SafeInt256 for int256;
using BalanceHandler for BalanceState;
using CashGroup for CashGroupParameters;
using Market for MarketParameters;
using nTokenHandler for nTokenPortfolio;
using PortfolioHandler for PortfolioState;
using AssetRate for AssetRateParameters;
using SafeMath for uint256;
using nTokenHandler for nTokenPortfolio;
/// @notice Converts the given amount of cash to nTokens in the same currency.
/// @param currencyId the currency associated the nToken
/// @param amountToDepositInternal the amount of asset tokens to deposit denominated in internal decimals
/// @return nTokens minted by this action
function nTokenMint(uint16 currencyId, int256 amountToDepositInternal)
external
returns (int256)
{
uint256 blockTime = block.timestamp;
nTokenPortfolio memory nToken;
nToken.loadNTokenPortfolioStateful(currencyId);
int256 tokensToMint = calculateTokensToMint(nToken, amountToDepositInternal, blockTime);
require(tokensToMint >= 0, "Invalid token amount");
if (nToken.portfolioState.storedAssets.length == 0) {
// If the token does not have any assets, then the markets must be initialized first.
nToken.cashBalance = nToken.cashBalance.add(amountToDepositInternal);
BalanceHandler.setBalanceStorageForNToken(
nToken.tokenAddress,
currencyId,
nToken.cashBalance
);
} else {
_depositIntoPortfolio(nToken, amountToDepositInternal, blockTime);
}
// NOTE: token supply does not change here, it will change after incentives have been claimed
// during BalanceHandler.finalize
return tokensToMint;
}
/// @notice Calculates the tokens to mint to the account as a ratio of the nToken
/// present value denominated in asset cash terms.
/// @return the amount of tokens to mint, the ifCash bitmap
function calculateTokensToMint(
nTokenPortfolio memory nToken,
int256 amountToDepositInternal,
uint256 blockTime
) internal view returns (int256) {
require(amountToDepositInternal >= 0); // dev: deposit amount negative
if (amountToDepositInternal == 0) return 0;
if (nToken.lastInitializedTime != 0) {
// For the sake of simplicity, nTokens cannot be minted if they have assets
// that need to be settled. This is only done during market initialization.
uint256 nextSettleTime = nToken.getNextSettleTime();
// If next settle time <= blockTime then the token can be settled
require(nextSettleTime > blockTime, "Requires settlement");
}
int256 assetCashPV = nTokenCalculations.getNTokenAssetPV(nToken, blockTime);
// Defensive check to ensure PV remains positive
require(assetCashPV >= 0);
// Allow for the first deposit
if (nToken.totalSupply == 0) {
return amountToDepositInternal;
} else {
// assetCashPVPost = assetCashPV + amountToDeposit
// (tokenSupply + tokensToMint) / tokenSupply == (assetCashPV + amountToDeposit) / assetCashPV
// (tokenSupply + tokensToMint) == (assetCashPV + amountToDeposit) * tokenSupply / assetCashPV
// (tokenSupply + tokensToMint) == tokenSupply + (amountToDeposit * tokenSupply) / assetCashPV
// tokensToMint == (amountToDeposit * tokenSupply) / assetCashPV
return amountToDepositInternal.mul(nToken.totalSupply).div(assetCashPV);
}
}
/// @notice Portions out assetCashDeposit into amounts to deposit into individual markets. When
/// entering this method we know that assetCashDeposit is positive and the nToken has been
/// initialized to have liquidity tokens.
function _depositIntoPortfolio(
nTokenPortfolio memory nToken,
int256 assetCashDeposit,
uint256 blockTime
) private {
(int256[] memory depositShares, int256[] memory leverageThresholds) =
nTokenHandler.getDepositParameters(
nToken.cashGroup.currencyId,
nToken.cashGroup.maxMarketIndex
);
// Loop backwards from the last market to the first market, the reasoning is a little complicated:
// If we have to deleverage the markets (i.e. lend instead of provide liquidity) it's quite gas inefficient
// to calculate the cash amount to lend. We do know that longer term maturities will have more
// slippage and therefore the residual from the perMarketDeposit will be lower as the maturities get
// closer to the current block time. Any residual cash from lending will be rolled into shorter
// markets as this loop progresses.
int256 residualCash;
MarketParameters memory market;
for (uint256 marketIndex = nToken.cashGroup.maxMarketIndex; marketIndex > 0; marketIndex--) {
int256 fCashAmount;
// Loads values into the market memory slot
nToken.cashGroup.loadMarket(
market,
marketIndex,
true, // Needs liquidity to true
blockTime
);
// If market has not been initialized, continue. This can occur when cash groups extend maxMarketIndex
// before initializing
if (market.totalLiquidity == 0) continue;
// Checked that assetCashDeposit must be positive before entering
int256 perMarketDeposit =
assetCashDeposit
.mul(depositShares[marketIndex - 1])
.div(Constants.DEPOSIT_PERCENT_BASIS)
.add(residualCash);
(fCashAmount, residualCash) = _lendOrAddLiquidity(
nToken,
market,
perMarketDeposit,
leverageThresholds[marketIndex - 1],
marketIndex,
blockTime
);
if (fCashAmount != 0) {
BitmapAssetsHandler.addifCashAsset(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
market.maturity,
nToken.lastInitializedTime,
fCashAmount
);
}
}
// nToken is allowed to store assets directly without updating account context.
nToken.portfolioState.storeAssets(nToken.tokenAddress);
// Defensive check to ensure that we do not somehow accrue negative residual cash.
require(residualCash >= 0, "Negative residual cash");
// This will occur if the three month market is over levered and we cannot lend into it
if (residualCash > 0) {
// Any remaining residual cash will be put into the nToken balance and added as liquidity on the
// next market initialization
nToken.cashBalance = nToken.cashBalance.add(residualCash);
BalanceHandler.setBalanceStorageForNToken(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.cashBalance
);
}
}
/// @notice For a given amount of cash to deposit, decides how much to lend or provide
/// given the market conditions.
function _lendOrAddLiquidity(
nTokenPortfolio memory nToken,
MarketParameters memory market,
int256 perMarketDeposit,
int256 leverageThreshold,
uint256 marketIndex,
uint256 blockTime
) private returns (int256 fCashAmount, int256 residualCash) {
// We start off with the entire per market deposit as residuals
residualCash = perMarketDeposit;
// If the market is over leveraged then we will lend to it instead of providing liquidity
if (_isMarketOverLeveraged(nToken.cashGroup, market, leverageThreshold)) {
(residualCash, fCashAmount) = _deleverageMarket(
nToken.cashGroup,
market,
perMarketDeposit,
blockTime,
marketIndex
);
// Recalculate this after lending into the market, if it is still over leveraged then
// we will not add liquidity and just exit.
if (_isMarketOverLeveraged(nToken.cashGroup, market, leverageThreshold)) {
// Returns the residual cash amount
return (fCashAmount, residualCash);
}
}
// Add liquidity to the market only if we have successfully delevered.
// (marketIndex - 1) is the index of the nToken portfolio array where the asset is stored
// If deleveraged, residualCash is what remains
// If not deleveraged, residual cash is per market deposit
fCashAmount = fCashAmount.add(
_addLiquidityToMarket(nToken, market, marketIndex - 1, residualCash)
);
// No residual cash if we're adding liquidity
return (fCashAmount, 0);
}
/// @notice Markets are over levered when their proportion is greater than a governance set
/// threshold. At this point, providing liquidity will incur too much negative fCash on the nToken
/// account for the given amount of cash deposited, putting the nToken account at risk of liquidation.
/// If the market is over leveraged, we call `deleverageMarket` to lend to the market instead.
function _isMarketOverLeveraged(
CashGroupParameters memory cashGroup,
MarketParameters memory market,
int256 leverageThreshold
) private pure returns (bool) {
int256 totalCashUnderlying = cashGroup.assetRate.convertToUnderlying(market.totalAssetCash);
// Comparison we want to do:
// (totalfCash) / (totalfCash + totalCashUnderlying) > leverageThreshold
// However, the division will introduce rounding errors so we change this to:
// totalfCash * RATE_PRECISION > leverageThreshold * (totalfCash + totalCashUnderlying)
// Leverage threshold is denominated in rate precision.
return (
market.totalfCash.mul(Constants.RATE_PRECISION) >
leverageThreshold.mul(market.totalfCash.add(totalCashUnderlying))
);
}
function _addLiquidityToMarket(
nTokenPortfolio memory nToken,
MarketParameters memory market,
uint256 index,
int256 perMarketDeposit
) private returns (int256) {
// Add liquidity to the market
PortfolioAsset memory asset = nToken.portfolioState.storedAssets[index];
// We expect that all the liquidity tokens are in the portfolio in order.
require(
asset.maturity == market.maturity &&
// Ensures that the asset type references the proper liquidity token
asset.assetType == index + Constants.MIN_LIQUIDITY_TOKEN_INDEX &&
// Ensures that the storage state will not be overwritten
asset.storageState == AssetStorageState.NoChange,
"PT: invalid liquidity token"
);
// This will update the market state as well, fCashAmount returned here is negative
(int256 liquidityTokens, int256 fCashAmount) = market.addLiquidity(perMarketDeposit);
asset.notional = asset.notional.add(liquidityTokens);
asset.storageState = AssetStorageState.Update;
return fCashAmount;
}
/// @notice Lends into the market to reduce the leverage that the nToken will add liquidity at. May fail due
/// to slippage or result in some amount of residual cash.
function _deleverageMarket(
CashGroupParameters memory cashGroup,
MarketParameters memory market,
int256 perMarketDeposit,
uint256 blockTime,
uint256 marketIndex
) private returns (int256, int256) {
uint256 timeToMaturity = market.maturity.sub(blockTime);
// Shift the last implied rate by some buffer and calculate the exchange rate to fCash. Hope that this
// is sufficient to cover all potential slippage. We don't use the `getfCashGivenCashAmount` method here
// because it is very gas inefficient.
int256 assumedExchangeRate;
if (market.lastImpliedRate < Constants.DELEVERAGE_BUFFER) {
// Floor the exchange rate at zero interest rate
assumedExchangeRate = Constants.RATE_PRECISION;
} else {
assumedExchangeRate = Market.getExchangeRateFromImpliedRate(
market.lastImpliedRate.sub(Constants.DELEVERAGE_BUFFER),
timeToMaturity
);
}
int256 fCashAmount;
{
int256 perMarketDepositUnderlying =
cashGroup.assetRate.convertToUnderlying(perMarketDeposit);
// NOTE: cash * exchangeRate = fCash
fCashAmount = perMarketDepositUnderlying.mulInRatePrecision(assumedExchangeRate);
}
int256 netAssetCash = market.executeTrade(cashGroup, fCashAmount, timeToMaturity, marketIndex);
// This means that the trade failed
if (netAssetCash == 0) {
return (perMarketDeposit, 0);
} else {
// Ensure that net the per market deposit figure does not drop below zero, this should not be possible
// given how we've calculated the exchange rate but extra caution here
int256 residual = perMarketDeposit.add(netAssetCash);
require(residual >= 0); // dev: insufficient cash
return (residual, fCashAmount);
}
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../internal/markets/Market.sol";
import "../../internal/nToken/nTokenHandler.sol";
import "../../internal/nToken/nTokenCalculations.sol";
import "../../internal/portfolio/PortfolioHandler.sol";
import "../../internal/portfolio/TransferAssets.sol";
import "../../internal/balances/BalanceHandler.sol";
import "../../math/SafeInt256.sol";
import "../../math/Bitmap.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library nTokenRedeemAction {
using SafeInt256 for int256;
using SafeMath for uint256;
using Bitmap for bytes32;
using BalanceHandler for BalanceState;
using Market for MarketParameters;
using CashGroup for CashGroupParameters;
using PortfolioHandler for PortfolioState;
using nTokenHandler for nTokenPortfolio;
/// @notice When redeeming nTokens via the batch they must all be sold to cash and this
/// method will return the amount of asset cash sold.
/// @param currencyId the currency associated the nToken
/// @param tokensToRedeem the amount of nTokens to convert to cash
/// @return amount of asset cash to return to the account, denominated in internal token decimals
function nTokenRedeemViaBatch(uint16 currencyId, int256 tokensToRedeem)
external
returns (int256)
{
uint256 blockTime = block.timestamp;
// prettier-ignore
(
int256 totalAssetCash,
bool hasResidual,
/* PortfolioAssets[] memory newfCashAssets */
) = _redeem(currencyId, tokensToRedeem, true, false, blockTime);
require(!hasResidual, "Cannot redeem via batch, residual");
return totalAssetCash;
}
/// @notice Redeems nTokens for asset cash and fCash
/// @param currencyId the currency associated the nToken
/// @param tokensToRedeem the amount of nTokens to convert to cash
/// @param sellTokenAssets attempt to sell residual fCash and convert to cash, if unsuccessful then place
/// back into the account's portfolio
/// @param acceptResidualAssets if true, then ifCash residuals will be placed into the account and there will
/// be no penalty assessed
/// @return assetCash positive amount of asset cash to the account
/// @return hasResidual true if there are fCash residuals left
/// @return assets an array of fCash asset residuals to place into the account
function redeem(
uint16 currencyId,
int256 tokensToRedeem,
bool sellTokenAssets,
bool acceptResidualAssets
) external returns (int256, bool, PortfolioAsset[] memory) {
return _redeem(
currencyId,
tokensToRedeem,
sellTokenAssets,
acceptResidualAssets,
block.timestamp
);
}
function _redeem(
uint16 currencyId,
int256 tokensToRedeem,
bool sellTokenAssets,
bool acceptResidualAssets,
uint256 blockTime
) internal returns (int256, bool, PortfolioAsset[] memory) {
require(tokensToRedeem > 0);
nTokenPortfolio memory nToken;
nToken.loadNTokenPortfolioStateful(currencyId);
// nTokens cannot be redeemed during the period of time where they require settlement.
require(nToken.getNextSettleTime() > blockTime, "Requires settlement");
require(tokensToRedeem < nToken.totalSupply, "Cannot redeem");
PortfolioAsset[] memory newifCashAssets;
// Get the ifCash bits that are idiosyncratic
bytes32 ifCashBits = nTokenCalculations.getNTokenifCashBits(
nToken.tokenAddress,
currencyId,
nToken.lastInitializedTime,
blockTime,
nToken.cashGroup.maxMarketIndex
);
if (ifCashBits != 0 && acceptResidualAssets) {
// This will remove all the ifCash assets proportionally from the account
newifCashAssets = _reduceifCashAssetsProportional(
nToken.tokenAddress,
currencyId,
nToken.lastInitializedTime,
tokensToRedeem,
nToken.totalSupply,
ifCashBits
);
// Once the ifCash bits have been withdrawn, set this to zero so that getLiquidityTokenWithdraw
// simply gets the proportional amount of liquidity tokens to remove
ifCashBits = 0;
}
// Returns the liquidity tokens to withdraw per market and the netfCash amounts. Net fCash amounts are only
// set when ifCashBits != 0. Otherwise they must be calculated in _withdrawLiquidityTokens
(int256[] memory tokensToWithdraw, int256[] memory netfCash) = nTokenCalculations.getLiquidityTokenWithdraw(
nToken,
tokensToRedeem,
blockTime,
ifCashBits
);
// Returns the totalAssetCash as a result of withdrawing liquidity tokens and cash. netfCash will be updated
// in memory if required and will contain the fCash to be sold or returned to the portfolio
int256 totalAssetCash = _reduceLiquidAssets(
nToken,
tokensToRedeem,
tokensToWithdraw,
netfCash,
ifCashBits == 0, // If there are no residuals then we need to populate netfCash amounts
blockTime
);
bool netfCashRemaining = true;
if (sellTokenAssets) {
int256 assetCash;
// NOTE: netfCash is modified in place and set to zero if the fCash is sold
(assetCash, netfCashRemaining) = _sellfCashAssets(nToken, netfCash, blockTime);
totalAssetCash = totalAssetCash.add(assetCash);
}
if (netfCashRemaining) {
// If the account is unwilling to accept residuals then will fail here.
require(acceptResidualAssets, "Residuals");
newifCashAssets = _addResidualsToAssets(nToken.portfolioState.storedAssets, newifCashAssets, netfCash);
}
return (totalAssetCash, netfCashRemaining, newifCashAssets);
}
/// @notice Removes liquidity tokens and cash from the nToken
/// @param nToken portfolio object
/// @param nTokensToRedeem tokens to redeem
/// @param tokensToWithdraw array of liquidity tokens to withdraw
/// @param netfCash array of netfCash figures
/// @param mustCalculatefCash true if netfCash must be calculated in the removeLiquidityTokens step
/// @param blockTime current block time
/// @return assetCashShare amount of cash the redeemer will receive from withdrawing cash assets from the nToken
function _reduceLiquidAssets(
nTokenPortfolio memory nToken,
int256 nTokensToRedeem,
int256[] memory tokensToWithdraw,
int256[] memory netfCash,
bool mustCalculatefCash,
uint256 blockTime
) private returns (int256 assetCashShare) {
// Get asset cash share for the nToken, if it exists. It is required in balance handler that the
// nToken can never have a negative cash asset cash balance so what we get here is always positive
// or zero.
assetCashShare = nToken.cashBalance.mul(nTokensToRedeem).div(nToken.totalSupply);
if (assetCashShare > 0) {
nToken.cashBalance = nToken.cashBalance.subNoNeg(assetCashShare);
BalanceHandler.setBalanceStorageForNToken(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.cashBalance
);
}
// Get share of liquidity tokens to remove, netfCash is modified in memory during this method if mustCalculatefcash
// is set to true
assetCashShare = assetCashShare.add(
_removeLiquidityTokens(nToken, nTokensToRedeem, tokensToWithdraw, netfCash, blockTime, mustCalculatefCash)
);
nToken.portfolioState.storeAssets(nToken.tokenAddress);
// NOTE: Token supply change will happen when we finalize balances and after minting of incentives
return assetCashShare;
}
/// @notice Removes nToken liquidity tokens and updates the netfCash figures.
/// @param nToken portfolio object
/// @param nTokensToRedeem tokens to redeem
/// @param tokensToWithdraw array of liquidity tokens to withdraw
/// @param netfCash array of netfCash figures
/// @param blockTime current block time
/// @param mustCalculatefCash true if netfCash must be calculated in the removeLiquidityTokens step
/// @return totalAssetCashClaims is the amount of asset cash raised from liquidity token cash claims
function _removeLiquidityTokens(
nTokenPortfolio memory nToken,
int256 nTokensToRedeem,
int256[] memory tokensToWithdraw,
int256[] memory netfCash,
uint256 blockTime,
bool mustCalculatefCash
) private returns (int256 totalAssetCashClaims) {
MarketParameters memory market;
for (uint256 i = 0; i < nToken.portfolioState.storedAssets.length; i++) {
PortfolioAsset memory asset = nToken.portfolioState.storedAssets[i];
asset.notional = asset.notional.sub(tokensToWithdraw[i]);
// Cannot redeem liquidity tokens down to zero or this will cause many issues with
// market initialization.
require(asset.notional > 0, "Cannot redeem to zero");
require(asset.storageState == AssetStorageState.NoChange);
asset.storageState = AssetStorageState.Update;
// This will load a market object in memory
nToken.cashGroup.loadMarket(market, i + 1, true, blockTime);
int256 fCashClaim;
{
int256 assetCash;
// Remove liquidity from the market
(assetCash, fCashClaim) = market.removeLiquidity(tokensToWithdraw[i]);
totalAssetCashClaims = totalAssetCashClaims.add(assetCash);
}
int256 fCashToNToken;
if (mustCalculatefCash) {
// Do this calculation if net ifCash is not set, will happen if there are no residuals
int256 fCashShare = BitmapAssetsHandler.getifCashNotional(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
asset.maturity
);
fCashShare = fCashShare.mul(nTokensToRedeem).div(nToken.totalSupply);
// netfCash = fCashClaim + fCashShare
netfCash[i] = fCashClaim.add(fCashShare);
fCashToNToken = fCashShare.neg();
} else {
// Account will receive netfCash amount. Deduct that from the fCash claim and add the
// remaining back to the nToken to net off the nToken's position
// fCashToNToken = -fCashShare
// netfCash = fCashClaim + fCashShare
// fCashToNToken = -(netfCash - fCashClaim)
// fCashToNToken = fCashClaim - netfCash
fCashToNToken = fCashClaim.sub(netfCash[i]);
}
// Removes the account's fCash position from the nToken
BitmapAssetsHandler.addifCashAsset(
nToken.tokenAddress,
asset.currencyId,
asset.maturity,
nToken.lastInitializedTime,
fCashToNToken
);
}
return totalAssetCashClaims;
}
/// @notice Sells fCash assets back into the market for cash. Negative fCash assets will decrease netAssetCash
/// as a result. The aim here is to ensure that accounts can redeem nTokens without having to take on
/// fCash assets.
function _sellfCashAssets(
nTokenPortfolio memory nToken,
int256[] memory netfCash,
uint256 blockTime
) private returns (int256 totalAssetCash, bool hasResidual) {
MarketParameters memory market;
hasResidual = false;
for (uint256 i = 0; i < netfCash.length; i++) {
if (netfCash[i] == 0) continue;
nToken.cashGroup.loadMarket(market, i + 1, false, blockTime);
int256 netAssetCash = market.executeTrade(
nToken.cashGroup,
// Use the negative of fCash notional here since we want to net it out
netfCash[i].neg(),
nToken.portfolioState.storedAssets[i].maturity.sub(blockTime),
i + 1
);
if (netAssetCash == 0) {
// This means that the trade failed
hasResidual = true;
} else {
totalAssetCash = totalAssetCash.add(netAssetCash);
netfCash[i] = 0;
}
}
}
/// @notice Combines newifCashAssets array with netfCash assets into a single finalfCashAssets array
function _addResidualsToAssets(
PortfolioAsset[] memory liquidityTokens,
PortfolioAsset[] memory newifCashAssets,
int256[] memory netfCash
) internal pure returns (PortfolioAsset[] memory finalfCashAssets) {
uint256 numAssetsToExtend;
for (uint256 i = 0; i < netfCash.length; i++) {
if (netfCash[i] != 0) numAssetsToExtend++;
}
uint256 newLength = newifCashAssets.length + numAssetsToExtend;
finalfCashAssets = new PortfolioAsset[](newLength);
uint index = 0;
for (; index < newifCashAssets.length; index++) {
finalfCashAssets[index] = newifCashAssets[index];
}
uint netfCashIndex = 0;
for (; index < finalfCashAssets.length; ) {
if (netfCash[netfCashIndex] != 0) {
PortfolioAsset memory asset = finalfCashAssets[index];
asset.currencyId = liquidityTokens[netfCashIndex].currencyId;
asset.maturity = liquidityTokens[netfCashIndex].maturity;
asset.assetType = Constants.FCASH_ASSET_TYPE;
asset.notional = netfCash[netfCashIndex];
index++;
}
netfCashIndex++;
}
return finalfCashAssets;
}
/// @notice Used to reduce an nToken ifCash assets portfolio proportionately when redeeming
/// nTokens to its underlying assets.
function _reduceifCashAssetsProportional(
address account,
uint256 currencyId,
uint256 lastInitializedTime,
int256 tokensToRedeem,
int256 totalSupply,
bytes32 assetsBitmap
) internal returns (PortfolioAsset[] memory) {
uint256 index = assetsBitmap.totalBitsSet();
mapping(address => mapping(uint256 =>
mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage();
PortfolioAsset[] memory assets = new PortfolioAsset[](index);
index = 0;
uint256 bitNum = assetsBitmap.getNextBitNum();
while (bitNum != 0) {
uint256 maturity = DateTime.getMaturityFromBitNum(lastInitializedTime, bitNum);
ifCashStorage storage fCashSlot = store[account][currencyId][maturity];
int256 notional = fCashSlot.notional;
int256 notionalToTransfer = notional.mul(tokensToRedeem).div(totalSupply);
int256 finalNotional = notional.sub(notionalToTransfer);
require(type(int128).min <= finalNotional && finalNotional <= type(int128).max); // dev: bitmap notional overflow
fCashSlot.notional = int128(finalNotional);
PortfolioAsset memory asset = assets[index];
asset.currencyId = currencyId;
asset.maturity = maturity;
asset.assetType = Constants.FCASH_ASSET_TYPE;
asset.notional = notionalToTransfer;
index += 1;
// Turn off the bit and look for the next one
assetsBitmap = assetsBitmap.setBit(bitNum, false);
bitNum = assetsBitmap.getNextBitNum();
}
return assets;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../internal/portfolio/PortfolioHandler.sol";
import "../internal/balances/BalanceHandler.sol";
import "../internal/settlement/SettlePortfolioAssets.sol";
import "../internal/settlement/SettleBitmapAssets.sol";
import "../internal/AccountContextHandler.sol";
/// @notice External library for settling assets
library SettleAssetsExternal {
using PortfolioHandler for PortfolioState;
using AccountContextHandler for AccountContext;
event AccountSettled(address indexed account);
/// @notice Settles an account, returns the new account context object after settlement.
/// @dev The memory location of the account context object is not the same as the one returned.
function settleAccount(
address account,
AccountContext memory accountContext
) external returns (AccountContext memory) {
// Defensive check to ensure that this is a valid settlement
require(accountContext.mustSettleAssets());
SettleAmount[] memory settleAmounts;
PortfolioState memory portfolioState;
if (accountContext.isBitmapEnabled()) {
(int256 settledCash, uint256 blockTimeUTC0) =
SettleBitmapAssets.settleBitmappedCashGroup(
account,
accountContext.bitmapCurrencyId,
accountContext.nextSettleTime,
block.timestamp
);
require(blockTimeUTC0 < type(uint40).max); // dev: block time utc0 overflow
accountContext.nextSettleTime = uint40(blockTimeUTC0);
settleAmounts = new SettleAmount[](1);
settleAmounts[0] = SettleAmount(accountContext.bitmapCurrencyId, settledCash);
} else {
portfolioState = PortfolioHandler.buildPortfolioState(
account,
accountContext.assetArrayLength,
0
);
settleAmounts = SettlePortfolioAssets.settlePortfolio(portfolioState, block.timestamp);
accountContext.storeAssetsAndUpdateContext(account, portfolioState, false);
}
BalanceHandler.finalizeSettleAmounts(account, accountContext, settleAmounts);
emit AccountSettled(account);
return accountContext;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../external/SettleAssetsExternal.sol";
import "../internal/AccountContextHandler.sol";
import "../internal/valuation/FreeCollateral.sol";
/// @title Externally deployed library for free collateral calculations
library FreeCollateralExternal {
using AccountContextHandler for AccountContext;
/// @notice Returns the ETH denominated free collateral of an account, represents the amount of
/// debt that the account can incur before liquidation. If an account's assets need to be settled this
/// will revert, either settle the account or use the off chain SDK to calculate free collateral.
/// @dev Called via the Views.sol method to return an account's free collateral. Does not work
/// for the nToken, the nToken does not have an account context.
/// @param account account to calculate free collateral for
/// @return total free collateral in ETH w/ 8 decimal places
/// @return array of net local values in asset values ordered by currency id
function getFreeCollateralView(address account)
external
view
returns (int256, int256[] memory)
{
AccountContext memory accountContext = AccountContextHandler.getAccountContext(account);
// The internal free collateral function does not account for settled assets. The Notional SDK
// can calculate the free collateral off chain if required at this point.
require(!accountContext.mustSettleAssets(), "Assets not settled");
return FreeCollateral.getFreeCollateralView(account, accountContext, block.timestamp);
}
/// @notice Calculates free collateral and will revert if it falls below zero. If the account context
/// must be updated due to changes in debt settings, will update. Cannot check free collateral if assets
/// need to be settled first.
/// @dev Cannot be called directly by users, used during various actions that require an FC check. Must be
/// called before the end of any transaction for accounts where FC can decrease.
/// @param account account to calculate free collateral for
function checkFreeCollateralAndRevert(address account) external {
AccountContext memory accountContext = AccountContextHandler.getAccountContext(account);
require(!accountContext.mustSettleAssets(), "Assets not settled");
(int256 ethDenominatedFC, bool updateContext) =
FreeCollateral.getFreeCollateralStateful(account, accountContext, block.timestamp);
if (updateContext) {
accountContext.setAccountContext(account);
}
require(ethDenominatedFC >= 0, "Insufficient free collateral");
}
/// @notice Calculates liquidation factors for an account
/// @dev Only called internally by liquidation actions, does some initial validation of currencies. If a currency is
/// specified that the account does not have, a asset available figure of zero will be returned. If this is the case then
/// liquidation actions will revert.
/// @dev an ntoken account will return 0 FC and revert if called
/// @param account account to liquidate
/// @param localCurrencyId currency that the debts are denominated in
/// @param collateralCurrencyId collateral currency to liquidate against, set to zero in the case of local currency liquidation
/// @return accountContext the accountContext of the liquidated account
/// @return factors struct of relevant factors for liquidation
/// @return portfolio the portfolio array of the account (bitmap accounts will return an empty array)
function getLiquidationFactors(
address account,
uint256 localCurrencyId,
uint256 collateralCurrencyId
)
external
returns (
AccountContext memory accountContext,
LiquidationFactors memory factors,
PortfolioAsset[] memory portfolio
)
{
accountContext = AccountContextHandler.getAccountContext(account);
if (accountContext.mustSettleAssets()) {
accountContext = SettleAssetsExternal.settleAccount(account, accountContext);
}
if (accountContext.isBitmapEnabled()) {
// A bitmap currency can only ever hold debt in this currency
require(localCurrencyId == accountContext.bitmapCurrencyId);
}
(factors, portfolio) = FreeCollateral.getLiquidationFactors(
account,
accountContext,
block.timestamp,
localCurrencyId,
collateralCurrencyId
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
import "../global/Constants.sol";
library SafeInt256 {
int256 private constant _INT256_MIN = type(int256).min;
/// @dev Returns the multiplication of two signed integers, reverting on
/// overflow.
/// Counterpart to Solidity's `*` operator.
/// Requirements:
/// - Multiplication cannot overflow.
function mul(int256 a, int256 b) internal pure returns (int256 c) {
c = a * b;
if (a == -1) require (b == 0 || c / b == a);
else require (a == 0 || c / a == b);
}
/// @dev Returns the integer division of two signed integers. Reverts on
/// division by zero. The result is rounded towards zero.
/// Counterpart to Solidity's `/` operator. Note: this function uses a
/// `revert` opcode (which leaves remaining gas untouched) while Solidity
/// uses an invalid opcode to revert (consuming all remaining gas).
/// Requirements:
/// - The divisor cannot be zero.
function div(int256 a, int256 b) internal pure returns (int256 c) {
require(!(b == -1 && a == _INT256_MIN)); // dev: int256 div overflow
// NOTE: solidity will automatically revert on divide by zero
c = a / b;
}
function sub(int256 x, int256 y) internal pure returns (int256 z) {
// taken from uniswap v3
require((z = x - y) <= x == (y >= 0));
}
function add(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x + y) >= x == (y >= 0));
}
function neg(int256 x) internal pure returns (int256 y) {
return mul(-1, x);
}
function abs(int256 x) internal pure returns (int256) {
if (x < 0) return neg(x);
else return x;
}
function subNoNeg(int256 x, int256 y) internal pure returns (int256 z) {
z = sub(x, y);
require(z >= 0); // dev: int256 sub to negative
return z;
}
/// @dev Calculates x * RATE_PRECISION / y while checking overflows
function divInRatePrecision(int256 x, int256 y) internal pure returns (int256) {
return div(mul(x, Constants.RATE_PRECISION), y);
}
/// @dev Calculates x * y / RATE_PRECISION while checking overflows
function mulInRatePrecision(int256 x, int256 y) internal pure returns (int256) {
return div(mul(x, y), Constants.RATE_PRECISION);
}
function toUint(int256 x) internal pure returns (uint256) {
require(x >= 0);
return uint256(x);
}
function toInt(uint256 x) internal pure returns (int256) {
require (x <= uint256(type(int256).max)); // dev: toInt overflow
return int256(x);
}
function max(int256 x, int256 y) internal pure returns (int256) {
return x > y ? x : y;
}
function min(int256 x, int256 y) internal pure returns (int256) {
return x < y ? x : y;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./Types.sol";
/**
* @notice Storage layout for the system. Do not change this file once deployed, future storage
* layouts must inherit this and increment the version number.
*/
contract StorageLayoutV1 {
// The current maximum currency id
uint16 internal maxCurrencyId;
// Sets the state of liquidations being enabled during a paused state. Each of the four lower
// bits can be turned on to represent one of the liquidation types being enabled.
bytes1 internal liquidationEnabledState;
// Set to true once the system has been initialized
bool internal hasInitialized;
/* Authentication Mappings */
// This is set to the timelock contract to execute governance functions
address public owner;
// This is set to an address of a router that can only call governance actions
address public pauseRouter;
// This is set to an address of a router that can only call governance actions
address public pauseGuardian;
// On upgrades this is set in the case that the pause router is used to pass the rollback check
address internal rollbackRouterImplementation;
// A blanket allowance for a spender to transfer any of an account's nTokens. This would allow a user
// to set an allowance on all nTokens for a particular integrating contract system.
// owner => spender => transferAllowance
mapping(address => mapping(address => uint256)) internal nTokenWhitelist;
// Individual transfer allowances for nTokens used for ERC20
// owner => spender => currencyId => transferAllowance
mapping(address => mapping(address => mapping(uint16 => uint256))) internal nTokenAllowance;
// Transfer operators
// Mapping from a global ERC1155 transfer operator contract to an approval value for it
mapping(address => bool) internal globalTransferOperator;
// Mapping from an account => operator => approval status for that operator. This is a specific
// approval between two addresses for ERC1155 transfers.
mapping(address => mapping(address => bool)) internal accountAuthorizedTransferOperator;
// Approval for a specific contract to use the `batchBalanceAndTradeActionWithCallback` method in
// BatchAction.sol, can only be set by governance
mapping(address => bool) internal authorizedCallbackContract;
// Reverse mapping from token addresses to currency ids, only used for referencing in views
// and checking for duplicate token listings.
mapping(address => uint16) internal tokenAddressToCurrencyId;
// Reentrancy guard
uint256 internal reentrancyStatus;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./Incentives.sol";
import "./TokenHandler.sol";
import "../AccountContextHandler.sol";
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../../math/SafeInt256.sol";
import "../../math/FloatingPoint56.sol";
library BalanceHandler {
using SafeInt256 for int256;
using TokenHandler for Token;
using AssetRate for AssetRateParameters;
using AccountContextHandler for AccountContext;
/// @notice Emitted when a cash balance changes
event CashBalanceChange(address indexed account, uint16 indexed currencyId, int256 netCashChange);
/// @notice Emitted when nToken supply changes (not the same as transfers)
event nTokenSupplyChange(address indexed account, uint16 indexed currencyId, int256 tokenSupplyChange);
/// @notice Emitted when reserve fees are accrued
event ReserveFeeAccrued(uint16 indexed currencyId, int256 fee);
/// @notice Emitted when reserve balance is updated
event ReserveBalanceUpdated(uint16 indexed currencyId, int256 newBalance);
/// @notice Emitted when reserve balance is harvested
event ExcessReserveBalanceHarvested(uint16 indexed currencyId, int256 harvestAmount);
/// @notice Deposits asset tokens into an account
/// @dev Handles two special cases when depositing tokens into an account.
/// - If a token has transfer fees then the amount specified does not equal the amount that the contract
/// will receive. Complete the deposit here rather than in finalize so that the contract has the correct
/// balance to work with.
/// - Force a transfer before finalize to allow a different account to deposit into an account
/// @return assetAmountInternal which is the converted asset amount accounting for transfer fees
function depositAssetToken(
BalanceState memory balanceState,
address account,
int256 assetAmountExternal,
bool forceTransfer
) internal returns (int256 assetAmountInternal) {
if (assetAmountExternal == 0) return 0;
require(assetAmountExternal > 0); // dev: deposit asset token amount negative
Token memory token = TokenHandler.getAssetToken(balanceState.currencyId);
if (token.tokenType == TokenType.aToken) {
// Handles special accounting requirements for aTokens
assetAmountExternal = AaveHandler.convertToScaledBalanceExternal(
balanceState.currencyId,
assetAmountExternal
);
}
// Force transfer is used to complete the transfer before going to finalize
if (token.hasTransferFee || forceTransfer) {
// If the token has a transfer fee the deposit amount may not equal the actual amount
// that the contract will receive. We handle the deposit here and then update the netCashChange
// accordingly which is denominated in internal precision.
int256 assetAmountExternalPrecisionFinal = token.transfer(account, balanceState.currencyId, assetAmountExternal);
// Convert the external precision to internal, it's possible that we lose dust amounts here but
// this is unavoidable because we do not know how transfer fees are calculated.
assetAmountInternal = token.convertToInternal(assetAmountExternalPrecisionFinal);
// Transfer has been called
balanceState.netCashChange = balanceState.netCashChange.add(assetAmountInternal);
return assetAmountInternal;
} else {
assetAmountInternal = token.convertToInternal(assetAmountExternal);
// Otherwise add the asset amount here. It may be net off later and we want to only do
// a single transfer during the finalize method. Use internal precision to ensure that internal accounting
// and external account remain in sync.
// Transfer will be deferred
balanceState.netAssetTransferInternalPrecision = balanceState
.netAssetTransferInternalPrecision
.add(assetAmountInternal);
// Returns the converted assetAmountExternal to the internal amount
return assetAmountInternal;
}
}
/// @notice Handle deposits of the underlying token
/// @dev In this case we must wrap the underlying token into an asset token, ensuring that we do not end up
/// with any underlying tokens left as dust on the contract.
function depositUnderlyingToken(
BalanceState memory balanceState,
address account,
int256 underlyingAmountExternal
) internal returns (int256) {
if (underlyingAmountExternal == 0) return 0;
require(underlyingAmountExternal > 0); // dev: deposit underlying token negative
Token memory underlyingToken = TokenHandler.getUnderlyingToken(balanceState.currencyId);
// This is the exact amount of underlying tokens the account has in external precision.
if (underlyingToken.tokenType == TokenType.Ether) {
// Underflow checked above
require(uint256(underlyingAmountExternal) == msg.value, "ETH Balance");
} else {
underlyingAmountExternal = underlyingToken.transfer(account, balanceState.currencyId, underlyingAmountExternal);
}
Token memory assetToken = TokenHandler.getAssetToken(balanceState.currencyId);
int256 assetTokensReceivedExternalPrecision =
assetToken.mint(balanceState.currencyId, SafeInt256.toUint(underlyingAmountExternal));
// cTokens match INTERNAL_TOKEN_PRECISION so this will short circuit but we leave this here in case a different
// type of asset token is listed in the future. It's possible if those tokens have a different precision dust may
// accrue but that is not relevant now.
int256 assetTokensReceivedInternal =
assetToken.convertToInternal(assetTokensReceivedExternalPrecision);
// Transfer / mint has taken effect
balanceState.netCashChange = balanceState.netCashChange.add(assetTokensReceivedInternal);
return assetTokensReceivedInternal;
}
/// @notice Finalizes an account's balances, handling any transfer logic required
/// @dev This method SHOULD NOT be used for nToken accounts, for that use setBalanceStorageForNToken
/// as the nToken is limited in what types of balances it can hold.
function finalize(
BalanceState memory balanceState,
address account,
AccountContext memory accountContext,
bool redeemToUnderlying
) internal returns (int256 transferAmountExternal) {
bool mustUpdate;
if (balanceState.netNTokenTransfer < 0) {
require(
balanceState.storedNTokenBalance
.add(balanceState.netNTokenSupplyChange)
.add(balanceState.netNTokenTransfer) >= 0,
"Neg nToken"
);
}
if (balanceState.netAssetTransferInternalPrecision < 0) {
require(
balanceState.storedCashBalance
.add(balanceState.netCashChange)
.add(balanceState.netAssetTransferInternalPrecision) >= 0,
"Neg Cash"
);
}
// Transfer amount is checked inside finalize transfers in case when converting to external we
// round down to zero. This returns the actual net transfer in internal precision as well.
(
transferAmountExternal,
balanceState.netAssetTransferInternalPrecision
) = _finalizeTransfers(balanceState, account, redeemToUnderlying);
// No changes to total cash after this point
int256 totalCashChange = balanceState.netCashChange.add(balanceState.netAssetTransferInternalPrecision);
if (totalCashChange != 0) {
balanceState.storedCashBalance = balanceState.storedCashBalance.add(totalCashChange);
mustUpdate = true;
emit CashBalanceChange(
account,
uint16(balanceState.currencyId),
totalCashChange
);
}
if (balanceState.netNTokenTransfer != 0 || balanceState.netNTokenSupplyChange != 0) {
// Final nToken balance is used to calculate the account incentive debt
int256 finalNTokenBalance = balanceState.storedNTokenBalance
.add(balanceState.netNTokenTransfer)
.add(balanceState.netNTokenSupplyChange);
// The toUint() call here will ensure that nToken balances never become negative
Incentives.claimIncentives(balanceState, account, finalNTokenBalance.toUint());
balanceState.storedNTokenBalance = finalNTokenBalance;
if (balanceState.netNTokenSupplyChange != 0) {
emit nTokenSupplyChange(
account,
uint16(balanceState.currencyId),
balanceState.netNTokenSupplyChange
);
}
mustUpdate = true;
}
if (mustUpdate) {
_setBalanceStorage(
account,
balanceState.currencyId,
balanceState.storedCashBalance,
balanceState.storedNTokenBalance,
balanceState.lastClaimTime,
balanceState.accountIncentiveDebt
);
}
accountContext.setActiveCurrency(
balanceState.currencyId,
// Set active currency to true if either balance is non-zero
balanceState.storedCashBalance != 0 || balanceState.storedNTokenBalance != 0,
Constants.ACTIVE_IN_BALANCES
);
if (balanceState.storedCashBalance < 0) {
// NOTE: HAS_CASH_DEBT cannot be extinguished except by a free collateral check where all balances
// are examined
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT;
}
}
/// @dev Returns the amount transferred in underlying or asset terms depending on how redeem to underlying
/// is specified.
function _finalizeTransfers(
BalanceState memory balanceState,
address account,
bool redeemToUnderlying
) private returns (int256 actualTransferAmountExternal, int256 assetTransferAmountInternal) {
Token memory assetToken = TokenHandler.getAssetToken(balanceState.currencyId);
// Dust accrual to the protocol is possible if the token decimals is less than internal token precision.
// See the comments in TokenHandler.convertToExternal and TokenHandler.convertToInternal
int256 assetTransferAmountExternal =
assetToken.convertToExternal(balanceState.netAssetTransferInternalPrecision);
if (assetTransferAmountExternal == 0) {
return (0, 0);
} else if (redeemToUnderlying && assetTransferAmountExternal < 0) {
// We only do the redeem to underlying if the asset transfer amount is less than zero. If it is greater than
// zero then we will do a normal transfer instead.
// We use the internal amount here and then scale it to the external amount so that there is
// no loss of precision between our internal accounting and the external account. In this case
// there will be no dust accrual in underlying tokens since we will transfer the exact amount
// of underlying that was received.
actualTransferAmountExternal = assetToken.redeem(
balanceState.currencyId,
account,
// No overflow, checked above
uint256(assetTransferAmountExternal.neg())
);
// In this case we're transferring underlying tokens, we want to convert the internal
// asset transfer amount to store in cash balances
assetTransferAmountInternal = assetToken.convertToInternal(assetTransferAmountExternal);
} else {
// NOTE: in the case of aTokens assetTransferAmountExternal is the scaledBalanceOf in external precision, it
// will be converted to balanceOf denomination inside transfer
actualTransferAmountExternal = assetToken.transfer(account, balanceState.currencyId, assetTransferAmountExternal);
// Convert the actual transferred amount
assetTransferAmountInternal = assetToken.convertToInternal(actualTransferAmountExternal);
}
}
/// @notice Special method for settling negative current cash debts. This occurs when an account
/// has a negative fCash balance settle to cash. A settler may come and force the account to borrow
/// at the prevailing 3 month rate
/// @dev Use this method to avoid any nToken and transfer logic in finalize which is unnecessary.
function setBalanceStorageForSettleCashDebt(
address account,
CashGroupParameters memory cashGroup,
int256 amountToSettleAsset,
AccountContext memory accountContext
) internal returns (int256) {
require(amountToSettleAsset >= 0); // dev: amount to settle negative
(int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt) =
getBalanceStorage(account, cashGroup.currencyId);
// Prevents settlement of positive balances
require(cashBalance < 0, "Invalid settle balance");
if (amountToSettleAsset == 0) {
// Symbolizes that the entire debt should be settled
amountToSettleAsset = cashBalance.neg();
cashBalance = 0;
} else {
// A partial settlement of the debt
require(amountToSettleAsset <= cashBalance.neg(), "Invalid amount to settle");
cashBalance = cashBalance.add(amountToSettleAsset);
}
// NOTE: we do not update HAS_CASH_DEBT here because it is possible that the other balances
// also have cash debts
if (cashBalance == 0 && nTokenBalance == 0) {
accountContext.setActiveCurrency(
cashGroup.currencyId,
false,
Constants.ACTIVE_IN_BALANCES
);
}
_setBalanceStorage(
account,
cashGroup.currencyId,
cashBalance,
nTokenBalance,
lastClaimTime,
accountIncentiveDebt
);
// Emit the event here, we do not call finalize
emit CashBalanceChange(account, cashGroup.currencyId, amountToSettleAsset);
return amountToSettleAsset;
}
/**
* @notice A special balance storage method for fCash liquidation to reduce the bytecode size.
*/
function setBalanceStorageForfCashLiquidation(
address account,
AccountContext memory accountContext,
uint16 currencyId,
int256 netCashChange
) internal {
(int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt) =
getBalanceStorage(account, currencyId);
int256 newCashBalance = cashBalance.add(netCashChange);
// If a cash balance is negative already we cannot put an account further into debt. In this case
// the netCashChange must be positive so that it is coming out of debt.
if (newCashBalance < 0) {
require(netCashChange > 0, "Neg Cash");
// NOTE: HAS_CASH_DEBT cannot be extinguished except by a free collateral check
// where all balances are examined. In this case the has cash debt flag should
// already be set (cash balances cannot get more negative) but we do it again
// here just to be safe.
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT;
}
bool isActive = newCashBalance != 0 || nTokenBalance != 0;
accountContext.setActiveCurrency(currencyId, isActive, Constants.ACTIVE_IN_BALANCES);
// Emit the event here, we do not call finalize
emit CashBalanceChange(account, currencyId, netCashChange);
_setBalanceStorage(
account,
currencyId,
newCashBalance,
nTokenBalance,
lastClaimTime,
accountIncentiveDebt
);
}
/// @notice Helper method for settling the output of the SettleAssets method
function finalizeSettleAmounts(
address account,
AccountContext memory accountContext,
SettleAmount[] memory settleAmounts
) internal {
for (uint256 i = 0; i < settleAmounts.length; i++) {
SettleAmount memory amt = settleAmounts[i];
if (amt.netCashChange == 0) continue;
(
int256 cashBalance,
int256 nTokenBalance,
uint256 lastClaimTime,
uint256 accountIncentiveDebt
) = getBalanceStorage(account, amt.currencyId);
cashBalance = cashBalance.add(amt.netCashChange);
accountContext.setActiveCurrency(
amt.currencyId,
cashBalance != 0 || nTokenBalance != 0,
Constants.ACTIVE_IN_BALANCES
);
if (cashBalance < 0) {
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT;
}
emit CashBalanceChange(
account,
uint16(amt.currencyId),
amt.netCashChange
);
_setBalanceStorage(
account,
amt.currencyId,
cashBalance,
nTokenBalance,
lastClaimTime,
accountIncentiveDebt
);
}
}
/// @notice Special method for setting balance storage for nToken
function setBalanceStorageForNToken(
address nTokenAddress,
uint256 currencyId,
int256 cashBalance
) internal {
require(cashBalance >= 0); // dev: invalid nToken cash balance
_setBalanceStorage(nTokenAddress, currencyId, cashBalance, 0, 0, 0);
}
/// @notice increments fees to the reserve
function incrementFeeToReserve(uint256 currencyId, int256 fee) internal {
require(fee >= 0); // dev: invalid fee
// prettier-ignore
(int256 totalReserve, /* */, /* */, /* */) = getBalanceStorage(Constants.RESERVE, currencyId);
totalReserve = totalReserve.add(fee);
_setBalanceStorage(Constants.RESERVE, currencyId, totalReserve, 0, 0, 0);
emit ReserveFeeAccrued(uint16(currencyId), fee);
}
/// @notice harvests excess reserve balance
function harvestExcessReserveBalance(uint16 currencyId, int256 reserve, int256 assetInternalRedeemAmount) internal {
// parameters are validated by the caller
reserve = reserve.subNoNeg(assetInternalRedeemAmount);
_setBalanceStorage(Constants.RESERVE, currencyId, reserve, 0, 0, 0);
emit ExcessReserveBalanceHarvested(currencyId, assetInternalRedeemAmount);
}
/// @notice sets the reserve balance, see TreasuryAction.setReserveCashBalance
function setReserveCashBalance(uint16 currencyId, int256 newBalance) internal {
require(newBalance >= 0); // dev: invalid balance
_setBalanceStorage(Constants.RESERVE, currencyId, newBalance, 0, 0, 0);
emit ReserveBalanceUpdated(currencyId, newBalance);
}
/// @notice Sets internal balance storage.
function _setBalanceStorage(
address account,
uint256 currencyId,
int256 cashBalance,
int256 nTokenBalance,
uint256 lastClaimTime,
uint256 accountIncentiveDebt
) private {
mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage();
BalanceStorage storage balanceStorage = store[account][currencyId];
require(cashBalance >= type(int88).min && cashBalance <= type(int88).max); // dev: stored cash balance overflow
// Allows for 12 quadrillion nToken balance in 1e8 decimals before overflow
require(nTokenBalance >= 0 && nTokenBalance <= type(uint80).max); // dev: stored nToken balance overflow
if (lastClaimTime == 0) {
// In this case the account has migrated and we set the accountIncentiveDebt
// The maximum NOTE supply is 100_000_000e8 (1e16) which is less than 2^56 (7.2e16) so we should never
// encounter an overflow for accountIncentiveDebt
require(accountIncentiveDebt <= type(uint56).max); // dev: account incentive debt overflow
balanceStorage.accountIncentiveDebt = uint56(accountIncentiveDebt);
} else {
// In this case the last claim time has not changed and we do not update the last integral supply
// (stored in the accountIncentiveDebt position)
require(lastClaimTime == balanceStorage.lastClaimTime);
}
balanceStorage.lastClaimTime = uint32(lastClaimTime);
balanceStorage.nTokenBalance = uint80(nTokenBalance);
balanceStorage.cashBalance = int88(cashBalance);
}
/// @notice Gets internal balance storage, nTokens are stored alongside cash balances
function getBalanceStorage(address account, uint256 currencyId)
internal
view
returns (
int256 cashBalance,
int256 nTokenBalance,
uint256 lastClaimTime,
uint256 accountIncentiveDebt
)
{
mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage();
BalanceStorage storage balanceStorage = store[account][currencyId];
nTokenBalance = balanceStorage.nTokenBalance;
lastClaimTime = balanceStorage.lastClaimTime;
if (lastClaimTime > 0) {
// NOTE: this is only necessary to support the deprecated integral supply values, which are stored
// in the accountIncentiveDebt slot
accountIncentiveDebt = FloatingPoint56.unpackFrom56Bits(balanceStorage.accountIncentiveDebt);
} else {
accountIncentiveDebt = balanceStorage.accountIncentiveDebt;
}
cashBalance = balanceStorage.cashBalance;
}
/// @notice Loads a balance state memory object
/// @dev Balance state objects occupy a lot of memory slots, so this method allows
/// us to reuse them if possible
function loadBalanceState(
BalanceState memory balanceState,
address account,
uint16 currencyId,
AccountContext memory accountContext
) internal view {
require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id
balanceState.currencyId = currencyId;
if (accountContext.isActiveInBalances(currencyId)) {
(
balanceState.storedCashBalance,
balanceState.storedNTokenBalance,
balanceState.lastClaimTime,
balanceState.accountIncentiveDebt
) = getBalanceStorage(account, currencyId);
} else {
balanceState.storedCashBalance = 0;
balanceState.storedNTokenBalance = 0;
balanceState.lastClaimTime = 0;
balanceState.accountIncentiveDebt = 0;
}
balanceState.netCashChange = 0;
balanceState.netAssetTransferInternalPrecision = 0;
balanceState.netNTokenTransfer = 0;
balanceState.netNTokenSupplyChange = 0;
}
/// @notice Used when manually claiming incentives in nTokenAction. Also sets the balance state
/// to storage to update the accountIncentiveDebt. lastClaimTime will be set to zero as accounts
/// are migrated to the new incentive calculation
function claimIncentivesManual(BalanceState memory balanceState, address account)
internal
returns (uint256 incentivesClaimed)
{
incentivesClaimed = Incentives.claimIncentives(
balanceState,
account,
balanceState.storedNTokenBalance.toUint()
);
_setBalanceStorage(
account,
balanceState.currencyId,
balanceState.storedCashBalance,
balanceState.storedNTokenBalance,
balanceState.lastClaimTime,
balanceState.accountIncentiveDebt
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./TransferAssets.sol";
import "../valuation/AssetHandler.sol";
import "../../math/SafeInt256.sol";
import "../../global/LibStorage.sol";
/// @notice Handles the management of an array of assets including reading from storage, inserting
/// updating, deleting and writing back to storage.
library PortfolioHandler {
using SafeInt256 for int256;
using AssetHandler for PortfolioAsset;
// Mirror of LibStorage.MAX_PORTFOLIO_ASSETS
uint256 private constant MAX_PORTFOLIO_ASSETS = 16;
/// @notice Primarily used by the TransferAssets library
function addMultipleAssets(PortfolioState memory portfolioState, PortfolioAsset[] memory assets)
internal
pure
{
for (uint256 i = 0; i < assets.length; i++) {
PortfolioAsset memory asset = assets[i];
if (asset.notional == 0) continue;
addAsset(
portfolioState,
asset.currencyId,
asset.maturity,
asset.assetType,
asset.notional
);
}
}
function _mergeAssetIntoArray(
PortfolioAsset[] memory assetArray,
uint256 currencyId,
uint256 maturity,
uint256 assetType,
int256 notional
) private pure returns (bool) {
for (uint256 i = 0; i < assetArray.length; i++) {
PortfolioAsset memory asset = assetArray[i];
if (
asset.assetType != assetType ||
asset.currencyId != currencyId ||
asset.maturity != maturity
) continue;
// Either of these storage states mean that some error in logic has occurred, we cannot
// store this portfolio
require(
asset.storageState != AssetStorageState.Delete &&
asset.storageState != AssetStorageState.RevertIfStored
); // dev: portfolio handler deleted storage
int256 newNotional = asset.notional.add(notional);
// Liquidity tokens cannot be reduced below zero.
if (AssetHandler.isLiquidityToken(assetType)) {
require(newNotional >= 0); // dev: portfolio handler negative liquidity token balance
}
require(newNotional >= type(int88).min && newNotional <= type(int88).max); // dev: portfolio handler notional overflow
asset.notional = newNotional;
asset.storageState = AssetStorageState.Update;
return true;
}
return false;
}
/// @notice Adds an asset to a portfolio state in memory (does not write to storage)
/// @dev Ensures that only one version of an asset exists in a portfolio (i.e. does not allow two fCash assets of the same maturity
/// to exist in a single portfolio). Also ensures that liquidity tokens do not have a negative notional.
function addAsset(
PortfolioState memory portfolioState,
uint256 currencyId,
uint256 maturity,
uint256 assetType,
int256 notional
) internal pure {
if (
// Will return true if merged
_mergeAssetIntoArray(
portfolioState.storedAssets,
currencyId,
maturity,
assetType,
notional
)
) return;
if (portfolioState.lastNewAssetIndex > 0) {
bool merged = _mergeAssetIntoArray(
portfolioState.newAssets,
currencyId,
maturity,
assetType,
notional
);
if (merged) return;
}
// At this point if we have not merged the asset then append to the array
// Cannot remove liquidity that the portfolio does not have
if (AssetHandler.isLiquidityToken(assetType)) {
require(notional >= 0); // dev: portfolio handler negative liquidity token balance
}
require(notional >= type(int88).min && notional <= type(int88).max); // dev: portfolio handler notional overflow
// Need to provision a new array at this point
if (portfolioState.lastNewAssetIndex == portfolioState.newAssets.length) {
portfolioState.newAssets = _extendNewAssetArray(portfolioState.newAssets);
}
// Otherwise add to the new assets array. It should not be possible to add matching assets in a single transaction, we will
// check this again when we write to storage. Assigning to memory directly here, do not allocate new memory via struct.
PortfolioAsset memory newAsset = portfolioState.newAssets[portfolioState.lastNewAssetIndex];
newAsset.currencyId = currencyId;
newAsset.maturity = maturity;
newAsset.assetType = assetType;
newAsset.notional = notional;
newAsset.storageState = AssetStorageState.NoChange;
portfolioState.lastNewAssetIndex += 1;
}
/// @dev Extends the new asset array if it is not large enough, this is likely to get a bit expensive if we do
/// it too much
function _extendNewAssetArray(PortfolioAsset[] memory newAssets)
private
pure
returns (PortfolioAsset[] memory)
{
// Double the size of the new asset array every time we have to extend to reduce the number of times
// that we have to extend it. This will go: 0, 1, 2, 4, 8 (probably stops there).
uint256 newLength = newAssets.length == 0 ? 1 : newAssets.length * 2;
PortfolioAsset[] memory extendedArray = new PortfolioAsset[](newLength);
for (uint256 i = 0; i < newAssets.length; i++) {
extendedArray[i] = newAssets[i];
}
return extendedArray;
}
/// @notice Takes a portfolio state and writes it to storage.
/// @dev This method should only be called directly by the nToken. Account updates to portfolios should happen via
/// the storeAssetsAndUpdateContext call in the AccountContextHandler.sol library.
/// @return updated variables to update the account context with
/// hasDebt: whether or not the portfolio has negative fCash assets
/// portfolioActiveCurrencies: a byte32 word with all the currencies in the portfolio
/// uint8: the length of the storage array
/// uint40: the new nextSettleTime for the portfolio
function storeAssets(PortfolioState memory portfolioState, address account)
internal
returns (
bool,
bytes32,
uint8,
uint40
)
{
bool hasDebt;
// NOTE: cannot have more than 16 assets or this byte object will overflow. Max assets is
// set to 7 and the worst case during liquidation would be 7 liquidity tokens that generate
// 7 additional fCash assets for a total of 14 assets. Although even in this case all assets
// would be of the same currency so it would not change the end result of the active currency
// calculation.
bytes32 portfolioActiveCurrencies;
uint256 nextSettleTime;
for (uint256 i = 0; i < portfolioState.storedAssets.length; i++) {
PortfolioAsset memory asset = portfolioState.storedAssets[i];
// NOTE: this is to prevent the storage of assets that have been modified in the AssetHandler
// during valuation.
require(asset.storageState != AssetStorageState.RevertIfStored);
// Mark any zero notional assets as deleted
if (asset.storageState != AssetStorageState.Delete && asset.notional == 0) {
deleteAsset(portfolioState, i);
}
}
// First delete assets from asset storage to maintain asset storage indexes
for (uint256 i = 0; i < portfolioState.storedAssets.length; i++) {
PortfolioAsset memory asset = portfolioState.storedAssets[i];
if (asset.storageState == AssetStorageState.Delete) {
// Delete asset from storage
uint256 currentSlot = asset.storageSlot;
assembly {
sstore(currentSlot, 0x00)
}
} else {
if (asset.storageState == AssetStorageState.Update) {
PortfolioAssetStorage storage assetStorage;
uint256 currentSlot = asset.storageSlot;
assembly {
assetStorage.slot := currentSlot
}
_storeAsset(asset, assetStorage);
}
// Update portfolio context for every asset that is in storage, whether it is
// updated in storage or not.
(hasDebt, portfolioActiveCurrencies, nextSettleTime) = _updatePortfolioContext(
asset,
hasDebt,
portfolioActiveCurrencies,
nextSettleTime
);
}
}
// Add new assets
uint256 assetStorageLength = portfolioState.storedAssetLength;
mapping(address =>
PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store = LibStorage.getPortfolioArrayStorage();
PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS] storage storageArray = store[account];
for (uint256 i = 0; i < portfolioState.newAssets.length; i++) {
PortfolioAsset memory asset = portfolioState.newAssets[i];
if (asset.notional == 0) continue;
require(
asset.storageState != AssetStorageState.Delete &&
asset.storageState != AssetStorageState.RevertIfStored
); // dev: store assets deleted storage
(hasDebt, portfolioActiveCurrencies, nextSettleTime) = _updatePortfolioContext(
asset,
hasDebt,
portfolioActiveCurrencies,
nextSettleTime
);
_storeAsset(asset, storageArray[assetStorageLength]);
assetStorageLength += 1;
}
// 16 is the maximum number of assets or portfolio active currencies will overflow at 32 bytes with
// 2 bytes per currency
require(assetStorageLength <= 16 && nextSettleTime <= type(uint40).max); // dev: portfolio return value overflow
return (
hasDebt,
portfolioActiveCurrencies,
uint8(assetStorageLength),
uint40(nextSettleTime)
);
}
/// @notice Updates context information during the store assets method
function _updatePortfolioContext(
PortfolioAsset memory asset,
bool hasDebt,
bytes32 portfolioActiveCurrencies,
uint256 nextSettleTime
)
private
pure
returns (
bool,
bytes32,
uint256
)
{
uint256 settlementDate = asset.getSettlementDate();
// Tis will set it to the minimum settlement date
if (nextSettleTime == 0 || nextSettleTime > settlementDate) {
nextSettleTime = settlementDate;
}
hasDebt = hasDebt || asset.notional < 0;
require(uint16(uint256(portfolioActiveCurrencies)) == 0); // dev: portfolio active currencies overflow
portfolioActiveCurrencies = (portfolioActiveCurrencies >> 16) | (bytes32(asset.currencyId) << 240);
return (hasDebt, portfolioActiveCurrencies, nextSettleTime);
}
/// @dev Encodes assets for storage
function _storeAsset(
PortfolioAsset memory asset,
PortfolioAssetStorage storage assetStorage
) internal {
require(0 < asset.currencyId && asset.currencyId <= Constants.MAX_CURRENCIES); // dev: encode asset currency id overflow
require(0 < asset.maturity && asset.maturity <= type(uint40).max); // dev: encode asset maturity overflow
require(0 < asset.assetType && asset.assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); // dev: encode asset type invalid
require(type(int88).min <= asset.notional && asset.notional <= type(int88).max); // dev: encode asset notional overflow
assetStorage.currencyId = uint16(asset.currencyId);
assetStorage.maturity = uint40(asset.maturity);
assetStorage.assetType = uint8(asset.assetType);
assetStorage.notional = int88(asset.notional);
}
/// @notice Deletes an asset from a portfolio
/// @dev This method should only be called during settlement, assets can only be removed from a portfolio before settlement
/// by adding the offsetting negative position
function deleteAsset(PortfolioState memory portfolioState, uint256 index) internal pure {
require(index < portfolioState.storedAssets.length); // dev: stored assets bounds
require(portfolioState.storedAssetLength > 0); // dev: stored assets length is zero
PortfolioAsset memory assetToDelete = portfolioState.storedAssets[index];
require(
assetToDelete.storageState != AssetStorageState.Delete &&
assetToDelete.storageState != AssetStorageState.RevertIfStored
); // dev: cannot delete asset
portfolioState.storedAssetLength -= 1;
uint256 maxActiveSlotIndex;
uint256 maxActiveSlot;
// The max active slot is the last storage slot where an asset exists, it's not clear where this will be in the
// array so we search for it here.
for (uint256 i; i < portfolioState.storedAssets.length; i++) {
PortfolioAsset memory a = portfolioState.storedAssets[i];
if (a.storageSlot > maxActiveSlot && a.storageState != AssetStorageState.Delete) {
maxActiveSlot = a.storageSlot;
maxActiveSlotIndex = i;
}
}
if (index == maxActiveSlotIndex) {
// In this case we are deleting the asset with the max storage slot so no swap is necessary.
assetToDelete.storageState = AssetStorageState.Delete;
return;
}
// Swap the storage slots of the deleted asset with the last non-deleted asset in the array. Mark them accordingly
// so that when we call store assets they will be updated appropriately
PortfolioAsset memory assetToSwap = portfolioState.storedAssets[maxActiveSlotIndex];
(
assetToSwap.storageSlot,
assetToDelete.storageSlot
) = (
assetToDelete.storageSlot,
assetToSwap.storageSlot
);
assetToSwap.storageState = AssetStorageState.Update;
assetToDelete.storageState = AssetStorageState.Delete;
}
/// @notice Returns a portfolio array, will be sorted
function getSortedPortfolio(address account, uint8 assetArrayLength)
internal
view
returns (PortfolioAsset[] memory)
{
PortfolioAsset[] memory assets = _loadAssetArray(account, assetArrayLength);
// No sorting required for length of 1
if (assets.length <= 1) return assets;
_sortInPlace(assets);
return assets;
}
/// @notice Builds a portfolio array from storage. The new assets hint parameter will
/// be used to provision a new array for the new assets. This will increase gas efficiency
/// so that we don't have to make copies when we extend the array.
function buildPortfolioState(
address account,
uint8 assetArrayLength,
uint256 newAssetsHint
) internal view returns (PortfolioState memory) {
PortfolioState memory state;
if (assetArrayLength == 0) return state;
state.storedAssets = getSortedPortfolio(account, assetArrayLength);
state.storedAssetLength = assetArrayLength;
state.newAssets = new PortfolioAsset[](newAssetsHint);
return state;
}
function _sortInPlace(PortfolioAsset[] memory assets) private pure {
uint256 length = assets.length;
uint256[] memory ids = new uint256[](length);
for (uint256 k; k < length; k++) {
PortfolioAsset memory asset = assets[k];
// Prepopulate the ids to calculate just once
ids[k] = TransferAssets.encodeAssetId(asset.currencyId, asset.maturity, asset.assetType);
}
// Uses insertion sort
uint256 i = 1;
while (i < length) {
uint256 j = i;
while (j > 0 && ids[j - 1] > ids[j]) {
// Swap j - 1 and j
(ids[j - 1], ids[j]) = (ids[j], ids[j - 1]);
(assets[j - 1], assets[j]) = (assets[j], assets[j - 1]);
j--;
}
i++;
}
}
function _loadAssetArray(address account, uint8 length)
private
view
returns (PortfolioAsset[] memory)
{
// This will overflow the storage pointer
require(length <= MAX_PORTFOLIO_ASSETS);
mapping(address =>
PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store = LibStorage.getPortfolioArrayStorage();
PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS] storage storageArray = store[account];
PortfolioAsset[] memory assets = new PortfolioAsset[](length);
for (uint256 i = 0; i < length; i++) {
PortfolioAssetStorage storage assetStorage = storageArray[i];
PortfolioAsset memory asset = assets[i];
uint256 slot;
assembly {
slot := assetStorage.slot
}
asset.currencyId = assetStorage.currencyId;
asset.maturity = assetStorage.maturity;
asset.assetType = assetStorage.assetType;
asset.notional = assetStorage.notional;
asset.storageSlot = slot;
}
return assets;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../global/LibStorage.sol";
import "./balances/BalanceHandler.sol";
import "./portfolio/BitmapAssetsHandler.sol";
import "./portfolio/PortfolioHandler.sol";
library AccountContextHandler {
using PortfolioHandler for PortfolioState;
bytes18 private constant TURN_OFF_PORTFOLIO_FLAGS = 0x7FFF7FFF7FFF7FFF7FFF7FFF7FFF7FFF7FFF;
event AccountContextUpdate(address indexed account);
/// @notice Returns the account context of a given account
function getAccountContext(address account) internal view returns (AccountContext memory) {
mapping(address => AccountContext) storage store = LibStorage.getAccountStorage();
return store[account];
}
/// @notice Sets the account context of a given account
function setAccountContext(AccountContext memory accountContext, address account) internal {
mapping(address => AccountContext) storage store = LibStorage.getAccountStorage();
store[account] = accountContext;
emit AccountContextUpdate(account);
}
function isBitmapEnabled(AccountContext memory accountContext) internal pure returns (bool) {
return accountContext.bitmapCurrencyId != 0;
}
/// @notice Enables a bitmap type portfolio for an account. A bitmap type portfolio allows
/// an account to hold more fCash than a normal portfolio, except only in a single currency.
/// Once enabled, it cannot be disabled or changed. An account can only enable a bitmap if
/// it has no assets or debt so that we ensure no assets are left stranded.
/// @param accountContext refers to the account where the bitmap will be enabled
/// @param currencyId the id of the currency to enable
/// @param blockTime the current block time to set the next settle time
function enableBitmapForAccount(
AccountContext memory accountContext,
uint16 currencyId,
uint256 blockTime
) internal view {
require(!isBitmapEnabled(accountContext), "Cannot change bitmap");
require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES, "Invalid currency id");
// Account cannot have assets or debts
require(accountContext.assetArrayLength == 0, "Cannot have assets");
require(accountContext.hasDebt == 0x00, "Cannot have debt");
// Ensure that the active currency is set to false in the array so that there is no double
// counting during FreeCollateral
setActiveCurrency(accountContext, currencyId, false, Constants.ACTIVE_IN_BALANCES);
accountContext.bitmapCurrencyId = currencyId;
// Setting this is required to initialize the assets bitmap
uint256 nextSettleTime = DateTime.getTimeUTC0(blockTime);
require(nextSettleTime < type(uint40).max); // dev: blockTime overflow
accountContext.nextSettleTime = uint40(nextSettleTime);
}
/// @notice Returns true if the context needs to settle
function mustSettleAssets(AccountContext memory accountContext) internal view returns (bool) {
uint256 blockTime = block.timestamp;
if (isBitmapEnabled(accountContext)) {
// nextSettleTime will be set to utc0 after settlement so we
// settle if this is strictly less than utc0
return accountContext.nextSettleTime < DateTime.getTimeUTC0(blockTime);
} else {
// 0 value occurs on an uninitialized account
// Assets mature exactly on the blockTime (not one second past) so in this
// case we settle on the block timestamp
return 0 < accountContext.nextSettleTime && accountContext.nextSettleTime <= blockTime;
}
}
/// @notice Checks if a currency id (uint16 max) is in the 9 slots in the account
/// context active currencies list.
/// @dev NOTE: this may be more efficient as a binary search since we know that the array
/// is sorted
function isActiveInBalances(AccountContext memory accountContext, uint256 currencyId)
internal
pure
returns (bool)
{
require(currencyId != 0 && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id
bytes18 currencies = accountContext.activeCurrencies;
if (accountContext.bitmapCurrencyId == currencyId) return true;
while (currencies != 0x00) {
uint256 cid = uint16(bytes2(currencies) & Constants.UNMASK_FLAGS);
if (cid == currencyId) {
// Currency found, return if it is active in balances or not
return bytes2(currencies) & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES;
}
currencies = currencies << 16;
}
return false;
}
/// @notice Iterates through the active currency list and removes, inserts or does nothing
/// to ensure that the active currency list is an ordered byte array of uint16 currency ids
/// that refer to the currencies that an account is active in.
///
/// This is called to ensure that currencies are active when the account has a non zero cash balance,
/// a non zero nToken balance or a portfolio asset.
function setActiveCurrency(
AccountContext memory accountContext,
uint256 currencyId,
bool isActive,
bytes2 flags
) internal pure {
require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id
// If the bitmapped currency is already set then return here. Turning off the bitmap currency
// id requires other logical handling so we will do it elsewhere.
if (isActive && accountContext.bitmapCurrencyId == currencyId) return;
bytes18 prefix;
bytes18 suffix = accountContext.activeCurrencies;
uint256 shifts;
/// There are six possible outcomes from this search:
/// 1. The currency id is in the list
/// - it must be set to active, do nothing
/// - it must be set to inactive, shift suffix and concatenate
/// 2. The current id is greater than the one in the search:
/// - it must be set to active, append to prefix and then concatenate the suffix,
/// ensure that we do not lose the last 2 bytes if set.
/// - it must be set to inactive, it is not in the list, do nothing
/// 3. Reached the end of the list:
/// - it must be set to active, check that the last two bytes are not set and then
/// append to the prefix
/// - it must be set to inactive, do nothing
while (suffix != 0x00) {
uint256 cid = uint256(uint16(bytes2(suffix) & Constants.UNMASK_FLAGS));
// if matches and isActive then return, already in list
if (cid == currencyId && isActive) {
// set flag and return
accountContext.activeCurrencies =
accountContext.activeCurrencies |
(bytes18(flags) >> (shifts * 16));
return;
}
// if matches and not active then shift suffix to remove
if (cid == currencyId && !isActive) {
// turn off flag, if both flags are off then remove
suffix = suffix & ~bytes18(flags);
if (bytes2(suffix) & ~Constants.UNMASK_FLAGS == 0x0000) suffix = suffix << 16;
accountContext.activeCurrencies = prefix | (suffix >> (shifts * 16));
return;
}
// if greater than and isActive then insert into prefix
if (cid > currencyId && isActive) {
prefix = prefix | (bytes18(bytes2(uint16(currencyId)) | flags) >> (shifts * 16));
// check that the total length is not greater than 9, meaning that the last
// two bytes of the active currencies array should be zero
require((accountContext.activeCurrencies << 128) == 0x00); // dev: AC: too many currencies
// append the suffix
accountContext.activeCurrencies = prefix | (suffix >> ((shifts + 1) * 16));
return;
}
// if past the point of the currency id and not active, not in list
if (cid > currencyId && !isActive) return;
prefix = prefix | (bytes18(bytes2(suffix)) >> (shifts * 16));
suffix = suffix << 16;
shifts += 1;
}
// If reached this point and not active then return
if (!isActive) return;
// if end and isActive then insert into suffix, check max length
require(shifts < 9); // dev: AC: too many currencies
accountContext.activeCurrencies =
prefix |
(bytes18(bytes2(uint16(currencyId)) | flags) >> (shifts * 16));
}
function _clearPortfolioActiveFlags(bytes18 activeCurrencies) internal pure returns (bytes18) {
bytes18 result;
// This is required to clear the suffix as we append below
bytes18 suffix = activeCurrencies & TURN_OFF_PORTFOLIO_FLAGS;
uint256 shifts;
// This loop will append all currencies that are active in balances into the result.
while (suffix != 0x00) {
if (bytes2(suffix) & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES) {
// If any flags are active, then append.
result = result | (bytes18(bytes2(suffix)) >> shifts);
shifts += 16;
}
suffix = suffix << 16;
}
return result;
}
/// @notice Stores a portfolio array and updates the account context information, this method should
/// be used whenever updating a portfolio array except in the case of nTokens
function storeAssetsAndUpdateContext(
AccountContext memory accountContext,
address account,
PortfolioState memory portfolioState,
bool isLiquidation
) internal {
// Each of these parameters is recalculated based on the entire array of assets in store assets,
// regardless of whether or not they have been updated.
(bool hasDebt, bytes32 portfolioCurrencies, uint8 assetArrayLength, uint40 nextSettleTime) =
portfolioState.storeAssets(account);
accountContext.nextSettleTime = nextSettleTime;
require(mustSettleAssets(accountContext) == false); // dev: cannot store matured assets
accountContext.assetArrayLength = assetArrayLength;
// During liquidation it is possible for an array to go over the max amount of assets allowed due to
// liquidity tokens being withdrawn into fCash.
if (!isLiquidation) {
require(assetArrayLength <= uint8(Constants.MAX_TRADED_MARKET_INDEX)); // dev: max assets allowed
}
// Sets the hasDebt flag properly based on whether or not portfolio has asset debt, meaning
// a negative fCash balance.
if (hasDebt) {
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT;
} else {
// Turns off the ASSET_DEBT flag
accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_ASSET_DEBT;
}
// Clear the active portfolio active flags and they will be recalculated in the next step
accountContext.activeCurrencies = _clearPortfolioActiveFlags(accountContext.activeCurrencies);
uint256 lastCurrency;
while (portfolioCurrencies != 0) {
// Portfolio currencies will not have flags, it is just an byte array of all the currencies found
// in a portfolio. They are appended in a sorted order so we can compare to the previous currency
// and only set it if they are different.
uint256 currencyId = uint16(bytes2(portfolioCurrencies));
if (currencyId != lastCurrency) {
setActiveCurrency(accountContext, currencyId, true, Constants.ACTIVE_IN_PORTFOLIO);
}
lastCurrency = currencyId;
portfolioCurrencies = portfolioCurrencies << 16;
}
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
interface NotionalCallback {
function notionalCallback(address sender, address account, bytes calldata callbackdata) external;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./AssetRate.sol";
import "./CashGroup.sol";
import "./DateTime.sol";
import "../balances/BalanceHandler.sol";
import "../../global/LibStorage.sol";
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../../math/SafeInt256.sol";
import "../../math/ABDKMath64x64.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library Market {
using SafeMath for uint256;
using SafeInt256 for int256;
using CashGroup for CashGroupParameters;
using AssetRate for AssetRateParameters;
// Max positive value for a ABDK64x64 integer
int256 private constant MAX64 = 0x7FFFFFFFFFFFFFFF;
/// @notice Add liquidity to a market, assuming that it is initialized. If not then
/// this method will revert and the market must be initialized first.
/// Return liquidityTokens and negative fCash to the portfolio
function addLiquidity(MarketParameters memory market, int256 assetCash)
internal
returns (int256 liquidityTokens, int256 fCash)
{
require(market.totalLiquidity > 0, "M: zero liquidity");
if (assetCash == 0) return (0, 0);
require(assetCash > 0); // dev: negative asset cash
liquidityTokens = market.totalLiquidity.mul(assetCash).div(market.totalAssetCash);
// No need to convert this to underlying, assetCash / totalAssetCash is a unitless proportion.
fCash = market.totalfCash.mul(assetCash).div(market.totalAssetCash);
market.totalLiquidity = market.totalLiquidity.add(liquidityTokens);
market.totalfCash = market.totalfCash.add(fCash);
market.totalAssetCash = market.totalAssetCash.add(assetCash);
_setMarketStorageForLiquidity(market);
// Flip the sign to represent the LP's net position
fCash = fCash.neg();
}
/// @notice Remove liquidity from a market, assuming that it is initialized.
/// Return assetCash and positive fCash to the portfolio
function removeLiquidity(MarketParameters memory market, int256 tokensToRemove)
internal
returns (int256 assetCash, int256 fCash)
{
if (tokensToRemove == 0) return (0, 0);
require(tokensToRemove > 0); // dev: negative tokens to remove
assetCash = market.totalAssetCash.mul(tokensToRemove).div(market.totalLiquidity);
fCash = market.totalfCash.mul(tokensToRemove).div(market.totalLiquidity);
market.totalLiquidity = market.totalLiquidity.subNoNeg(tokensToRemove);
market.totalfCash = market.totalfCash.subNoNeg(fCash);
market.totalAssetCash = market.totalAssetCash.subNoNeg(assetCash);
_setMarketStorageForLiquidity(market);
}
function executeTrade(
MarketParameters memory market,
CashGroupParameters memory cashGroup,
int256 fCashToAccount,
uint256 timeToMaturity,
uint256 marketIndex
) internal returns (int256 netAssetCash) {
int256 netAssetCashToReserve;
(netAssetCash, netAssetCashToReserve) = calculateTrade(
market,
cashGroup,
fCashToAccount,
timeToMaturity,
marketIndex
);
MarketStorage storage marketStorage = _getMarketStoragePointer(market);
_setMarketStorage(
marketStorage,
market.totalfCash,
market.totalAssetCash,
market.lastImpliedRate,
market.oracleRate,
market.previousTradeTime
);
BalanceHandler.incrementFeeToReserve(cashGroup.currencyId, netAssetCashToReserve);
}
/// @notice Calculates the asset cash amount the results from trading fCashToAccount with the market. A positive
/// fCashToAccount is equivalent of lending, a negative is borrowing. Updates the market state in memory.
/// @param market the current market state
/// @param cashGroup cash group configuration parameters
/// @param fCashToAccount the fCash amount that will be deposited into the user's portfolio. The net change
/// to the market is in the opposite direction.
/// @param timeToMaturity number of seconds until maturity
/// @return netAssetCash, netAssetCashToReserve
function calculateTrade(
MarketParameters memory market,
CashGroupParameters memory cashGroup,
int256 fCashToAccount,
uint256 timeToMaturity,
uint256 marketIndex
) internal view returns (int256, int256) {
// We return false if there is not enough fCash to support this trade.
// if fCashToAccount > 0 and totalfCash - fCashToAccount <= 0 then the trade will fail
// if fCashToAccount < 0 and totalfCash > 0 then this will always pass
if (market.totalfCash <= fCashToAccount) return (0, 0);
// Calculates initial rate factors for the trade
(int256 rateScalar, int256 totalCashUnderlying, int256 rateAnchor) =
getExchangeRateFactors(market, cashGroup, timeToMaturity, marketIndex);
// Calculates the exchange rate from cash to fCash before any liquidity fees
// are applied
int256 preFeeExchangeRate;
{
bool success;
(preFeeExchangeRate, success) = _getExchangeRate(
market.totalfCash,
totalCashUnderlying,
rateScalar,
rateAnchor,
fCashToAccount
);
if (!success) return (0, 0);
}
// Given the exchange rate, returns the net cash amounts to apply to each of the
// three relevant balances.
(int256 netCashToAccount, int256 netCashToMarket, int256 netCashToReserve) =
_getNetCashAmountsUnderlying(
cashGroup,
preFeeExchangeRate,
fCashToAccount,
timeToMaturity
);
// Signifies a failed net cash amount calculation
if (netCashToAccount == 0) return (0, 0);
{
// Set the new implied interest rate after the trade has taken effect, this
// will be used to calculate the next trader's interest rate.
market.totalfCash = market.totalfCash.subNoNeg(fCashToAccount);
market.lastImpliedRate = getImpliedRate(
market.totalfCash,
totalCashUnderlying.add(netCashToMarket),
rateScalar,
rateAnchor,
timeToMaturity
);
// It's technically possible that the implied rate is actually exactly zero (or
// more accurately the natural log rounds down to zero) but we will still fail
// in this case. If this does happen we may assume that markets are not initialized.
if (market.lastImpliedRate == 0) return (0, 0);
}
return
_setNewMarketState(
market,
cashGroup.assetRate,
netCashToAccount,
netCashToMarket,
netCashToReserve
);
}
/// @notice Returns factors for calculating exchange rates
/// @return
/// rateScalar: a scalar value in rate precision that defines the slope of the line
/// totalCashUnderlying: the converted asset cash to underlying cash for calculating
/// the exchange rates for the trade
/// rateAnchor: an offset from the x axis to maintain interest rate continuity over time
function getExchangeRateFactors(
MarketParameters memory market,
CashGroupParameters memory cashGroup,
uint256 timeToMaturity,
uint256 marketIndex
)
internal
pure
returns (
int256,
int256,
int256
)
{
int256 rateScalar = cashGroup.getRateScalar(marketIndex, timeToMaturity);
int256 totalCashUnderlying = cashGroup.assetRate.convertToUnderlying(market.totalAssetCash);
// This would result in a divide by zero
if (market.totalfCash == 0 || totalCashUnderlying == 0) return (0, 0, 0);
// Get the rate anchor given the market state, this will establish the baseline for where
// the exchange rate is set.
int256 rateAnchor;
{
bool success;
(rateAnchor, success) = _getRateAnchor(
market.totalfCash,
market.lastImpliedRate,
totalCashUnderlying,
rateScalar,
timeToMaturity
);
if (!success) return (0, 0, 0);
}
return (rateScalar, totalCashUnderlying, rateAnchor);
}
/// @dev Returns net asset cash amounts to the account, the market and the reserve
/// @return
/// netCashToAccount: this is a positive or negative amount of cash change to the account
/// netCashToMarket: this is a positive or negative amount of cash change in the market
// netCashToReserve: this is always a positive amount of cash accrued to the reserve
function _getNetCashAmountsUnderlying(
CashGroupParameters memory cashGroup,
int256 preFeeExchangeRate,
int256 fCashToAccount,
uint256 timeToMaturity
)
private
pure
returns (
int256,
int256,
int256
)
{
// Fees are specified in basis points which is an rate precision denomination. We convert this to
// an exchange rate denomination for the given time to maturity. (i.e. get e^(fee * t) and multiply
// or divide depending on the side of the trade).
// tradeExchangeRate = exp((tradeInterestRateNoFee +/- fee) * timeToMaturity)
// tradeExchangeRate = tradeExchangeRateNoFee (* or /) exp(fee * timeToMaturity)
// cash = fCash / exchangeRate, exchangeRate > 1
int256 preFeeCashToAccount =
fCashToAccount.divInRatePrecision(preFeeExchangeRate).neg();
int256 fee = getExchangeRateFromImpliedRate(cashGroup.getTotalFee(), timeToMaturity);
if (fCashToAccount > 0) {
// Lending
// Dividing reduces exchange rate, lending should receive less fCash for cash
int256 postFeeExchangeRate = preFeeExchangeRate.divInRatePrecision(fee);
// It's possible that the fee pushes exchange rates into negative territory. This is not possible
// when borrowing. If this happens then the trade has failed.
if (postFeeExchangeRate < Constants.RATE_PRECISION) return (0, 0, 0);
// cashToAccount = -(fCashToAccount / exchangeRate)
// postFeeExchangeRate = preFeeExchangeRate / feeExchangeRate
// preFeeCashToAccount = -(fCashToAccount / preFeeExchangeRate)
// postFeeCashToAccount = -(fCashToAccount / postFeeExchangeRate)
// netFee = preFeeCashToAccount - postFeeCashToAccount
// netFee = (fCashToAccount / postFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate)
// netFee = ((fCashToAccount * feeExchangeRate) / preFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate)
// netFee = (fCashToAccount / preFeeExchangeRate) * (feeExchangeRate - 1)
// netFee = -(preFeeCashToAccount) * (feeExchangeRate - 1)
// netFee = preFeeCashToAccount * (1 - feeExchangeRate)
// RATE_PRECISION - fee will be negative here, preFeeCashToAccount < 0, fee > 0
fee = preFeeCashToAccount.mulInRatePrecision(Constants.RATE_PRECISION.sub(fee));
} else {
// Borrowing
// cashToAccount = -(fCashToAccount / exchangeRate)
// postFeeExchangeRate = preFeeExchangeRate * feeExchangeRate
// netFee = preFeeCashToAccount - postFeeCashToAccount
// netFee = (fCashToAccount / postFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate)
// netFee = ((fCashToAccount / (feeExchangeRate * preFeeExchangeRate)) - (fCashToAccount / preFeeExchangeRate)
// netFee = (fCashToAccount / preFeeExchangeRate) * (1 / feeExchangeRate - 1)
// netFee = preFeeCashToAccount * ((1 - feeExchangeRate) / feeExchangeRate)
// NOTE: preFeeCashToAccount is negative in this branch so we negate it to ensure that fee is a positive number
// preFee * (1 - fee) / fee will be negative, use neg() to flip to positive
// RATE_PRECISION - fee will be negative
fee = preFeeCashToAccount.mul(Constants.RATE_PRECISION.sub(fee)).div(fee).neg();
}
int256 cashToReserve =
fee.mul(cashGroup.getReserveFeeShare()).div(Constants.PERCENTAGE_DECIMALS);
return (
// postFeeCashToAccount = preFeeCashToAccount - fee
preFeeCashToAccount.sub(fee),
// netCashToMarket = -(preFeeCashToAccount - fee + cashToReserve)
(preFeeCashToAccount.sub(fee).add(cashToReserve)).neg(),
cashToReserve
);
}
/// @notice Sets the new market state
/// @return
/// netAssetCashToAccount: the positive or negative change in asset cash to the account
/// assetCashToReserve: the positive amount of cash that accrues to the reserve
function _setNewMarketState(
MarketParameters memory market,
AssetRateParameters memory assetRate,
int256 netCashToAccount,
int256 netCashToMarket,
int256 netCashToReserve
) private view returns (int256, int256) {
int256 netAssetCashToMarket = assetRate.convertFromUnderlying(netCashToMarket);
// Set storage checks that total asset cash is above zero
market.totalAssetCash = market.totalAssetCash.add(netAssetCashToMarket);
// Sets the trade time for the next oracle update
market.previousTradeTime = block.timestamp;
int256 assetCashToReserve = assetRate.convertFromUnderlying(netCashToReserve);
int256 netAssetCashToAccount = assetRate.convertFromUnderlying(netCashToAccount);
return (netAssetCashToAccount, assetCashToReserve);
}
/// @notice Rate anchors update as the market gets closer to maturity. Rate anchors are not comparable
/// across time or markets but implied rates are. The goal here is to ensure that the implied rate
/// before and after the rate anchor update is the same. Therefore, the market will trade at the same implied
/// rate that it last traded at. If these anchors do not update then it opens up the opportunity for arbitrage
/// which will hurt the liquidity providers.
///
/// The rate anchor will update as the market rolls down to maturity. The calculation is:
/// newExchangeRate = e^(lastImpliedRate * timeToMaturity / Constants.IMPLIED_RATE_TIME)
/// newAnchor = newExchangeRate - ln((proportion / (1 - proportion)) / rateScalar
///
/// where:
/// lastImpliedRate = ln(exchangeRate') * (Constants.IMPLIED_RATE_TIME / timeToMaturity')
/// (calculated when the last trade in the market was made)
/// @return the new rate anchor and a boolean that signifies success
function _getRateAnchor(
int256 totalfCash,
uint256 lastImpliedRate,
int256 totalCashUnderlying,
int256 rateScalar,
uint256 timeToMaturity
) internal pure returns (int256, bool) {
// This is the exchange rate at the new time to maturity
int256 newExchangeRate = getExchangeRateFromImpliedRate(lastImpliedRate, timeToMaturity);
if (newExchangeRate < Constants.RATE_PRECISION) return (0, false);
int256 rateAnchor;
{
// totalfCash / (totalfCash + totalCashUnderlying)
int256 proportion =
totalfCash.divInRatePrecision(totalfCash.add(totalCashUnderlying));
(int256 lnProportion, bool success) = _logProportion(proportion);
if (!success) return (0, false);
// newExchangeRate - ln(proportion / (1 - proportion)) / rateScalar
rateAnchor = newExchangeRate.sub(lnProportion.divInRatePrecision(rateScalar));
}
return (rateAnchor, true);
}
/// @notice Calculates the current market implied rate.
/// @return the implied rate and a bool that is true on success
function getImpliedRate(
int256 totalfCash,
int256 totalCashUnderlying,
int256 rateScalar,
int256 rateAnchor,
uint256 timeToMaturity
) internal pure returns (uint256) {
// This will check for exchange rates < Constants.RATE_PRECISION
(int256 exchangeRate, bool success) =
_getExchangeRate(totalfCash, totalCashUnderlying, rateScalar, rateAnchor, 0);
if (!success) return 0;
// Uses continuous compounding to calculate the implied rate:
// ln(exchangeRate) * Constants.IMPLIED_RATE_TIME / timeToMaturity
int128 rate = ABDKMath64x64.fromInt(exchangeRate);
// Scales down to a floating point for LN
int128 rateScaled = ABDKMath64x64.div(rate, Constants.RATE_PRECISION_64x64);
// We will not have a negative log here because we check that exchangeRate > Constants.RATE_PRECISION
// inside getExchangeRate
int128 lnRateScaled = ABDKMath64x64.ln(rateScaled);
// Scales up to a fixed point
uint256 lnRate =
ABDKMath64x64.toUInt(ABDKMath64x64.mul(lnRateScaled, Constants.RATE_PRECISION_64x64));
// lnRate * IMPLIED_RATE_TIME / ttm
uint256 impliedRate = lnRate.mul(Constants.IMPLIED_RATE_TIME).div(timeToMaturity);
// Implied rates over 429% will overflow, this seems like a safe assumption
if (impliedRate > type(uint32).max) return 0;
return impliedRate;
}
/// @notice Converts an implied rate to an exchange rate given a time to maturity. The
/// formula is E = e^rt
function getExchangeRateFromImpliedRate(uint256 impliedRate, uint256 timeToMaturity)
internal
pure
returns (int256)
{
int128 expValue =
ABDKMath64x64.fromUInt(
impliedRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME)
);
int128 expValueScaled = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64);
int128 expResult = ABDKMath64x64.exp(expValueScaled);
int128 expResultScaled = ABDKMath64x64.mul(expResult, Constants.RATE_PRECISION_64x64);
return ABDKMath64x64.toInt(expResultScaled);
}
/// @notice Returns the exchange rate between fCash and cash for the given market
/// Calculates the following exchange rate:
/// (1 / rateScalar) * ln(proportion / (1 - proportion)) + rateAnchor
/// where:
/// proportion = totalfCash / (totalfCash + totalUnderlyingCash)
/// @dev has an underscore to denote as private but is marked internal for the mock
function _getExchangeRate(
int256 totalfCash,
int256 totalCashUnderlying,
int256 rateScalar,
int256 rateAnchor,
int256 fCashToAccount
) internal pure returns (int256, bool) {
int256 numerator = totalfCash.subNoNeg(fCashToAccount);
// This is the proportion scaled by Constants.RATE_PRECISION
// (totalfCash + fCash) / (totalfCash + totalCashUnderlying)
int256 proportion =
numerator.divInRatePrecision(totalfCash.add(totalCashUnderlying));
// This limit is here to prevent the market from reaching extremely high interest rates via an
// excessively large proportion (high amounts of fCash relative to cash).
// Market proportion can only increase via borrowing (fCash is added to the market and cash is
// removed). Over time, the returns from asset cash will slightly decrease the proportion (the
// value of cash underlying in the market must be monotonically increasing). Therefore it is not
// possible for the proportion to go over max market proportion unless borrowing occurs.
if (proportion > Constants.MAX_MARKET_PROPORTION) return (0, false);
(int256 lnProportion, bool success) = _logProportion(proportion);
if (!success) return (0, false);
// lnProportion / rateScalar + rateAnchor
int256 rate = lnProportion.divInRatePrecision(rateScalar).add(rateAnchor);
// Do not succeed if interest rates fall below 1
if (rate < Constants.RATE_PRECISION) {
return (0, false);
} else {
return (rate, true);
}
}
/// @dev This method calculates the log of the proportion inside the logit function which is
/// defined as ln(proportion / (1 - proportion)). Special handling here is required to deal with
/// fixed point precision and the ABDK library.
function _logProportion(int256 proportion) internal pure returns (int256, bool) {
// This will result in divide by zero, short circuit
if (proportion == Constants.RATE_PRECISION) return (0, false);
// Convert proportion to what is used inside the logit function (p / (1-p))
int256 logitP = proportion.divInRatePrecision(Constants.RATE_PRECISION.sub(proportion));
// ABDK does not handle log of numbers that are less than 1, in order to get the right value
// scaled by RATE_PRECISION we use the log identity:
// (ln(logitP / RATE_PRECISION)) * RATE_PRECISION = (ln(logitP) - ln(RATE_PRECISION)) * RATE_PRECISION
int128 abdkProportion = ABDKMath64x64.fromInt(logitP);
// Here, abdk will revert due to negative log so abort
if (abdkProportion <= 0) return (0, false);
int256 result =
ABDKMath64x64.toInt(
ABDKMath64x64.mul(
ABDKMath64x64.sub(
ABDKMath64x64.ln(abdkProportion),
Constants.LOG_RATE_PRECISION_64x64
),
Constants.RATE_PRECISION_64x64
)
);
return (result, true);
}
/// @notice Oracle rate protects against short term price manipulation. Time window will be set to a value
/// on the order of minutes to hours. This is to protect fCash valuations from market manipulation. For example,
/// a trader could use a flash loan to dump a large amount of cash into the market and depress interest rates.
/// Since we value fCash in portfolios based on these rates, portfolio values will decrease and they may then
/// be liquidated.
///
/// Oracle rates are calculated when the market is loaded from storage.
///
/// The oracle rate is a lagged weighted average over a short term price window. If we are past
/// the short term window then we just set the rate to the lastImpliedRate, otherwise we take the
/// weighted average:
/// lastImpliedRatePreTrade * (currentTs - previousTs) / timeWindow +
/// oracleRatePrevious * (1 - (currentTs - previousTs) / timeWindow)
function _updateRateOracle(
uint256 previousTradeTime,
uint256 lastImpliedRate,
uint256 oracleRate,
uint256 rateOracleTimeWindow,
uint256 blockTime
) private pure returns (uint256) {
require(rateOracleTimeWindow > 0); // dev: update rate oracle, time window zero
// This can occur when using a view function get to a market state in the past
if (previousTradeTime > blockTime) return lastImpliedRate;
uint256 timeDiff = blockTime.sub(previousTradeTime);
if (timeDiff > rateOracleTimeWindow) {
// If past the time window just return the lastImpliedRate
return lastImpliedRate;
}
// (currentTs - previousTs) / timeWindow
uint256 lastTradeWeight =
timeDiff.mul(uint256(Constants.RATE_PRECISION)).div(rateOracleTimeWindow);
// 1 - (currentTs - previousTs) / timeWindow
uint256 oracleWeight = uint256(Constants.RATE_PRECISION).sub(lastTradeWeight);
uint256 newOracleRate =
(lastImpliedRate.mul(lastTradeWeight).add(oracleRate.mul(oracleWeight))).div(
uint256(Constants.RATE_PRECISION)
);
return newOracleRate;
}
function getOracleRate(
uint256 currencyId,
uint256 maturity,
uint256 rateOracleTimeWindow,
uint256 blockTime
) internal view returns (uint256) {
mapping(uint256 => mapping(uint256 =>
mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage();
uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER;
MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate];
uint256 lastImpliedRate = marketStorage.lastImpliedRate;
uint256 oracleRate = marketStorage.oracleRate;
uint256 previousTradeTime = marketStorage.previousTradeTime;
// If the oracle rate is set to zero this can only be because the markets have past their settlement
// date but the new set of markets has not yet been initialized. This means that accounts cannot be liquidated
// during this time, but market initialization can be called by anyone so the actual time that this condition
// exists for should be quite short.
require(oracleRate > 0, "Market not initialized");
return
_updateRateOracle(
previousTradeTime,
lastImpliedRate,
oracleRate,
rateOracleTimeWindow,
blockTime
);
}
/// @notice Reads a market object directly from storage. `loadMarket` should be called instead of this method
/// which ensures that the rate oracle is set properly.
function _loadMarketStorage(
MarketParameters memory market,
uint256 currencyId,
uint256 maturity,
bool needsLiquidity,
uint256 settlementDate
) private view {
// Market object always uses the most current reference time as the settlement date
mapping(uint256 => mapping(uint256 =>
mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage();
MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate];
bytes32 slot;
assembly {
slot := marketStorage.slot
}
market.storageSlot = slot;
market.maturity = maturity;
market.totalfCash = marketStorage.totalfCash;
market.totalAssetCash = marketStorage.totalAssetCash;
market.lastImpliedRate = marketStorage.lastImpliedRate;
market.oracleRate = marketStorage.oracleRate;
market.previousTradeTime = marketStorage.previousTradeTime;
if (needsLiquidity) {
market.totalLiquidity = marketStorage.totalLiquidity;
} else {
market.totalLiquidity = 0;
}
}
function _getMarketStoragePointer(
MarketParameters memory market
) private pure returns (MarketStorage storage marketStorage) {
bytes32 slot = market.storageSlot;
assembly {
marketStorage.slot := slot
}
}
function _setMarketStorageForLiquidity(MarketParameters memory market) internal {
MarketStorage storage marketStorage = _getMarketStoragePointer(market);
// Oracle rate does not change on liquidity
uint32 storedOracleRate = marketStorage.oracleRate;
_setMarketStorage(
marketStorage,
market.totalfCash,
market.totalAssetCash,
market.lastImpliedRate,
storedOracleRate,
market.previousTradeTime
);
_setTotalLiquidity(marketStorage, market.totalLiquidity);
}
function setMarketStorageForInitialize(
MarketParameters memory market,
uint256 currencyId,
uint256 settlementDate
) internal {
// On initialization we have not yet calculated the storage slot so we get it here.
mapping(uint256 => mapping(uint256 =>
mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage();
MarketStorage storage marketStorage = store[currencyId][market.maturity][settlementDate];
_setMarketStorage(
marketStorage,
market.totalfCash,
market.totalAssetCash,
market.lastImpliedRate,
market.oracleRate,
market.previousTradeTime
);
_setTotalLiquidity(marketStorage, market.totalLiquidity);
}
function _setTotalLiquidity(
MarketStorage storage marketStorage,
int256 totalLiquidity
) internal {
require(totalLiquidity >= 0 && totalLiquidity <= type(uint80).max); // dev: market storage totalLiquidity overflow
marketStorage.totalLiquidity = uint80(totalLiquidity);
}
function _setMarketStorage(
MarketStorage storage marketStorage,
int256 totalfCash,
int256 totalAssetCash,
uint256 lastImpliedRate,
uint256 oracleRate,
uint256 previousTradeTime
) private {
require(totalfCash >= 0 && totalfCash <= type(uint80).max); // dev: storage totalfCash overflow
require(totalAssetCash >= 0 && totalAssetCash <= type(uint80).max); // dev: storage totalAssetCash overflow
require(0 < lastImpliedRate && lastImpliedRate <= type(uint32).max); // dev: storage lastImpliedRate overflow
require(0 < oracleRate && oracleRate <= type(uint32).max); // dev: storage oracleRate overflow
require(0 <= previousTradeTime && previousTradeTime <= type(uint32).max); // dev: storage previous trade time overflow
marketStorage.totalfCash = uint80(totalfCash);
marketStorage.totalAssetCash = uint80(totalAssetCash);
marketStorage.lastImpliedRate = uint32(lastImpliedRate);
marketStorage.oracleRate = uint32(oracleRate);
marketStorage.previousTradeTime = uint32(previousTradeTime);
}
/// @notice Creates a market object and ensures that the rate oracle time window is updated appropriately.
function loadMarket(
MarketParameters memory market,
uint256 currencyId,
uint256 maturity,
uint256 blockTime,
bool needsLiquidity,
uint256 rateOracleTimeWindow
) internal view {
// Always reference the current settlement date
uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER;
loadMarketWithSettlementDate(
market,
currencyId,
maturity,
blockTime,
needsLiquidity,
rateOracleTimeWindow,
settlementDate
);
}
/// @notice Creates a market object and ensures that the rate oracle time window is updated appropriately, this
/// is mainly used in the InitializeMarketAction contract.
function loadMarketWithSettlementDate(
MarketParameters memory market,
uint256 currencyId,
uint256 maturity,
uint256 blockTime,
bool needsLiquidity,
uint256 rateOracleTimeWindow,
uint256 settlementDate
) internal view {
_loadMarketStorage(market, currencyId, maturity, needsLiquidity, settlementDate);
market.oracleRate = _updateRateOracle(
market.previousTradeTime,
market.lastImpliedRate,
market.oracleRate,
rateOracleTimeWindow,
blockTime
);
}
function loadSettlementMarket(
MarketParameters memory market,
uint256 currencyId,
uint256 maturity,
uint256 settlementDate
) internal view {
_loadMarketStorage(market, currencyId, maturity, true, settlementDate);
}
/// Uses Newton's method to converge on an fCash amount given the amount of
/// cash. The relation between cash and fcash is:
/// cashAmount * exchangeRate * fee + fCash = 0
/// where exchangeRate(fCash) = (rateScalar ^ -1) * ln(p / (1 - p)) + rateAnchor
/// p = (totalfCash - fCash) / (totalfCash + totalCash)
/// if cashAmount < 0: fee = feeRate ^ -1
/// if cashAmount > 0: fee = feeRate
///
/// Newton's method is:
/// fCash_(n+1) = fCash_n - f(fCash) / f'(fCash)
///
/// f(fCash) = cashAmount * exchangeRate(fCash) * fee + fCash
///
/// (totalfCash + totalCash)
/// exchangeRate'(fCash) = - ------------------------------------------
/// (totalfCash - fCash) * (totalCash + fCash)
///
/// https://www.wolframalpha.com/input/?i=ln%28%28%28a-x%29%2F%28a%2Bb%29%29%2F%281-%28a-x%29%2F%28a%2Bb%29%29%29
///
/// (cashAmount * fee) * (totalfCash + totalCash)
/// f'(fCash) = 1 - ------------------------------------------------------
/// rateScalar * (totalfCash - fCash) * (totalCash + fCash)
///
/// NOTE: each iteration costs about 11.3k so this is only done via a view function.
function getfCashGivenCashAmount(
int256 totalfCash,
int256 netCashToAccount,
int256 totalCashUnderlying,
int256 rateScalar,
int256 rateAnchor,
int256 feeRate,
int256 maxDelta
) internal pure returns (int256) {
require(maxDelta >= 0);
int256 fCashChangeToAccountGuess = netCashToAccount.mulInRatePrecision(rateAnchor).neg();
for (uint8 i = 0; i < 250; i++) {
(int256 exchangeRate, bool success) =
_getExchangeRate(
totalfCash,
totalCashUnderlying,
rateScalar,
rateAnchor,
fCashChangeToAccountGuess
);
require(success); // dev: invalid exchange rate
int256 delta =
_calculateDelta(
netCashToAccount,
totalfCash,
totalCashUnderlying,
rateScalar,
fCashChangeToAccountGuess,
exchangeRate,
feeRate
);
if (delta.abs() <= maxDelta) return fCashChangeToAccountGuess;
fCashChangeToAccountGuess = fCashChangeToAccountGuess.sub(delta);
}
revert("No convergence");
}
/// @dev Calculates: f(fCash) / f'(fCash)
/// f(fCash) = cashAmount * exchangeRate * fee + fCash
/// (cashAmount * fee) * (totalfCash + totalCash)
/// f'(fCash) = 1 - ------------------------------------------------------
/// rateScalar * (totalfCash - fCash) * (totalCash + fCash)
function _calculateDelta(
int256 cashAmount,
int256 totalfCash,
int256 totalCashUnderlying,
int256 rateScalar,
int256 fCashGuess,
int256 exchangeRate,
int256 feeRate
) private pure returns (int256) {
int256 derivative;
// rateScalar * (totalfCash - fCash) * (totalCash + fCash)
// Precision: TOKEN_PRECISION ^ 2
int256 denominator =
rateScalar.mulInRatePrecision(
(totalfCash.sub(fCashGuess)).mul(totalCashUnderlying.add(fCashGuess))
);
if (fCashGuess > 0) {
// Lending
exchangeRate = exchangeRate.divInRatePrecision(feeRate);
require(exchangeRate >= Constants.RATE_PRECISION); // dev: rate underflow
// (cashAmount / fee) * (totalfCash + totalCash)
// Precision: TOKEN_PRECISION ^ 2
derivative = cashAmount
.mul(totalfCash.add(totalCashUnderlying))
.divInRatePrecision(feeRate);
} else {
// Borrowing
exchangeRate = exchangeRate.mulInRatePrecision(feeRate);
require(exchangeRate >= Constants.RATE_PRECISION); // dev: rate underflow
// (cashAmount * fee) * (totalfCash + totalCash)
// Precision: TOKEN_PRECISION ^ 2
derivative = cashAmount.mulInRatePrecision(
feeRate.mul(totalfCash.add(totalCashUnderlying))
);
}
// 1 - numerator / denominator
// Precision: TOKEN_PRECISION
derivative = Constants.INTERNAL_TOKEN_PRECISION.sub(derivative.div(denominator));
// f(fCash) = cashAmount * exchangeRate * fee + fCash
// NOTE: exchangeRate at this point already has the fee taken into account
int256 numerator = cashAmount.mulInRatePrecision(exchangeRate);
numerator = numerator.add(fCashGuess);
// f(fCash) / f'(fCash), note that they are both denominated as cashAmount so use TOKEN_PRECISION
// here instead of RATE_PRECISION
return numerator.mul(Constants.INTERNAL_TOKEN_PRECISION).div(derivative);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./Market.sol";
import "./AssetRate.sol";
import "./DateTime.sol";
import "../../global/LibStorage.sol";
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library CashGroup {
using SafeMath for uint256;
using SafeInt256 for int256;
using AssetRate for AssetRateParameters;
using Market for MarketParameters;
// Bit number references for each parameter in the 32 byte word (0-indexed)
uint256 private constant MARKET_INDEX_BIT = 31;
uint256 private constant RATE_ORACLE_TIME_WINDOW_BIT = 30;
uint256 private constant TOTAL_FEE_BIT = 29;
uint256 private constant RESERVE_FEE_SHARE_BIT = 28;
uint256 private constant DEBT_BUFFER_BIT = 27;
uint256 private constant FCASH_HAIRCUT_BIT = 26;
uint256 private constant SETTLEMENT_PENALTY_BIT = 25;
uint256 private constant LIQUIDATION_FCASH_HAIRCUT_BIT = 24;
uint256 private constant LIQUIDATION_DEBT_BUFFER_BIT = 23;
// 7 bytes allocated, one byte per market for the liquidity token haircut
uint256 private constant LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT = 22;
// 7 bytes allocated, one byte per market for the rate scalar
uint256 private constant RATE_SCALAR_FIRST_BIT = 15;
// Offsets for the bytes of the different parameters
uint256 private constant MARKET_INDEX = (31 - MARKET_INDEX_BIT) * 8;
uint256 private constant RATE_ORACLE_TIME_WINDOW = (31 - RATE_ORACLE_TIME_WINDOW_BIT) * 8;
uint256 private constant TOTAL_FEE = (31 - TOTAL_FEE_BIT) * 8;
uint256 private constant RESERVE_FEE_SHARE = (31 - RESERVE_FEE_SHARE_BIT) * 8;
uint256 private constant DEBT_BUFFER = (31 - DEBT_BUFFER_BIT) * 8;
uint256 private constant FCASH_HAIRCUT = (31 - FCASH_HAIRCUT_BIT) * 8;
uint256 private constant SETTLEMENT_PENALTY = (31 - SETTLEMENT_PENALTY_BIT) * 8;
uint256 private constant LIQUIDATION_FCASH_HAIRCUT = (31 - LIQUIDATION_FCASH_HAIRCUT_BIT) * 8;
uint256 private constant LIQUIDATION_DEBT_BUFFER = (31 - LIQUIDATION_DEBT_BUFFER_BIT) * 8;
uint256 private constant LIQUIDITY_TOKEN_HAIRCUT = (31 - LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT) * 8;
uint256 private constant RATE_SCALAR = (31 - RATE_SCALAR_FIRST_BIT) * 8;
/// @notice Returns the rate scalar scaled by time to maturity. The rate scalar multiplies
/// the ln() portion of the liquidity curve as an inverse so it increases with time to
/// maturity. The effect of the rate scalar on slippage must decrease with time to maturity.
function getRateScalar(
CashGroupParameters memory cashGroup,
uint256 marketIndex,
uint256 timeToMaturity
) internal pure returns (int256) {
require(1 <= marketIndex && marketIndex <= cashGroup.maxMarketIndex); // dev: invalid market index
uint256 offset = RATE_SCALAR + 8 * (marketIndex - 1);
int256 scalar = int256(uint8(uint256(cashGroup.data >> offset))) * Constants.RATE_PRECISION;
int256 rateScalar =
scalar.mul(int256(Constants.IMPLIED_RATE_TIME)).div(SafeInt256.toInt(timeToMaturity));
// Rate scalar is denominated in RATE_PRECISION, it is unlikely to underflow in the
// division above.
require(rateScalar > 0); // dev: rate scalar underflow
return rateScalar;
}
/// @notice Haircut on liquidity tokens to account for the risk associated with changes in the
/// proportion of cash to fCash within the pool. This is set as a percentage less than or equal to 100.
function getLiquidityHaircut(CashGroupParameters memory cashGroup, uint256 assetType)
internal
pure
returns (uint8)
{
require(
Constants.MIN_LIQUIDITY_TOKEN_INDEX <= assetType &&
assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX
); // dev: liquidity haircut invalid asset type
uint256 offset =
LIQUIDITY_TOKEN_HAIRCUT + 8 * (assetType - Constants.MIN_LIQUIDITY_TOKEN_INDEX);
return uint8(uint256(cashGroup.data >> offset));
}
/// @notice Total trading fee denominated in RATE_PRECISION with basis point increments
function getTotalFee(CashGroupParameters memory cashGroup) internal pure returns (uint256) {
return uint256(uint8(uint256(cashGroup.data >> TOTAL_FEE))) * Constants.BASIS_POINT;
}
/// @notice Percentage of the total trading fee that goes to the reserve
function getReserveFeeShare(CashGroupParameters memory cashGroup)
internal
pure
returns (int256)
{
return uint8(uint256(cashGroup.data >> RESERVE_FEE_SHARE));
}
/// @notice fCash haircut for valuation denominated in rate precision with five basis point increments
function getfCashHaircut(CashGroupParameters memory cashGroup) internal pure returns (uint256) {
return
uint256(uint8(uint256(cashGroup.data >> FCASH_HAIRCUT))) * Constants.FIVE_BASIS_POINTS;
}
/// @notice fCash debt buffer for valuation denominated in rate precision with five basis point increments
function getDebtBuffer(CashGroupParameters memory cashGroup) internal pure returns (uint256) {
return uint256(uint8(uint256(cashGroup.data >> DEBT_BUFFER))) * Constants.FIVE_BASIS_POINTS;
}
/// @notice Time window factor for the rate oracle denominated in seconds with five minute increments.
function getRateOracleTimeWindow(CashGroupParameters memory cashGroup)
internal
pure
returns (uint256)
{
// This is denominated in 5 minute increments in storage
return uint256(uint8(uint256(cashGroup.data >> RATE_ORACLE_TIME_WINDOW))) * Constants.FIVE_MINUTES;
}
/// @notice Penalty rate for settling cash debts denominated in basis points
function getSettlementPenalty(CashGroupParameters memory cashGroup)
internal
pure
returns (uint256)
{
return
uint256(uint8(uint256(cashGroup.data >> SETTLEMENT_PENALTY))) * Constants.FIVE_BASIS_POINTS;
}
/// @notice Haircut for positive fCash during liquidation denominated rate precision
/// with five basis point increments
function getLiquidationfCashHaircut(CashGroupParameters memory cashGroup)
internal
pure
returns (uint256)
{
return
uint256(uint8(uint256(cashGroup.data >> LIQUIDATION_FCASH_HAIRCUT))) * Constants.FIVE_BASIS_POINTS;
}
/// @notice Haircut for negative fCash during liquidation denominated rate precision
/// with five basis point increments
function getLiquidationDebtBuffer(CashGroupParameters memory cashGroup)
internal
pure
returns (uint256)
{
return
uint256(uint8(uint256(cashGroup.data >> LIQUIDATION_DEBT_BUFFER))) * Constants.FIVE_BASIS_POINTS;
}
function loadMarket(
CashGroupParameters memory cashGroup,
MarketParameters memory market,
uint256 marketIndex,
bool needsLiquidity,
uint256 blockTime
) internal view {
require(1 <= marketIndex && marketIndex <= cashGroup.maxMarketIndex, "Invalid market");
uint256 maturity =
DateTime.getReferenceTime(blockTime).add(DateTime.getTradedMarket(marketIndex));
market.loadMarket(
cashGroup.currencyId,
maturity,
blockTime,
needsLiquidity,
getRateOracleTimeWindow(cashGroup)
);
}
/// @notice Returns the linear interpolation between two market rates. The formula is
/// slope = (longMarket.oracleRate - shortMarket.oracleRate) / (longMarket.maturity - shortMarket.maturity)
/// interpolatedRate = slope * (assetMaturity - shortMarket.maturity) + shortMarket.oracleRate
function interpolateOracleRate(
uint256 shortMaturity,
uint256 longMaturity,
uint256 shortRate,
uint256 longRate,
uint256 assetMaturity
) internal pure returns (uint256) {
require(shortMaturity < assetMaturity); // dev: cash group interpolation error, short maturity
require(assetMaturity < longMaturity); // dev: cash group interpolation error, long maturity
// It's possible that the rates are inverted where the short market rate > long market rate and
// we will get an underflow here so we check for that
if (longRate >= shortRate) {
return
(longRate - shortRate)
.mul(assetMaturity - shortMaturity)
// No underflow here, checked above
.div(longMaturity - shortMaturity)
.add(shortRate);
} else {
// In this case the slope is negative so:
// interpolatedRate = shortMarket.oracleRate - slope * (assetMaturity - shortMarket.maturity)
// NOTE: this subtraction should never overflow, the linear interpolation between two points above zero
// cannot go below zero
return
shortRate.sub(
// This is reversed to keep it it positive
(shortRate - longRate)
.mul(assetMaturity - shortMaturity)
// No underflow here, checked above
.div(longMaturity - shortMaturity)
);
}
}
/// @dev Gets an oracle rate given any valid maturity.
function calculateOracleRate(
CashGroupParameters memory cashGroup,
uint256 maturity,
uint256 blockTime
) internal view returns (uint256) {
(uint256 marketIndex, bool idiosyncratic) =
DateTime.getMarketIndex(cashGroup.maxMarketIndex, maturity, blockTime);
uint256 timeWindow = getRateOracleTimeWindow(cashGroup);
if (!idiosyncratic) {
return Market.getOracleRate(cashGroup.currencyId, maturity, timeWindow, blockTime);
} else {
uint256 referenceTime = DateTime.getReferenceTime(blockTime);
// DateTime.getMarketIndex returns the market that is past the maturity if idiosyncratic
uint256 longMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex));
uint256 longRate =
Market.getOracleRate(cashGroup.currencyId, longMaturity, timeWindow, blockTime);
uint256 shortMaturity;
uint256 shortRate;
if (marketIndex == 1) {
// In this case the short market is the annualized asset supply rate
shortMaturity = blockTime;
shortRate = cashGroup.assetRate.getSupplyRate();
} else {
// Minimum value for marketIndex here is 2
shortMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex - 1));
shortRate = Market.getOracleRate(
cashGroup.currencyId,
shortMaturity,
timeWindow,
blockTime
);
}
return interpolateOracleRate(shortMaturity, longMaturity, shortRate, longRate, maturity);
}
}
function _getCashGroupStorageBytes(uint256 currencyId) private view returns (bytes32 data) {
mapping(uint256 => bytes32) storage store = LibStorage.getCashGroupStorage();
return store[currencyId];
}
/// @dev Helper method for validating maturities in ERC1155Action
function getMaxMarketIndex(uint256 currencyId) internal view returns (uint8) {
bytes32 data = _getCashGroupStorageBytes(currencyId);
return uint8(data[MARKET_INDEX_BIT]);
}
/// @notice Checks all cash group settings for invalid values and sets them into storage
function setCashGroupStorage(uint256 currencyId, CashGroupSettings calldata cashGroup)
internal
{
// Due to the requirements of the yield curve we do not allow a cash group to have solely a 3 month market.
// The reason is that borrowers will not have a further maturity to roll from their 3 month fixed to a 6 month
// fixed. It also complicates the logic in the nToken initialization method. Additionally, we cannot have cash
// groups with 0 market index, it has no effect.
require(2 <= cashGroup.maxMarketIndex && cashGroup.maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX,
"CG: invalid market index"
);
require(
cashGroup.reserveFeeShare <= Constants.PERCENTAGE_DECIMALS,
"CG: invalid reserve share"
);
require(cashGroup.liquidityTokenHaircuts.length == cashGroup.maxMarketIndex);
require(cashGroup.rateScalars.length == cashGroup.maxMarketIndex);
// This is required so that fCash liquidation can proceed correctly
require(cashGroup.liquidationfCashHaircut5BPS < cashGroup.fCashHaircut5BPS);
require(cashGroup.liquidationDebtBuffer5BPS < cashGroup.debtBuffer5BPS);
// Market indexes cannot decrease or they will leave fCash assets stranded in the future with no valuation curve
uint8 previousMaxMarketIndex = getMaxMarketIndex(currencyId);
require(
previousMaxMarketIndex <= cashGroup.maxMarketIndex,
"CG: market index cannot decrease"
);
// Per cash group settings
bytes32 data =
(bytes32(uint256(cashGroup.maxMarketIndex)) |
(bytes32(uint256(cashGroup.rateOracleTimeWindow5Min)) << RATE_ORACLE_TIME_WINDOW) |
(bytes32(uint256(cashGroup.totalFeeBPS)) << TOTAL_FEE) |
(bytes32(uint256(cashGroup.reserveFeeShare)) << RESERVE_FEE_SHARE) |
(bytes32(uint256(cashGroup.debtBuffer5BPS)) << DEBT_BUFFER) |
(bytes32(uint256(cashGroup.fCashHaircut5BPS)) << FCASH_HAIRCUT) |
(bytes32(uint256(cashGroup.settlementPenaltyRate5BPS)) << SETTLEMENT_PENALTY) |
(bytes32(uint256(cashGroup.liquidationfCashHaircut5BPS)) <<
LIQUIDATION_FCASH_HAIRCUT) |
(bytes32(uint256(cashGroup.liquidationDebtBuffer5BPS)) << LIQUIDATION_DEBT_BUFFER));
// Per market group settings
for (uint256 i = 0; i < cashGroup.liquidityTokenHaircuts.length; i++) {
require(
cashGroup.liquidityTokenHaircuts[i] <= Constants.PERCENTAGE_DECIMALS,
"CG: invalid token haircut"
);
data =
data |
(bytes32(uint256(cashGroup.liquidityTokenHaircuts[i])) <<
(LIQUIDITY_TOKEN_HAIRCUT + i * 8));
}
for (uint256 i = 0; i < cashGroup.rateScalars.length; i++) {
// Causes a divide by zero error
require(cashGroup.rateScalars[i] != 0, "CG: invalid rate scalar");
data = data | (bytes32(uint256(cashGroup.rateScalars[i])) << (RATE_SCALAR + i * 8));
}
mapping(uint256 => bytes32) storage store = LibStorage.getCashGroupStorage();
store[currencyId] = data;
}
/// @notice Deserialize the cash group storage bytes into a user friendly object
function deserializeCashGroupStorage(uint256 currencyId)
internal
view
returns (CashGroupSettings memory)
{
bytes32 data = _getCashGroupStorageBytes(currencyId);
uint8 maxMarketIndex = uint8(data[MARKET_INDEX_BIT]);
uint8[] memory tokenHaircuts = new uint8[](uint256(maxMarketIndex));
uint8[] memory rateScalars = new uint8[](uint256(maxMarketIndex));
for (uint8 i = 0; i < maxMarketIndex; i++) {
tokenHaircuts[i] = uint8(data[LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT - i]);
rateScalars[i] = uint8(data[RATE_SCALAR_FIRST_BIT - i]);
}
return
CashGroupSettings({
maxMarketIndex: maxMarketIndex,
rateOracleTimeWindow5Min: uint8(data[RATE_ORACLE_TIME_WINDOW_BIT]),
totalFeeBPS: uint8(data[TOTAL_FEE_BIT]),
reserveFeeShare: uint8(data[RESERVE_FEE_SHARE_BIT]),
debtBuffer5BPS: uint8(data[DEBT_BUFFER_BIT]),
fCashHaircut5BPS: uint8(data[FCASH_HAIRCUT_BIT]),
settlementPenaltyRate5BPS: uint8(data[SETTLEMENT_PENALTY_BIT]),
liquidationfCashHaircut5BPS: uint8(data[LIQUIDATION_FCASH_HAIRCUT_BIT]),
liquidationDebtBuffer5BPS: uint8(data[LIQUIDATION_DEBT_BUFFER_BIT]),
liquidityTokenHaircuts: tokenHaircuts,
rateScalars: rateScalars
});
}
function _buildCashGroup(uint16 currencyId, AssetRateParameters memory assetRate)
private
view
returns (CashGroupParameters memory)
{
bytes32 data = _getCashGroupStorageBytes(currencyId);
uint256 maxMarketIndex = uint8(data[MARKET_INDEX_BIT]);
return
CashGroupParameters({
currencyId: currencyId,
maxMarketIndex: maxMarketIndex,
assetRate: assetRate,
data: data
});
}
/// @notice Builds a cash group using a view version of the asset rate
function buildCashGroupView(uint16 currencyId)
internal
view
returns (CashGroupParameters memory)
{
AssetRateParameters memory assetRate = AssetRate.buildAssetRateView(currencyId);
return _buildCashGroup(currencyId, assetRate);
}
/// @notice Builds a cash group using a stateful version of the asset rate
function buildCashGroupStateful(uint16 currencyId)
internal
returns (CashGroupParameters memory)
{
AssetRateParameters memory assetRate = AssetRate.buildAssetRateStateful(currencyId);
return _buildCashGroup(currencyId, assetRate);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/Types.sol";
import "../../global/LibStorage.sol";
import "../../global/Constants.sol";
import "../../math/SafeInt256.sol";
import "../../../interfaces/notional/AssetRateAdapter.sol";
library AssetRate {
using SafeInt256 for int256;
event SetSettlementRate(uint256 indexed currencyId, uint256 indexed maturity, uint128 rate);
// Asset rates are in 1e18 decimals (cToken exchange rates), internal balances
// are in 1e8 decimals. Therefore we leave this as 1e18 / 1e8 = 1e10
int256 private constant ASSET_RATE_DECIMAL_DIFFERENCE = 1e10;
/// @notice Converts an internal asset cash value to its underlying token value.
/// @param ar exchange rate object between asset and underlying
/// @param assetBalance amount to convert to underlying
function convertToUnderlying(AssetRateParameters memory ar, int256 assetBalance)
internal
pure
returns (int256)
{
// Calculation here represents:
// rate * balance * internalPrecision / rateDecimals * underlyingPrecision
int256 underlyingBalance = ar.rate
.mul(assetBalance)
.div(ASSET_RATE_DECIMAL_DIFFERENCE)
.div(ar.underlyingDecimals);
return underlyingBalance;
}
/// @notice Converts an internal underlying cash value to its asset cash value
/// @param ar exchange rate object between asset and underlying
/// @param underlyingBalance amount to convert to asset cash, denominated in internal token precision
function convertFromUnderlying(AssetRateParameters memory ar, int256 underlyingBalance)
internal
pure
returns (int256)
{
// Calculation here represents:
// rateDecimals * balance * underlyingPrecision / rate * internalPrecision
int256 assetBalance = underlyingBalance
.mul(ASSET_RATE_DECIMAL_DIFFERENCE)
.mul(ar.underlyingDecimals)
.div(ar.rate);
return assetBalance;
}
/// @notice Returns the current per block supply rate, is used when calculating oracle rates
/// for idiosyncratic fCash with a shorter duration than the 3 month maturity.
function getSupplyRate(AssetRateParameters memory ar) internal view returns (uint256) {
// If the rate oracle is not set, the asset is not interest bearing and has an oracle rate of zero.
if (address(ar.rateOracle) == address(0)) return 0;
uint256 rate = ar.rateOracle.getAnnualizedSupplyRate();
// Zero supply rate is valid since this is an interest rate, we do not divide by
// the supply rate so we do not get div by zero errors.
require(rate >= 0); // dev: invalid supply rate
return rate;
}
function _getAssetRateStorage(uint256 currencyId)
private
view
returns (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces)
{
mapping(uint256 => AssetRateStorage) storage store = LibStorage.getAssetRateStorage();
AssetRateStorage storage ar = store[currencyId];
rateOracle = AssetRateAdapter(ar.rateOracle);
underlyingDecimalPlaces = ar.underlyingDecimalPlaces;
}
/// @notice Gets an asset rate using a view function, does not accrue interest so the
/// exchange rate will not be up to date. Should only be used for non-stateful methods
function _getAssetRateView(uint256 currencyId)
private
view
returns (
int256,
AssetRateAdapter,
uint8
)
{
(AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStorage(currencyId);
int256 rate;
if (address(rateOracle) == address(0)) {
// If no rate oracle is set, then set this to the identity
rate = ASSET_RATE_DECIMAL_DIFFERENCE;
// This will get raised to 10^x and return 1, will not end up with div by zero
underlyingDecimalPlaces = 0;
} else {
rate = rateOracle.getExchangeRateView();
require(rate > 0); // dev: invalid exchange rate
}
return (rate, rateOracle, underlyingDecimalPlaces);
}
/// @notice Gets an asset rate using a stateful function, accrues interest so the
/// exchange rate will be up to date for the current block.
function _getAssetRateStateful(uint256 currencyId)
private
returns (
int256,
AssetRateAdapter,
uint8
)
{
(AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStorage(currencyId);
int256 rate;
if (address(rateOracle) == address(0)) {
// If no rate oracle is set, then set this to the identity
rate = ASSET_RATE_DECIMAL_DIFFERENCE;
// This will get raised to 10^x and return 1, will not end up with div by zero
underlyingDecimalPlaces = 0;
} else {
rate = rateOracle.getExchangeRateStateful();
require(rate > 0); // dev: invalid exchange rate
}
return (rate, rateOracle, underlyingDecimalPlaces);
}
/// @notice Returns an asset rate object using the view method
function buildAssetRateView(uint256 currencyId)
internal
view
returns (AssetRateParameters memory)
{
(int256 rate, AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) =
_getAssetRateView(currencyId);
return
AssetRateParameters({
rateOracle: rateOracle,
rate: rate,
// No overflow, restricted on storage
underlyingDecimals: int256(10**underlyingDecimalPlaces)
});
}
/// @notice Returns an asset rate object using the stateful method
function buildAssetRateStateful(uint256 currencyId)
internal
returns (AssetRateParameters memory)
{
(int256 rate, AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) =
_getAssetRateStateful(currencyId);
return
AssetRateParameters({
rateOracle: rateOracle,
rate: rate,
// No overflow, restricted on storage
underlyingDecimals: int256(10**underlyingDecimalPlaces)
});
}
/// @dev Gets a settlement rate object
function _getSettlementRateStorage(uint256 currencyId, uint256 maturity)
private
view
returns (
int256 settlementRate,
uint8 underlyingDecimalPlaces
)
{
mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store = LibStorage.getSettlementRateStorage();
SettlementRateStorage storage rateStorage = store[currencyId][maturity];
settlementRate = rateStorage.settlementRate;
underlyingDecimalPlaces = rateStorage.underlyingDecimalPlaces;
}
/// @notice Returns a settlement rate object using the view method
function buildSettlementRateView(uint256 currencyId, uint256 maturity)
internal
view
returns (AssetRateParameters memory)
{
// prettier-ignore
(
int256 settlementRate,
uint8 underlyingDecimalPlaces
) = _getSettlementRateStorage(currencyId, maturity);
// Asset exchange rates cannot be zero
if (settlementRate == 0) {
// If settlement rate has not been set then we need to fetch it
// prettier-ignore
(
settlementRate,
/* address */,
underlyingDecimalPlaces
) = _getAssetRateView(currencyId);
}
return AssetRateParameters(
AssetRateAdapter(address(0)),
settlementRate,
// No overflow, restricted on storage
int256(10**underlyingDecimalPlaces)
);
}
/// @notice Returns a settlement rate object and sets the rate if it has not been set yet
function buildSettlementRateStateful(
uint256 currencyId,
uint256 maturity,
uint256 blockTime
) internal returns (AssetRateParameters memory) {
(int256 settlementRate, uint8 underlyingDecimalPlaces) =
_getSettlementRateStorage(currencyId, maturity);
if (settlementRate == 0) {
// Settlement rate has not yet been set, set it in this branch
AssetRateAdapter rateOracle;
// If rate oracle == 0 then this will return the identity settlement rate
// prettier-ignore
(
settlementRate,
rateOracle,
underlyingDecimalPlaces
) = _getAssetRateStateful(currencyId);
if (address(rateOracle) != address(0)) {
mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store = LibStorage.getSettlementRateStorage();
// Only need to set settlement rates when the rate oracle is set (meaning the asset token has
// a conversion rate to an underlying). If not set then the asset cash always settles to underlying at a 1-1
// rate since they are the same.
require(0 < blockTime && maturity <= blockTime && blockTime <= type(uint40).max); // dev: settlement rate timestamp overflow
require(0 < settlementRate && settlementRate <= type(uint128).max); // dev: settlement rate overflow
SettlementRateStorage storage rateStorage = store[currencyId][maturity];
rateStorage.blockTime = uint40(blockTime);
rateStorage.settlementRate = uint128(settlementRate);
rateStorage.underlyingDecimalPlaces = underlyingDecimalPlaces;
emit SetSettlementRate(currencyId, maturity, uint128(settlementRate));
}
}
return AssetRateParameters(
AssetRateAdapter(address(0)),
settlementRate,
// No overflow, restricted on storage
int256(10**underlyingDecimalPlaces)
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./PortfolioHandler.sol";
import "./BitmapAssetsHandler.sol";
import "../AccountContextHandler.sol";
import "../../global/Types.sol";
import "../../math/SafeInt256.sol";
/// @notice Helper library for transferring assets from one portfolio to another
library TransferAssets {
using AccountContextHandler for AccountContext;
using PortfolioHandler for PortfolioState;
using SafeInt256 for int256;
/// @notice Decodes asset ids
function decodeAssetId(uint256 id)
internal
pure
returns (
uint256 currencyId,
uint256 maturity,
uint256 assetType
)
{
assetType = uint8(id);
maturity = uint40(id >> 8);
currencyId = uint16(id >> 48);
}
/// @notice Encodes asset ids
function encodeAssetId(
uint256 currencyId,
uint256 maturity,
uint256 assetType
) internal pure returns (uint256) {
require(currencyId <= Constants.MAX_CURRENCIES);
require(maturity <= type(uint40).max);
require(assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX);
return
uint256(
(bytes32(uint256(uint16(currencyId))) << 48) |
(bytes32(uint256(uint40(maturity))) << 8) |
bytes32(uint256(uint8(assetType)))
);
}
/// @dev Used to flip the sign of assets to decrement the `from` account that is sending assets
function invertNotionalAmountsInPlace(PortfolioAsset[] memory assets) internal pure {
for (uint256 i; i < assets.length; i++) {
assets[i].notional = assets[i].notional.neg();
}
}
/// @dev Useful method for hiding the logic of updating an account. WARNING: the account
/// context returned from this method may not be the same memory location as the account
/// context provided if the account is settled.
function placeAssetsInAccount(
address account,
AccountContext memory accountContext,
PortfolioAsset[] memory assets
) internal returns (AccountContext memory) {
// If an account has assets that require settlement then placing assets inside it
// may cause issues.
require(!accountContext.mustSettleAssets(), "Account must settle");
if (accountContext.isBitmapEnabled()) {
// Adds fCash assets into the account and finalized storage
BitmapAssetsHandler.addMultipleifCashAssets(account, accountContext, assets);
} else {
PortfolioState memory portfolioState = PortfolioHandler.buildPortfolioState(
account,
accountContext.assetArrayLength,
assets.length
);
// This will add assets in memory
portfolioState.addMultipleAssets(assets);
// This will store assets and update the account context in memory
accountContext.storeAssetsAndUpdateContext(account, portfolioState, false);
}
return accountContext;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./AssetHandler.sol";
import "./ExchangeRate.sol";
import "../markets/CashGroup.sol";
import "../AccountContextHandler.sol";
import "../balances/BalanceHandler.sol";
import "../portfolio/PortfolioHandler.sol";
import "../nToken/nTokenHandler.sol";
import "../nToken/nTokenCalculations.sol";
import "../../math/SafeInt256.sol";
library FreeCollateral {
using SafeInt256 for int256;
using Bitmap for bytes;
using ExchangeRate for ETHRate;
using AssetRate for AssetRateParameters;
using AccountContextHandler for AccountContext;
using nTokenHandler for nTokenPortfolio;
/// @dev This is only used within the library to clean up the stack
struct FreeCollateralFactors {
int256 netETHValue;
bool updateContext;
uint256 portfolioIndex;
CashGroupParameters cashGroup;
MarketParameters market;
PortfolioAsset[] portfolio;
AssetRateParameters assetRate;
nTokenPortfolio nToken;
}
/// @notice Checks if an asset is active in the portfolio
function _isActiveInPortfolio(bytes2 currencyBytes) private pure returns (bool) {
return currencyBytes & Constants.ACTIVE_IN_PORTFOLIO == Constants.ACTIVE_IN_PORTFOLIO;
}
/// @notice Checks if currency balances are active in the account returns them if true
/// @return cash balance, nTokenBalance
function _getCurrencyBalances(address account, bytes2 currencyBytes)
private
view
returns (int256, int256)
{
if (currencyBytes & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES) {
uint256 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS);
// prettier-ignore
(
int256 cashBalance,
int256 nTokenBalance,
/* lastClaimTime */,
/* accountIncentiveDebt */
) = BalanceHandler.getBalanceStorage(account, currencyId);
return (cashBalance, nTokenBalance);
}
return (0, 0);
}
/// @notice Calculates the nToken asset value with a haircut set by governance
/// @return the value of the account's nTokens after haircut, the nToken parameters
function _getNTokenHaircutAssetPV(
CashGroupParameters memory cashGroup,
nTokenPortfolio memory nToken,
int256 tokenBalance,
uint256 blockTime
) internal view returns (int256, bytes6) {
nToken.loadNTokenPortfolioNoCashGroup(cashGroup.currencyId);
nToken.cashGroup = cashGroup;
int256 nTokenAssetPV = nTokenCalculations.getNTokenAssetPV(nToken, blockTime);
// (tokenBalance * nTokenValue * haircut) / totalSupply
int256 nTokenHaircutAssetPV =
tokenBalance
.mul(nTokenAssetPV)
.mul(uint8(nToken.parameters[Constants.PV_HAIRCUT_PERCENTAGE]))
.div(Constants.PERCENTAGE_DECIMALS)
.div(nToken.totalSupply);
// nToken.parameters is returned for use in liquidation
return (nTokenHaircutAssetPV, nToken.parameters);
}
/// @notice Calculates portfolio and/or nToken values while using the supplied cash groups and
/// markets. The reason these are grouped together is because they both require storage reads of the same
/// values.
function _getPortfolioAndNTokenAssetValue(
FreeCollateralFactors memory factors,
int256 nTokenBalance,
uint256 blockTime
)
private
view
returns (
int256 netPortfolioValue,
int256 nTokenHaircutAssetValue,
bytes6 nTokenParameters
)
{
// If the next asset matches the currency id then we need to calculate the cash group value
if (
factors.portfolioIndex < factors.portfolio.length &&
factors.portfolio[factors.portfolioIndex].currencyId == factors.cashGroup.currencyId
) {
// netPortfolioValue is in asset cash
(netPortfolioValue, factors.portfolioIndex) = AssetHandler.getNetCashGroupValue(
factors.portfolio,
factors.cashGroup,
factors.market,
blockTime,
factors.portfolioIndex
);
} else {
netPortfolioValue = 0;
}
if (nTokenBalance > 0) {
(nTokenHaircutAssetValue, nTokenParameters) = _getNTokenHaircutAssetPV(
factors.cashGroup,
factors.nToken,
nTokenBalance,
blockTime
);
} else {
nTokenHaircutAssetValue = 0;
nTokenParameters = 0;
}
}
/// @notice Returns balance values for the bitmapped currency
function _getBitmapBalanceValue(
address account,
uint256 blockTime,
AccountContext memory accountContext,
FreeCollateralFactors memory factors
)
private
view
returns (
int256 cashBalance,
int256 nTokenHaircutAssetValue,
bytes6 nTokenParameters
)
{
int256 nTokenBalance;
// prettier-ignore
(
cashBalance,
nTokenBalance,
/* lastClaimTime */,
/* accountIncentiveDebt */
) = BalanceHandler.getBalanceStorage(account, accountContext.bitmapCurrencyId);
if (nTokenBalance > 0) {
(nTokenHaircutAssetValue, nTokenParameters) = _getNTokenHaircutAssetPV(
factors.cashGroup,
factors.nToken,
nTokenBalance,
blockTime
);
} else {
nTokenHaircutAssetValue = 0;
}
}
/// @notice Returns portfolio value for the bitmapped currency
function _getBitmapPortfolioValue(
address account,
uint256 blockTime,
AccountContext memory accountContext,
FreeCollateralFactors memory factors
) private view returns (int256) {
(int256 netPortfolioValueUnderlying, bool bitmapHasDebt) =
BitmapAssetsHandler.getifCashNetPresentValue(
account,
accountContext.bitmapCurrencyId,
accountContext.nextSettleTime,
blockTime,
factors.cashGroup,
true // risk adjusted
);
// Turns off has debt flag if it has changed
bool contextHasAssetDebt =
accountContext.hasDebt & Constants.HAS_ASSET_DEBT == Constants.HAS_ASSET_DEBT;
if (bitmapHasDebt && !contextHasAssetDebt) {
// Turn on has debt
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT;
factors.updateContext = true;
} else if (!bitmapHasDebt && contextHasAssetDebt) {
// Turn off has debt
accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_ASSET_DEBT;
factors.updateContext = true;
}
// Return asset cash value
return factors.cashGroup.assetRate.convertFromUnderlying(netPortfolioValueUnderlying);
}
function _updateNetETHValue(
uint256 currencyId,
int256 netLocalAssetValue,
FreeCollateralFactors memory factors
) private view returns (ETHRate memory) {
ETHRate memory ethRate = ExchangeRate.buildExchangeRate(currencyId);
// Converts to underlying first, ETH exchange rates are in underlying
factors.netETHValue = factors.netETHValue.add(
ethRate.convertToETH(factors.assetRate.convertToUnderlying(netLocalAssetValue))
);
return ethRate;
}
/// @notice Stateful version of get free collateral, returns the total net ETH value and true or false if the account
/// context needs to be updated.
function getFreeCollateralStateful(
address account,
AccountContext memory accountContext,
uint256 blockTime
) internal returns (int256, bool) {
FreeCollateralFactors memory factors;
bool hasCashDebt;
if (accountContext.isBitmapEnabled()) {
factors.cashGroup = CashGroup.buildCashGroupStateful(accountContext.bitmapCurrencyId);
// prettier-ignore
(
int256 netCashBalance,
int256 nTokenHaircutAssetValue,
/* nTokenParameters */
) = _getBitmapBalanceValue(account, blockTime, accountContext, factors);
if (netCashBalance < 0) hasCashDebt = true;
int256 portfolioAssetValue =
_getBitmapPortfolioValue(account, blockTime, accountContext, factors);
int256 netLocalAssetValue =
netCashBalance.add(nTokenHaircutAssetValue).add(portfolioAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
_updateNetETHValue(accountContext.bitmapCurrencyId, netLocalAssetValue, factors);
} else {
factors.portfolio = PortfolioHandler.getSortedPortfolio(
account,
accountContext.assetArrayLength
);
}
bytes18 currencies = accountContext.activeCurrencies;
while (currencies != 0) {
bytes2 currencyBytes = bytes2(currencies);
uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS);
// Explicitly ensures that bitmap currency cannot be double counted
require(currencyId != accountContext.bitmapCurrencyId);
(int256 netLocalAssetValue, int256 nTokenBalance) =
_getCurrencyBalances(account, currencyBytes);
if (netLocalAssetValue < 0) hasCashDebt = true;
if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) {
factors.cashGroup = CashGroup.buildCashGroupStateful(currencyId);
// prettier-ignore
(
int256 netPortfolioAssetValue,
int256 nTokenHaircutAssetValue,
/* nTokenParameters */
) = _getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime);
netLocalAssetValue = netLocalAssetValue
.add(netPortfolioAssetValue)
.add(nTokenHaircutAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
} else {
// NOTE: we must set the proper assetRate when we updateNetETHValue
factors.assetRate = AssetRate.buildAssetRateStateful(currencyId);
}
_updateNetETHValue(currencyId, netLocalAssetValue, factors);
currencies = currencies << 16;
}
// Free collateral is the only method that examines all cash balances for an account at once. If there is no cash debt (i.e.
// they have been repaid or settled via more debt) then this will turn off the flag. It's possible that this flag is out of
// sync temporarily after a cash settlement and before the next free collateral check. The only downside for that is forcing
// an account to do an extra free collateral check to turn off this setting.
if (
accountContext.hasDebt & Constants.HAS_CASH_DEBT == Constants.HAS_CASH_DEBT &&
!hasCashDebt
) {
accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_CASH_DEBT;
factors.updateContext = true;
}
return (factors.netETHValue, factors.updateContext);
}
/// @notice View version of getFreeCollateral, does not use the stateful version of build cash group and skips
/// all the update context logic.
function getFreeCollateralView(
address account,
AccountContext memory accountContext,
uint256 blockTime
) internal view returns (int256, int256[] memory) {
FreeCollateralFactors memory factors;
uint256 netLocalIndex;
int256[] memory netLocalAssetValues = new int256[](10);
if (accountContext.isBitmapEnabled()) {
factors.cashGroup = CashGroup.buildCashGroupView(accountContext.bitmapCurrencyId);
// prettier-ignore
(
int256 netCashBalance,
int256 nTokenHaircutAssetValue,
/* nTokenParameters */
) = _getBitmapBalanceValue(account, blockTime, accountContext, factors);
int256 portfolioAssetValue =
_getBitmapPortfolioValue(account, blockTime, accountContext, factors);
netLocalAssetValues[netLocalIndex] = netCashBalance
.add(nTokenHaircutAssetValue)
.add(portfolioAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
_updateNetETHValue(
accountContext.bitmapCurrencyId,
netLocalAssetValues[netLocalIndex],
factors
);
netLocalIndex++;
} else {
factors.portfolio = PortfolioHandler.getSortedPortfolio(
account,
accountContext.assetArrayLength
);
}
bytes18 currencies = accountContext.activeCurrencies;
while (currencies != 0) {
bytes2 currencyBytes = bytes2(currencies);
uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS);
// Explicitly ensures that bitmap currency cannot be double counted
require(currencyId != accountContext.bitmapCurrencyId);
int256 nTokenBalance;
(netLocalAssetValues[netLocalIndex], nTokenBalance) = _getCurrencyBalances(
account,
currencyBytes
);
if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) {
factors.cashGroup = CashGroup.buildCashGroupView(currencyId);
// prettier-ignore
(
int256 netPortfolioValue,
int256 nTokenHaircutAssetValue,
/* nTokenParameters */
) = _getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime);
netLocalAssetValues[netLocalIndex] = netLocalAssetValues[netLocalIndex]
.add(netPortfolioValue)
.add(nTokenHaircutAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
} else {
factors.assetRate = AssetRate.buildAssetRateView(currencyId);
}
_updateNetETHValue(currencyId, netLocalAssetValues[netLocalIndex], factors);
netLocalIndex++;
currencies = currencies << 16;
}
return (factors.netETHValue, netLocalAssetValues);
}
/// @notice Calculates the net value of a currency within a portfolio, this is a bit
/// convoluted to fit into the stack frame
function _calculateLiquidationAssetValue(
FreeCollateralFactors memory factors,
LiquidationFactors memory liquidationFactors,
bytes2 currencyBytes,
bool setLiquidationFactors,
uint256 blockTime
) private returns (int256) {
uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS);
(int256 netLocalAssetValue, int256 nTokenBalance) =
_getCurrencyBalances(liquidationFactors.account, currencyBytes);
if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) {
factors.cashGroup = CashGroup.buildCashGroupStateful(currencyId);
(int256 netPortfolioValue, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters) =
_getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime);
netLocalAssetValue = netLocalAssetValue
.add(netPortfolioValue)
.add(nTokenHaircutAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
// If collateralCurrencyId is set to zero then this is a local currency liquidation
if (setLiquidationFactors) {
liquidationFactors.collateralCashGroup = factors.cashGroup;
liquidationFactors.nTokenParameters = nTokenParameters;
liquidationFactors.nTokenHaircutAssetValue = nTokenHaircutAssetValue;
}
} else {
factors.assetRate = AssetRate.buildAssetRateStateful(currencyId);
}
return netLocalAssetValue;
}
/// @notice A version of getFreeCollateral used during liquidation to save off necessary additional information.
function getLiquidationFactors(
address account,
AccountContext memory accountContext,
uint256 blockTime,
uint256 localCurrencyId,
uint256 collateralCurrencyId
) internal returns (LiquidationFactors memory, PortfolioAsset[] memory) {
FreeCollateralFactors memory factors;
LiquidationFactors memory liquidationFactors;
// This is only set to reduce the stack size
liquidationFactors.account = account;
if (accountContext.isBitmapEnabled()) {
factors.cashGroup = CashGroup.buildCashGroupStateful(accountContext.bitmapCurrencyId);
(int256 netCashBalance, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters) =
_getBitmapBalanceValue(account, blockTime, accountContext, factors);
int256 portfolioBalance =
_getBitmapPortfolioValue(account, blockTime, accountContext, factors);
int256 netLocalAssetValue =
netCashBalance.add(nTokenHaircutAssetValue).add(portfolioBalance);
factors.assetRate = factors.cashGroup.assetRate;
ETHRate memory ethRate =
_updateNetETHValue(accountContext.bitmapCurrencyId, netLocalAssetValue, factors);
// If the bitmap currency id can only ever be the local currency where debt is held.
// During enable bitmap we check that the account has no assets in their portfolio and
// no cash debts.
if (accountContext.bitmapCurrencyId == localCurrencyId) {
liquidationFactors.localAssetAvailable = netLocalAssetValue;
liquidationFactors.localETHRate = ethRate;
liquidationFactors.localAssetRate = factors.assetRate;
// This will be the case during local currency or local fCash liquidation
if (collateralCurrencyId == 0) {
// If this is local fCash liquidation, the cash group information is required
// to calculate fCash haircuts and buffers.
liquidationFactors.collateralCashGroup = factors.cashGroup;
liquidationFactors.nTokenHaircutAssetValue = nTokenHaircutAssetValue;
liquidationFactors.nTokenParameters = nTokenParameters;
}
}
} else {
factors.portfolio = PortfolioHandler.getSortedPortfolio(
account,
accountContext.assetArrayLength
);
}
bytes18 currencies = accountContext.activeCurrencies;
while (currencies != 0) {
bytes2 currencyBytes = bytes2(currencies);
// This next bit of code here is annoyingly structured to get around stack size issues
bool setLiquidationFactors;
{
uint256 tempId = uint256(uint16(currencyBytes & Constants.UNMASK_FLAGS));
// Explicitly ensures that bitmap currency cannot be double counted
require(tempId != accountContext.bitmapCurrencyId);
setLiquidationFactors =
(tempId == localCurrencyId && collateralCurrencyId == 0) ||
tempId == collateralCurrencyId;
}
int256 netLocalAssetValue =
_calculateLiquidationAssetValue(
factors,
liquidationFactors,
currencyBytes,
setLiquidationFactors,
blockTime
);
uint256 currencyId = uint256(uint16(currencyBytes & Constants.UNMASK_FLAGS));
ETHRate memory ethRate = _updateNetETHValue(currencyId, netLocalAssetValue, factors);
if (currencyId == collateralCurrencyId) {
// Ensure that this is set even if the cash group is not loaded, it will not be
// loaded if the account only has a cash balance and no nTokens or assets
liquidationFactors.collateralCashGroup.assetRate = factors.assetRate;
liquidationFactors.collateralAssetAvailable = netLocalAssetValue;
liquidationFactors.collateralETHRate = ethRate;
} else if (currencyId == localCurrencyId) {
// This branch will not be entered if bitmap is enabled
liquidationFactors.localAssetAvailable = netLocalAssetValue;
liquidationFactors.localETHRate = ethRate;
liquidationFactors.localAssetRate = factors.assetRate;
// If this is local fCash liquidation, the cash group information is required
// to calculate fCash haircuts and buffers and it will have been set in
// _calculateLiquidationAssetValue above because the account must have fCash assets,
// there is no need to set cash group in this branch.
}
currencies = currencies << 16;
}
liquidationFactors.netETHValue = factors.netETHValue;
require(liquidationFactors.netETHValue < 0, "Sufficient collateral");
// Refetch the portfolio if it exists, AssetHandler.getNetCashValue updates values in memory to do fCash
// netting which will make further calculations incorrect.
if (accountContext.assetArrayLength > 0) {
factors.portfolio = PortfolioHandler.getSortedPortfolio(
account,
accountContext.assetArrayLength
);
}
return (liquidationFactors, factors.portfolio);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../valuation/AssetHandler.sol";
import "../markets/Market.sol";
import "../markets/AssetRate.sol";
import "../portfolio/PortfolioHandler.sol";
import "../../math/SafeInt256.sol";
import "../../global/Constants.sol";
import "../../global/Types.sol";
library SettlePortfolioAssets {
using SafeInt256 for int256;
using AssetRate for AssetRateParameters;
using Market for MarketParameters;
using PortfolioHandler for PortfolioState;
using AssetHandler for PortfolioAsset;
/// @dev Returns a SettleAmount array for the assets that will be settled
function _getSettleAmountArray(PortfolioState memory portfolioState, uint256 blockTime)
private
pure
returns (SettleAmount[] memory)
{
uint256 currenciesSettled;
uint256 lastCurrencyId = 0;
if (portfolioState.storedAssets.length == 0) return new SettleAmount[](0);
// Loop backwards so "lastCurrencyId" will be set to the first currency in the portfolio
// NOTE: if this contract is ever upgraded to Solidity 0.8+ then this i-- will underflow and cause
// a revert, must wrap in an unchecked.
for (uint256 i = portfolioState.storedAssets.length; (i--) > 0;) {
PortfolioAsset memory asset = portfolioState.storedAssets[i];
// Assets settle on exactly blockTime
if (asset.getSettlementDate() > blockTime) continue;
// Assume that this is sorted by cash group and maturity, currencyId = 0 is unused so this
// will work for the first asset
if (lastCurrencyId != asset.currencyId) {
lastCurrencyId = asset.currencyId;
currenciesSettled++;
}
}
// Actual currency ids will be set as we loop through the portfolio and settle assets
SettleAmount[] memory settleAmounts = new SettleAmount[](currenciesSettled);
if (currenciesSettled > 0) settleAmounts[0].currencyId = lastCurrencyId;
return settleAmounts;
}
/// @notice Settles a portfolio array
function settlePortfolio(PortfolioState memory portfolioState, uint256 blockTime)
internal
returns (SettleAmount[] memory)
{
AssetRateParameters memory settlementRate;
SettleAmount[] memory settleAmounts = _getSettleAmountArray(portfolioState, blockTime);
MarketParameters memory market;
if (settleAmounts.length == 0) return settleAmounts;
uint256 settleAmountIndex;
for (uint256 i; i < portfolioState.storedAssets.length; i++) {
PortfolioAsset memory asset = portfolioState.storedAssets[i];
uint256 settleDate = asset.getSettlementDate();
// Settlement date is on block time exactly
if (settleDate > blockTime) continue;
// On the first loop the lastCurrencyId is already set.
if (settleAmounts[settleAmountIndex].currencyId != asset.currencyId) {
// New currency in the portfolio
settleAmountIndex += 1;
settleAmounts[settleAmountIndex].currencyId = asset.currencyId;
}
int256 assetCash;
if (asset.assetType == Constants.FCASH_ASSET_TYPE) {
// Gets or sets the settlement rate, only do this before settling fCash
settlementRate = AssetRate.buildSettlementRateStateful(
asset.currencyId,
asset.maturity,
blockTime
);
assetCash = settlementRate.convertFromUnderlying(asset.notional);
portfolioState.deleteAsset(i);
} else if (AssetHandler.isLiquidityToken(asset.assetType)) {
Market.loadSettlementMarket(market, asset.currencyId, asset.maturity, settleDate);
int256 fCash;
(assetCash, fCash) = market.removeLiquidity(asset.notional);
// Assets mature exactly on block time
if (asset.maturity > blockTime) {
// If fCash has not yet matured then add it to the portfolio
_settleLiquidityTokenTofCash(portfolioState, i, fCash);
} else {
// Gets or sets the settlement rate, only do this before settling fCash
settlementRate = AssetRate.buildSettlementRateStateful(
asset.currencyId,
asset.maturity,
blockTime
);
// If asset has matured then settle fCash to asset cash
assetCash = assetCash.add(settlementRate.convertFromUnderlying(fCash));
portfolioState.deleteAsset(i);
}
}
settleAmounts[settleAmountIndex].netCashChange = settleAmounts[settleAmountIndex]
.netCashChange
.add(assetCash);
}
return settleAmounts;
}
/// @notice Settles a liquidity token to idiosyncratic fCash, this occurs when the maturity is still in the future
function _settleLiquidityTokenTofCash(
PortfolioState memory portfolioState,
uint256 index,
int256 fCash
) private pure {
PortfolioAsset memory liquidityToken = portfolioState.storedAssets[index];
// If the liquidity token's maturity is still in the future then we change the entry to be
// an idiosyncratic fCash entry with the net fCash amount.
if (index != 0) {
// Check to see if the previous index is the matching fCash asset, this will be the case when the
// portfolio is sorted
PortfolioAsset memory fCashAsset = portfolioState.storedAssets[index - 1];
if (
fCashAsset.currencyId == liquidityToken.currencyId &&
fCashAsset.maturity == liquidityToken.maturity &&
fCashAsset.assetType == Constants.FCASH_ASSET_TYPE
) {
// This fCash asset has not matured if we are settling to fCash
fCashAsset.notional = fCashAsset.notional.add(fCash);
fCashAsset.storageState = AssetStorageState.Update;
portfolioState.deleteAsset(index);
}
}
// We are going to delete this asset anyway, convert to an fCash position
liquidityToken.assetType = Constants.FCASH_ASSET_TYPE;
liquidityToken.notional = fCash;
liquidityToken.storageState = AssetStorageState.Update;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../markets/AssetRate.sol";
import "../../global/LibStorage.sol";
import "../portfolio/BitmapAssetsHandler.sol";
import "../../math/SafeInt256.sol";
import "../../math/Bitmap.sol";
import "../../global/Constants.sol";
import "../../global/Types.sol";
/**
* Settles a bitmap portfolio by checking for all matured fCash assets and turning them into cash
* at the prevailing settlement rate. It will also update the asset bitmap to ensure that it continues
* to correctly reference all actual maturities. fCash asset notional values are stored in *absolute*
* time terms and bitmap bits are *relative* time terms based on the bitNumber and the stored oldSettleTime.
* Remapping bits requires converting the old relative bit numbers to new relative bit numbers based on
* newSettleTime and the absolute times (maturities) that the previous bitmap references.
*/
library SettleBitmapAssets {
using SafeInt256 for int256;
using AssetRate for AssetRateParameters;
using Bitmap for bytes32;
/// @notice Given a bitmap for a cash group and timestamps, will settle all assets
/// that have matured and remap the bitmap to correspond to the current time.
function settleBitmappedCashGroup(
address account,
uint256 currencyId,
uint256 oldSettleTime,
uint256 blockTime
) internal returns (int256 totalAssetCash, uint256 newSettleTime) {
bytes32 bitmap = BitmapAssetsHandler.getAssetsBitmap(account, currencyId);
// This newSettleTime will be set to the new `oldSettleTime`. The bits between 1 and
// `lastSettleBit` (inclusive) will be shifted out of the bitmap and settled. The reason
// that lastSettleBit is inclusive is that it refers to newSettleTime which always less
// than the current block time.
newSettleTime = DateTime.getTimeUTC0(blockTime);
// If newSettleTime == oldSettleTime lastSettleBit will be zero
require(newSettleTime >= oldSettleTime); // dev: new settle time before previous
// Do not need to worry about validity, if newSettleTime is not on an exact bit we will settle up until
// the closest maturity that is less than newSettleTime.
(uint256 lastSettleBit, /* isValid */) = DateTime.getBitNumFromMaturity(oldSettleTime, newSettleTime);
if (lastSettleBit == 0) return (totalAssetCash, newSettleTime);
// Returns the next bit that is set in the bitmap
uint256 nextBitNum = bitmap.getNextBitNum();
while (nextBitNum != 0 && nextBitNum <= lastSettleBit) {
uint256 maturity = DateTime.getMaturityFromBitNum(oldSettleTime, nextBitNum);
totalAssetCash = totalAssetCash.add(
_settlefCashAsset(account, currencyId, maturity, blockTime)
);
// Turn the bit off now that it is settled
bitmap = bitmap.setBit(nextBitNum, false);
nextBitNum = bitmap.getNextBitNum();
}
bytes32 newBitmap;
while (nextBitNum != 0) {
uint256 maturity = DateTime.getMaturityFromBitNum(oldSettleTime, nextBitNum);
(uint256 newBitNum, bool isValid) = DateTime.getBitNumFromMaturity(newSettleTime, maturity);
require(isValid); // dev: invalid new bit num
newBitmap = newBitmap.setBit(newBitNum, true);
// Turn the bit off now that it is remapped
bitmap = bitmap.setBit(nextBitNum, false);
nextBitNum = bitmap.getNextBitNum();
}
BitmapAssetsHandler.setAssetsBitmap(account, currencyId, newBitmap);
}
/// @dev Stateful settlement function to settle a bitmapped asset. Deletes the
/// asset from storage after calculating it.
function _settlefCashAsset(
address account,
uint256 currencyId,
uint256 maturity,
uint256 blockTime
) private returns (int256 assetCash) {
mapping(address => mapping(uint256 =>
mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage();
int256 notional = store[account][currencyId][maturity].notional;
// Gets the current settlement rate or will store a new settlement rate if it does not
// yet exist.
AssetRateParameters memory rate =
AssetRate.buildSettlementRateStateful(currencyId, maturity, blockTime);
assetCash = rate.convertFromUnderlying(notional);
delete store[account][currencyId][maturity];
return assetCash;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../markets/CashGroup.sol";
import "../markets/AssetRate.sol";
import "../markets/DateTime.sol";
import "../portfolio/PortfolioHandler.sol";
import "../../math/SafeInt256.sol";
import "../../math/ABDKMath64x64.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library AssetHandler {
using SafeMath for uint256;
using SafeInt256 for int256;
using CashGroup for CashGroupParameters;
using AssetRate for AssetRateParameters;
function isLiquidityToken(uint256 assetType) internal pure returns (bool) {
return
assetType >= Constants.MIN_LIQUIDITY_TOKEN_INDEX &&
assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX;
}
/// @notice Liquidity tokens settle every 90 days (not at the designated maturity). This method
/// calculates the settlement date for any PortfolioAsset.
function getSettlementDate(PortfolioAsset memory asset) internal pure returns (uint256) {
require(asset.assetType > 0 && asset.assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); // dev: settlement date invalid asset type
// 3 month tokens and fCash tokens settle at maturity
if (asset.assetType <= Constants.MIN_LIQUIDITY_TOKEN_INDEX) return asset.maturity;
uint256 marketLength = DateTime.getTradedMarket(asset.assetType - 1);
// Liquidity tokens settle at tRef + 90 days. The formula to get a maturity is:
// maturity = tRef + marketLength
// Here we calculate:
// tRef = (maturity - marketLength) + 90 days
return asset.maturity.sub(marketLength).add(Constants.QUARTER);
}
/// @notice Returns the continuously compounded discount rate given an oracle rate and a time to maturity.
/// The formula is: e^(-rate * timeToMaturity).
function getDiscountFactor(uint256 timeToMaturity, uint256 oracleRate)
internal
pure
returns (int256)
{
int128 expValue =
ABDKMath64x64.fromUInt(oracleRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME));
expValue = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64);
expValue = ABDKMath64x64.exp(ABDKMath64x64.neg(expValue));
expValue = ABDKMath64x64.mul(expValue, Constants.RATE_PRECISION_64x64);
int256 discountFactor = ABDKMath64x64.toInt(expValue);
return discountFactor;
}
/// @notice Present value of an fCash asset without any risk adjustments.
function getPresentfCashValue(
int256 notional,
uint256 maturity,
uint256 blockTime,
uint256 oracleRate
) internal pure returns (int256) {
if (notional == 0) return 0;
// NOTE: this will revert if maturity < blockTime. That is the correct behavior because we cannot
// discount matured assets.
uint256 timeToMaturity = maturity.sub(blockTime);
int256 discountFactor = getDiscountFactor(timeToMaturity, oracleRate);
require(discountFactor <= Constants.RATE_PRECISION); // dev: get present value invalid discount factor
return notional.mulInRatePrecision(discountFactor);
}
/// @notice Present value of an fCash asset with risk adjustments. Positive fCash value will be discounted more
/// heavily than the oracle rate given and vice versa for negative fCash.
function getRiskAdjustedPresentfCashValue(
CashGroupParameters memory cashGroup,
int256 notional,
uint256 maturity,
uint256 blockTime,
uint256 oracleRate
) internal pure returns (int256) {
if (notional == 0) return 0;
// NOTE: this will revert if maturity < blockTime. That is the correct behavior because we cannot
// discount matured assets.
uint256 timeToMaturity = maturity.sub(blockTime);
int256 discountFactor;
if (notional > 0) {
// If fCash is positive then discounting by a higher rate will result in a smaller
// discount factor (e ^ -x), meaning a lower positive fCash value.
discountFactor = getDiscountFactor(
timeToMaturity,
oracleRate.add(cashGroup.getfCashHaircut())
);
} else {
uint256 debtBuffer = cashGroup.getDebtBuffer();
// If the adjustment exceeds the oracle rate we floor the value of the fCash
// at the notional value. We don't want to require the account to hold more than
// absolutely required.
if (debtBuffer >= oracleRate) return notional;
discountFactor = getDiscountFactor(timeToMaturity, oracleRate - debtBuffer);
}
require(discountFactor <= Constants.RATE_PRECISION); // dev: get risk adjusted pv, invalid discount factor
return notional.mulInRatePrecision(discountFactor);
}
/// @notice Returns the non haircut claims on cash and fCash by the liquidity token.
function getCashClaims(PortfolioAsset memory token, MarketParameters memory market)
internal
pure
returns (int256 assetCash, int256 fCash)
{
require(isLiquidityToken(token.assetType) && token.notional >= 0); // dev: invalid asset, get cash claims
assetCash = market.totalAssetCash.mul(token.notional).div(market.totalLiquidity);
fCash = market.totalfCash.mul(token.notional).div(market.totalLiquidity);
}
/// @notice Returns the haircut claims on cash and fCash
function getHaircutCashClaims(
PortfolioAsset memory token,
MarketParameters memory market,
CashGroupParameters memory cashGroup
) internal pure returns (int256 assetCash, int256 fCash) {
require(isLiquidityToken(token.assetType) && token.notional >= 0); // dev: invalid asset get haircut cash claims
require(token.currencyId == cashGroup.currencyId); // dev: haircut cash claims, currency id mismatch
// This won't overflow, the liquidity token haircut is stored as an uint8
int256 haircut = int256(cashGroup.getLiquidityHaircut(token.assetType));
assetCash =
_calcToken(market.totalAssetCash, token.notional, haircut, market.totalLiquidity);
fCash =
_calcToken(market.totalfCash, token.notional, haircut, market.totalLiquidity);
return (assetCash, fCash);
}
/// @dev This is here to clean up the stack in getHaircutCashClaims
function _calcToken(
int256 numerator,
int256 tokens,
int256 haircut,
int256 liquidity
) private pure returns (int256) {
return numerator.mul(tokens).mul(haircut).div(Constants.PERCENTAGE_DECIMALS).div(liquidity);
}
/// @notice Returns the asset cash claim and the present value of the fCash asset (if it exists)
function getLiquidityTokenValue(
uint256 index,
CashGroupParameters memory cashGroup,
MarketParameters memory market,
PortfolioAsset[] memory assets,
uint256 blockTime,
bool riskAdjusted
) internal view returns (int256, int256) {
PortfolioAsset memory liquidityToken = assets[index];
{
(uint256 marketIndex, bool idiosyncratic) =
DateTime.getMarketIndex(
cashGroup.maxMarketIndex,
liquidityToken.maturity,
blockTime
);
// Liquidity tokens can never be idiosyncratic
require(!idiosyncratic); // dev: idiosyncratic liquidity token
// This market will always be initialized, if a liquidity token exists that means the
// market has some liquidity in it.
cashGroup.loadMarket(market, marketIndex, true, blockTime);
}
int256 assetCashClaim;
int256 fCashClaim;
if (riskAdjusted) {
(assetCashClaim, fCashClaim) = getHaircutCashClaims(liquidityToken, market, cashGroup);
} else {
(assetCashClaim, fCashClaim) = getCashClaims(liquidityToken, market);
}
// Find the matching fCash asset and net off the value, assumes that the portfolio is sorted and
// in that case we know the previous asset will be the matching fCash asset
if (index > 0) {
PortfolioAsset memory maybefCash = assets[index - 1];
if (
maybefCash.assetType == Constants.FCASH_ASSET_TYPE &&
maybefCash.currencyId == liquidityToken.currencyId &&
maybefCash.maturity == liquidityToken.maturity
) {
// Net off the fCashClaim here and we will discount it to present value in the second pass.
// WARNING: this modifies the portfolio in memory and therefore we cannot store this portfolio!
maybefCash.notional = maybefCash.notional.add(fCashClaim);
// This state will prevent the fCash asset from being stored.
maybefCash.storageState = AssetStorageState.RevertIfStored;
return (assetCashClaim, 0);
}
}
// If not matching fCash asset found then get the pv directly
if (riskAdjusted) {
int256 pv =
getRiskAdjustedPresentfCashValue(
cashGroup,
fCashClaim,
liquidityToken.maturity,
blockTime,
market.oracleRate
);
return (assetCashClaim, pv);
} else {
int256 pv =
getPresentfCashValue(fCashClaim, liquidityToken.maturity, blockTime, market.oracleRate);
return (assetCashClaim, pv);
}
}
/// @notice Returns present value of all assets in the cash group as asset cash and the updated
/// portfolio index where the function has ended.
/// @return the value of the cash group in asset cash
function getNetCashGroupValue(
PortfolioAsset[] memory assets,
CashGroupParameters memory cashGroup,
MarketParameters memory market,
uint256 blockTime,
uint256 portfolioIndex
) internal view returns (int256, uint256) {
int256 presentValueAsset;
int256 presentValueUnderlying;
// First calculate value of liquidity tokens because we need to net off fCash value
// before discounting to present value
for (uint256 i = portfolioIndex; i < assets.length; i++) {
if (!isLiquidityToken(assets[i].assetType)) continue;
if (assets[i].currencyId != cashGroup.currencyId) break;
(int256 assetCashClaim, int256 pv) =
getLiquidityTokenValue(
i,
cashGroup,
market,
assets,
blockTime,
true // risk adjusted
);
presentValueAsset = presentValueAsset.add(assetCashClaim);
presentValueUnderlying = presentValueUnderlying.add(pv);
}
uint256 j = portfolioIndex;
for (; j < assets.length; j++) {
PortfolioAsset memory a = assets[j];
if (a.assetType != Constants.FCASH_ASSET_TYPE) continue;
// If we hit a different currency id then we've accounted for all assets in this currency
// j will mark the index where we don't have this currency anymore
if (a.currencyId != cashGroup.currencyId) break;
uint256 oracleRate = cashGroup.calculateOracleRate(a.maturity, blockTime);
int256 pv =
getRiskAdjustedPresentfCashValue(
cashGroup,
a.notional,
a.maturity,
blockTime,
oracleRate
);
presentValueUnderlying = presentValueUnderlying.add(pv);
}
presentValueAsset = presentValueAsset.add(
cashGroup.assetRate.convertFromUnderlying(presentValueUnderlying)
);
return (presentValueAsset, j);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./Types.sol";
import "./Constants.sol";
import "../../interfaces/notional/IRewarder.sol";
import "../../interfaces/aave/ILendingPool.sol";
library LibStorage {
/// @dev Offset for the initial slot in lib storage, gives us this number of storage slots
/// available in StorageLayoutV1 and all subsequent storage layouts that inherit from it.
uint256 private constant STORAGE_SLOT_BASE = 1000000;
/// @dev Set to MAX_TRADED_MARKET_INDEX * 2, Solidity does not allow assigning constants from imported values
uint256 private constant NUM_NTOKEN_MARKET_FACTORS = 14;
/// @dev Theoretical maximum for MAX_PORTFOLIO_ASSETS, however, we limit this to MAX_TRADED_MARKET_INDEX
/// in practice. It is possible to exceed that value during liquidation up to 14 potential assets.
uint256 private constant MAX_PORTFOLIO_ASSETS = 16;
/// @dev Storage IDs for storage buckets. Each id maps to an internal storage
/// slot used for a particular mapping
/// WARNING: APPEND ONLY
enum StorageId {
Unused,
AccountStorage,
nTokenContext,
nTokenAddress,
nTokenDeposit,
nTokenInitialization,
Balance,
Token,
SettlementRate,
CashGroup,
Market,
AssetsBitmap,
ifCashBitmap,
PortfolioArray,
// WARNING: this nTokenTotalSupply storage object was used for a buggy version
// of the incentives calculation. It should only be used for accounts who have
// not claimed before the migration
nTokenTotalSupply_deprecated,
AssetRate,
ExchangeRate,
nTokenTotalSupply,
SecondaryIncentiveRewarder,
LendingPool
}
/// @dev Mapping from an account address to account context
function getAccountStorage() internal pure
returns (mapping(address => AccountContext) storage store)
{
uint256 slot = _getStorageSlot(StorageId.AccountStorage);
assembly { store.slot := slot }
}
/// @dev Mapping from an nToken address to nTokenContext
function getNTokenContextStorage() internal pure
returns (mapping(address => nTokenContext) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenContext);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to nTokenAddress
function getNTokenAddressStorage() internal pure
returns (mapping(uint256 => address) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenAddress);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to uint32 fixed length array of
/// deposit factors. Deposit shares and leverage thresholds are stored striped to
/// reduce the number of storage reads.
function getNTokenDepositStorage() internal pure
returns (mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenDeposit);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to fixed length array of initialization factors,
/// stored striped like deposit shares.
function getNTokenInitStorage() internal pure
returns (mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenInitialization);
assembly { store.slot := slot }
}
/// @dev Mapping from account to currencyId to it's balance storage for that currency
function getBalanceStorage() internal pure
returns (mapping(address => mapping(uint256 => BalanceStorage)) storage store)
{
uint256 slot = _getStorageSlot(StorageId.Balance);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to a boolean for underlying or asset token to
/// the TokenStorage
function getTokenStorage() internal pure
returns (mapping(uint256 => mapping(bool => TokenStorage)) storage store)
{
uint256 slot = _getStorageSlot(StorageId.Token);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to maturity to its corresponding SettlementRate
function getSettlementRateStorage() internal pure
returns (mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store)
{
uint256 slot = _getStorageSlot(StorageId.SettlementRate);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to maturity to its tightly packed cash group parameters
function getCashGroupStorage() internal pure
returns (mapping(uint256 => bytes32) storage store)
{
uint256 slot = _getStorageSlot(StorageId.CashGroup);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to maturity to settlement date for a market
function getMarketStorage() internal pure
returns (mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store)
{
uint256 slot = _getStorageSlot(StorageId.Market);
assembly { store.slot := slot }
}
/// @dev Mapping from account to currency id to its assets bitmap
function getAssetsBitmapStorage() internal pure
returns (mapping(address => mapping(uint256 => bytes32)) storage store)
{
uint256 slot = _getStorageSlot(StorageId.AssetsBitmap);
assembly { store.slot := slot }
}
/// @dev Mapping from account to currency id to its maturity to its corresponding ifCash balance
function getifCashBitmapStorage() internal pure
returns (mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store)
{
uint256 slot = _getStorageSlot(StorageId.ifCashBitmap);
assembly { store.slot := slot }
}
/// @dev Mapping from account to its fixed length array of portfolio assets
function getPortfolioArrayStorage() internal pure
returns (mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store)
{
uint256 slot = _getStorageSlot(StorageId.PortfolioArray);
assembly { store.slot := slot }
}
function getDeprecatedNTokenTotalSupplyStorage() internal pure
returns (mapping(address => nTokenTotalSupplyStorage_deprecated) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenTotalSupply_deprecated);
assembly { store.slot := slot }
}
/// @dev Mapping from nToken address to its total supply values
function getNTokenTotalSupplyStorage() internal pure
returns (mapping(address => nTokenTotalSupplyStorage) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenTotalSupply);
assembly { store.slot := slot }
}
/// @dev Returns the exchange rate between an underlying currency and asset for trading
/// and free collateral. Mapping is from currency id to rate storage object.
function getAssetRateStorage() internal pure
returns (mapping(uint256 => AssetRateStorage) storage store)
{
uint256 slot = _getStorageSlot(StorageId.AssetRate);
assembly { store.slot := slot }
}
/// @dev Returns the exchange rate between an underlying currency and ETH for free
/// collateral purposes. Mapping is from currency id to rate storage object.
function getExchangeRateStorage() internal pure
returns (mapping(uint256 => ETHRateStorage) storage store)
{
uint256 slot = _getStorageSlot(StorageId.ExchangeRate);
assembly { store.slot := slot }
}
/// @dev Returns the address of a secondary incentive rewarder for an nToken if it exists
function getSecondaryIncentiveRewarder() internal pure
returns (mapping(address => IRewarder) storage store)
{
uint256 slot = _getStorageSlot(StorageId.SecondaryIncentiveRewarder);
assembly { store.slot := slot }
}
/// @dev Returns the address of the lending pool
function getLendingPool() internal pure returns (LendingPoolStorage storage store) {
uint256 slot = _getStorageSlot(StorageId.LendingPool);
assembly { store.slot := slot }
}
/// @dev Get the storage slot given a storage ID.
/// @param storageId An entry in `StorageId`
/// @return slot The storage slot.
function _getStorageSlot(StorageId storageId)
private
pure
returns (uint256 slot)
{
// This should never overflow with a reasonable `STORAGE_SLOT_EXP`
// because Solidity will do a range check on `storageId` during the cast.
return uint256(storageId) + STORAGE_SLOT_BASE;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../AccountContextHandler.sol";
import "../markets/CashGroup.sol";
import "../valuation/AssetHandler.sol";
import "../../math/Bitmap.sol";
import "../../math/SafeInt256.sol";
import "../../global/LibStorage.sol";
import "../../global/Constants.sol";
import "../../global/Types.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library BitmapAssetsHandler {
using SafeMath for uint256;
using SafeInt256 for int256;
using Bitmap for bytes32;
using CashGroup for CashGroupParameters;
using AccountContextHandler for AccountContext;
function getAssetsBitmap(address account, uint256 currencyId) internal view returns (bytes32 assetsBitmap) {
mapping(address => mapping(uint256 => bytes32)) storage store = LibStorage.getAssetsBitmapStorage();
return store[account][currencyId];
}
function setAssetsBitmap(
address account,
uint256 currencyId,
bytes32 assetsBitmap
) internal {
require(assetsBitmap.totalBitsSet() <= Constants.MAX_BITMAP_ASSETS, "Over max assets");
mapping(address => mapping(uint256 => bytes32)) storage store = LibStorage.getAssetsBitmapStorage();
store[account][currencyId] = assetsBitmap;
}
function getifCashNotional(
address account,
uint256 currencyId,
uint256 maturity
) internal view returns (int256 notional) {
mapping(address => mapping(uint256 =>
mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage();
return store[account][currencyId][maturity].notional;
}
/// @notice Adds multiple assets to a bitmap portfolio
function addMultipleifCashAssets(
address account,
AccountContext memory accountContext,
PortfolioAsset[] memory assets
) internal {
require(accountContext.isBitmapEnabled()); // dev: bitmap currency not set
uint256 currencyId = accountContext.bitmapCurrencyId;
for (uint256 i; i < assets.length; i++) {
PortfolioAsset memory asset = assets[i];
if (asset.notional == 0) continue;
require(asset.currencyId == currencyId); // dev: invalid asset in set ifcash assets
require(asset.assetType == Constants.FCASH_ASSET_TYPE); // dev: invalid asset in set ifcash assets
int256 finalNotional;
finalNotional = addifCashAsset(
account,
currencyId,
asset.maturity,
accountContext.nextSettleTime,
asset.notional
);
if (finalNotional < 0)
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT;
}
}
/// @notice Add an ifCash asset in the bitmap and mapping. Updates the bitmap in memory
/// but not in storage.
/// @return the updated assets bitmap and the final notional amount
function addifCashAsset(
address account,
uint256 currencyId,
uint256 maturity,
uint256 nextSettleTime,
int256 notional
) internal returns (int256) {
bytes32 assetsBitmap = getAssetsBitmap(account, currencyId);
mapping(address => mapping(uint256 =>
mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage();
ifCashStorage storage fCashSlot = store[account][currencyId][maturity];
(uint256 bitNum, bool isExact) = DateTime.getBitNumFromMaturity(nextSettleTime, maturity);
require(isExact); // dev: invalid maturity in set ifcash asset
if (assetsBitmap.isBitSet(bitNum)) {
// Bit is set so we read and update the notional amount
int256 finalNotional = notional.add(fCashSlot.notional);
require(type(int128).min <= finalNotional && finalNotional <= type(int128).max); // dev: bitmap notional overflow
fCashSlot.notional = int128(finalNotional);
// If the new notional is zero then turn off the bit
if (finalNotional == 0) {
assetsBitmap = assetsBitmap.setBit(bitNum, false);
}
setAssetsBitmap(account, currencyId, assetsBitmap);
return finalNotional;
}
if (notional != 0) {
// Bit is not set so we turn it on and update the mapping directly, no read required.
require(type(int128).min <= notional && notional <= type(int128).max); // dev: bitmap notional overflow
fCashSlot.notional = int128(notional);
assetsBitmap = assetsBitmap.setBit(bitNum, true);
setAssetsBitmap(account, currencyId, assetsBitmap);
}
return notional;
}
/// @notice Returns the present value of an asset
function getPresentValue(
address account,
uint256 currencyId,
uint256 maturity,
uint256 blockTime,
CashGroupParameters memory cashGroup,
bool riskAdjusted
) internal view returns (int256) {
int256 notional = getifCashNotional(account, currencyId, maturity);
// In this case the asset has matured and the total value is just the notional amount
if (maturity <= blockTime) {
return notional;
} else {
uint256 oracleRate = cashGroup.calculateOracleRate(maturity, blockTime);
if (riskAdjusted) {
return AssetHandler.getRiskAdjustedPresentfCashValue(
cashGroup,
notional,
maturity,
blockTime,
oracleRate
);
} else {
return AssetHandler.getPresentfCashValue(
notional,
maturity,
blockTime,
oracleRate
);
}
}
}
function getNetPresentValueFromBitmap(
address account,
uint256 currencyId,
uint256 nextSettleTime,
uint256 blockTime,
CashGroupParameters memory cashGroup,
bool riskAdjusted,
bytes32 assetsBitmap
) internal view returns (int256 totalValueUnderlying, bool hasDebt) {
uint256 bitNum = assetsBitmap.getNextBitNum();
while (bitNum != 0) {
uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum);
int256 pv = getPresentValue(
account,
currencyId,
maturity,
blockTime,
cashGroup,
riskAdjusted
);
totalValueUnderlying = totalValueUnderlying.add(pv);
if (pv < 0) hasDebt = true;
// Turn off the bit and look for the next one
assetsBitmap = assetsBitmap.setBit(bitNum, false);
bitNum = assetsBitmap.getNextBitNum();
}
}
/// @notice Get the net present value of all the ifCash assets
function getifCashNetPresentValue(
address account,
uint256 currencyId,
uint256 nextSettleTime,
uint256 blockTime,
CashGroupParameters memory cashGroup,
bool riskAdjusted
) internal view returns (int256 totalValueUnderlying, bool hasDebt) {
bytes32 assetsBitmap = getAssetsBitmap(account, currencyId);
return getNetPresentValueFromBitmap(
account,
currencyId,
nextSettleTime,
blockTime,
cashGroup,
riskAdjusted,
assetsBitmap
);
}
/// @notice Returns the ifCash assets as an array
function getifCashArray(
address account,
uint256 currencyId,
uint256 nextSettleTime
) internal view returns (PortfolioAsset[] memory) {
bytes32 assetsBitmap = getAssetsBitmap(account, currencyId);
uint256 index = assetsBitmap.totalBitsSet();
PortfolioAsset[] memory assets = new PortfolioAsset[](index);
index = 0;
uint256 bitNum = assetsBitmap.getNextBitNum();
while (bitNum != 0) {
uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum);
int256 notional = getifCashNotional(account, currencyId, maturity);
PortfolioAsset memory asset = assets[index];
asset.currencyId = currencyId;
asset.maturity = maturity;
asset.assetType = Constants.FCASH_ASSET_TYPE;
asset.notional = notional;
index += 1;
// Turn off the bit and look for the next one
assetsBitmap = assetsBitmap.setBit(bitNum, false);
bitNum = assetsBitmap.getNextBitNum();
}
return assets;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../interfaces/chainlink/AggregatorV2V3Interface.sol";
import "../../interfaces/notional/AssetRateAdapter.sol";
/// @notice Different types of internal tokens
/// - UnderlyingToken: underlying asset for a cToken (except for Ether)
/// - cToken: Compound interest bearing token
/// - cETH: Special handling for cETH tokens
/// - Ether: the one and only
/// - NonMintable: tokens that do not have an underlying (therefore not cTokens)
/// - aToken: Aave interest bearing tokens
enum TokenType {UnderlyingToken, cToken, cETH, Ether, NonMintable, aToken}
/// @notice Specifies the different trade action types in the system. Each trade action type is
/// encoded in a tightly packed bytes32 object. Trade action type is the first big endian byte of the
/// 32 byte trade action object. The schemas for each trade action type are defined below.
enum TradeActionType {
// (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 minImpliedRate, uint120 unused)
Lend,
// (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 maxImpliedRate, uint128 unused)
Borrow,
// (uint8 TradeActionType, uint8 MarketIndex, uint88 assetCashAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused)
AddLiquidity,
// (uint8 TradeActionType, uint8 MarketIndex, uint88 tokenAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused)
RemoveLiquidity,
// (uint8 TradeActionType, uint32 Maturity, int88 fCashResidualAmount, uint128 unused)
PurchaseNTokenResidual,
// (uint8 TradeActionType, address CounterpartyAddress, int88 fCashAmountToSettle)
SettleCashDebt
}
/// @notice Specifies different deposit actions that can occur during BalanceAction or BalanceActionWithTrades
enum DepositActionType {
// No deposit action
None,
// Deposit asset cash, depositActionAmount is specified in asset cash external precision
DepositAsset,
// Deposit underlying tokens that are mintable to asset cash, depositActionAmount is specified in underlying token
// external precision
DepositUnderlying,
// Deposits specified asset cash external precision amount into an nToken and mints the corresponding amount of
// nTokens into the account
DepositAssetAndMintNToken,
// Deposits specified underlying in external precision, mints asset cash, and uses that asset cash to mint nTokens
DepositUnderlyingAndMintNToken,
// Redeems an nToken balance to asset cash. depositActionAmount is specified in nToken precision. Considered a deposit action
// because it deposits asset cash into an account. If there are fCash residuals that cannot be sold off, will revert.
RedeemNToken,
// Converts specified amount of asset cash balance already in Notional to nTokens. depositActionAmount is specified in
// Notional internal 8 decimal precision.
ConvertCashToNToken
}
/// @notice Used internally for PortfolioHandler state
enum AssetStorageState {NoChange, Update, Delete, RevertIfStored}
/****** Calldata objects ******/
/// @notice Defines a balance action for batchAction
struct BalanceAction {
// Deposit action to take (if any)
DepositActionType actionType;
uint16 currencyId;
// Deposit action amount must correspond to the depositActionType, see documentation above.
uint256 depositActionAmount;
// Withdraw an amount of asset cash specified in Notional internal 8 decimal precision
uint256 withdrawAmountInternalPrecision;
// If set to true, will withdraw entire cash balance. Useful if there may be an unknown amount of asset cash
// residual left from trading.
bool withdrawEntireCashBalance;
// If set to true, will redeem asset cash to the underlying token on withdraw.
bool redeemToUnderlying;
}
/// @notice Defines a balance action with a set of trades to do as well
struct BalanceActionWithTrades {
DepositActionType actionType;
uint16 currencyId;
uint256 depositActionAmount;
uint256 withdrawAmountInternalPrecision;
bool withdrawEntireCashBalance;
bool redeemToUnderlying;
// Array of tightly packed 32 byte objects that represent trades. See TradeActionType documentation
bytes32[] trades;
}
/****** In memory objects ******/
/// @notice Internal object that represents settled cash balances
struct SettleAmount {
uint256 currencyId;
int256 netCashChange;
}
/// @notice Internal object that represents a token
struct Token {
address tokenAddress;
bool hasTransferFee;
int256 decimals;
TokenType tokenType;
uint256 maxCollateralBalance;
}
/// @notice Internal object that represents an nToken portfolio
struct nTokenPortfolio {
CashGroupParameters cashGroup;
PortfolioState portfolioState;
int256 totalSupply;
int256 cashBalance;
uint256 lastInitializedTime;
bytes6 parameters;
address tokenAddress;
}
/// @notice Internal object used during liquidation
struct LiquidationFactors {
address account;
// Aggregate free collateral of the account denominated in ETH underlying, 8 decimal precision
int256 netETHValue;
// Amount of net local currency asset cash before haircuts and buffers available
int256 localAssetAvailable;
// Amount of net collateral currency asset cash before haircuts and buffers available
int256 collateralAssetAvailable;
// Haircut value of nToken holdings denominated in asset cash, will be local or collateral nTokens based
// on liquidation type
int256 nTokenHaircutAssetValue;
// nToken parameters for calculating liquidation amount
bytes6 nTokenParameters;
// ETH exchange rate from local currency to ETH
ETHRate localETHRate;
// ETH exchange rate from collateral currency to ETH
ETHRate collateralETHRate;
// Asset rate for the local currency, used in cross currency calculations to calculate local asset cash required
AssetRateParameters localAssetRate;
// Used during currency liquidations if the account has liquidity tokens
CashGroupParameters collateralCashGroup;
// Used during currency liquidations if it is only a calculation, defaults to false
bool isCalculation;
}
/// @notice Internal asset array portfolio state
struct PortfolioState {
// Array of currently stored assets
PortfolioAsset[] storedAssets;
// Array of new assets to add
PortfolioAsset[] newAssets;
uint256 lastNewAssetIndex;
// Holds the length of stored assets after accounting for deleted assets
uint256 storedAssetLength;
}
/// @notice In memory ETH exchange rate used during free collateral calculation.
struct ETHRate {
// The decimals (i.e. 10^rateDecimalPlaces) of the exchange rate, defined by the rate oracle
int256 rateDecimals;
// The exchange rate from base to ETH (if rate invert is required it is already done)
int256 rate;
// Amount of buffer as a multiple with a basis of 100 applied to negative balances.
int256 buffer;
// Amount of haircut as a multiple with a basis of 100 applied to positive balances
int256 haircut;
// Liquidation discount as a multiple with a basis of 100 applied to the exchange rate
// as an incentive given to liquidators.
int256 liquidationDiscount;
}
/// @notice Internal object used to handle balance state during a transaction
struct BalanceState {
uint16 currencyId;
// Cash balance stored in balance state at the beginning of the transaction
int256 storedCashBalance;
// nToken balance stored at the beginning of the transaction
int256 storedNTokenBalance;
// The net cash change as a result of asset settlement or trading
int256 netCashChange;
// Net asset transfers into or out of the account
int256 netAssetTransferInternalPrecision;
// Net token transfers into or out of the account
int256 netNTokenTransfer;
// Net token supply change from minting or redeeming
int256 netNTokenSupplyChange;
// The last time incentives were claimed for this currency
uint256 lastClaimTime;
// Accumulator for incentives that the account no longer has a claim over
uint256 accountIncentiveDebt;
}
/// @dev Asset rate used to convert between underlying cash and asset cash
struct AssetRateParameters {
// Address of the asset rate oracle
AssetRateAdapter rateOracle;
// The exchange rate from base to quote (if invert is required it is already done)
int256 rate;
// The decimals of the underlying, the rate converts to the underlying decimals
int256 underlyingDecimals;
}
/// @dev Cash group when loaded into memory
struct CashGroupParameters {
uint16 currencyId;
uint256 maxMarketIndex;
AssetRateParameters assetRate;
bytes32 data;
}
/// @dev A portfolio asset when loaded in memory
struct PortfolioAsset {
// Asset currency id
uint256 currencyId;
uint256 maturity;
// Asset type, fCash or liquidity token.
uint256 assetType;
// fCash amount or liquidity token amount
int256 notional;
// Used for managing portfolio asset state
uint256 storageSlot;
// The state of the asset for when it is written to storage
AssetStorageState storageState;
}
/// @dev Market object as represented in memory
struct MarketParameters {
bytes32 storageSlot;
uint256 maturity;
// Total amount of fCash available for purchase in the market.
int256 totalfCash;
// Total amount of cash available for purchase in the market.
int256 totalAssetCash;
// Total amount of liquidity tokens (representing a claim on liquidity) in the market.
int256 totalLiquidity;
// This is the previous annualized interest rate in RATE_PRECISION that the market traded
// at. This is used to calculate the rate anchor to smooth interest rates over time.
uint256 lastImpliedRate;
// Time lagged version of lastImpliedRate, used to value fCash assets at market rates while
// remaining resistent to flash loan attacks.
uint256 oracleRate;
// This is the timestamp of the previous trade
uint256 previousTradeTime;
}
/****** Storage objects ******/
/// @dev Token object in storage:
/// 20 bytes for token address
/// 1 byte for hasTransferFee
/// 1 byte for tokenType
/// 1 byte for tokenDecimals
/// 9 bytes for maxCollateralBalance (may not always be set)
struct TokenStorage {
// Address of the token
address tokenAddress;
// Transfer fees will change token deposit behavior
bool hasTransferFee;
TokenType tokenType;
uint8 decimalPlaces;
// Upper limit on how much of this token the contract can hold at any time
uint72 maxCollateralBalance;
}
/// @dev Exchange rate object as it is represented in storage, total storage is 25 bytes.
struct ETHRateStorage {
// Address of the rate oracle
AggregatorV2V3Interface rateOracle;
// The decimal places of precision that the rate oracle uses
uint8 rateDecimalPlaces;
// True of the exchange rate must be inverted
bool mustInvert;
// NOTE: both of these governance values are set with BUFFER_DECIMALS precision
// Amount of buffer to apply to the exchange rate for negative balances.
uint8 buffer;
// Amount of haircut to apply to the exchange rate for positive balances
uint8 haircut;
// Liquidation discount in percentage point terms, 106 means a 6% discount
uint8 liquidationDiscount;
}
/// @dev Asset rate oracle object as it is represented in storage, total storage is 21 bytes.
struct AssetRateStorage {
// Address of the rate oracle
AssetRateAdapter rateOracle;
// The decimal places of the underlying asset
uint8 underlyingDecimalPlaces;
}
/// @dev Governance parameters for a cash group, total storage is 9 bytes + 7 bytes for liquidity token haircuts
/// and 7 bytes for rate scalars, total of 23 bytes. Note that this is stored packed in the storage slot so there
/// are no indexes stored for liquidityTokenHaircuts or rateScalars, maxMarketIndex is used instead to determine the
/// length.
struct CashGroupSettings {
// Index of the AMMs on chain that will be made available. Idiosyncratic fCash
// that is dated less than the longest AMM will be tradable.
uint8 maxMarketIndex;
// Time window in 5 minute increments that the rate oracle will be averaged over
uint8 rateOracleTimeWindow5Min;
// Total fees per trade, specified in BPS
uint8 totalFeeBPS;
// Share of the fees given to the protocol, denominated in percentage
uint8 reserveFeeShare;
// Debt buffer specified in 5 BPS increments
uint8 debtBuffer5BPS;
// fCash haircut specified in 5 BPS increments
uint8 fCashHaircut5BPS;
// If an account has a negative cash balance, it can be settled by incurring debt at the 3 month market. This
// is the basis points for the penalty rate that will be added the current 3 month oracle rate.
uint8 settlementPenaltyRate5BPS;
// If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for
uint8 liquidationfCashHaircut5BPS;
// If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for
uint8 liquidationDebtBuffer5BPS;
// Liquidity token haircut applied to cash claims, specified as a percentage between 0 and 100
uint8[] liquidityTokenHaircuts;
// Rate scalar used to determine the slippage of the market
uint8[] rateScalars;
}
/// @dev Holds account level context information used to determine settlement and
/// free collateral actions. Total storage is 28 bytes
struct AccountContext {
// Used to check when settlement must be triggered on an account
uint40 nextSettleTime;
// For lenders that never incur debt, we use this flag to skip the free collateral check.
bytes1 hasDebt;
// Length of the account's asset array
uint8 assetArrayLength;
// If this account has bitmaps set, this is the corresponding currency id
uint16 bitmapCurrencyId;
// 9 total active currencies possible (2 bytes each)
bytes18 activeCurrencies;
}
/// @dev Holds nToken context information mapped via the nToken address, total storage is
/// 16 bytes
struct nTokenContext {
// Currency id that the nToken represents
uint16 currencyId;
// Annual incentive emission rate denominated in WHOLE TOKENS (multiply by
// INTERNAL_TOKEN_PRECISION to get the actual rate)
uint32 incentiveAnnualEmissionRate;
// The last block time at utc0 that the nToken was initialized at, zero if it
// has never been initialized
uint32 lastInitializedTime;
// Length of the asset array, refers to the number of liquidity tokens an nToken
// currently holds
uint8 assetArrayLength;
// Each byte is a specific nToken parameter
bytes5 nTokenParameters;
// Reserved bytes for future usage
bytes15 _unused;
// Set to true if a secondary rewarder is set
bool hasSecondaryRewarder;
}
/// @dev Holds account balance information, total storage 32 bytes
struct BalanceStorage {
// Number of nTokens held by the account
uint80 nTokenBalance;
// Last time the account claimed their nTokens
uint32 lastClaimTime;
// Incentives that the account no longer has a claim over
uint56 accountIncentiveDebt;
// Cash balance of the account
int88 cashBalance;
}
/// @dev Holds information about a settlement rate, total storage 25 bytes
struct SettlementRateStorage {
uint40 blockTime;
uint128 settlementRate;
uint8 underlyingDecimalPlaces;
}
/// @dev Holds information about a market, total storage is 42 bytes so this spans
/// two storage words
struct MarketStorage {
// Total fCash in the market
uint80 totalfCash;
// Total asset cash in the market
uint80 totalAssetCash;
// Last annualized interest rate the market traded at
uint32 lastImpliedRate;
// Last recorded oracle rate for the market
uint32 oracleRate;
// Last time a trade was made
uint32 previousTradeTime;
// This is stored in slot + 1
uint80 totalLiquidity;
}
struct ifCashStorage {
// Notional amount of fCash at the slot, limited to int128 to allow for
// future expansion
int128 notional;
}
/// @dev A single portfolio asset in storage, total storage of 19 bytes
struct PortfolioAssetStorage {
// Currency Id for the asset
uint16 currencyId;
// Maturity of the asset
uint40 maturity;
// Asset type (fCash or Liquidity Token marker)
uint8 assetType;
// Notional
int88 notional;
}
/// @dev nToken total supply factors for the nToken, includes factors related
/// to claiming incentives, total storage 32 bytes. This is the deprecated version
struct nTokenTotalSupplyStorage_deprecated {
// Total supply of the nToken
uint96 totalSupply;
// Integral of the total supply used for calculating the average total supply
uint128 integralTotalSupply;
// Last timestamp the supply value changed, used for calculating the integralTotalSupply
uint32 lastSupplyChangeTime;
}
/// @dev nToken total supply factors for the nToken, includes factors related
/// to claiming incentives, total storage 32 bytes.
struct nTokenTotalSupplyStorage {
// Total supply of the nToken
uint96 totalSupply;
// How many NOTE incentives should be issued per nToken in 1e18 precision
uint128 accumulatedNOTEPerNToken;
// Last timestamp when the accumulation happened
uint32 lastAccumulatedTime;
}
/// @dev Used in view methods to return account balances in a developer friendly manner
struct AccountBalance {
uint16 currencyId;
int256 cashBalance;
int256 nTokenBalance;
uint256 lastClaimTime;
uint256 accountIncentiveDebt;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
/// @title All shared constants for the Notional system should be declared here.
library Constants {
uint8 internal constant CETH_DECIMAL_PLACES = 8;
// Token precision used for all internal balances, TokenHandler library ensures that we
// limit the dust amount caused by precision mismatches
int256 internal constant INTERNAL_TOKEN_PRECISION = 1e8;
uint256 internal constant INCENTIVE_ACCUMULATION_PRECISION = 1e18;
// ETH will be initialized as the first currency
uint256 internal constant ETH_CURRENCY_ID = 1;
uint8 internal constant ETH_DECIMAL_PLACES = 18;
int256 internal constant ETH_DECIMALS = 1e18;
// Used to prevent overflow when converting decimal places to decimal precision values via
// 10**decimalPlaces. This is a safe value for int256 and uint256 variables. We apply this
// constraint when storing decimal places in governance.
uint256 internal constant MAX_DECIMAL_PLACES = 36;
// Address of the reserve account
address internal constant RESERVE = address(0);
// Most significant bit
bytes32 internal constant MSB =
0x8000000000000000000000000000000000000000000000000000000000000000;
// Each bit set in this mask marks where an active market should be in the bitmap
// if the first bit refers to the reference time. Used to detect idiosyncratic
// fcash in the nToken accounts
bytes32 internal constant ACTIVE_MARKETS_MASK = (
MSB >> ( 90 - 1) | // 3 month
MSB >> (105 - 1) | // 6 month
MSB >> (135 - 1) | // 1 year
MSB >> (147 - 1) | // 2 year
MSB >> (183 - 1) | // 5 year
MSB >> (211 - 1) | // 10 year
MSB >> (251 - 1) // 20 year
);
// Basis for percentages
int256 internal constant PERCENTAGE_DECIMALS = 100;
// Max number of traded markets, also used as the maximum number of assets in a portfolio array
uint256 internal constant MAX_TRADED_MARKET_INDEX = 7;
// Max number of fCash assets in a bitmap, this is based on the gas costs of calculating free collateral
// for a bitmap portfolio
uint256 internal constant MAX_BITMAP_ASSETS = 20;
uint256 internal constant FIVE_MINUTES = 300;
// Internal date representations, note we use a 6/30/360 week/month/year convention here
uint256 internal constant DAY = 86400;
// We use six day weeks to ensure that all time references divide evenly
uint256 internal constant WEEK = DAY * 6;
uint256 internal constant MONTH = WEEK * 5;
uint256 internal constant QUARTER = MONTH * 3;
uint256 internal constant YEAR = QUARTER * 4;
// These constants are used in DateTime.sol
uint256 internal constant DAYS_IN_WEEK = 6;
uint256 internal constant DAYS_IN_MONTH = 30;
uint256 internal constant DAYS_IN_QUARTER = 90;
// Offsets for each time chunk denominated in days
uint256 internal constant MAX_DAY_OFFSET = 90;
uint256 internal constant MAX_WEEK_OFFSET = 360;
uint256 internal constant MAX_MONTH_OFFSET = 2160;
uint256 internal constant MAX_QUARTER_OFFSET = 7650;
// Offsets for each time chunk denominated in bits
uint256 internal constant WEEK_BIT_OFFSET = 90;
uint256 internal constant MONTH_BIT_OFFSET = 135;
uint256 internal constant QUARTER_BIT_OFFSET = 195;
// This is a constant that represents the time period that all rates are normalized by, 360 days
uint256 internal constant IMPLIED_RATE_TIME = 360 * DAY;
// Number of decimal places that rates are stored in, equals 100%
int256 internal constant RATE_PRECISION = 1e9;
// One basis point in RATE_PRECISION terms
uint256 internal constant BASIS_POINT = uint256(RATE_PRECISION / 10000);
// Used to when calculating the amount to deleverage of a market when minting nTokens
uint256 internal constant DELEVERAGE_BUFFER = 300 * BASIS_POINT;
// Used for scaling cash group factors
uint256 internal constant FIVE_BASIS_POINTS = 5 * BASIS_POINT;
// Used for residual purchase incentive and cash withholding buffer
uint256 internal constant TEN_BASIS_POINTS = 10 * BASIS_POINT;
// This is the ABDK64x64 representation of RATE_PRECISION
// RATE_PRECISION_64x64 = ABDKMath64x64.fromUint(RATE_PRECISION)
int128 internal constant RATE_PRECISION_64x64 = 0x3b9aca000000000000000000;
int128 internal constant LOG_RATE_PRECISION_64x64 = 382276781265598821176;
// Limit the market proportion so that borrowing cannot hit extremely high interest rates
int256 internal constant MAX_MARKET_PROPORTION = RATE_PRECISION * 99 / 100;
uint8 internal constant FCASH_ASSET_TYPE = 1;
// Liquidity token asset types are 1 + marketIndex (where marketIndex is 1-indexed)
uint8 internal constant MIN_LIQUIDITY_TOKEN_INDEX = 2;
uint8 internal constant MAX_LIQUIDITY_TOKEN_INDEX = 8;
// Used for converting bool to bytes1, solidity does not have a native conversion
// method for this
bytes1 internal constant BOOL_FALSE = 0x00;
bytes1 internal constant BOOL_TRUE = 0x01;
// Account context flags
bytes1 internal constant HAS_ASSET_DEBT = 0x01;
bytes1 internal constant HAS_CASH_DEBT = 0x02;
bytes2 internal constant ACTIVE_IN_PORTFOLIO = 0x8000;
bytes2 internal constant ACTIVE_IN_BALANCES = 0x4000;
bytes2 internal constant UNMASK_FLAGS = 0x3FFF;
uint16 internal constant MAX_CURRENCIES = uint16(UNMASK_FLAGS);
// Equal to 100% of all deposit amounts for nToken liquidity across fCash markets.
int256 internal constant DEPOSIT_PERCENT_BASIS = 1e8;
// nToken Parameters: there are offsets in the nTokenParameters bytes6 variable returned
// in nTokenHandler. Each constant represents a position in the byte array.
uint8 internal constant LIQUIDATION_HAIRCUT_PERCENTAGE = 0;
uint8 internal constant CASH_WITHHOLDING_BUFFER = 1;
uint8 internal constant RESIDUAL_PURCHASE_TIME_BUFFER = 2;
uint8 internal constant PV_HAIRCUT_PERCENTAGE = 3;
uint8 internal constant RESIDUAL_PURCHASE_INCENTIVE = 4;
// Liquidation parameters
// Default percentage of collateral that a liquidator is allowed to liquidate, will be higher if the account
// requires more collateral to be liquidated
int256 internal constant DEFAULT_LIQUIDATION_PORTION = 40;
// Percentage of local liquidity token cash claim delivered to the liquidator for liquidating liquidity tokens
int256 internal constant TOKEN_REPO_INCENTIVE_PERCENT = 30;
// Pause Router liquidation enabled states
bytes1 internal constant LOCAL_CURRENCY_ENABLED = 0x01;
bytes1 internal constant COLLATERAL_CURRENCY_ENABLED = 0x02;
bytes1 internal constant LOCAL_FCASH_ENABLED = 0x04;
bytes1 internal constant CROSS_CURRENCY_FCASH_ENABLED = 0x08;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/Constants.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library DateTime {
using SafeMath for uint256;
/// @notice Returns the current reference time which is how all the AMM dates are calculated.
function getReferenceTime(uint256 blockTime) internal pure returns (uint256) {
require(blockTime >= Constants.QUARTER);
return blockTime - (blockTime % Constants.QUARTER);
}
/// @notice Truncates a date to midnight UTC time
function getTimeUTC0(uint256 time) internal pure returns (uint256) {
require(time >= Constants.DAY);
return time - (time % Constants.DAY);
}
/// @notice These are the predetermined market offsets for trading
/// @dev Markets are 1-indexed because the 0 index means that no markets are listed for the cash group.
function getTradedMarket(uint256 index) internal pure returns (uint256) {
if (index == 1) return Constants.QUARTER;
if (index == 2) return 2 * Constants.QUARTER;
if (index == 3) return Constants.YEAR;
if (index == 4) return 2 * Constants.YEAR;
if (index == 5) return 5 * Constants.YEAR;
if (index == 6) return 10 * Constants.YEAR;
if (index == 7) return 20 * Constants.YEAR;
revert("Invalid index");
}
/// @notice Determines if the maturity falls on one of the valid on chain market dates.
function isValidMarketMaturity(
uint256 maxMarketIndex,
uint256 maturity,
uint256 blockTime
) internal pure returns (bool) {
require(maxMarketIndex > 0, "CG: no markets listed");
require(maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: market index bound");
if (maturity % Constants.QUARTER != 0) return false;
uint256 tRef = DateTime.getReferenceTime(blockTime);
for (uint256 i = 1; i <= maxMarketIndex; i++) {
if (maturity == tRef.add(DateTime.getTradedMarket(i))) return true;
}
return false;
}
/// @notice Determines if an idiosyncratic maturity is valid and returns the bit reference that is the case.
function isValidMaturity(
uint256 maxMarketIndex,
uint256 maturity,
uint256 blockTime
) internal pure returns (bool) {
uint256 tRef = DateTime.getReferenceTime(blockTime);
uint256 maxMaturity = tRef.add(DateTime.getTradedMarket(maxMarketIndex));
// Cannot trade past max maturity
if (maturity > maxMaturity) return false;
// prettier-ignore
(/* */, bool isValid) = DateTime.getBitNumFromMaturity(blockTime, maturity);
return isValid;
}
/// @notice Returns the market index for a given maturity, if the maturity is idiosyncratic
/// will return the nearest market index that is larger than the maturity.
/// @return uint marketIndex, bool isIdiosyncratic
function getMarketIndex(
uint256 maxMarketIndex,
uint256 maturity,
uint256 blockTime
) internal pure returns (uint256, bool) {
require(maxMarketIndex > 0, "CG: no markets listed");
require(maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: market index bound");
uint256 tRef = DateTime.getReferenceTime(blockTime);
for (uint256 i = 1; i <= maxMarketIndex; i++) {
uint256 marketMaturity = tRef.add(DateTime.getTradedMarket(i));
// If market matches then is not idiosyncratic
if (marketMaturity == maturity) return (i, false);
// Returns the market that is immediately greater than the maturity
if (marketMaturity > maturity) return (i, true);
}
revert("CG: no market found");
}
/// @notice Given a bit number and the reference time of the first bit, returns the bit number
/// of a given maturity.
/// @return bitNum and a true or false if the maturity falls on the exact bit
function getBitNumFromMaturity(uint256 blockTime, uint256 maturity)
internal
pure
returns (uint256, bool)
{
uint256 blockTimeUTC0 = getTimeUTC0(blockTime);
// Maturities must always divide days evenly
if (maturity % Constants.DAY != 0) return (0, false);
// Maturity cannot be in the past
if (blockTimeUTC0 >= maturity) return (0, false);
// Overflow check done above
// daysOffset has no remainders, checked above
uint256 daysOffset = (maturity - blockTimeUTC0) / Constants.DAY;
// These if statements need to fall through to the next one
if (daysOffset <= Constants.MAX_DAY_OFFSET) {
return (daysOffset, true);
} else if (daysOffset <= Constants.MAX_WEEK_OFFSET) {
// (daysOffset - MAX_DAY_OFFSET) is the days overflow into the week portion, must be > 0
// (blockTimeUTC0 % WEEK) / DAY is the offset into the week portion
// This returns the offset from the previous max offset in days
uint256 offsetInDays =
daysOffset -
Constants.MAX_DAY_OFFSET +
(blockTimeUTC0 % Constants.WEEK) /
Constants.DAY;
return (
// This converts the offset in days to its corresponding bit position, truncating down
// if it does not divide evenly into DAYS_IN_WEEK
Constants.WEEK_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_WEEK,
(offsetInDays % Constants.DAYS_IN_WEEK) == 0
);
} else if (daysOffset <= Constants.MAX_MONTH_OFFSET) {
uint256 offsetInDays =
daysOffset -
Constants.MAX_WEEK_OFFSET +
(blockTimeUTC0 % Constants.MONTH) /
Constants.DAY;
return (
Constants.MONTH_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_MONTH,
(offsetInDays % Constants.DAYS_IN_MONTH) == 0
);
} else if (daysOffset <= Constants.MAX_QUARTER_OFFSET) {
uint256 offsetInDays =
daysOffset -
Constants.MAX_MONTH_OFFSET +
(blockTimeUTC0 % Constants.QUARTER) /
Constants.DAY;
return (
Constants.QUARTER_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_QUARTER,
(offsetInDays % Constants.DAYS_IN_QUARTER) == 0
);
}
// This is the maximum 1-indexed bit num, it is never valid because it is beyond the 20
// year max maturity
return (256, false);
}
/// @notice Given a bit number and a block time returns the maturity that the bit number
/// should reference. Bit numbers are one indexed.
function getMaturityFromBitNum(uint256 blockTime, uint256 bitNum)
internal
pure
returns (uint256)
{
require(bitNum != 0); // dev: cash group get maturity from bit num is zero
require(bitNum <= 256); // dev: cash group get maturity from bit num overflow
uint256 blockTimeUTC0 = getTimeUTC0(blockTime);
uint256 firstBit;
if (bitNum <= Constants.WEEK_BIT_OFFSET) {
return blockTimeUTC0 + bitNum * Constants.DAY;
} else if (bitNum <= Constants.MONTH_BIT_OFFSET) {
firstBit =
blockTimeUTC0 +
Constants.MAX_DAY_OFFSET * Constants.DAY -
// This backs up to the day that is divisible by a week
(blockTimeUTC0 % Constants.WEEK);
return firstBit + (bitNum - Constants.WEEK_BIT_OFFSET) * Constants.WEEK;
} else if (bitNum <= Constants.QUARTER_BIT_OFFSET) {
firstBit =
blockTimeUTC0 +
Constants.MAX_WEEK_OFFSET * Constants.DAY -
(blockTimeUTC0 % Constants.MONTH);
return firstBit + (bitNum - Constants.MONTH_BIT_OFFSET) * Constants.MONTH;
} else {
firstBit =
blockTimeUTC0 +
Constants.MAX_MONTH_OFFSET * Constants.DAY -
(blockTimeUTC0 % Constants.QUARTER);
return firstBit + (bitNum - Constants.QUARTER_BIT_OFFSET) * Constants.QUARTER;
}
}
}
// SPDX-License-Identifier: BSD-4-Clause
/*
* ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^0.5.0 || ^0.6.0 || ^0.7.0;
/**
* Smart contract library of mathematical functions operating with signed
* 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is
* basically a simple fraction whose numerator is signed 128-bit integer and
* denominator is 2^64. As long as denominator is always the same, there is no
* need to store it, thus in Solidity signed 64.64-bit fixed point numbers are
* represented by int128 type holding only the numerator.
*/
library ABDKMath64x64 {
/*
* Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/*
* Maximum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Convert signed 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromInt (int256 x) internal pure returns (int128) {
require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* Convert signed 64.64 fixed point number into signed 64-bit integer number
* rounding down.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64-bit integer number
*/
function toInt (int128 x) internal pure returns (int64) {
return int64 (x >> 64);
}
/**
* Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromUInt (uint256 x) internal pure returns (int128) {
require (x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* Convert signed 64.64 fixed point number into unsigned 64-bit integer
* number rounding down. Revert on underflow.
*
* @param x signed 64.64-bit fixed point number
* @return unsigned 64-bit integer number
*/
function toUInt (int128 x) internal pure returns (uint64) {
require (x >= 0);
return uint64 (x >> 64);
}
/**
* Convert signed 128.128 fixed point number into signed 64.64-bit fixed point
* number rounding down. Revert on overflow.
*
* @param x signed 128.128-bin fixed point number
* @return signed 64.64-bit fixed point number
*/
function from128x128 (int256 x) internal pure returns (int128) {
int256 result = x >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Convert signed 64.64 fixed point number into signed 128.128 fixed point
* number.
*
* @param x signed 64.64-bit fixed point number
* @return signed 128.128 fixed point number
*/
function to128x128 (int128 x) internal pure returns (int256) {
return int256 (x) << 64;
}
/**
* Calculate x + y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function add (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) + y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x - y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sub (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) - y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x * y rounding down. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function mul (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) * y >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x * y rounding towards zero, where x is signed 64.64 fixed point
* number and y is signed 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y signed 256-bit integer number
* @return signed 256-bit integer number
*/
function muli (int128 x, int256 y) internal pure returns (int256) {
if (x == MIN_64x64) {
require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&
y <= 0x1000000000000000000000000000000000000000000000000);
return -y << 63;
} else {
bool negativeResult = false;
if (x < 0) {
x = -x;
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint256 absoluteResult = mulu (x, uint256 (y));
if (negativeResult) {
require (absoluteResult <=
0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256 (absoluteResult);
}
}
}
/**
* Calculate x * y rounding down, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y unsigned 256-bit integer number
* @return unsigned 256-bit integer number
*/
function mulu (int128 x, uint256 y) internal pure returns (uint256) {
if (y == 0) return 0;
require (x >= 0);
uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = uint256 (x) * (y >> 128);
require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
hi <<= 64;
require (hi <=
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);
return hi + lo;
}
/**
* Calculate x / y rounding towards zero. Revert on overflow or when y is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function div (int128 x, int128 y) internal pure returns (int128) {
require (y != 0);
int256 result = (int256 (x) << 64) / y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x / y rounding towards zero, where x and y are signed 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x signed 256-bit integer number
* @param y signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divi (int256 x, int256 y) internal pure returns (int128) {
require (y != 0);
bool negativeResult = false;
if (x < 0) {
x = -x; // We rely on overflow behavior here
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint128 absoluteResult = divuu (uint256 (x), uint256 (y));
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divu (uint256 x, uint256 y) internal pure returns (int128) {
require (y != 0);
uint128 result = divuu (x, y);
require (result <= uint128 (MAX_64x64));
return int128 (result);
}
/**
* Calculate -x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function neg (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return -x;
}
/**
* Calculate |x|. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function abs (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return x < 0 ? -x : x;
}
/**
* Calculate 1 / x rounding towards zero. Revert on overflow or when x is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function inv (int128 x) internal pure returns (int128) {
require (x != 0);
int256 result = int256 (0x100000000000000000000000000000000) / x;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function avg (int128 x, int128 y) internal pure returns (int128) {
return int128 ((int256 (x) + int256 (y)) >> 1);
}
/**
* Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.
* Revert on overflow or in case x * y is negative.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function gavg (int128 x, int128 y) internal pure returns (int128) {
int256 m = int256 (x) * int256 (y);
require (m >= 0);
require (m <
0x4000000000000000000000000000000000000000000000000000000000000000);
return int128 (sqrtu (uint256 (m)));
}
/**
* Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y uint256 value
* @return signed 64.64-bit fixed point number
*/
function pow (int128 x, uint256 y) internal pure returns (int128) {
bool negative = x < 0 && y & 1 == 1;
uint256 absX = uint128 (x < 0 ? -x : x);
uint256 absResult;
absResult = 0x100000000000000000000000000000000;
if (absX <= 0x10000000000000000) {
absX <<= 63;
while (y != 0) {
if (y & 0x1 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x2 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x4 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x8 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
y >>= 4;
}
absResult >>= 64;
} else {
uint256 absXShift = 63;
if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }
if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }
if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }
if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }
if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }
if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }
uint256 resultShift = 0;
while (y != 0) {
require (absXShift < 64);
if (y & 0x1 != 0) {
absResult = absResult * absX >> 127;
resultShift += absXShift;
if (absResult > 0x100000000000000000000000000000000) {
absResult >>= 1;
resultShift += 1;
}
}
absX = absX * absX >> 127;
absXShift <<= 1;
if (absX >= 0x100000000000000000000000000000000) {
absX >>= 1;
absXShift += 1;
}
y >>= 1;
}
require (resultShift < 64);
absResult >>= 64 - resultShift;
}
int256 result = negative ? -int256 (absResult) : int256 (absResult);
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate sqrt (x) rounding down. Revert if x < 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sqrt (int128 x) internal pure returns (int128) {
require (x >= 0);
return int128 (sqrtu (uint256 (x) << 64));
}
/**
* Calculate binary logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function log_2 (int128 x) internal pure returns (int128) {
require (x > 0);
int256 msb = 0;
int256 xc = x;
if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 result = msb - 64 << 64;
uint256 ux = uint256 (x) << uint256 (127 - msb);
for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * int256 (b);
}
return int128 (result);
}
/**
* Calculate natural logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function ln (int128 x) internal pure returns (int128) {
require (x > 0);
return int128 (
uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128);
}
/**
* Calculate binary exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp_2 (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
uint256 result = 0x80000000000000000000000000000000;
if (x & 0x8000000000000000 > 0)
result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;
if (x & 0x4000000000000000 > 0)
result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;
if (x & 0x2000000000000000 > 0)
result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;
if (x & 0x1000000000000000 > 0)
result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;
if (x & 0x800000000000000 > 0)
result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;
if (x & 0x400000000000000 > 0)
result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;
if (x & 0x200000000000000 > 0)
result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;
if (x & 0x100000000000000 > 0)
result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;
if (x & 0x80000000000000 > 0)
result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;
if (x & 0x40000000000000 > 0)
result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;
if (x & 0x20000000000000 > 0)
result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;
if (x & 0x10000000000000 > 0)
result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;
if (x & 0x8000000000000 > 0)
result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;
if (x & 0x4000000000000 > 0)
result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;
if (x & 0x2000000000000 > 0)
result = result * 0x1000162E525EE054754457D5995292026 >> 128;
if (x & 0x1000000000000 > 0)
result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;
if (x & 0x800000000000 > 0)
result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;
if (x & 0x400000000000 > 0)
result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;
if (x & 0x200000000000 > 0)
result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;
if (x & 0x100000000000 > 0)
result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;
if (x & 0x80000000000 > 0)
result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;
if (x & 0x40000000000 > 0)
result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;
if (x & 0x20000000000 > 0)
result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;
if (x & 0x10000000000 > 0)
result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;
if (x & 0x8000000000 > 0)
result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;
if (x & 0x4000000000 > 0)
result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;
if (x & 0x2000000000 > 0)
result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;
if (x & 0x1000000000 > 0)
result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;
if (x & 0x800000000 > 0)
result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;
if (x & 0x400000000 > 0)
result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;
if (x & 0x200000000 > 0)
result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;
if (x & 0x100000000 > 0)
result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;
if (x & 0x80000000 > 0)
result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;
if (x & 0x40000000 > 0)
result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;
if (x & 0x20000000 > 0)
result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;
if (x & 0x10000000 > 0)
result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;
if (x & 0x8000000 > 0)
result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;
if (x & 0x4000000 > 0)
result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;
if (x & 0x2000000 > 0)
result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;
if (x & 0x1000000 > 0)
result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;
if (x & 0x800000 > 0)
result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;
if (x & 0x400000 > 0)
result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;
if (x & 0x200000 > 0)
result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;
if (x & 0x100000 > 0)
result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;
if (x & 0x80000 > 0)
result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;
if (x & 0x40000 > 0)
result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;
if (x & 0x20000 > 0)
result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;
if (x & 0x10000 > 0)
result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;
if (x & 0x8000 > 0)
result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;
if (x & 0x4000 > 0)
result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;
if (x & 0x2000 > 0)
result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;
if (x & 0x1000 > 0)
result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;
if (x & 0x800 > 0)
result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;
if (x & 0x400 > 0)
result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;
if (x & 0x200 > 0)
result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;
if (x & 0x100 > 0)
result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;
if (x & 0x80 > 0)
result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;
if (x & 0x40 > 0)
result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;
if (x & 0x20 > 0)
result = result * 0x100000000000000162E42FEFA39EF366F >> 128;
if (x & 0x10 > 0)
result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;
if (x & 0x8 > 0)
result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;
if (x & 0x4 > 0)
result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;
if (x & 0x2 > 0)
result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;
if (x & 0x1 > 0)
result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;
result >>= uint256 (63 - (x >> 64));
require (result <= uint256 (MAX_64x64));
return int128 (result);
}
/**
* Calculate natural exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
return exp_2 (
int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return unsigned 64.64-bit fixed point number
*/
function divuu (uint256 x, uint256 y) private pure returns (uint128) {
require (y != 0);
uint256 result;
if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
result = (x << 64) / y;
else {
uint256 msb = 192;
uint256 xc = x >> 192;
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 hi = result * (y >> 128);
uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 xh = x >> 192;
uint256 xl = x << 64;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
lo = hi << 128;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
assert (xh == hi >> 128);
result += xl / y;
}
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint128 (result);
}
/**
* Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
* number.
*
* @param x unsigned 256-bit integer number
* @return unsigned 128-bit integer number
*/
function sqrtu (uint256 x) private pure returns (uint128) {
if (x == 0) return 0;
else {
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }
if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }
if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }
if (xx >= 0x10000) { xx >>= 16; r <<= 8; }
if (xx >= 0x100) { xx >>= 8; r <<= 4; }
if (xx >= 0x10) { xx >>= 4; r <<= 2; }
if (xx >= 0x8) { r <<= 1; }
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return uint128 (r < r1 ? r : r1);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
import "./AggregatorInterface.sol";
import "./AggregatorV3Interface.sol";
interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface
{
}
// SPDX-License-Identifier: GPL-v3
pragma solidity >=0.7.0;
/// @notice Used as a wrapper for tokens that are interest bearing for an
/// underlying token. Follows the cToken interface, however, can be adapted
/// for other interest bearing tokens.
interface AssetRateAdapter {
function token() external view returns (address);
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
function underlying() external view returns (address);
function getExchangeRateStateful() external returns (int256);
function getExchangeRateView() external view returns (int256);
function getAnnualizedSupplyRate() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
interface AggregatorInterface {
function latestAnswer() external view returns (int256);
function latestTimestamp() external view returns (uint256);
function latestRound() external view returns (uint256);
function getAnswer(uint256 roundId) external view returns (int256);
function getTimestamp(uint256 roundId) external view returns (uint256);
event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt);
event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
interface IRewarder {
function claimRewards(
address account,
uint16 currencyId,
uint256 nTokenBalanceBefore,
uint256 nTokenBalanceAfter,
int256 netNTokenSupplyChange,
uint256 NOTETokensClaimed
) external;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
struct LendingPoolStorage {
ILendingPool lendingPool;
}
interface ILendingPool {
/**
* @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.
* - E.g. User deposits 100 USDC and gets in return 100 aUSDC
* @param asset The address of the underlying asset to deposit
* @param amount The amount to be deposited
* @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
* is a different wallet
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
/**
* @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned
* E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC
* @param asset The address of the underlying asset to withdraw
* @param amount The underlying amount to be withdrawn
* - Send the value type(uint256).max in order to withdraw the whole aToken balance
* @param to Address that will receive the underlying, same as msg.sender if the user
* wants to receive it on his own wallet, or a different address if the beneficiary is a
* different wallet
* @return The final amount withdrawn
**/
function withdraw(
address asset,
uint256 amount,
address to
) external returns (uint256);
/**
* @dev Returns the normalized income normalized income of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The reserve's normalized income
*/
function getReserveNormalizedIncome(address asset) external view returns (uint256);
/**
* @dev Returns the state and configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The state of the reserve
**/
function getReserveData(address asset) external view returns (ReserveData memory);
// refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties.
struct ReserveData {
//stores the reserve configuration
ReserveConfigurationMap configuration;
//the liquidity index. Expressed in ray
uint128 liquidityIndex;
//variable borrow index. Expressed in ray
uint128 variableBorrowIndex;
//the current supply rate. Expressed in ray
uint128 currentLiquidityRate;
//the current variable borrow rate. Expressed in ray
uint128 currentVariableBorrowRate;
//the current stable borrow rate. Expressed in ray
uint128 currentStableBorrowRate;
uint40 lastUpdateTimestamp;
//tokens addresses
address aTokenAddress;
address stableDebtTokenAddress;
address variableDebtTokenAddress;
//address of the interest rate strategy
address interestRateStrategyAddress;
//the id of the reserve. Represents the position in the list of the active reserves
uint8 id;
}
struct ReserveConfigurationMap {
//bit 0-15: LTV
//bit 16-31: Liq. threshold
//bit 32-47: Liq. bonus
//bit 48-55: Decimals
//bit 56: Reserve is active
//bit 57: reserve is frozen
//bit 58: borrowing is enabled
//bit 59: stable rate borrowing enabled
//bit 60-63: reserved
//bit 64-79: reserve factor
uint256 data;
}
struct UserConfigurationMap {
uint256 data;
}
enum InterestRateMode {NONE, STABLE, VARIABLE}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./TokenHandler.sol";
import "../nToken/nTokenHandler.sol";
import "../nToken/nTokenSupply.sol";
import "../../math/SafeInt256.sol";
import "../../external/MigrateIncentives.sol";
import "../../../interfaces/notional/IRewarder.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library Incentives {
using SafeMath for uint256;
using SafeInt256 for int256;
/// @notice Calculates the total incentives to claim including those claimed under the previous
/// less accurate calculation. Once an account is migrated it will only claim incentives under
/// the more accurate regime
function calculateIncentivesToClaim(
BalanceState memory balanceState,
address tokenAddress,
uint256 accumulatedNOTEPerNToken,
uint256 finalNTokenBalance
) internal view returns (uint256 incentivesToClaim) {
if (balanceState.lastClaimTime > 0) {
// If lastClaimTime is set then the account had incentives under the
// previous regime. Will calculate the final amount of incentives to claim here
// under the previous regime.
incentivesToClaim = MigrateIncentives.migrateAccountFromPreviousCalculation(
tokenAddress,
balanceState.storedNTokenBalance.toUint(),
balanceState.lastClaimTime,
// In this case the accountIncentiveDebt is stored as lastClaimIntegralSupply under
// the old calculation
balanceState.accountIncentiveDebt
);
// This marks the account as migrated and lastClaimTime will no longer be used
balanceState.lastClaimTime = 0;
// This value will be set immediately after this, set this to zero so that the calculation
// establishes a new baseline.
balanceState.accountIncentiveDebt = 0;
}
// If an account was migrated then they have no accountIncentivesDebt and should accumulate
// incentives based on their share since the new regime calculation started.
// If an account is just initiating their nToken balance then storedNTokenBalance will be zero
// and they will have no incentives to claim.
// This calculation uses storedNTokenBalance which is the balance of the account up until this point,
// this is important to ensure that the account does not claim for nTokens that they will mint or
// redeem on a going forward basis.
// The calculation below has the following precision:
// storedNTokenBalance (INTERNAL_TOKEN_PRECISION)
// MUL accumulatedNOTEPerNToken (INCENTIVE_ACCUMULATION_PRECISION)
// DIV INCENTIVE_ACCUMULATION_PRECISION
// = INTERNAL_TOKEN_PRECISION - (accountIncentivesDebt) INTERNAL_TOKEN_PRECISION
incentivesToClaim = incentivesToClaim.add(
balanceState.storedNTokenBalance.toUint()
.mul(accumulatedNOTEPerNToken)
.div(Constants.INCENTIVE_ACCUMULATION_PRECISION)
.sub(balanceState.accountIncentiveDebt)
);
// Update accountIncentivesDebt denominated in INTERNAL_TOKEN_PRECISION which marks the portion
// of the accumulatedNOTE that the account no longer has a claim over. Use the finalNTokenBalance
// here instead of storedNTokenBalance to mark the overall incentives claim that the account
// does not have a claim over. We do not aggregate this value with the previous accountIncentiveDebt
// because accumulatedNOTEPerNToken is already an aggregated value.
// The calculation below has the following precision:
// finalNTokenBalance (INTERNAL_TOKEN_PRECISION)
// MUL accumulatedNOTEPerNToken (INCENTIVE_ACCUMULATION_PRECISION)
// DIV INCENTIVE_ACCUMULATION_PRECISION
// = INTERNAL_TOKEN_PRECISION
balanceState.accountIncentiveDebt = finalNTokenBalance
.mul(accumulatedNOTEPerNToken)
.div(Constants.INCENTIVE_ACCUMULATION_PRECISION);
}
/// @notice Incentives must be claimed every time nToken balance changes.
/// @dev BalanceState.accountIncentiveDebt is updated in place here
function claimIncentives(
BalanceState memory balanceState,
address account,
uint256 finalNTokenBalance
) internal returns (uint256 incentivesToClaim) {
uint256 blockTime = block.timestamp;
address tokenAddress = nTokenHandler.nTokenAddress(balanceState.currencyId);
// This will updated the nToken storage and return what the accumulatedNOTEPerNToken
// is up until this current block time in 1e18 precision
uint256 accumulatedNOTEPerNToken = nTokenSupply.changeNTokenSupply(
tokenAddress,
balanceState.netNTokenSupplyChange,
blockTime
);
incentivesToClaim = calculateIncentivesToClaim(
balanceState,
tokenAddress,
accumulatedNOTEPerNToken,
finalNTokenBalance
);
// If a secondary incentive rewarder is set, then call it
IRewarder rewarder = nTokenHandler.getSecondaryRewarder(tokenAddress);
if (address(rewarder) != address(0)) {
rewarder.claimRewards(
account,
balanceState.currencyId,
// When this method is called from finalize, the storedNTokenBalance has not
// been updated to finalNTokenBalance yet so this is the balance before the change.
balanceState.storedNTokenBalance.toUint(),
finalNTokenBalance,
// When the rewarder is called, totalSupply has been updated already so may need to
// adjust its calculation using the net supply change figure here. Supply change
// may be zero when nTokens are transferred.
balanceState.netNTokenSupplyChange,
incentivesToClaim
);
}
if (incentivesToClaim > 0) TokenHandler.transferIncentive(account, incentivesToClaim);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../math/SafeInt256.sol";
import "../../global/LibStorage.sol";
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../../global/Deployments.sol";
import "./protocols/AaveHandler.sol";
import "./protocols/CompoundHandler.sol";
import "./protocols/GenericToken.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/// @notice Handles all external token transfers and events
library TokenHandler {
using SafeInt256 for int256;
using SafeMath for uint256;
function setMaxCollateralBalance(uint256 currencyId, uint72 maxCollateralBalance) internal {
mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage();
TokenStorage storage tokenStorage = store[currencyId][false];
tokenStorage.maxCollateralBalance = maxCollateralBalance;
}
function getAssetToken(uint256 currencyId) internal view returns (Token memory) {
return _getToken(currencyId, false);
}
function getUnderlyingToken(uint256 currencyId) internal view returns (Token memory) {
return _getToken(currencyId, true);
}
/// @notice Gets token data for a particular currency id, if underlying is set to true then returns
/// the underlying token. (These may not always exist)
function _getToken(uint256 currencyId, bool underlying) private view returns (Token memory) {
mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage();
TokenStorage storage tokenStorage = store[currencyId][underlying];
return
Token({
tokenAddress: tokenStorage.tokenAddress,
hasTransferFee: tokenStorage.hasTransferFee,
// No overflow, restricted on storage
decimals: int256(10**tokenStorage.decimalPlaces),
tokenType: tokenStorage.tokenType,
maxCollateralBalance: tokenStorage.maxCollateralBalance
});
}
/// @notice Sets a token for a currency id.
function setToken(
uint256 currencyId,
bool underlying,
TokenStorage memory tokenStorage
) internal {
mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage();
if (tokenStorage.tokenType == TokenType.Ether && currencyId == Constants.ETH_CURRENCY_ID) {
// Hardcoded parameters for ETH just to make sure we don't get it wrong.
TokenStorage storage ts = store[currencyId][true];
ts.tokenAddress = address(0);
ts.hasTransferFee = false;
ts.tokenType = TokenType.Ether;
ts.decimalPlaces = Constants.ETH_DECIMAL_PLACES;
ts.maxCollateralBalance = 0;
return;
}
// Check token address
require(tokenStorage.tokenAddress != address(0), "TH: address is zero");
// Once a token is set we cannot override it. In the case that we do need to do change a token address
// then we should explicitly upgrade this method to allow for a token to be changed.
Token memory token = _getToken(currencyId, underlying);
require(
token.tokenAddress == tokenStorage.tokenAddress || token.tokenAddress == address(0),
"TH: token cannot be reset"
);
require(0 < tokenStorage.decimalPlaces
&& tokenStorage.decimalPlaces <= Constants.MAX_DECIMAL_PLACES, "TH: invalid decimals");
// Validate token type
require(tokenStorage.tokenType != TokenType.Ether); // dev: ether can only be set once
if (underlying) {
// Underlying tokens cannot have max collateral balances, the contract only has a balance temporarily
// during mint and redeem actions.
require(tokenStorage.maxCollateralBalance == 0); // dev: underlying cannot have max collateral balance
require(tokenStorage.tokenType == TokenType.UnderlyingToken); // dev: underlying token inconsistent
} else {
require(tokenStorage.tokenType != TokenType.UnderlyingToken); // dev: underlying token inconsistent
}
if (tokenStorage.tokenType == TokenType.cToken || tokenStorage.tokenType == TokenType.aToken) {
// Set the approval for the underlying so that we can mint cTokens or aTokens
Token memory underlyingToken = getUnderlyingToken(currencyId);
// cTokens call transfer from the tokenAddress, but aTokens use the LendingPool
// to initiate all transfers
address approvalAddress = tokenStorage.tokenType == TokenType.cToken ?
tokenStorage.tokenAddress :
address(LibStorage.getLendingPool().lendingPool);
// ERC20 tokens should return true on success for an approval, but Tether
// does not return a value here so we use the NonStandard interface here to
// check that the approval was successful.
IEIP20NonStandard(underlyingToken.tokenAddress).approve(
approvalAddress,
type(uint256).max
);
GenericToken.checkReturnCode();
}
store[currencyId][underlying] = tokenStorage;
}
/**
* @notice If a token is mintable then will mint it. At this point we expect to have the underlying
* balance in the contract already.
* @param assetToken the asset token to mint
* @param underlyingAmountExternal the amount of underlying to transfer to the mintable token
* @return the amount of asset tokens minted, will always be a positive integer
*/
function mint(Token memory assetToken, uint16 currencyId, uint256 underlyingAmountExternal) internal returns (int256) {
// aTokens return the principal plus interest value when calling the balanceOf selector. We cannot use this
// value in internal accounting since it will not allow individual users to accrue aToken interest. Use the
// scaledBalanceOf function call instead for internal accounting.
bytes4 balanceOfSelector = assetToken.tokenType == TokenType.aToken ?
AaveHandler.scaledBalanceOfSelector :
GenericToken.defaultBalanceOfSelector;
uint256 startingBalance = GenericToken.checkBalanceViaSelector(assetToken.tokenAddress, address(this), balanceOfSelector);
if (assetToken.tokenType == TokenType.aToken) {
Token memory underlyingToken = getUnderlyingToken(currencyId);
AaveHandler.mint(underlyingToken, underlyingAmountExternal);
} else if (assetToken.tokenType == TokenType.cToken) {
CompoundHandler.mint(assetToken, underlyingAmountExternal);
} else if (assetToken.tokenType == TokenType.cETH) {
CompoundHandler.mintCETH(assetToken);
} else {
revert(); // dev: non mintable token
}
uint256 endingBalance = GenericToken.checkBalanceViaSelector(assetToken.tokenAddress, address(this), balanceOfSelector);
// This is the starting and ending balance in external precision
return SafeInt256.toInt(endingBalance.sub(startingBalance));
}
/**
* @notice If a token is redeemable to underlying will redeem it and transfer the underlying balance
* to the account
* @param assetToken asset token to redeem
* @param currencyId the currency id of the token
* @param account account to transfer the underlying to
* @param assetAmountExternal the amount to transfer in asset token denomination and external precision
* @return the actual amount of underlying tokens transferred. this is used as a return value back to the
* user, is not used for internal accounting purposes
*/
function redeem(
Token memory assetToken,
uint256 currencyId,
address account,
uint256 assetAmountExternal
) internal returns (int256) {
uint256 transferAmount;
if (assetToken.tokenType == TokenType.cETH) {
transferAmount = CompoundHandler.redeemCETH(assetToken, account, assetAmountExternal);
} else {
Token memory underlyingToken = getUnderlyingToken(currencyId);
if (assetToken.tokenType == TokenType.aToken) {
transferAmount = AaveHandler.redeem(underlyingToken, account, assetAmountExternal);
} else if (assetToken.tokenType == TokenType.cToken) {
transferAmount = CompoundHandler.redeem(assetToken, underlyingToken, account, assetAmountExternal);
} else {
revert(); // dev: non redeemable token
}
}
// Use the negative value here to signify that assets have left the protocol
return SafeInt256.toInt(transferAmount).neg();
}
/// @notice Handles transfers into and out of the system denominated in the external token decimal
/// precision.
function transfer(
Token memory token,
address account,
uint256 currencyId,
int256 netTransferExternal
) internal returns (int256 actualTransferExternal) {
// This will be true in all cases except for deposits where the token has transfer fees. For
// aTokens this value is set before convert from scaled balances to principal plus interest
actualTransferExternal = netTransferExternal;
if (token.tokenType == TokenType.aToken) {
Token memory underlyingToken = getUnderlyingToken(currencyId);
// aTokens need to be converted when we handle the transfer since the external balance format
// is not the same as the internal balance format that we use
netTransferExternal = AaveHandler.convertFromScaledBalanceExternal(
underlyingToken.tokenAddress,
netTransferExternal
);
}
if (netTransferExternal > 0) {
// Deposits must account for transfer fees.
int256 netDeposit = _deposit(token, account, uint256(netTransferExternal));
// If an aToken has a transfer fee this will still return a balance figure
// in scaledBalanceOf terms due to the selector
if (token.hasTransferFee) actualTransferExternal = netDeposit;
} else if (token.tokenType == TokenType.Ether) {
// netTransferExternal can only be negative or zero at this point
GenericToken.transferNativeTokenOut(account, uint256(netTransferExternal.neg()));
} else {
GenericToken.safeTransferOut(
token.tokenAddress,
account,
// netTransferExternal is zero or negative here
uint256(netTransferExternal.neg())
);
}
}
/// @notice Handles token deposits into Notional. If there is a transfer fee then we must
/// calculate the net balance after transfer. Amounts are denominated in the destination token's
/// precision.
function _deposit(
Token memory token,
address account,
uint256 amount
) private returns (int256) {
uint256 startingBalance;
uint256 endingBalance;
bytes4 balanceOfSelector = token.tokenType == TokenType.aToken ?
AaveHandler.scaledBalanceOfSelector :
GenericToken.defaultBalanceOfSelector;
if (token.hasTransferFee) {
startingBalance = GenericToken.checkBalanceViaSelector(token.tokenAddress, address(this), balanceOfSelector);
}
GenericToken.safeTransferIn(token.tokenAddress, account, amount);
if (token.hasTransferFee || token.maxCollateralBalance > 0) {
// If aTokens have a max collateral balance then it will be applied against the scaledBalanceOf. This is probably
// the correct behavior because if collateral accrues interest over time we should not somehow go over the
// maxCollateralBalance due to the passage of time.
endingBalance = GenericToken.checkBalanceViaSelector(token.tokenAddress, address(this), balanceOfSelector);
}
if (token.maxCollateralBalance > 0) {
int256 internalPrecisionBalance = convertToInternal(token, SafeInt256.toInt(endingBalance));
// Max collateral balance is stored as uint72, no overflow
require(internalPrecisionBalance <= SafeInt256.toInt(token.maxCollateralBalance)); // dev: over max collateral balance
}
// Math is done in uint inside these statements and will revert on negative
if (token.hasTransferFee) {
return SafeInt256.toInt(endingBalance.sub(startingBalance));
} else {
return SafeInt256.toInt(amount);
}
}
function convertToInternal(Token memory token, int256 amount) internal pure returns (int256) {
// If token decimals > INTERNAL_TOKEN_PRECISION:
// on deposit: resulting dust will accumulate to protocol
// on withdraw: protocol may lose dust amount. However, withdraws are only calculated based
// on a conversion from internal token precision to external token precision so therefore dust
// amounts cannot be specified for withdraws.
// If token decimals < INTERNAL_TOKEN_PRECISION then this will add zeros to the
// end of amount and will not result in dust.
if (token.decimals == Constants.INTERNAL_TOKEN_PRECISION) return amount;
return amount.mul(Constants.INTERNAL_TOKEN_PRECISION).div(token.decimals);
}
function convertToExternal(Token memory token, int256 amount) internal pure returns (int256) {
if (token.decimals == Constants.INTERNAL_TOKEN_PRECISION) return amount;
// If token decimals > INTERNAL_TOKEN_PRECISION then this will increase amount
// by adding a number of zeros to the end and will not result in dust.
// If token decimals < INTERNAL_TOKEN_PRECISION:
// on deposit: Deposits are specified in external token precision and there is no loss of precision when
// tokens are converted from external to internal precision
// on withdraw: this calculation will round down such that the protocol retains the residual cash balance
return amount.mul(token.decimals).div(Constants.INTERNAL_TOKEN_PRECISION);
}
function transferIncentive(address account, uint256 tokensToTransfer) internal {
GenericToken.safeTransferOut(Deployments.NOTE_TOKEN_ADDRESS, account, tokensToTransfer);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
import "./Bitmap.sol";
/**
* Packs an uint value into a "floating point" storage slot. Used for storing
* lastClaimIntegralSupply values in balance storage. For these values, we don't need
* to maintain exact precision but we don't want to be limited by storage size overflows.
*
* A floating point value is defined by the 48 most significant bits and an 8 bit number
* of bit shifts required to restore its precision. The unpacked value will always be less
* than the packed value with a maximum absolute loss of precision of (2 ** bitShift) - 1.
*/
library FloatingPoint56 {
function packTo56Bits(uint256 value) internal pure returns (uint56) {
uint256 bitShift;
// If the value is over the uint48 max value then we will shift it down
// given the index of the most significant bit. We store this bit shift
// in the least significant byte of the 56 bit slot available.
if (value > type(uint48).max) bitShift = (Bitmap.getMSB(value) - 47);
uint256 shiftedValue = value >> bitShift;
return uint56((shiftedValue << 8) | bitShift);
}
function unpackFrom56Bits(uint256 value) internal pure returns (uint256) {
// The least significant 8 bits will be the amount to bit shift
uint256 bitShift = uint256(uint8(value));
return ((value >> 8) << bitShift);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./nTokenSupply.sol";
import "../markets/CashGroup.sol";
import "../markets/AssetRate.sol";
import "../portfolio/PortfolioHandler.sol";
import "../balances/BalanceHandler.sol";
import "../../global/LibStorage.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library nTokenHandler {
using SafeInt256 for int256;
/// @dev Mirror of the value in LibStorage, solidity compiler does not allow assigning
/// two constants to each other.
uint256 private constant NUM_NTOKEN_MARKET_FACTORS = 14;
/// @notice Returns an account context object that is specific to nTokens.
function getNTokenContext(address tokenAddress)
internal
view
returns (
uint16 currencyId,
uint256 incentiveAnnualEmissionRate,
uint256 lastInitializedTime,
uint8 assetArrayLength,
bytes5 parameters
)
{
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
currencyId = context.currencyId;
incentiveAnnualEmissionRate = context.incentiveAnnualEmissionRate;
lastInitializedTime = context.lastInitializedTime;
assetArrayLength = context.assetArrayLength;
parameters = context.nTokenParameters;
}
/// @notice Returns the nToken token address for a given currency
function nTokenAddress(uint256 currencyId) internal view returns (address tokenAddress) {
mapping(uint256 => address) storage store = LibStorage.getNTokenAddressStorage();
return store[currencyId];
}
/// @notice Called by governance to set the nToken token address and its reverse lookup. Cannot be
/// reset once this is set.
function setNTokenAddress(uint16 currencyId, address tokenAddress) internal {
mapping(uint256 => address) storage addressStore = LibStorage.getNTokenAddressStorage();
require(addressStore[currencyId] == address(0), "PT: token address exists");
mapping(address => nTokenContext) storage contextStore = LibStorage.getNTokenContextStorage();
nTokenContext storage context = contextStore[tokenAddress];
require(context.currencyId == 0, "PT: currency exists");
// This will initialize all other context slots to zero
context.currencyId = currencyId;
addressStore[currencyId] = tokenAddress;
}
/// @notice Set nToken token collateral parameters
function setNTokenCollateralParameters(
address tokenAddress,
uint8 residualPurchaseIncentive10BPS,
uint8 pvHaircutPercentage,
uint8 residualPurchaseTimeBufferHours,
uint8 cashWithholdingBuffer10BPS,
uint8 liquidationHaircutPercentage
) internal {
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
require(liquidationHaircutPercentage <= Constants.PERCENTAGE_DECIMALS, "Invalid haircut");
// The pv haircut percentage must be less than the liquidation percentage or else liquidators will not
// get profit for liquidating nToken.
require(pvHaircutPercentage < liquidationHaircutPercentage, "Invalid pv haircut");
// Ensure that the cash withholding buffer is greater than the residual purchase incentive or
// the nToken may not have enough cash to pay accounts to buy its negative ifCash
require(residualPurchaseIncentive10BPS <= cashWithholdingBuffer10BPS, "Invalid discounts");
bytes5 parameters =
(bytes5(uint40(residualPurchaseIncentive10BPS)) |
(bytes5(uint40(pvHaircutPercentage)) << 8) |
(bytes5(uint40(residualPurchaseTimeBufferHours)) << 16) |
(bytes5(uint40(cashWithholdingBuffer10BPS)) << 24) |
(bytes5(uint40(liquidationHaircutPercentage)) << 32));
// Set the parameters
context.nTokenParameters = parameters;
}
/// @notice Sets a secondary rewarder contract on an nToken so that incentives can come from a different
/// contract, aside from the native NOTE token incentives.
function setSecondaryRewarder(
uint16 currencyId,
IRewarder rewarder
) internal {
address tokenAddress = nTokenAddress(currencyId);
// nToken must exist for a secondary rewarder
require(tokenAddress != address(0));
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
// Setting the rewarder to address(0) will disable it. We use a context setting here so that
// we can save a storage read before getting the rewarder
context.hasSecondaryRewarder = (address(rewarder) != address(0));
LibStorage.getSecondaryIncentiveRewarder()[tokenAddress] = rewarder;
}
/// @notice Returns the secondary rewarder if it is set
function getSecondaryRewarder(address tokenAddress) internal view returns (IRewarder) {
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
if (context.hasSecondaryRewarder) {
return LibStorage.getSecondaryIncentiveRewarder()[tokenAddress];
} else {
return IRewarder(address(0));
}
}
function setArrayLengthAndInitializedTime(
address tokenAddress,
uint8 arrayLength,
uint256 lastInitializedTime
) internal {
require(lastInitializedTime >= 0 && uint256(lastInitializedTime) < type(uint32).max); // dev: next settle time overflow
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
context.lastInitializedTime = uint32(lastInitializedTime);
context.assetArrayLength = arrayLength;
}
/// @notice Returns the array of deposit shares and leverage thresholds for nTokens
function getDepositParameters(uint256 currencyId, uint256 maxMarketIndex)
internal
view
returns (int256[] memory depositShares, int256[] memory leverageThresholds)
{
mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenDepositStorage();
uint32[NUM_NTOKEN_MARKET_FACTORS] storage depositParameters = store[currencyId];
(depositShares, leverageThresholds) = _getParameters(depositParameters, maxMarketIndex, false);
}
/// @notice Sets the deposit parameters
/// @dev We pack the values in alternating between the two parameters into either one or two
// storage slots depending on the number of markets. This is to save storage reads when we use the parameters.
function setDepositParameters(
uint256 currencyId,
uint32[] calldata depositShares,
uint32[] calldata leverageThresholds
) internal {
require(
depositShares.length <= Constants.MAX_TRADED_MARKET_INDEX,
"PT: deposit share length"
);
require(depositShares.length == leverageThresholds.length, "PT: leverage share length");
uint256 shareSum;
for (uint256 i; i < depositShares.length; i++) {
// This cannot overflow in uint 256 with 9 max slots
shareSum = shareSum + depositShares[i];
require(
leverageThresholds[i] > 0 && leverageThresholds[i] < Constants.RATE_PRECISION,
"PT: leverage threshold"
);
}
// Total deposit share must add up to 100%
require(shareSum == uint256(Constants.DEPOSIT_PERCENT_BASIS), "PT: deposit shares sum");
mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenDepositStorage();
uint32[NUM_NTOKEN_MARKET_FACTORS] storage depositParameters = store[currencyId];
_setParameters(depositParameters, depositShares, leverageThresholds);
}
/// @notice Sets the initialization parameters for the markets, these are read only when markets
/// are initialized
function setInitializationParameters(
uint256 currencyId,
uint32[] calldata annualizedAnchorRates,
uint32[] calldata proportions
) internal {
require(annualizedAnchorRates.length <= Constants.MAX_TRADED_MARKET_INDEX, "PT: annualized anchor rates length");
require(proportions.length == annualizedAnchorRates.length, "PT: proportions length");
for (uint256 i; i < proportions.length; i++) {
// Proportions must be between zero and the rate precision
require(annualizedAnchorRates[i] > 0, "NT: anchor rate zero");
require(
proportions[i] > 0 && proportions[i] < Constants.RATE_PRECISION,
"PT: invalid proportion"
);
}
mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenInitStorage();
uint32[NUM_NTOKEN_MARKET_FACTORS] storage initParameters = store[currencyId];
_setParameters(initParameters, annualizedAnchorRates, proportions);
}
/// @notice Returns the array of initialization parameters for a given currency.
function getInitializationParameters(uint256 currencyId, uint256 maxMarketIndex)
internal
view
returns (int256[] memory annualizedAnchorRates, int256[] memory proportions)
{
mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenInitStorage();
uint32[NUM_NTOKEN_MARKET_FACTORS] storage initParameters = store[currencyId];
(annualizedAnchorRates, proportions) = _getParameters(initParameters, maxMarketIndex, true);
}
function _getParameters(
uint32[NUM_NTOKEN_MARKET_FACTORS] storage slot,
uint256 maxMarketIndex,
bool noUnset
) private view returns (int256[] memory, int256[] memory) {
uint256 index = 0;
int256[] memory array1 = new int256[](maxMarketIndex);
int256[] memory array2 = new int256[](maxMarketIndex);
for (uint256 i; i < maxMarketIndex; i++) {
array1[i] = slot[index];
index++;
array2[i] = slot[index];
index++;
if (noUnset) {
require(array1[i] > 0 && array2[i] > 0, "PT: init value zero");
}
}
return (array1, array2);
}
function _setParameters(
uint32[NUM_NTOKEN_MARKET_FACTORS] storage slot,
uint32[] calldata array1,
uint32[] calldata array2
) private {
uint256 index = 0;
for (uint256 i = 0; i < array1.length; i++) {
slot[index] = array1[i];
index++;
slot[index] = array2[i];
index++;
}
}
function loadNTokenPortfolioNoCashGroup(nTokenPortfolio memory nToken, uint16 currencyId)
internal
view
{
nToken.tokenAddress = nTokenAddress(currencyId);
// prettier-ignore
(
/* currencyId */,
/* incentiveRate */,
uint256 lastInitializedTime,
uint8 assetArrayLength,
bytes5 parameters
) = getNTokenContext(nToken.tokenAddress);
// prettier-ignore
(
uint256 totalSupply,
/* accumulatedNOTEPerNToken */,
/* lastAccumulatedTime */
) = nTokenSupply.getStoredNTokenSupplyFactors(nToken.tokenAddress);
nToken.lastInitializedTime = lastInitializedTime;
nToken.totalSupply = int256(totalSupply);
nToken.parameters = parameters;
nToken.portfolioState = PortfolioHandler.buildPortfolioState(
nToken.tokenAddress,
assetArrayLength,
0
);
// prettier-ignore
(
nToken.cashBalance,
/* nTokenBalance */,
/* lastClaimTime */,
/* accountIncentiveDebt */
) = BalanceHandler.getBalanceStorage(nToken.tokenAddress, currencyId);
}
/// @notice Uses buildCashGroupStateful
function loadNTokenPortfolioStateful(nTokenPortfolio memory nToken, uint16 currencyId)
internal
{
loadNTokenPortfolioNoCashGroup(nToken, currencyId);
nToken.cashGroup = CashGroup.buildCashGroupStateful(currencyId);
}
/// @notice Uses buildCashGroupView
function loadNTokenPortfolioView(nTokenPortfolio memory nToken, uint16 currencyId)
internal
view
{
loadNTokenPortfolioNoCashGroup(nToken, currencyId);
nToken.cashGroup = CashGroup.buildCashGroupView(currencyId);
}
/// @notice Returns the next settle time for the nToken which is 1 quarter away
function getNextSettleTime(nTokenPortfolio memory nToken) internal pure returns (uint256) {
if (nToken.lastInitializedTime == 0) return 0;
return DateTime.getReferenceTime(nToken.lastInitializedTime) + Constants.QUARTER;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./nTokenHandler.sol";
import "../../global/LibStorage.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library nTokenSupply {
using SafeInt256 for int256;
using SafeMath for uint256;
/// @notice Retrieves stored nToken supply and related factors. Do not use accumulatedNOTEPerNToken for calculating
/// incentives! Use `getUpdatedAccumulatedNOTEPerNToken` instead.
function getStoredNTokenSupplyFactors(address tokenAddress)
internal
view
returns (
uint256 totalSupply,
uint256 accumulatedNOTEPerNToken,
uint256 lastAccumulatedTime
)
{
mapping(address => nTokenTotalSupplyStorage) storage store = LibStorage.getNTokenTotalSupplyStorage();
nTokenTotalSupplyStorage storage nTokenStorage = store[tokenAddress];
totalSupply = nTokenStorage.totalSupply;
// NOTE: DO NOT USE THIS RETURNED VALUE FOR CALCULATING INCENTIVES. The accumulatedNOTEPerNToken
// must be updated given the block time. Use `getUpdatedAccumulatedNOTEPerNToken` instead
accumulatedNOTEPerNToken = nTokenStorage.accumulatedNOTEPerNToken;
lastAccumulatedTime = nTokenStorage.lastAccumulatedTime;
}
/// @notice Returns the updated accumulated NOTE per nToken for calculating incentives
function getUpdatedAccumulatedNOTEPerNToken(address tokenAddress, uint256 blockTime)
internal view
returns (
uint256 totalSupply,
uint256 accumulatedNOTEPerNToken,
uint256 lastAccumulatedTime
)
{
(
totalSupply,
accumulatedNOTEPerNToken,
lastAccumulatedTime
) = getStoredNTokenSupplyFactors(tokenAddress);
// nToken totalSupply is never allowed to drop to zero but we check this here to avoid
// divide by zero errors during initialization. Also ensure that lastAccumulatedTime is not
// zero to avoid a massive accumulation amount on initialization.
if (blockTime > lastAccumulatedTime && lastAccumulatedTime > 0 && totalSupply > 0) {
// prettier-ignore
(
/* currencyId */,
uint256 emissionRatePerYear,
/* initializedTime */,
/* assetArrayLength */,
/* parameters */
) = nTokenHandler.getNTokenContext(tokenAddress);
uint256 additionalNOTEAccumulatedPerNToken = _calculateAdditionalNOTE(
// Emission rate is denominated in whole tokens, scale to 1e8 decimals here
emissionRatePerYear.mul(uint256(Constants.INTERNAL_TOKEN_PRECISION)),
// Time since last accumulation (overflow checked above)
blockTime - lastAccumulatedTime,
totalSupply
);
accumulatedNOTEPerNToken = accumulatedNOTEPerNToken.add(additionalNOTEAccumulatedPerNToken);
require(accumulatedNOTEPerNToken < type(uint128).max); // dev: accumulated NOTE overflow
}
}
/// @notice additionalNOTEPerNToken accumulated since last accumulation time in 1e18 precision
function _calculateAdditionalNOTE(
uint256 emissionRatePerYear,
uint256 timeSinceLastAccumulation,
uint256 totalSupply
)
private
pure
returns (uint256)
{
// If we use 18 decimal places as the accumulation precision then we will overflow uint128 when
// a single nToken has accumulated 3.4 x 10^20 NOTE tokens. This isn't possible since the max
// NOTE that can accumulate is 10^16 (100 million NOTE in 1e8 precision) so we should be safe
// using 18 decimal places and uint128 storage slot
// timeSinceLastAccumulation (SECONDS)
// accumulatedNOTEPerSharePrecision (1e18)
// emissionRatePerYear (INTERNAL_TOKEN_PRECISION)
// DIVIDE BY
// YEAR (SECONDS)
// totalSupply (INTERNAL_TOKEN_PRECISION)
return timeSinceLastAccumulation
.mul(Constants.INCENTIVE_ACCUMULATION_PRECISION)
.mul(emissionRatePerYear)
.div(Constants.YEAR)
// totalSupply > 0 is checked in the calling function
.div(totalSupply);
}
/// @notice Updates the nToken token supply amount when minting or redeeming.
/// @param tokenAddress address of the nToken
/// @param netChange positive or negative change to the total nToken supply
/// @param blockTime current block time
/// @return accumulatedNOTEPerNToken updated to the given block time
function changeNTokenSupply(
address tokenAddress,
int256 netChange,
uint256 blockTime
) internal returns (uint256) {
(
uint256 totalSupply,
uint256 accumulatedNOTEPerNToken,
/* uint256 lastAccumulatedTime */
) = getUpdatedAccumulatedNOTEPerNToken(tokenAddress, blockTime);
// Update storage variables
mapping(address => nTokenTotalSupplyStorage) storage store = LibStorage.getNTokenTotalSupplyStorage();
nTokenTotalSupplyStorage storage nTokenStorage = store[tokenAddress];
int256 newTotalSupply = int256(totalSupply).add(netChange);
// We allow newTotalSupply to equal zero here even though it is prevented from being redeemed down to
// exactly zero by other internal logic inside nTokenRedeem. This is meant to be purely an overflow check.
require(0 <= newTotalSupply && uint256(newTotalSupply) < type(uint96).max); // dev: nToken supply overflow
nTokenStorage.totalSupply = uint96(newTotalSupply);
// NOTE: overflow checked inside getUpdatedAccumulatedNOTEPerNToken so that behavior here mirrors what
// the user would see if querying the view function
nTokenStorage.accumulatedNOTEPerNToken = uint128(accumulatedNOTEPerNToken);
require(blockTime < type(uint32).max); // dev: block time overflow
nTokenStorage.lastAccumulatedTime = uint32(blockTime);
return accumulatedNOTEPerNToken;
}
/// @notice Called by governance to set the new emission rate
function setIncentiveEmissionRate(address tokenAddress, uint32 newEmissionsRate, uint256 blockTime) internal {
// Ensure that the accumulatedNOTEPerNToken updates to the current block time before we update the
// emission rate
changeNTokenSupply(tokenAddress, 0, blockTime);
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
context.incentiveAnnualEmissionRate = newEmissionsRate;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../global/LibStorage.sol";
import "../internal/nToken/nTokenHandler.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @notice Deployed library for migration of incentives from the old (inaccurate) calculation
* to a newer, more accurate calculation based on SushiSwap MasterChef math. The more accurate
* calculation is inside `Incentives.sol` and this library holds the legacy calculation. System
* migration code can be found in `MigrateIncentivesFix.sol`
*/
library MigrateIncentives {
using SafeMath for uint256;
/// @notice Calculates the claimable incentives for a particular nToken and account in the
/// previous regime. This should only ever be called ONCE for an account / currency combination
/// to get the incentives accrued up until the migration date.
function migrateAccountFromPreviousCalculation(
address tokenAddress,
uint256 nTokenBalance,
uint256 lastClaimTime,
uint256 lastClaimIntegralSupply
) external view returns (uint256) {
(
uint256 finalEmissionRatePerYear,
uint256 finalTotalIntegralSupply,
uint256 finalMigrationTime
) = _getMigratedIncentiveValues(tokenAddress);
// This if statement should never be true but we return 0 just in case
if (lastClaimTime == 0 || lastClaimTime >= finalMigrationTime) return 0;
// No overflow here, checked above. All incentives are claimed up until finalMigrationTime
// using the finalTotalIntegralSupply. Both these values are set on migration and will not
// change.
uint256 timeSinceMigration = finalMigrationTime - lastClaimTime;
// (timeSinceMigration * INTERNAL_TOKEN_PRECISION * finalEmissionRatePerYear) / YEAR
uint256 incentiveRate =
timeSinceMigration
.mul(uint256(Constants.INTERNAL_TOKEN_PRECISION))
// Migration emission rate is stored as is, denominated in whole tokens
.mul(finalEmissionRatePerYear).mul(uint256(Constants.INTERNAL_TOKEN_PRECISION))
.div(Constants.YEAR);
// Returns the average supply using the integral of the total supply.
uint256 avgTotalSupply = finalTotalIntegralSupply.sub(lastClaimIntegralSupply).div(timeSinceMigration);
if (avgTotalSupply == 0) return 0;
uint256 incentivesToClaim = nTokenBalance.mul(incentiveRate).div(avgTotalSupply);
// incentiveRate has a decimal basis of 1e16 so divide by token precision to reduce to 1e8
incentivesToClaim = incentivesToClaim.div(uint256(Constants.INTERNAL_TOKEN_PRECISION));
return incentivesToClaim;
}
function _getMigratedIncentiveValues(
address tokenAddress
) private view returns (
uint256 finalEmissionRatePerYear,
uint256 finalTotalIntegralSupply,
uint256 finalMigrationTime
) {
mapping(address => nTokenTotalSupplyStorage_deprecated) storage store = LibStorage.getDeprecatedNTokenTotalSupplyStorage();
nTokenTotalSupplyStorage_deprecated storage d_nTokenStorage = store[tokenAddress];
// The total supply value is overridden as emissionRatePerYear during the initialization
finalEmissionRatePerYear = d_nTokenStorage.totalSupply;
finalTotalIntegralSupply = d_nTokenStorage.integralTotalSupply;
finalMigrationTime = d_nTokenStorage.lastSupplyChangeTime;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
/// @title Hardcoded deployed contracts are listed here. These are hardcoded to reduce
/// gas costs for immutable addresses. They must be updated per environment that Notional
/// is deployed to.
library Deployments {
address internal constant NOTE_TOKEN_ADDRESS = 0xCFEAead4947f0705A14ec42aC3D44129E1Ef3eD5;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../../global/Types.sol";
import "../../../global/LibStorage.sol";
import "../../../math/SafeInt256.sol";
import "../TokenHandler.sol";
import "../../../../interfaces/aave/IAToken.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library AaveHandler {
using SafeMath for uint256;
using SafeInt256 for int256;
int256 internal constant RAY = 1e27;
int256 internal constant halfRAY = RAY / 2;
bytes4 internal constant scaledBalanceOfSelector = IAToken.scaledBalanceOf.selector;
/**
* @notice Mints an amount of aTokens corresponding to the the underlying.
* @param underlyingToken address of the underlying token to pass to Aave
* @param underlyingAmountExternal amount of underlying to deposit, in external precision
*/
function mint(Token memory underlyingToken, uint256 underlyingAmountExternal) internal {
// In AaveV3 this method is renamed to supply() but deposit() is still available for
// backwards compatibility: https://github.com/aave/aave-v3-core/blob/master/contracts/protocol/pool/Pool.sol#L755
// We use deposit here so that mainnet-fork tests against Aave v2 will pass.
LibStorage.getLendingPool().lendingPool.deposit(
underlyingToken.tokenAddress,
underlyingAmountExternal,
address(this),
0
);
}
/**
* @notice Redeems and sends an amount of aTokens to the specified account
* @param underlyingToken address of the underlying token to pass to Aave
* @param account account to receive the underlying
* @param assetAmountExternal amount of aTokens in scaledBalanceOf terms
*/
function redeem(
Token memory underlyingToken,
address account,
uint256 assetAmountExternal
) internal returns (uint256 underlyingAmountExternal) {
underlyingAmountExternal = convertFromScaledBalanceExternal(
underlyingToken.tokenAddress,
SafeInt256.toInt(assetAmountExternal)
).toUint();
LibStorage.getLendingPool().lendingPool.withdraw(
underlyingToken.tokenAddress,
underlyingAmountExternal,
account
);
}
/**
* @notice Takes an assetAmountExternal (in this case is the Aave balanceOf representing principal plus interest)
* and returns another assetAmountExternal value which represents the Aave scaledBalanceOf (representing a proportional
* claim on Aave principal plus interest onto the future). This conversion ensures that depositors into Notional will
* receive future Aave interest.
* @dev There is no loss of precision within this function since it does the exact same calculation as Aave.
* @param currencyId is the currency id
* @param assetAmountExternal an Aave token amount representing principal plus interest supplied by the user. This must
* be positive in this function, this method is only called when depositing aTokens directly
* @return scaledAssetAmountExternal the Aave scaledBalanceOf equivalent. The decimal precision of this value will
* be in external precision.
*/
function convertToScaledBalanceExternal(uint256 currencyId, int256 assetAmountExternal) internal view returns (int256) {
if (assetAmountExternal == 0) return 0;
require(assetAmountExternal > 0);
Token memory underlyingToken = TokenHandler.getUnderlyingToken(currencyId);
// We know that this value must be positive
int256 index = _getReserveNormalizedIncome(underlyingToken.tokenAddress);
// Mimic the WadRay math performed by Aave (but do it in int256 instead)
int256 halfIndex = index / 2;
// Overflow will occur when: (a * RAY + halfIndex) > int256.max
require(assetAmountExternal <= (type(int256).max - halfIndex) / RAY);
// if index is zero then this will revert
return (assetAmountExternal * RAY + halfIndex) / index;
}
/**
* @notice Takes an assetAmountExternal (in this case is the internal scaledBalanceOf in external decimal precision)
* and returns another assetAmountExternal value which represents the Aave balanceOf representing the principal plus interest
* that will be transferred. This is required to maintain compatibility with Aave's ERC20 transfer functions.
* @dev There is no loss of precision because this does exactly what Aave's calculation would do
* @param underlyingToken token address of the underlying asset
* @param netScaledBalanceExternal an amount representing the scaledBalanceOf in external decimal precision calculated from
* Notional cash balances. This amount may be positive or negative depending on if assets are being deposited (positive) or
* withdrawn (negative).
* @return netBalanceExternal the Aave balanceOf equivalent as a signed integer
*/
function convertFromScaledBalanceExternal(address underlyingToken, int256 netScaledBalanceExternal) internal view returns (int256 netBalanceExternal) {
if (netScaledBalanceExternal == 0) return 0;
// We know that this value must be positive
int256 index = _getReserveNormalizedIncome(underlyingToken);
// Use the absolute value here so that the halfRay rounding is applied correctly for negative values
int256 abs = netScaledBalanceExternal.abs();
// Mimic the WadRay math performed by Aave (but do it in int256 instead)
// Overflow will occur when: (abs * index + halfRay) > int256.max
// Here the first term is computed at compile time so it just does a division. If index is zero then
// solidity will revert.
require(abs <= (type(int256).max - halfRAY) / index);
int256 absScaled = (abs * index + halfRAY) / RAY;
return netScaledBalanceExternal > 0 ? absScaled : absScaled.neg();
}
/// @dev getReserveNormalizedIncome returns a uint256, so we know that the return value here is
/// always positive even though we are converting to a signed int
function _getReserveNormalizedIncome(address underlyingAsset) private view returns (int256) {
return
SafeInt256.toInt(
LibStorage.getLendingPool().lendingPool.getReserveNormalizedIncome(underlyingAsset)
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./GenericToken.sol";
import "../../../../interfaces/compound/CErc20Interface.sol";
import "../../../../interfaces/compound/CEtherInterface.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../global/Types.sol";
library CompoundHandler {
using SafeMath for uint256;
// Return code for cTokens that represents no error
uint256 internal constant COMPOUND_RETURN_CODE_NO_ERROR = 0;
function mintCETH(Token memory token) internal {
// Reverts on error
CEtherInterface(token.tokenAddress).mint{value: msg.value}();
}
function mint(Token memory token, uint256 underlyingAmountExternal) internal returns (int256) {
uint256 success = CErc20Interface(token.tokenAddress).mint(underlyingAmountExternal);
require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Mint");
}
function redeemCETH(
Token memory assetToken,
address account,
uint256 assetAmountExternal
) internal returns (uint256 underlyingAmountExternal) {
// Although the contract should never end with any ETH or underlying token balances, we still do this
// starting and ending check in the case that tokens are accidentally sent to the contract address. They
// will not be sent to some lucky address in a windfall.
uint256 startingBalance = address(this).balance;
uint256 success = CErc20Interface(assetToken.tokenAddress).redeem(assetAmountExternal);
require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Redeem");
uint256 endingBalance = address(this).balance;
underlyingAmountExternal = endingBalance.sub(startingBalance);
// Withdraws the underlying amount out to the destination account
GenericToken.transferNativeTokenOut(account, underlyingAmountExternal);
}
function redeem(
Token memory assetToken,
Token memory underlyingToken,
address account,
uint256 assetAmountExternal
) internal returns (uint256 underlyingAmountExternal) {
// Although the contract should never end with any ETH or underlying token balances, we still do this
// starting and ending check in the case that tokens are accidentally sent to the contract address. They
// will not be sent to some lucky address in a windfall.
uint256 startingBalance = GenericToken.checkBalanceViaSelector(underlyingToken.tokenAddress, address(this), GenericToken.defaultBalanceOfSelector);
uint256 success = CErc20Interface(assetToken.tokenAddress).redeem(assetAmountExternal);
require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Redeem");
uint256 endingBalance = GenericToken.checkBalanceViaSelector(underlyingToken.tokenAddress, address(this), GenericToken.defaultBalanceOfSelector);
underlyingAmountExternal = endingBalance.sub(startingBalance);
// Withdraws the underlying amount out to the destination account
GenericToken.safeTransferOut(underlyingToken.tokenAddress, account, underlyingAmountExternal);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
import "../../../../interfaces/IEIP20NonStandard.sol";
library GenericToken {
bytes4 internal constant defaultBalanceOfSelector = IEIP20NonStandard.balanceOf.selector;
/**
* @dev Manually checks the balance of an account using the method selector. Reduces bytecode size and allows
* for overriding the balanceOf selector to use scaledBalanceOf for aTokens
*/
function checkBalanceViaSelector(
address token,
address account,
bytes4 balanceOfSelector
) internal returns (uint256 balance) {
(bool success, bytes memory returnData) = token.staticcall(abi.encodeWithSelector(balanceOfSelector, account));
require(success);
(balance) = abi.decode(returnData, (uint256));
}
function transferNativeTokenOut(
address account,
uint256 amount
) internal {
// This does not work with contracts, but is reentrancy safe. If contracts want to withdraw underlying
// ETH they will have to withdraw the cETH token and then redeem it manually.
payable(account).transfer(amount);
}
function safeTransferOut(
address token,
address account,
uint256 amount
) internal {
IEIP20NonStandard(token).transfer(account, amount);
checkReturnCode();
}
function safeTransferIn(
address token,
address account,
uint256 amount
) internal {
IEIP20NonStandard(token).transferFrom(account, address(this), amount);
checkReturnCode();
}
function checkReturnCode() internal pure {
bool success;
uint256[1] memory result;
assembly {
switch returndatasize()
case 0 {
// This is a non-standard ERC-20
success := 1 // set success to true
}
case 32 {
// This is a compliant ERC-20
returndatacopy(result, 0, 32)
success := mload(result) // Set `success = returndata` of external call
}
default {
// This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "ERC20");
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IAToken {
/**
* @dev Returns the scaled balance of the user. The scaled balance is the sum of all the
* updated stored balance divided by the reserve's liquidity index at the moment of the update
* @param user The user whose balance is calculated
* @return The scaled balance of the user
**/
function scaledBalanceOf(address user) external view returns (uint256);
function UNDERLYING_ASSET_ADDRESS() external view returns (address);
function symbol() external view returns (string memory);
}
interface IScaledBalanceToken {
/**
* @dev Returns the scaled balance of the user. The scaled balance is the sum of all the
* updated stored balance divided by the reserve's liquidity index at the moment of the update
* @param user The user whose balance is calculated
* @return The scaled balance of the user
**/
function scaledBalanceOf(address user) external view returns (uint256);
/**
* @dev Returns the scaled balance of the user and the scaled total supply.
* @param user The address of the user
* @return The scaled balance of the user
* @return The scaled balance and the scaled total supply
**/
function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256);
/**
* @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index)
* @return The scaled total supply
**/
function scaledTotalSupply() external view returns (uint256);
}
interface IATokenFull is IScaledBalanceToken, IERC20 {
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.7.0;
import "./CTokenInterface.sol";
interface CErc20Interface {
/*** User Interface ***/
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.7.0;
interface CEtherInterface {
function mint() external payable;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface IEIP20NonStandard {
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transferFrom(address src, address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `approve` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved
*/
function approve(address spender, uint256 amount) external;
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return remaining The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.7.0;
interface CTokenInterface {
/*** User Interface ***/
function underlying() external view returns (address);
function transfer(address dst, uint amount) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function borrowBalanceStored(address account) external view returns (uint);
function exchangeRateCurrent() external returns (uint);
function exchangeRateStored() external view returns (uint);
function getCash() external view returns (uint);
function accrueInterest() external returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../global/Types.sol";
import "../global/Constants.sol";
/// @notice Helper methods for bitmaps, they are big-endian and 1-indexed.
library Bitmap {
/// @notice Set a bit on or off in a bitmap, index is 1-indexed
function setBit(
bytes32 bitmap,
uint256 index,
bool setOn
) internal pure returns (bytes32) {
require(index >= 1 && index <= 256); // dev: set bit index bounds
if (setOn) {
return bitmap | (Constants.MSB >> (index - 1));
} else {
return bitmap & ~(Constants.MSB >> (index - 1));
}
}
/// @notice Check if a bit is set
function isBitSet(bytes32 bitmap, uint256 index) internal pure returns (bool) {
require(index >= 1 && index <= 256); // dev: set bit index bounds
return ((bitmap << (index - 1)) & Constants.MSB) == Constants.MSB;
}
/// @notice Count the total bits set
function totalBitsSet(bytes32 bitmap) internal pure returns (uint256) {
uint256 x = uint256(bitmap);
x = (x & 0x5555555555555555555555555555555555555555555555555555555555555555) + (x >> 1 & 0x5555555555555555555555555555555555555555555555555555555555555555);
x = (x & 0x3333333333333333333333333333333333333333333333333333333333333333) + (x >> 2 & 0x3333333333333333333333333333333333333333333333333333333333333333);
x = (x & 0x0707070707070707070707070707070707070707070707070707070707070707) + (x >> 4);
x = (x & 0x000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F) + (x >> 8 & 0x000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F);
x = x + (x >> 16);
x = x + (x >> 32);
x = x + (x >> 64);
return (x & 0xFF) + (x >> 128 & 0xFF);
}
// Does a binary search over x to get the position of the most significant bit
function getMSB(uint256 x) internal pure returns (uint256 msb) {
// If x == 0 then there is no MSB and this method will return zero. That would
// be the same as the return value when x == 1 (MSB is zero indexed), so instead
// we have this require here to ensure that the values don't get mixed up.
require(x != 0); // dev: get msb zero value
if (x >= 0x100000000000000000000000000000000) {
x >>= 128;
msb += 128;
}
if (x >= 0x10000000000000000) {
x >>= 64;
msb += 64;
}
if (x >= 0x100000000) {
x >>= 32;
msb += 32;
}
if (x >= 0x10000) {
x >>= 16;
msb += 16;
}
if (x >= 0x100) {
x >>= 8;
msb += 8;
}
if (x >= 0x10) {
x >>= 4;
msb += 4;
}
if (x >= 0x4) {
x >>= 2;
msb += 2;
}
if (x >= 0x2) msb += 1; // No need to shift xc anymore
}
/// @dev getMSB returns a zero indexed bit number where zero is the first bit counting
/// from the right (little endian). Asset Bitmaps are counted from the left (big endian)
/// and one indexed.
function getNextBitNum(bytes32 bitmap) internal pure returns (uint256 bitNum) {
// Short circuit the search if bitmap is all zeros
if (bitmap == 0x00) return 0;
return 255 - getMSB(uint256(bitmap)) + 1;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../balances/TokenHandler.sol";
import "../../math/SafeInt256.sol";
import "../../../interfaces/chainlink/AggregatorV2V3Interface.sol";
library ExchangeRate {
using SafeInt256 for int256;
/// @notice Converts a balance to ETH from a base currency. Buffers or haircuts are
/// always applied in this method.
/// @param er exchange rate object from base to ETH
/// @return the converted balance denominated in ETH with Constants.INTERNAL_TOKEN_PRECISION
function convertToETH(ETHRate memory er, int256 balance) internal pure returns (int256) {
int256 multiplier = balance > 0 ? er.haircut : er.buffer;
// We are converting internal balances here so we know they have INTERNAL_TOKEN_PRECISION decimals
// internalDecimals * rateDecimals * multiplier / (rateDecimals * multiplierDecimals)
// Therefore the result is in ethDecimals
int256 result =
balance.mul(er.rate).mul(multiplier).div(Constants.PERCENTAGE_DECIMALS).div(
er.rateDecimals
);
return result;
}
/// @notice Converts the balance denominated in ETH to the equivalent value in a base currency.
/// Buffers and haircuts ARE NOT applied in this method.
/// @param er exchange rate object from base to ETH
/// @param balance amount (denominated in ETH) to convert
function convertETHTo(ETHRate memory er, int256 balance) internal pure returns (int256) {
// We are converting internal balances here so we know they have INTERNAL_TOKEN_PRECISION decimals
// internalDecimals * rateDecimals / rateDecimals
int256 result = balance.mul(er.rateDecimals).div(er.rate);
return result;
}
/// @notice Calculates the exchange rate between two currencies via ETH. Returns the rate denominated in
/// base exchange rate decimals: (baseRateDecimals * quoteRateDecimals) / quoteRateDecimals
/// @param baseER base exchange rate struct
/// @param quoteER quote exchange rate struct
function exchangeRate(ETHRate memory baseER, ETHRate memory quoteER)
internal
pure
returns (int256)
{
return baseER.rate.mul(quoteER.rateDecimals).div(quoteER.rate);
}
/// @notice Returns an ETHRate object used to calculate free collateral
function buildExchangeRate(uint256 currencyId) internal view returns (ETHRate memory) {
mapping(uint256 => ETHRateStorage) storage store = LibStorage.getExchangeRateStorage();
ETHRateStorage storage ethStorage = store[currencyId];
int256 rateDecimals;
int256 rate;
if (currencyId == Constants.ETH_CURRENCY_ID) {
// ETH rates will just be 1e18, but will still have buffers, haircuts,
// and liquidation discounts
rateDecimals = Constants.ETH_DECIMALS;
rate = Constants.ETH_DECIMALS;
} else {
// prettier-ignore
(
/* roundId */,
rate,
/* uint256 startedAt */,
/* updatedAt */,
/* answeredInRound */
) = ethStorage.rateOracle.latestRoundData();
require(rate > 0, "Invalid rate");
// No overflow, restricted on storage
rateDecimals = int256(10**ethStorage.rateDecimalPlaces);
if (ethStorage.mustInvert) {
rate = rateDecimals.mul(rateDecimals).div(rate);
}
}
return
ETHRate({
rateDecimals: rateDecimals,
rate: rate,
buffer: ethStorage.buffer,
haircut: ethStorage.haircut,
liquidationDiscount: ethStorage.liquidationDiscount
});
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./nTokenHandler.sol";
import "../portfolio/BitmapAssetsHandler.sol";
import "../../math/SafeInt256.sol";
import "../../math/Bitmap.sol";
library nTokenCalculations {
using Bitmap for bytes32;
using SafeInt256 for int256;
using AssetRate for AssetRateParameters;
using CashGroup for CashGroupParameters;
/// @notice Returns the nToken present value denominated in asset terms.
function getNTokenAssetPV(nTokenPortfolio memory nToken, uint256 blockTime)
internal
view
returns (int256)
{
int256 totalAssetPV;
int256 totalUnderlyingPV;
{
uint256 nextSettleTime = nTokenHandler.getNextSettleTime(nToken);
// If the first asset maturity has passed (the 3 month), this means that all the LTs must
// be settled except the 6 month (which is now the 3 month). We don't settle LTs except in
// initialize markets so we calculate the cash value of the portfolio here.
if (nextSettleTime <= blockTime) {
// NOTE: this condition should only be present for a very short amount of time, which is the window between
// when the markets are no longer tradable at quarter end and when the new markets have been initialized.
// We time travel back to one second before maturity to value the liquidity tokens. Although this value is
// not strictly correct the different should be quite slight. We do this to ensure that free collateral checks
// for withdraws and liquidations can still be processed. If this condition persists for a long period of time then
// the entire protocol will have serious problems as markets will not be tradable.
blockTime = nextSettleTime - 1;
}
}
// This is the total value in liquid assets
(int256 totalAssetValueInMarkets, /* int256[] memory netfCash */) = getNTokenMarketValue(nToken, blockTime);
// Then get the total value in any idiosyncratic fCash residuals (if they exist)
bytes32 ifCashBits = getNTokenifCashBits(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.lastInitializedTime,
blockTime,
nToken.cashGroup.maxMarketIndex
);
int256 ifCashResidualUnderlyingPV = 0;
if (ifCashBits != 0) {
// Non idiosyncratic residuals have already been accounted for
(ifCashResidualUnderlyingPV, /* hasDebt */) = BitmapAssetsHandler.getNetPresentValueFromBitmap(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.lastInitializedTime,
blockTime,
nToken.cashGroup,
false, // nToken present value calculation does not use risk adjusted values
ifCashBits
);
}
// Return the total present value denominated in asset terms
return totalAssetValueInMarkets
.add(nToken.cashGroup.assetRate.convertFromUnderlying(ifCashResidualUnderlyingPV))
.add(nToken.cashBalance);
}
/**
* @notice Handles the case when liquidity tokens should be withdrawn in proportion to their amounts
* in the market. This will be the case when there is no idiosyncratic fCash residuals in the nToken
* portfolio.
* @param nToken portfolio object for nToken
* @param nTokensToRedeem amount of nTokens to redeem
* @param tokensToWithdraw array of liquidity tokens to withdraw from each market, proportional to
* the account's share of the total supply
* @param netfCash an empty array to hold net fCash values calculated later when the tokens are actually
* withdrawn from markets
*/
function _getProportionalLiquidityTokens(
nTokenPortfolio memory nToken,
int256 nTokensToRedeem
) private pure returns (int256[] memory tokensToWithdraw, int256[] memory netfCash) {
uint256 numMarkets = nToken.portfolioState.storedAssets.length;
tokensToWithdraw = new int256[](numMarkets);
netfCash = new int256[](numMarkets);
for (uint256 i = 0; i < numMarkets; i++) {
int256 totalTokens = nToken.portfolioState.storedAssets[i].notional;
tokensToWithdraw[i] = totalTokens.mul(nTokensToRedeem).div(nToken.totalSupply);
}
}
/**
* @notice Returns the number of liquidity tokens to withdraw from each market if the nToken
* has idiosyncratic residuals during nToken redeem. In this case the redeemer will take
* their cash from the rest of the fCash markets, redeeming around the nToken.
* @param nToken portfolio object for nToken
* @param nTokensToRedeem amount of nTokens to redeem
* @param blockTime block time
* @param ifCashBits the bits in the bitmap that represent ifCash assets
* @return tokensToWithdraw array of tokens to withdraw from each corresponding market
* @return netfCash array of netfCash amounts to go back to the account
*/
function getLiquidityTokenWithdraw(
nTokenPortfolio memory nToken,
int256 nTokensToRedeem,
uint256 blockTime,
bytes32 ifCashBits
) internal view returns (int256[] memory, int256[] memory) {
// If there are no ifCash bits set then this will just return the proportion of all liquidity tokens
if (ifCashBits == 0) return _getProportionalLiquidityTokens(nToken, nTokensToRedeem);
(
int256 totalAssetValueInMarkets,
int256[] memory netfCash
) = getNTokenMarketValue(nToken, blockTime);
int256[] memory tokensToWithdraw = new int256[](netfCash.length);
// NOTE: this total portfolio asset value does not include any cash balance the nToken may hold.
// The redeemer will always get a proportional share of this cash balance and therefore we don't
// need to account for it here when we calculate the share of liquidity tokens to withdraw. We are
// only concerned with the nToken's portfolio assets in this method.
int256 totalPortfolioAssetValue;
{
// Returns the risk adjusted net present value for the idiosyncratic residuals
(int256 underlyingPV, /* hasDebt */) = BitmapAssetsHandler.getNetPresentValueFromBitmap(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.lastInitializedTime,
blockTime,
nToken.cashGroup,
true, // use risk adjusted here to assess a penalty for withdrawing around the residual
ifCashBits
);
// NOTE: we do not include cash balance here because the account will always take their share
// of the cash balance regardless of the residuals
totalPortfolioAssetValue = totalAssetValueInMarkets.add(
nToken.cashGroup.assetRate.convertFromUnderlying(underlyingPV)
);
}
// Loops through each liquidity token and calculates how much the redeemer can withdraw to get
// the requisite amount of present value after adjusting for the ifCash residual value that is
// not accessible via redemption.
for (uint256 i = 0; i < tokensToWithdraw.length; i++) {
int256 totalTokens = nToken.portfolioState.storedAssets[i].notional;
// Redeemer's baseline share of the liquidity tokens based on total supply:
// redeemerShare = totalTokens * nTokensToRedeem / totalSupply
// Scalar factor to account for residual value (need to inflate the tokens to withdraw
// proportional to the value locked up in ifCash residuals):
// scaleFactor = totalPortfolioAssetValue / totalAssetValueInMarkets
// Final math equals:
// tokensToWithdraw = redeemerShare * scalarFactor
// tokensToWithdraw = (totalTokens * nTokensToRedeem * totalPortfolioAssetValue)
// / (totalAssetValueInMarkets * totalSupply)
tokensToWithdraw[i] = totalTokens
.mul(nTokensToRedeem)
.mul(totalPortfolioAssetValue);
tokensToWithdraw[i] = tokensToWithdraw[i]
.div(totalAssetValueInMarkets)
.div(nToken.totalSupply);
// This is the share of net fcash that will be credited back to the account
netfCash[i] = netfCash[i].mul(tokensToWithdraw[i]).div(totalTokens);
}
return (tokensToWithdraw, netfCash);
}
/// @notice Returns the value of all the liquid assets in an nToken portfolio which are defined by
/// the liquidity tokens held in each market and their corresponding fCash positions. The formula
/// can be described as:
/// totalAssetValue = sum_per_liquidity_token(cashClaim + presentValue(netfCash))
/// where netfCash = fCashClaim + fCash
/// and fCash refers the the fCash position at the corresponding maturity
function getNTokenMarketValue(nTokenPortfolio memory nToken, uint256 blockTime)
internal
view
returns (int256 totalAssetValue, int256[] memory netfCash)
{
uint256 numMarkets = nToken.portfolioState.storedAssets.length;
netfCash = new int256[](numMarkets);
MarketParameters memory market;
for (uint256 i = 0; i < numMarkets; i++) {
// Load the corresponding market into memory
nToken.cashGroup.loadMarket(market, i + 1, true, blockTime);
PortfolioAsset memory liquidityToken = nToken.portfolioState.storedAssets[i];
uint256 maturity = liquidityToken.maturity;
// Get the fCash claims and fCash assets. We do not use haircut versions here because
// nTokenRedeem does not require it and getNTokenPV does not use it (a haircut is applied
// at the end of the calculation to the entire PV instead).
(int256 assetCashClaim, int256 fCashClaim) = AssetHandler.getCashClaims(liquidityToken, market);
// fCash is denominated in underlying
netfCash[i] = fCashClaim.add(
BitmapAssetsHandler.getifCashNotional(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
maturity
)
);
// This calculates for a single liquidity token:
// assetCashClaim + convertToAssetCash(pv(netfCash))
int256 netAssetValueInMarket = assetCashClaim.add(
nToken.cashGroup.assetRate.convertFromUnderlying(
AssetHandler.getPresentfCashValue(
netfCash[i],
maturity,
blockTime,
// No need to call cash group for oracle rate, it is up to date here
// and we are assured to be referring to this market.
market.oracleRate
)
)
);
// Calculate the running total
totalAssetValue = totalAssetValue.add(netAssetValueInMarket);
}
}
/// @notice Returns just the bits in a bitmap that are idiosyncratic
function getNTokenifCashBits(
address tokenAddress,
uint256 currencyId,
uint256 lastInitializedTime,
uint256 blockTime,
uint256 maxMarketIndex
) internal view returns (bytes32) {
// If max market index is less than or equal to 2, there are never ifCash assets by construction
if (maxMarketIndex <= 2) return bytes32(0);
bytes32 assetsBitmap = BitmapAssetsHandler.getAssetsBitmap(tokenAddress, currencyId);
// Handles the case when there are no assets at the first initialization
if (assetsBitmap == 0) return assetsBitmap;
uint256 tRef = DateTime.getReferenceTime(blockTime);
if (tRef == lastInitializedTime) {
// This is a more efficient way to turn off ifCash assets in the common case when the market is
// initialized immediately
return assetsBitmap & ~(Constants.ACTIVE_MARKETS_MASK);
} else {
// In this branch, initialize markets has occurred past the time above. It would occur in these
// two scenarios (both should be exceedingly rare):
// 1. initializing a cash group with 3+ markets for the first time (not beginning on the tRef)
// 2. somehow initialize markets has been delayed for more than 24 hours
for (uint i = 1; i <= maxMarketIndex; i++) {
// In this loop we get the maturity of each active market and turn off the corresponding bit
// one by one. It is less efficient than the option above.
uint256 maturity = tRef + DateTime.getTradedMarket(i);
(uint256 bitNum, /* */) = DateTime.getBitNumFromMaturity(lastInitializedTime, maturity);
assetsBitmap = assetsBitmap.setBit(bitNum, false);
}
return assetsBitmap;
}
}
}
|
Sets the account context of a given account
|
function setAccountContext(AccountContext memory accountContext, address account) internal {
mapping(address => AccountContext) storage store = LibStorage.getAccountStorage();
store[account] = accountContext;
emit AccountContextUpdate(account);
}
| 12,187
|
/*
"SPDX-License-Identifier: UNLICENSED"
ElonMoon.finance
*/
pragma solidity ^0.6.12;
/*
* @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;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev 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;
}
}
/**
* @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);
}
}
}
}
/**
* @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");
}
}
}
/**
* @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 {
/**
* @dev So here we seperate the rights of the classic ownership into 'owner' and 'minter'
* this way the developer/owner stays the 'owner' and can make changes like adding a pool
* at any time but cannot mint anymore as soon as the 'minter' gets changes (to the chef contract)
*/
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;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an minter) that can be granted exclusive access to
* specific functions.
*
* By default, the minter account will be the one that deploys the contract. This
* can later be changed with {transferMintership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyMinter`, which can be applied to your functions to restrict their use to
* the minter.
*/
contract Mintable is Context {
/**
* @dev So here we seperate the rights of the classic ownership into 'owner' and 'minter'
* this way the developer/owner stays the 'owner' and can make changes like adding a pool
* at any time but cannot mint anymore as soon as the 'minter' gets changes (to the chef contract)
*/
address private _minter;
event MintershipTransferred(address indexed previousMinter, address indexed newMinter);
/**
* @dev Initializes the contract setting the deployer as the initial minter.
*/
constructor () internal {
address msgSender = _msgSender();
_minter = msgSender;
emit MintershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current minter.
*/
function minter() public view returns (address) {
return _minter;
}
/**
* @dev Throws if called by any account other than the minter.
*/
modifier onlyMinter() {
require(_minter == _msgSender(), "Mintable: caller is not the minter");
_;
}
/**
* @dev Transfers mintership of the contract to a new account (`newMinter`).
* Can only be called by the current minter.
*/
function transferMintership(address newMinter) public virtual onlyMinter {
require(newMinter != address(0), "Mintable: new minter is the zero address");
emit MintershipTransferred(_minter, newMinter);
_minter = newMinter;
}
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
uint256 private _burnedSupply;
uint256 private _burnRate;
string private _name;
string private _symbol;
uint256 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, uint256 decimals, uint256 burnrate, uint256 initSupply) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
_burnRate = burnrate;
_totalSupply = 0;
_mint(msg.sender, initSupply*(10**_decimals));
_burnedSupply = 0;
}
/**
* @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 (uint256) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev Returns the amount of burned tokens.
*/
function burnedSupply() public view returns (uint256) {
return _burnedSupply;
}
/**
* @dev Returns the burnrate.
*/
function burnRate() public view returns (uint256) {
return _burnRate;
}
/**
* @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-transfer}.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function burn(uint256 amount) public virtual returns (bool) {
_burn(_msgSender(), 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");
uint256 amount_burn = amount.mul(_burnRate).div(100);
uint256 amount_send = amount.sub(amount_burn);
require(amount == amount_send + amount_burn, "Burn value invalid");
_burn(sender, amount_burn);
amount = amount_send;
_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.
*
* HINT: This function is 'internal' and therefore can only be called from another
* function inside this contract!
*/
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);
_burnedSupply = _burnedSupply.add(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 {burnRate} to a value other than the initial one.
*/
function _setupBurnrate(uint8 burnrate_) internal virtual {
_burnRate = burnrate_;
}
/**
* @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 { }
}
// ERC20 (name, symbol, decimals, burnrate, initSupply)
contract Token is ERC20("ElonMoon.Finance", "ELONMOON", 18, 0, 36000000), Ownable, Mintable {
function mint(address _to, uint256 _amount) public onlyMinter {
_mint(_to, _amount);
}
function setupBurnrate(uint8 burnrate_) public onlyOwner {
_setupBurnrate(burnrate_);
}
}
|
Moves tokens `amount` from `sender` to `recipient`. This is internal function is equivalent to {transfer}, and can be used to e.g. implement automatic token fees, slashing mechanisms, etc. Emits a {Transfer} event. Requirements: - `sender` cannot be the zero address. - `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`./
|
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
uint256 amount_burn = amount.mul(_burnRate).div(100);
uint256 amount_send = amount.sub(amount_burn);
require(amount == amount_send + amount_burn, "Burn value invalid");
_burn(sender, amount_burn);
amount = amount_send;
_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);
}
| 254,054
|
./partial_match/3/0xd95209cBb12652C10e0B49a0CdfD8bDDc27848E9/sources/testcontract.sol
|
Uniswap srcToken => dstToken Approve Uniswap to spend tokens Setup transfer uint[] memory minOuts = uniswap.getAmountsOut(amount, path); As you can see I changed the address to msg.sender and added time
|
function runTokenUniswapTransfer(uint amount, uint minOuts, address srcTokenAddress, address dstTokenAddress) onlyOwner() external {
IERC20 srcToken = IERC20(srcTokenAddress);
IERC20 dstToken = IERC20(dstTokenAddress);
IUniswapV2Router01 uniswap = IUniswapV2Router01(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
srcToken.approve(address(uniswapAddress), amount);
srcToken.transferFrom(msg.sender, address(this), amount);
address[] memory path = new address[](2);
path[0] = address(srcToken);
path[1] = address(dstToken);
uniswap.swapExactTokensForTokens(amount, minOuts, path, msg.sender, block.timestamp);
}
| 5,062,490
|
pragma solidity ^0.6.0;
import "../utils/GasBurner.sol";
import "../interfaces/IAToken.sol";
import "../interfaces/ILendingPool.sol";
import "../interfaces/ILendingPoolAddressesProvider.sol";
import "../utils/SafeERC20.sol";
/// @title Basic compound interactions through the DSProxy
contract AaveBasicProxy is GasBurner {
using SafeERC20 for ERC20;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8;
uint16 public constant AAVE_REFERRAL_CODE = 64;
/// @notice User deposits tokens to the Aave protocol
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @param _tokenAddr The address of the token to be deposited
/// @param _amount Amount of tokens to be deposited
function deposit(address _tokenAddr, uint256 _amount) public burnGas(5) payable {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
uint ethValue = _amount;
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
approveToken(_tokenAddr, lendingPoolCore);
ethValue = 0;
}
ILendingPool(lendingPool).deposit{value: ethValue}(_tokenAddr, _amount, AAVE_REFERRAL_CODE);
setUserUseReserveAsCollateralIfNeeded(_tokenAddr);
}
/// @notice User withdraws tokens from the Aave protocol
/// @param _tokenAddr The address of the token to be withdrawn
/// @param _aTokenAddr ATokens to be withdrawn
/// @param _amount Amount of tokens to be withdrawn
/// @param _wholeAmount If true we will take the whole amount on chain
function withdraw(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeAmount) public burnGas(8) {
uint256 amount = _wholeAmount ? ERC20(_aTokenAddr).balanceOf(address(this)) : _amount;
IAToken(_aTokenAddr).redeem(amount);
withdrawTokens(_tokenAddr);
}
/// @notice User borrows tokens to the Aave protocol
/// @param _tokenAddr The address of the token to be borrowed
/// @param _amount Amount of tokens to be borrowed
/// @param _type Send 1 for stable rate and 2 for variable rate
function borrow(address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) {
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
ILendingPool(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE);
withdrawTokens(_tokenAddr);
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the Aave protocol
/// @param _tokenAddr The address of the token to be paybacked
/// @param _aTokenAddr ATokens to be paybacked
/// @param _amount Amount of tokens to be payed back
/// @param _wholeDebt If true the _amount will be set to the whole amount of the debt
function payback(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt) public burnGas(3) payable {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
uint256 amount = _amount;
(,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this));
if (_wholeDebt) {
amount = borrowAmount + originationFee;
}
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount);
approveToken(_tokenAddr, lendingPoolCore);
}
ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, payable(address(this)));
withdrawTokens(_tokenAddr);
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the Aave protocol
/// @param _tokenAddr The address of the token to be paybacked
/// @param _aTokenAddr ATokens to be paybacked
/// @param _amount Amount of tokens to be payed back
/// @param _wholeDebt If true the _amount will be set to the whole amount of the debt
function paybackOnBehalf(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt, address payable _onBehalf) public burnGas(3) payable {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
uint256 amount = _amount;
(,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, _onBehalf);
if (_wholeDebt) {
amount = borrowAmount + originationFee;
}
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount);
approveToken(_tokenAddr, lendingPoolCore);
}
ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, _onBehalf);
withdrawTokens(_tokenAddr);
}
/// @notice Helper method to withdraw tokens from the DSProxy
/// @param _tokenAddr Address of the token to be withdrawn
function withdrawTokens(address _tokenAddr) public {
uint256 amount = _tokenAddr == ETH_ADDR ? address(this).balance : ERC20(_tokenAddr).balanceOf(address(this));
if (amount > 0) {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, amount);
} else {
msg.sender.transfer(amount);
}
}
}
/// @notice Approves token contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _caller Address which will gain the approval
function approveToken(address _tokenAddr, address _caller) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_caller, uint256(-1));
}
}
function setUserUseReserveAsCollateralIfNeeded(address _tokenAddr) public {
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
(,,,,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this));
if (!collateralEnabled) {
ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true);
}
}
function setUserUseReserveAsCollateral(address _tokenAddr, bool _true) public {
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true);
}
function swapBorrowRateMode(address _reserve) public {
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
ILendingPool(lendingPool).swapBorrowRateMode(_reserve);
}
}
pragma solidity ^0.6.0;
import "../interfaces/GasTokenInterface.sol";
contract GasBurner {
// solhint-disable-next-line const-name-snakecase
GasTokenInterface public constant gasToken = GasTokenInterface(0x0000000000b3F879cb30FE243b4Dfee438691c04);
modifier burnGas(uint _amount) {
if (gasToken.balanceOf(address(this)) >= _amount) {
gasToken.free(_amount);
}
_;
}
}
pragma solidity ^0.6.0;
abstract contract IAToken {
function redeem(uint256 _amount) external virtual;
function balanceOf(address _owner) external virtual view returns (uint256 balance);
}
pragma solidity ^0.6.0;
abstract contract ILendingPool {
function flashLoan( address payable _receiver, address _reserve, uint _amount, bytes calldata _params) external virtual;
function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external virtual payable;
function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral) external virtual;
function borrow(address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode) external virtual;
function repay( address _reserve, uint256 _amount, address payable _onBehalfOf) external virtual payable;
function swapBorrowRateMode(address _reserve) external virtual;
function getReserves() external virtual view returns(address[] memory);
/// @param _reserve underlying token address
function getReserveData(address _reserve)
external virtual
view
returns (
uint256 totalLiquidity, // reserve total liquidity
uint256 availableLiquidity, // reserve available liquidity for borrowing
uint256 totalBorrowsStable, // total amount of outstanding borrows at Stable rate
uint256 totalBorrowsVariable, // total amount of outstanding borrows at Variable rate
uint256 liquidityRate, // current deposit APY of the reserve for depositors, in Ray units.
uint256 variableBorrowRate, // current variable rate APY of the reserve pool, in Ray units.
uint256 stableBorrowRate, // current stable rate APY of the reserve pool, in Ray units.
uint256 averageStableBorrowRate, // current average stable borrow rate
uint256 utilizationRate, // expressed as total borrows/total liquidity.
uint256 liquidityIndex, // cumulative liquidity index
uint256 variableBorrowIndex, // cumulative variable borrow index
address aTokenAddress, // aTokens contract address for the specific _reserve
uint40 lastUpdateTimestamp // timestamp of the last update of reserve data
);
/// @param _user users address
function getUserAccountData(address _user)
external virtual
view
returns (
uint256 totalLiquidityETH, // user aggregated deposits across all the reserves. In Wei
uint256 totalCollateralETH, // user aggregated collateral across all the reserves. In Wei
uint256 totalBorrowsETH, // user aggregated outstanding borrows across all the reserves. In Wei
uint256 totalFeesETH, // user aggregated current outstanding fees in ETH. In Wei
uint256 availableBorrowsETH, // user available amount to borrow in ETH
uint256 currentLiquidationThreshold, // user current average liquidation threshold across all the collaterals deposited
uint256 ltv, // user average Loan-to-Value between all the collaterals
uint256 healthFactor // user current Health Factor
);
/// @param _reserve underlying token address
/// @param _user users address
function getUserReserveData(address _reserve, address _user)
external virtual
view
returns (
uint256 currentATokenBalance, // user current reserve aToken balance
uint256 currentBorrowBalance, // user current reserve outstanding borrow balance
uint256 principalBorrowBalance, // user balance of borrowed asset
uint256 borrowRateMode, // user borrow rate mode either Stable or Variable
uint256 borrowRate, // user current borrow rate APY
uint256 liquidityRate, // user current earn rate on _reserve
uint256 originationFee, // user outstanding loan origination fee
uint256 variableBorrowIndex, // user variable cumulative index
uint256 lastUpdateTimestamp, // Timestamp of the last data update
bool usageAsCollateralEnabled // Whether the user's current reserve is enabled as a collateral
);
function getReserveConfigurationData(address _reserve)
external virtual
view
returns (
uint256 ltv,
uint256 liquidationThreshold,
uint256 liquidationBonus,
address rateStrategyAddress,
bool usageAsCollateralEnabled,
bool borrowingEnabled,
bool stableBorrowRateEnabled,
bool isActive
);
// ------------------ LendingPoolCoreData ------------------------
function getReserveATokenAddress(address _reserve) public virtual view returns (address);
function getReserveConfiguration(address _reserve)
external virtual
view
returns (uint256, uint256, uint256, bool);
function getUserUnderlyingAssetBalance(address _reserve, address _user)
public virtual
view
returns (uint256);
function getReserveCurrentLiquidityRate(address _reserve)
public virtual
view
returns (uint256);
function getReserveCurrentVariableBorrowRate(address _reserve)
public virtual
view
returns (uint256);
function getReserveCurrentStableBorrowRate(address _reserve)
public virtual
view
returns (uint256);
function getReserveTotalLiquidity(address _reserve)
public virtual
view
returns (uint256);
function getReserveAvailableLiquidity(address _reserve)
public virtual
view
returns (uint256);
function getReserveTotalBorrowsVariable(address _reserve)
public virtual
view
returns (uint256);
function getReserveTotalBorrowsStable(address _reserve)
public virtual
view
returns (uint256);
// ---------------- LendingPoolDataProvider ---------------------
function calculateUserGlobalData(address _user)
public virtual
view
returns (
uint256 totalLiquidityBalanceETH,
uint256 totalCollateralBalanceETH,
uint256 totalBorrowBalanceETH,
uint256 totalFeesETH,
uint256 currentLtv,
uint256 currentLiquidationThreshold,
uint256 healthFactor,
bool healthFactorBelowThreshold
);
}
pragma solidity ^0.6.0;
/**
@title ILendingPoolAddressesProvider interface
@notice provides the interface to fetch the LendingPoolCore address
*/
abstract contract ILendingPoolAddressesProvider {
function getLendingPool() public virtual view returns (address);
function getLendingPoolCore() public virtual view returns (address payable);
function getLendingPoolConfigurator() public virtual view returns (address);
function getLendingPoolDataProvider() public virtual view returns (address);
function getLendingPoolParametersProvider() public virtual view returns (address);
function getTokenDistributor() public virtual view returns (address);
function getFeeProvider() public virtual view returns (address);
function getLendingPoolLiquidationManager() public virtual view returns (address);
function getLendingPoolManager() public virtual view returns (address);
function getPriceOracle() public virtual view returns (address);
function getLendingRateOracle() public virtual view returns (address);
}
pragma solidity ^0.6.0;
import "../interfaces/ERC20.sol";
import "./Address.sol";
import "./SafeMath.sol";
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(ERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(ERC20 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.
*/
function safeApprove(ERC20 token, address spender, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(ERC20 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(ERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function _callOptionalReturn(ERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
pragma solidity ^0.6.0;
import "./ERC20.sol";
abstract contract GasTokenInterface is ERC20 {
function free(uint256 value) public virtual returns (bool success);
function freeUpTo(uint256 value) public virtual returns (uint256 freed);
function freeFrom(address from, uint256 value) public virtual returns (bool success);
function freeFromUpTo(address from, uint256 value) public virtual returns (uint256 freed);
}
pragma solidity ^0.6.0;
interface ERC20 {
function totalSupply() external view returns (uint256 supply);
function balanceOf(address _owner) external view returns (uint256 balance);
function transfer(address _to, uint256 _value) external returns (bool success);
function transferFrom(address _from, address _to, uint256 _value)
external
returns (bool success);
function approve(address _spender, uint256 _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
function decimals() external view returns (uint256 digits);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
pragma solidity ^0.6.0;
library Address {
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
pragma solidity ^0.6.0;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.6.0;
import "../interfaces/DSProxyInterface.sol";
import "./SafeERC20.sol";
/// @title Pulls a specified amount of tokens from the EOA owner account to the proxy
contract PullTokensProxy {
using SafeERC20 for ERC20;
/// @notice Pulls a token from the proxyOwner -> proxy
/// @dev Proxy owner must first give approve to the proxy address
/// @param _tokenAddr Address of the ERC20 token
/// @param _amount Amount of tokens which will be transfered to the proxy
function pullTokens(address _tokenAddr, uint _amount) public {
address proxyOwner = DSProxyInterface(address(this)).owner();
ERC20(_tokenAddr).safeTransferFrom(proxyOwner, address(this), _amount);
}
}
pragma solidity ^0.6.0;
abstract contract DSProxyInterface {
/// Truffle wont compile if this isn't commented
// function execute(bytes memory _code, bytes memory _data)
// public virtual
// payable
// returns (address, bytes32);
function execute(address _target, bytes memory _data) public virtual payable returns (bytes32);
function setCache(address _cacheAddr) public virtual payable returns (bool);
function owner() public virtual returns (address);
}
pragma solidity ^0.6.0;
import "../auth/Auth.sol";
import "../interfaces/DSProxyInterface.sol";
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
contract DFSProxy is Auth {
string public constant NAME = "DFSProxy";
string public constant VERSION = "v0.1";
mapping(address => mapping(uint => bool)) public nonces;
// --- EIP712 niceties ---
bytes32 public DOMAIN_SEPARATOR;
bytes32 public constant PERMIT_TYPEHASH = keccak256("callProxy(address _user,address _proxy,address _contract,bytes _txData,uint256 _nonce)");
constructor(uint256 chainId_) public {
DOMAIN_SEPARATOR = keccak256(abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(NAME)),
keccak256(bytes(VERSION)),
chainId_,
address(this)
));
}
function callProxy(address _user, address _proxy, address _contract, bytes calldata _txData, uint256 _nonce,
uint8 _v, bytes32 _r, bytes32 _s) external payable onlyAuthorized
{
bytes32 digest =
keccak256(abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH,
_user,
_proxy,
_contract,
_txData,
_nonce))
));
// user must be proxy owner
require(DSProxyInterface(_proxy).owner() == _user);
require(_user == ecrecover(digest, _v, _r, _s), "DFSProxy/user-not-valid");
require(!nonces[_user][_nonce], "DFSProxy/invalid-nonce");
nonces[_user][_nonce] = true;
DSProxyInterface(_proxy).execute{value: msg.value}(_contract, _txData);
}
}
pragma solidity ^0.6.0;
import "./AdminAuth.sol";
contract Auth is AdminAuth {
bool public ALL_AUTHORIZED = false;
mapping(address => bool) public authorized;
modifier onlyAuthorized() {
require(ALL_AUTHORIZED || authorized[msg.sender]);
_;
}
constructor() public {
authorized[msg.sender] = true;
}
function setAuthorized(address _user, bool _approved) public onlyOwner {
authorized[_user] = _approved;
}
function setAllAuthorized(bool _authorized) public onlyOwner {
ALL_AUTHORIZED = _authorized;
}
}
pragma solidity ^0.6.0;
import "../utils/SafeERC20.sol";
contract AdminAuth {
using SafeERC20 for ERC20;
address public owner;
address public admin;
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
modifier onlyAdmin() {
require(admin == msg.sender);
_;
}
constructor() public {
owner = msg.sender;
admin = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9;
}
/// @notice Admin is set by owner first time, after that admin is super role and has permission to change owner
/// @param _admin Address of multisig that becomes admin
function setAdminByOwner(address _admin) public {
require(msg.sender == owner);
require(admin == address(0));
admin = _admin;
}
/// @notice Admin is able to set new admin
/// @param _admin Address of multisig that becomes new admin
function setAdminByAdmin(address _admin) public {
require(msg.sender == admin);
admin = _admin;
}
/// @notice Admin is able to change owner
/// @param _owner Address of new owner
function setOwnerByAdmin(address _owner) public {
require(msg.sender == admin);
owner = _owner;
}
/// @notice Destroy the contract
function kill() public onlyOwner {
selfdestruct(payable(owner));
}
/// @notice withdraw stuck funds
function withdrawStuckFunds(address _token, uint _amount) public onlyOwner {
if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
payable(owner).transfer(_amount);
} else {
ERC20(_token).safeTransfer(owner, _amount);
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../interfaces/ILendingPool.sol";
import "../interfaces/CTokenInterface.sol";
import "../interfaces/ILoanShifter.sol";
import "../interfaces/DSProxyInterface.sol";
import "../interfaces/Vat.sol";
import "../interfaces/Manager.sol";
import "../interfaces/IMCDSubscriptions.sol";
import "../interfaces/ICompoundSubscriptions.sol";
import "../auth/AdminAuth.sol";
import "../auth/ProxyPermission.sol";
import "../exchangeV3/DFSExchangeData.sol";
import "./ShifterRegistry.sol";
import "../utils/GasBurner.sol";
import "../loggers/DefisaverLogger.sol";
/// @title LoanShifterTaker Entry point for using the shifting operation
contract LoanShifterTaker is AdminAuth, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant MCD_SUB_ADDRESS = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a;
address public constant COMPOUND_SUB_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207;
address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
Manager public constant manager = Manager(MANAGER_ADDRESS);
ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e);
enum Protocols { MCD, COMPOUND }
enum SwapType { NO_SWAP, COLL_SWAP, DEBT_SWAP }
enum Unsub { NO_UNSUB, FIRST_UNSUB, SECOND_UNSUB, BOTH_UNSUB }
struct LoanShiftData {
Protocols fromProtocol;
Protocols toProtocol;
SwapType swapType;
Unsub unsub;
bool wholeDebt;
uint collAmount;
uint debtAmount;
address debtAddr1;
address debtAddr2;
address addrLoan1;
address addrLoan2;
uint id1;
uint id2;
}
/// @notice Main entry point, it will move or transform a loan
/// @dev Called through DSProxy
function moveLoan(
DFSExchangeData.ExchangeData memory _exchangeData,
LoanShiftData memory _loanShift
) public payable burnGas(20) {
if (_isSameTypeVaults(_loanShift)) {
_forkVault(_loanShift);
logEvent(_exchangeData, _loanShift);
return;
}
_callCloseAndOpen(_exchangeData, _loanShift);
}
//////////////////////// INTERNAL FUNCTIONS //////////////////////////
function _callCloseAndOpen(
DFSExchangeData.ExchangeData memory _exchangeData,
LoanShiftData memory _loanShift
) internal {
address protoAddr = shifterRegistry.getAddr(getNameByProtocol(uint8(_loanShift.fromProtocol)));
if (_loanShift.wholeDebt) {
_loanShift.debtAmount = ILoanShifter(protoAddr).getLoanAmount(_loanShift.id1, _loanShift.debtAddr1);
}
// encode data
bytes memory paramsData = abi.encode(_loanShift, _exchangeData, address(this));
address payable loanShifterReceiverAddr = payable(shifterRegistry.getAddr("LOAN_SHIFTER_RECEIVER"));
loanShifterReceiverAddr.transfer(address(this).balance);
// call FL
givePermission(loanShifterReceiverAddr);
lendingPool.flashLoan(loanShifterReceiverAddr,
getLoanAddr(_loanShift.debtAddr1, _loanShift.fromProtocol), _loanShift.debtAmount, paramsData);
removePermission(loanShifterReceiverAddr);
unsubFromAutomation(
_loanShift.unsub,
_loanShift.id1,
_loanShift.id2,
_loanShift.fromProtocol,
_loanShift.toProtocol
);
logEvent(_exchangeData, _loanShift);
}
function _forkVault(LoanShiftData memory _loanShift) internal {
// Create new Vault to move to
if (_loanShift.id2 == 0) {
_loanShift.id2 = manager.open(manager.ilks(_loanShift.id1), address(this));
}
if (_loanShift.wholeDebt) {
manager.shift(_loanShift.id1, _loanShift.id2);
}
}
function _isSameTypeVaults(LoanShiftData memory _loanShift) internal pure returns (bool) {
return _loanShift.fromProtocol == Protocols.MCD && _loanShift.toProtocol == Protocols.MCD
&& _loanShift.addrLoan1 == _loanShift.addrLoan2;
}
function getNameByProtocol(uint8 _proto) internal pure returns (string memory) {
if (_proto == 0) {
return "MCD_SHIFTER";
} else if (_proto == 1) {
return "COMP_SHIFTER";
}
}
function getLoanAddr(address _address, Protocols _fromProtocol) internal returns (address) {
if (_fromProtocol == Protocols.COMPOUND) {
return getUnderlyingAddr(_address);
} else if (_fromProtocol == Protocols.MCD) {
return DAI_ADDRESS;
} else {
return address(0);
}
}
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
function logEvent(
DFSExchangeData.ExchangeData memory _exchangeData,
LoanShiftData memory _loanShift
) internal {
address srcAddr = _exchangeData.srcAddr;
address destAddr = _exchangeData.destAddr;
uint collAmount = _exchangeData.srcAmount;
uint debtAmount = _exchangeData.destAmount;
if (_loanShift.swapType == SwapType.NO_SWAP) {
srcAddr = _loanShift.addrLoan1;
destAddr = _loanShift.debtAddr1;
collAmount = _loanShift.collAmount;
debtAmount = _loanShift.debtAmount;
}
DefisaverLogger(DEFISAVER_LOGGER)
.Log(address(this), msg.sender, "LoanShifter",
abi.encode(
_loanShift.fromProtocol,
_loanShift.toProtocol,
_loanShift.swapType,
srcAddr,
destAddr,
collAmount,
debtAmount
));
}
function unsubFromAutomation(Unsub _unsub, uint _cdp1, uint _cdp2, Protocols _from, Protocols _to) internal {
if (_unsub != Unsub.NO_UNSUB) {
if (_unsub == Unsub.FIRST_UNSUB || _unsub == Unsub.BOTH_UNSUB) {
unsubscribe(_cdp1, _from);
}
if (_unsub == Unsub.SECOND_UNSUB || _unsub == Unsub.BOTH_UNSUB) {
unsubscribe(_cdp2, _to);
}
}
}
function unsubscribe(uint _cdpId, Protocols _protocol) internal {
if (_cdpId != 0 && _protocol == Protocols.MCD) {
IMCDSubscriptions(MCD_SUB_ADDRESS).unsubscribe(_cdpId);
}
if (_protocol == Protocols.COMPOUND) {
ICompoundSubscriptions(COMPOUND_SUB_ADDRESS).unsubscribe();
}
}
}
pragma solidity ^0.6.0;
import "./ERC20.sol";
abstract contract CTokenInterface is ERC20 {
function mint(uint256 mintAmount) external virtual returns (uint256);
// function mint() external virtual payable;
function accrueInterest() public virtual returns (uint);
function redeem(uint256 redeemTokens) external virtual returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external virtual returns (uint256);
function borrow(uint256 borrowAmount) external virtual returns (uint256);
function borrowIndex() public view virtual returns (uint);
function borrowBalanceStored(address) public view virtual returns(uint);
function repayBorrow(uint256 repayAmount) external virtual returns (uint256);
function repayBorrow() external virtual payable;
function repayBorrowBehalf(address borrower, uint256 repayAmount) external virtual returns (uint256);
function repayBorrowBehalf(address borrower) external virtual payable;
function liquidateBorrow(address borrower, uint256 repayAmount, address cTokenCollateral)
external virtual
returns (uint256);
function liquidateBorrow(address borrower, address cTokenCollateral) external virtual payable;
function exchangeRateCurrent() external virtual returns (uint256);
function supplyRatePerBlock() external virtual returns (uint256);
function borrowRatePerBlock() external virtual returns (uint256);
function totalReserves() external virtual returns (uint256);
function reserveFactorMantissa() external virtual returns (uint256);
function borrowBalanceCurrent(address account) external virtual returns (uint256);
function totalBorrowsCurrent() external virtual returns (uint256);
function getCash() external virtual returns (uint256);
function balanceOfUnderlying(address owner) external virtual returns (uint256);
function underlying() external virtual returns (address);
function getAccountSnapshot(address account) external virtual view returns (uint, uint, uint, uint);
}
pragma solidity ^0.6.0;
abstract contract ILoanShifter {
function getLoanAmount(uint, address) public virtual returns (uint);
function getUnderlyingAsset(address _addr) public view virtual returns (address);
}
pragma solidity ^0.6.0;
abstract contract Vat {
struct Urn {
uint256 ink; // Locked Collateral [wad]
uint256 art; // Normalised Debt [wad]
}
struct Ilk {
uint256 Art; // Total Normalised Debt [wad]
uint256 rate; // Accumulated Rates [ray]
uint256 spot; // Price with Safety Margin [ray]
uint256 line; // Debt Ceiling [rad]
uint256 dust; // Urn Debt Floor [rad]
}
mapping (bytes32 => mapping (address => Urn )) public urns;
mapping (bytes32 => Ilk) public ilks;
mapping (bytes32 => mapping (address => uint)) public gem; // [wad]
function can(address, address) virtual public view returns (uint);
function dai(address) virtual public view returns (uint);
function frob(bytes32, address, address, address, int, int) virtual public;
function hope(address) virtual public;
function move(address, address, uint) virtual public;
function fork(bytes32, address, address, int, int) virtual public;
}
pragma solidity ^0.6.0;
abstract contract Manager {
function last(address) virtual public returns (uint);
function cdpCan(address, uint, address) virtual public view returns (uint);
function ilks(uint) virtual public view returns (bytes32);
function owns(uint) virtual public view returns (address);
function urns(uint) virtual public view returns (address);
function vat() virtual public view returns (address);
function open(bytes32, address) virtual public returns (uint);
function give(uint, address) virtual public;
function cdpAllow(uint, address, uint) virtual public;
function urnAllow(address, uint) virtual public;
function frob(uint, int, int) virtual public;
function flux(uint, address, uint) virtual public;
function move(uint, address, uint) virtual public;
function exit(address, uint, address, uint) virtual public;
function quit(uint, address) virtual public;
function enter(address, uint) virtual public;
function shift(uint, uint) virtual public;
}
pragma solidity ^0.6.0;
abstract contract IMCDSubscriptions {
function unsubscribe(uint256 _cdpId) external virtual ;
function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool);
}
pragma solidity ^0.6.0;
abstract contract ICompoundSubscriptions {
function unsubscribe() external virtual ;
}
pragma solidity ^0.6.0;
import "../DS/DSGuard.sol";
import "../DS/DSAuth.sol";
contract ProxyPermission {
address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7;
/// @notice Called in the context of DSProxy to authorize an address
/// @param _contractAddr Address which will be authorized
function givePermission(address _contractAddr) public {
address currAuthority = address(DSAuth(address(this)).authority());
DSGuard guard = DSGuard(currAuthority);
if (currAuthority == address(0)) {
guard = DSGuardFactory(FACTORY_ADDRESS).newGuard();
DSAuth(address(this)).setAuthority(DSAuthority(address(guard)));
}
guard.permit(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)")));
}
/// @notice Called in the context of DSProxy to remove authority of an address
/// @param _contractAddr Auth address which will be removed from authority list
function removePermission(address _contractAddr) public {
address currAuthority = address(DSAuth(address(this)).authority());
// if there is no authority, that means that contract doesn't have permission
if (currAuthority == address(0)) {
return;
}
DSGuard guard = DSGuard(currAuthority);
guard.forbid(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)")));
}
function proxyOwner() internal returns(address) {
return DSAuth(address(this)).owner();
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
contract DFSExchangeData {
// first is empty to keep the legacy order in place
enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX }
enum ActionType { SELL, BUY }
struct OffchainData {
address wrapper;
address exchangeAddr;
address allowanceTarget;
uint256 price;
uint256 protocolFee;
bytes callData;
}
struct ExchangeData {
address srcAddr;
address destAddr;
uint256 srcAmount;
uint256 destAmount;
uint256 minPrice;
uint256 dfsFeeDivider; // service fee divider
address user; // user to check special fee
address wrapper;
bytes wrapperData;
OffchainData offchainData;
}
function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) {
return abi.encode(_exData);
}
function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) {
_exData = abi.decode(_data, (ExchangeData));
}
}
pragma solidity ^0.6.0;
import "../auth/AdminAuth.sol";
contract ShifterRegistry is AdminAuth {
mapping (string => address) public contractAddresses;
bool public finalized;
function changeContractAddr(string memory _contractName, address _protoAddr) public onlyOwner {
require(!finalized);
contractAddresses[_contractName] = _protoAddr;
}
function lock() public onlyOwner {
finalized = true;
}
function getAddr(string memory _contractName) public view returns (address contractAddr) {
contractAddr = contractAddresses[_contractName];
require(contractAddr != address(0), "No contract address registred");
}
}
pragma solidity ^0.6.0;
contract DefisaverLogger {
event LogEvent(
address indexed contractAddress,
address indexed caller,
string indexed logName,
bytes data
);
// solhint-disable-next-line func-name-mixedcase
function Log(address _contract, address _caller, string memory _logName, bytes memory _data)
public
{
emit LogEvent(_contract, _caller, _logName, _data);
}
}
pragma solidity ^0.6.0;
abstract contract DSGuard {
function canCall(address src_, address dst_, bytes4 sig) public view virtual returns (bool);
function permit(bytes32 src, bytes32 dst, bytes32 sig) public virtual;
function forbid(bytes32 src, bytes32 dst, bytes32 sig) public virtual;
function permit(address src, address dst, bytes32 sig) public virtual;
function forbid(address src, address dst, bytes32 sig) public virtual;
}
abstract contract DSGuardFactory {
function newGuard() public virtual returns (DSGuard guard);
}
pragma solidity ^0.6.0;
import "./DSAuthority.sol";
contract DSAuthEvents {
event LogSetAuthority(address indexed authority);
event LogSetOwner(address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
constructor() public {
owner = msg.sender;
emit LogSetOwner(msg.sender);
}
function setOwner(address owner_) public auth {
owner = owner_;
emit LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_) public auth {
authority = authority_;
emit LogSetAuthority(address(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, address(this), sig);
}
}
}
pragma solidity ^0.6.0;
abstract contract DSAuthority {
function canCall(address src, address dst, bytes4 sig) public virtual view returns (bool);
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../mcd/saver/MCDSaverProxy.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../interfaces/ILendingPool.sol";
import "../../exchangeV3/DFSExchangeData.sol";
import "../../utils/SafeERC20.sol";
import "../../utils/GasBurner.sol";
contract MCDCreateTaker is GasBurner {
using SafeERC20 for ERC20;
address payable public constant MCD_CREATE_FLASH_LOAN = 0x409F216aa8034a12135ab6b74Bf6444335004BBd;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
// solhint-disable-next-line const-name-snakecase
Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
struct CreateData {
uint collAmount;
uint daiAmount;
address joinAddr;
}
function openWithLoan(
DFSExchangeData.ExchangeData memory _exchangeData,
CreateData memory _createData
) public payable burnGas(20) {
MCD_CREATE_FLASH_LOAN.transfer(msg.value); //0x fee
if (!isEthJoinAddr(_createData.joinAddr)) {
ERC20(getCollateralAddr(_createData.joinAddr)).safeTransferFrom(msg.sender, address(this), _createData.collAmount);
ERC20(getCollateralAddr(_createData.joinAddr)).safeTransfer(MCD_CREATE_FLASH_LOAN, _createData.collAmount);
}
bytes memory packedData = _packData(_createData, _exchangeData);
bytes memory paramsData = abi.encode(address(this), packedData);
lendingPool.flashLoan(MCD_CREATE_FLASH_LOAN, DAI_ADDRESS, _createData.daiAmount, paramsData);
logger.Log(address(this), msg.sender, "MCDCreate", abi.encode(manager.last(address(this)), _createData.collAmount, _createData.daiAmount));
}
function getCollateralAddr(address _joinAddr) internal view returns (address) {
return address(Join(_joinAddr).gem());
}
/// @notice Checks if the join address is one of the Ether coll. types
/// @param _joinAddr Join address to check
function isEthJoinAddr(address _joinAddr) internal view returns (bool) {
// if it's dai_join_addr don't check gem() it will fail
if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false;
// if coll is weth it's and eth type coll
if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) {
return true;
}
return false;
}
function _packData(
CreateData memory _createData,
DFSExchangeData.ExchangeData memory _exchangeData
) internal pure returns (bytes memory) {
return abi.encode(_createData, _exchangeData);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../loggers/DefisaverLogger.sol";
import "../../utils/Discount.sol";
import "../../interfaces/Spotter.sol";
import "../../interfaces/Jug.sol";
import "../../interfaces/DaiJoin.sol";
import "../../interfaces/Join.sol";
import "./MCDSaverProxyHelper.sol";
import "../../utils/BotRegistry.sol";
import "../../exchangeV3/DFSExchangeCore.sol";
/// @title Implements Boost and Repay for MCD CDPs
contract MCDSaverProxy is DFSExchangeCore, MCDSaverProxyHelper {
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
Vat public constant vat = Vat(VAT_ADDRESS);
DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS);
Spotter public constant spotter = Spotter(SPOTTER_ADDRESS);
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Repay - draws collateral, converts to Dai and repays the debt
/// @dev Must be called by the DSProxy contract that owns the CDP
function repay(
ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr,
ManagerType _managerType
) public payable {
address managerAddr = getManagerAddr(_managerType);
address user = getOwner(Manager(managerAddr), _cdpId);
bytes32 ilk = Manager(managerAddr).ilks(_cdpId);
drawCollateral(managerAddr, _cdpId, _joinAddr, _exchangeData.srcAmount);
_exchangeData.user = user;
_exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
(, uint daiAmount) = _sell(_exchangeData);
daiAmount -= takeFee(_gasCost, daiAmount);
paybackDebt(managerAddr, _cdpId, ilk, daiAmount, user);
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, user, _exchangeData.srcAmount, daiAmount));
}
/// @notice Boost - draws Dai, converts to collateral and adds to CDP
/// @dev Must be called by the DSProxy contract that owns the CDP
function boost(
ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr,
ManagerType _managerType
) public payable {
address managerAddr = getManagerAddr(_managerType);
address user = getOwner(Manager(managerAddr), _cdpId);
bytes32 ilk = Manager(managerAddr).ilks(_cdpId);
uint daiDrawn = drawDai(managerAddr, _cdpId, ilk, _exchangeData.srcAmount);
_exchangeData.user = user;
_exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
_exchangeData.srcAmount = daiDrawn - takeFee(_gasCost, daiDrawn);
(, uint swapedColl) = _sell(_exchangeData);
addCollateral(managerAddr, _cdpId, _joinAddr, swapedColl);
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, user, _exchangeData.srcAmount, swapedColl));
}
/// @notice Draws Dai from the CDP
/// @dev If _daiAmount is bigger than max available we'll draw max
/// @param _managerAddr Address of the CDP Manager
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @param _daiAmount Amount of Dai to draw
function drawDai(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) {
uint rate = Jug(JUG_ADDRESS).drip(_ilk);
uint daiVatBalance = vat.dai(Manager(_managerAddr).urns(_cdpId));
uint maxAmount = getMaxDebt(_managerAddr, _cdpId, _ilk);
if (_daiAmount >= maxAmount) {
_daiAmount = sub(maxAmount, 1);
}
Manager(_managerAddr).frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance));
Manager(_managerAddr).move(_cdpId, address(this), toRad(_daiAmount));
if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) {
vat.hope(DAI_JOIN_ADDRESS);
}
DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount);
return _daiAmount;
}
/// @notice Adds collateral to the CDP
/// @param _managerAddr Address of the CDP Manager
/// @param _cdpId Id of the CDP
/// @param _joinAddr Address of the join contract for the CDP collateral
/// @param _amount Amount of collateral to add
function addCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal {
int convertAmount = 0;
if (isEthJoinAddr(_joinAddr)) {
Join(_joinAddr).gem().deposit{value: _amount}();
convertAmount = toPositiveInt(_amount);
} else {
convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount));
}
ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, _amount);
Join(_joinAddr).join(address(this), _amount);
vat.frob(
Manager(_managerAddr).ilks(_cdpId),
Manager(_managerAddr).urns(_cdpId),
address(this),
address(this),
convertAmount,
0
);
}
/// @notice Draws collateral and returns it to DSProxy
/// @param _managerAddr Address of the CDP Manager
/// @dev If _amount is bigger than max available we'll draw max
/// @param _cdpId Id of the CDP
/// @param _joinAddr Address of the join contract for the CDP collateral
/// @param _amount Amount of collateral to draw
function drawCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) {
uint frobAmount = _amount;
if (Join(_joinAddr).dec() != 18) {
frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec()));
}
Manager(_managerAddr).frob(_cdpId, -toPositiveInt(frobAmount), 0);
Manager(_managerAddr).flux(_cdpId, address(this), frobAmount);
Join(_joinAddr).exit(address(this), _amount);
if (isEthJoinAddr(_joinAddr)) {
Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth
}
return _amount;
}
/// @notice Paybacks Dai debt
/// @param _managerAddr Address of the CDP Manager
/// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @param _daiAmount Amount of Dai to payback
/// @param _owner Address that owns the DSProxy that owns the CDP
function paybackDebt(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal {
address urn = Manager(_managerAddr).urns(_cdpId);
uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk);
if (_daiAmount > wholeDebt) {
ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt));
_daiAmount = wholeDebt;
}
if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) {
ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1));
}
daiJoin.join(urn, _daiAmount);
Manager(_managerAddr).frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk));
}
/// @notice Gets the maximum amount of collateral available to draw
/// @param _managerAddr Address of the CDP Manager
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @param _joinAddr Joind address of collateral
/// @dev Substracts 10 wei to aviod rounding error later on
function getMaxCollateral(address _managerAddr, uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) {
uint price = getPrice(_ilk);
(uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk);
(, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk);
uint maxCollateral = sub(collateral, (div(mul(mat, debt), price)));
uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec()));
// take one percent due to precision issues
return normalizeMaxCollateral * 99 / 100;
}
/// @notice Gets the maximum amount of debt available to generate
/// @param _managerAddr Address of the CDP Manager
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
/// @dev Substracts 10 wei to aviod rounding error later on
function getMaxDebt(address _managerAddr, uint _cdpId, bytes32 _ilk) public virtual view returns (uint) {
uint price = getPrice(_ilk);
(, uint mat) = spotter.ilks(_ilk);
(uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk);
return sub(sub(div(mul(collateral, price), mat), debt), 10);
}
/// @notice Gets a price of the asset
/// @param _ilk Ilk of the CDP
function getPrice(bytes32 _ilk) public view returns (uint) {
(, uint mat) = spotter.ilks(_ilk);
(,,uint spot,,) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
function isAutomation() internal view returns(bool) {
return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin);
}
function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) {
if (_gasCost > 0) {
uint ethDaiPrice = getPrice(ETH_ILK);
uint feeAmount = rmul(_gasCost, ethDaiPrice);
if (feeAmount > _amount / 5) {
feeAmount = _amount / 5;
}
address walletAddr = _feeRecipient.getFeeAddr();
ERC20(DAI_ADDRESS).transfer(walletAddr, feeAmount);
return feeAmount;
}
return 0;
}
}
pragma solidity ^0.6.0;
contract Discount {
address public owner;
mapping(address => CustomServiceFee) public serviceFees;
uint256 constant MAX_SERVICE_FEE = 400;
struct CustomServiceFee {
bool active;
uint256 amount;
}
constructor() public {
owner = msg.sender;
}
function isCustomFeeSet(address _user) public view returns (bool) {
return serviceFees[_user].active;
}
function getCustomServiceFee(address _user) public view returns (uint256) {
return serviceFees[_user].amount;
}
function setServiceFee(address _user, uint256 _fee) public {
require(msg.sender == owner, "Only owner");
require(_fee >= MAX_SERVICE_FEE || _fee == 0);
serviceFees[_user] = CustomServiceFee({active: true, amount: _fee});
}
function disableServiceFee(address _user) public {
require(msg.sender == owner, "Only owner");
serviceFees[_user] = CustomServiceFee({active: false, amount: 0});
}
}
pragma solidity ^0.6.0;
import "./PipInterface.sol";
abstract contract Spotter {
struct Ilk {
PipInterface pip;
uint256 mat;
}
mapping (bytes32 => Ilk) public ilks;
uint256 public par;
}
pragma solidity ^0.6.0;
abstract contract Jug {
struct Ilk {
uint256 duty;
uint256 rho;
}
mapping (bytes32 => Ilk) public ilks;
function drip(bytes32) public virtual returns (uint);
}
pragma solidity ^0.6.0;
import "./Vat.sol";
import "./Gem.sol";
abstract contract DaiJoin {
function vat() public virtual returns (Vat);
function dai() public virtual returns (Gem);
function join(address, uint) public virtual payable;
function exit(address, uint) public virtual;
}
pragma solidity ^0.6.0;
import "./Gem.sol";
abstract contract Join {
bytes32 public ilk;
function dec() virtual public view returns (uint);
function gem() virtual public view returns (Gem);
function join(address, uint) virtual public payable;
function exit(address, uint) virtual public;
}
pragma solidity ^0.6.0;
import "../../DS/DSMath.sol";
import "../../DS/DSProxy.sol";
import "../../interfaces/Manager.sol";
import "../../interfaces/Join.sol";
import "../../interfaces/Vat.sol";
/// @title Helper methods for MCDSaverProxy
contract MCDSaverProxyHelper is DSMath {
enum ManagerType { MCD, BPROTOCOL }
/// @notice Returns a normalized debt _amount based on the current rate
/// @param _amount Amount of dai to be normalized
/// @param _rate Current rate of the stability fee
/// @param _daiVatBalance Balance od Dai in the Vat for that CDP
function normalizeDrawAmount(uint _amount, uint _rate, uint _daiVatBalance) internal pure returns (int dart) {
if (_daiVatBalance < mul(_amount, RAY)) {
dart = toPositiveInt(sub(mul(_amount, RAY), _daiVatBalance) / _rate);
dart = mul(uint(dart), _rate) < mul(_amount, RAY) ? dart + 1 : dart;
}
}
/// @notice Converts a number to Rad percision
/// @param _wad The input number in wad percision
function toRad(uint _wad) internal pure returns (uint) {
return mul(_wad, 10 ** 27);
}
/// @notice Converts a number to 18 decimal percision
/// @param _joinAddr Join address of the collateral
/// @param _amount Number to be converted
function convertTo18(address _joinAddr, uint256 _amount) internal view returns (uint256) {
return mul(_amount, 10 ** (18 - Join(_joinAddr).dec()));
}
/// @notice Converts a uint to int and checks if positive
/// @param _x Number to be converted
function toPositiveInt(uint _x) internal pure returns (int y) {
y = int(_x);
require(y >= 0, "int-overflow");
}
/// @notice Gets Dai amount in Vat which can be added to Cdp
/// @param _vat Address of Vat contract
/// @param _urn Urn of the Cdp
/// @param _ilk Ilk of the Cdp
function normalizePaybackAmount(address _vat, address _urn, bytes32 _ilk) internal view returns (int amount) {
uint dai = Vat(_vat).dai(_urn);
(, uint rate,,,) = Vat(_vat).ilks(_ilk);
(, uint art) = Vat(_vat).urns(_ilk, _urn);
amount = toPositiveInt(dai / rate);
amount = uint(amount) <= art ? - amount : - toPositiveInt(art);
}
/// @notice Gets the whole debt of the CDP
/// @param _vat Address of Vat contract
/// @param _usr Address of the Dai holder
/// @param _urn Urn of the Cdp
/// @param _ilk Ilk of the Cdp
function getAllDebt(address _vat, address _usr, address _urn, bytes32 _ilk) internal view returns (uint daiAmount) {
(, uint rate,,,) = Vat(_vat).ilks(_ilk);
(, uint art) = Vat(_vat).urns(_ilk, _urn);
uint dai = Vat(_vat).dai(_usr);
uint rad = sub(mul(art, rate), dai);
daiAmount = rad / RAY;
daiAmount = mul(daiAmount, RAY) < rad ? daiAmount + 1 : daiAmount;
}
/// @notice Gets the token address from the Join contract
/// @param _joinAddr Address of the Join contract
function getCollateralAddr(address _joinAddr) internal view returns (address) {
return address(Join(_joinAddr).gem());
}
/// @notice Checks if the join address is one of the Ether coll. types
/// @param _joinAddr Join address to check
function isEthJoinAddr(address _joinAddr) internal view returns (bool) {
// if it's dai_join_addr don't check gem() it will fail
if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false;
// if coll is weth it's and eth type coll
if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) {
return true;
}
return false;
}
/// @notice Gets CDP info (collateral, debt)
/// @param _manager Manager contract
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getCdpInfo(Manager _manager, uint _cdpId, bytes32 _ilk) public view returns (uint, uint) {
address vat = _manager.vat();
address urn = _manager.urns(_cdpId);
(uint collateral, uint debt) = Vat(vat).urns(_ilk, urn);
(,uint rate,,,) = Vat(vat).ilks(_ilk);
return (collateral, rmul(debt, rate));
}
/// @notice Address that owns the DSProxy that owns the CDP
/// @param _manager Manager contract
/// @param _cdpId Id of the CDP
function getOwner(Manager _manager, uint _cdpId) public view returns (address) {
DSProxy proxy = DSProxy(uint160(_manager.owns(_cdpId)));
return proxy.owner();
}
/// @notice Based on the manager type returns the address
/// @param _managerType Type of vault manager to use
function getManagerAddr(ManagerType _managerType) public pure returns (address) {
if (_managerType == ManagerType.MCD) {
return 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
} else if (_managerType == ManagerType.BPROTOCOL) {
return 0x3f30c2381CD8B917Dd96EB2f1A4F96D91324BBed;
}
}
}
pragma solidity ^0.6.0;
import "../auth/AdminAuth.sol";
contract BotRegistry is AdminAuth {
mapping (address => bool) public botList;
constructor() public {
botList[0x776B4a13093e30B05781F97F6A4565B6aa8BE330] = true;
botList[0xAED662abcC4FA3314985E67Ea993CAD064a7F5cF] = true;
botList[0xa5d330F6619d6bF892A5B87D80272e1607b3e34D] = true;
botList[0x5feB4DeE5150B589a7f567EA7CADa2759794A90A] = true;
botList[0x7ca06417c1d6f480d3bB195B80692F95A6B66158] = true;
}
function setBot(address _botAddr, bool _state) public onlyOwner {
botList[_botAddr] = _state;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../DS/DSMath.sol";
import "../interfaces/TokenInterface.sol";
import "../interfaces/ExchangeInterfaceV3.sol";
import "../utils/ZrxAllowlist.sol";
import "./DFSExchangeData.sol";
import "./DFSExchangeHelper.sol";
import "../exchange/SaverExchangeRegistry.sol";
import "../interfaces/OffchainWrapperInterface.sol";
contract DFSExchangeCore is DFSExchangeHelper, DSMath, DFSExchangeData {
string public constant ERR_SLIPPAGE_HIT = "Slippage hit";
string public constant ERR_DEST_AMOUNT_MISSING = "Dest amount missing";
string public constant ERR_WRAPPER_INVALID = "Wrapper invalid";
string public constant ERR_NOT_ZEROX_EXCHANGE = "Zerox exchange invalid";
/// @notice Internal method that preforms a sell on 0x/on-chain
/// @dev Usefull for other DFS contract to integrate for exchanging
/// @param exData Exchange data struct
/// @return (address, uint) Address of the wrapper used and destAmount
function _sell(ExchangeData memory exData) internal returns (address, uint) {
address wrapper;
uint swapedTokens;
bool success;
// if selling eth, convert to weth
if (exData.srcAddr == KYBER_ETH_ADDRESS) {
exData.srcAddr = ethToWethAddr(exData.srcAddr);
TokenInterface(EXCHANGE_WETH_ADDRESS).deposit{value: exData.srcAmount}();
}
exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider);
// Try 0x first and then fallback on specific wrapper
if (exData.offchainData.price > 0) {
(success, swapedTokens) = takeOrder(exData, ActionType.SELL);
if (success) {
wrapper = exData.offchainData.exchangeAddr;
}
}
// fallback to desired wrapper if 0x failed
if (!success) {
swapedTokens = saverSwap(exData, ActionType.SELL);
wrapper = exData.wrapper;
}
// if anything is left in weth, pull it to user as eth
if (getBalance(EXCHANGE_WETH_ADDRESS) > 0) {
TokenInterface(EXCHANGE_WETH_ADDRESS).withdraw(
TokenInterface(EXCHANGE_WETH_ADDRESS).balanceOf(address(this))
);
}
if (exData.destAddr == EXCHANGE_WETH_ADDRESS) {
require(getBalance(KYBER_ETH_ADDRESS) >= wmul(exData.minPrice, exData.srcAmount), ERR_SLIPPAGE_HIT);
} else {
require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), ERR_SLIPPAGE_HIT);
}
return (wrapper, swapedTokens);
}
/// @notice Internal method that preforms a buy on 0x/on-chain
/// @dev Usefull for other DFS contract to integrate for exchanging
/// @param exData Exchange data struct
/// @return (address, uint) Address of the wrapper used and srcAmount
function _buy(ExchangeData memory exData) internal returns (address, uint) {
address wrapper;
uint swapedTokens;
bool success;
require(exData.destAmount != 0, ERR_DEST_AMOUNT_MISSING);
exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider);
// if selling eth, convert to weth
if (exData.srcAddr == KYBER_ETH_ADDRESS) {
exData.srcAddr = ethToWethAddr(exData.srcAddr);
TokenInterface(EXCHANGE_WETH_ADDRESS).deposit{value: exData.srcAmount}();
}
if (exData.offchainData.price > 0) {
(success, swapedTokens) = takeOrder(exData, ActionType.BUY);
if (success) {
wrapper = exData.offchainData.exchangeAddr;
}
}
// fallback to desired wrapper if 0x failed
if (!success) {
swapedTokens = saverSwap(exData, ActionType.BUY);
wrapper = exData.wrapper;
}
// if anything is left in weth, pull it to user as eth
if (getBalance(EXCHANGE_WETH_ADDRESS) > 0) {
TokenInterface(EXCHANGE_WETH_ADDRESS).withdraw(
TokenInterface(EXCHANGE_WETH_ADDRESS).balanceOf(address(this))
);
}
if (exData.destAddr == EXCHANGE_WETH_ADDRESS) {
require(getBalance(KYBER_ETH_ADDRESS) >= exData.destAmount, ERR_SLIPPAGE_HIT);
} else {
require(getBalance(exData.destAddr) >= exData.destAmount, ERR_SLIPPAGE_HIT);
}
return (wrapper, getBalance(exData.destAddr));
}
/// @notice Takes order from 0x and returns bool indicating if it is successful
/// @param _exData Exchange data
function takeOrder(
ExchangeData memory _exData,
ActionType _type
) private returns (bool success, uint256) {
if (!ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.offchainData.exchangeAddr)) {
return (false, 0);
}
if (!SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.offchainData.wrapper)) {
return (false, 0);
}
// send src amount
ERC20(_exData.srcAddr).safeTransfer(_exData.offchainData.wrapper, _exData.srcAmount);
return OffchainWrapperInterface(_exData.offchainData.wrapper).takeOrder{value: _exData.offchainData.protocolFee}(_exData, _type);
}
/// @notice Calls wraper contract for exchage to preform an on-chain swap
/// @param _exData Exchange data struct
/// @param _type Type of action SELL|BUY
/// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount
function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) {
require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), ERR_WRAPPER_INVALID);
ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount);
if (_type == ActionType.SELL) {
swapedTokens = ExchangeInterfaceV3(_exData.wrapper).
sell(_exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.wrapperData);
} else {
swapedTokens = ExchangeInterfaceV3(_exData.wrapper).
buy(_exData.srcAddr, _exData.destAddr, _exData.destAmount, _exData.wrapperData);
}
}
// solhint-disable-next-line no-empty-blocks
receive() external virtual payable {}
}
pragma solidity ^0.6.0;
abstract contract PipInterface {
function read() public virtual returns (bytes32);
}
pragma solidity ^0.6.0;
abstract contract Gem {
function dec() virtual public returns (uint);
function gem() virtual public returns (Gem);
function join(address, uint) virtual public payable;
function exit(address, uint) virtual public;
function approve(address, uint) virtual public;
function transfer(address, uint) virtual public returns (bool);
function transferFrom(address, address, uint) virtual public returns (bool);
function deposit() virtual public payable;
function withdraw(uint) virtual public;
function allowance(address, address) virtual public returns (uint);
}
pragma solidity ^0.6.0;
contract DSMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x);
}
function div(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x / y;
}
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x <= y ? x : y;
}
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x >= y ? x : y;
}
function imin(int256 x, int256 y) internal pure returns (int256 z) {
return x <= y ? x : y;
}
function imax(int256 x, int256 y) internal pure returns (int256 z) {
return x >= y ? x : y;
}
uint256 constant WAD = 10**18;
uint256 constant RAY = 10**27;
function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint256 x, uint256 y) internal pure returns (uint256 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(uint256 x, uint256 n) internal pure returns (uint256 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);
}
}
}
}
pragma solidity ^0.6.0;
import "./DSAuth.sol";
import "./DSNote.sol";
abstract contract DSProxy is DSAuth, DSNote {
DSProxyCache public cache; // global cache for contracts
constructor(address _cacheAddr) public {
require(setCache(_cacheAddr));
}
// solhint-disable-next-line no-empty-blocks
receive() external payable {}
// use the proxy to execute calldata _data on contract _code
// function execute(bytes memory _code, bytes memory _data)
// public
// payable
// virtual
// returns (address target, bytes32 response);
function execute(address _target, bytes memory _data)
public
payable
virtual
returns (bytes32 response);
//set new cache
function setCache(address _cacheAddr) public virtual payable returns (bool);
}
contract DSProxyCache {
mapping(bytes32 => address) cache;
function read(bytes memory _code) public view returns (address) {
bytes32 hash = keccak256(_code);
return cache[hash];
}
function write(bytes memory _code) public returns (address target) {
assembly {
target := create(0, add(_code, 0x20), mload(_code))
switch iszero(extcodesize(target))
case 1 {
// throw if contract failed to deploy
revert(0, 0)
}
}
bytes32 hash = keccak256(_code);
cache[hash] = target;
}
}
pragma solidity ^0.6.0;
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint256 wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
assembly {
foo := calldataload(4)
bar := calldataload(36)
}
emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data);
_;
}
}
pragma solidity ^0.6.0;
abstract contract TokenInterface {
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
function allowance(address, address) public virtual returns (uint256);
function balanceOf(address) public virtual returns (uint256);
function approve(address, uint256) public virtual;
function transfer(address, uint256) public virtual returns (bool);
function transferFrom(address, address, uint256) public virtual returns (bool);
function deposit() public virtual payable;
function withdraw(uint256) public virtual;
}
pragma solidity ^0.6.0;
interface ExchangeInterfaceV3 {
function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external payable returns (uint);
function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external payable returns(uint);
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint);
function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint);
}
pragma solidity ^0.6.0;
import "../auth/AdminAuth.sol";
contract ZrxAllowlist is AdminAuth {
mapping (address => bool) public zrxAllowlist;
mapping(address => bool) private nonPayableAddrs;
constructor() public {
zrxAllowlist[0x6958F5e95332D93D21af0D7B9Ca85B8212fEE0A5] = true;
zrxAllowlist[0x61935CbDd02287B511119DDb11Aeb42F1593b7Ef] = true;
zrxAllowlist[0xDef1C0ded9bec7F1a1670819833240f027b25EfF] = true;
zrxAllowlist[0x080bf510FCbF18b91105470639e9561022937712] = true;
nonPayableAddrs[0x080bf510FCbF18b91105470639e9561022937712] = true;
}
function setAllowlistAddr(address _zrxAddr, bool _state) public onlyOwner {
zrxAllowlist[_zrxAddr] = _state;
}
function isZrxAddr(address _zrxAddr) public view returns (bool) {
return zrxAllowlist[_zrxAddr];
}
function addNonPayableAddr(address _nonPayableAddr) public onlyOwner {
nonPayableAddrs[_nonPayableAddr] = true;
}
function removeNonPayableAddr(address _nonPayableAddr) public onlyOwner {
nonPayableAddrs[_nonPayableAddr] = false;
}
function isNonPayableAddr(address _addr) public view returns(bool) {
return nonPayableAddrs[_addr];
}
}
pragma solidity ^0.6.0;
import "../utils/SafeERC20.sol";
import "../utils/Discount.sol";
import "../interfaces/IFeeRecipient.sol";
contract DFSExchangeHelper {
string public constant ERR_OFFCHAIN_DATA_INVALID = "Offchain data invalid";
using SafeERC20 for ERC20;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant EXCHANGE_WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
IFeeRecipient public constant _feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A);
address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D;
address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F;
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
function getBalance(address _tokenAddr) internal view returns (uint balance) {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
balance = address(this).balance;
} else {
balance = ERC20(_tokenAddr).balanceOf(address(this));
}
}
function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal {
// send back any leftover ether or tokens
if (address(this).balance > 0) {
_to.transfer(address(this).balance);
}
if (getBalance(_srcAddr) > 0) {
ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr));
}
if (getBalance(_destAddr) > 0) {
ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr));
}
}
/// @notice Takes a feePercentage and sends it to wallet
/// @param _amount Dai amount of the whole trade
/// @param _user Address of the user
/// @param _token Address of the token
/// @param _dfsFeeDivider Dfs fee divider
/// @return feeAmount Amount in Dai owner earned on the fee
function getFee(uint256 _amount, address _user, address _token, uint256 _dfsFeeDivider) internal returns (uint256 feeAmount) {
if (_dfsFeeDivider != 0 && Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_user)) {
_dfsFeeDivider = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_user);
}
if (_dfsFeeDivider == 0) {
feeAmount = 0;
} else {
feeAmount = _amount / _dfsFeeDivider;
// fee can't go over 10% of the whole amount
if (feeAmount > (_amount / 10)) {
feeAmount = _amount / 10;
}
address walletAddr = _feeRecipient.getFeeAddr();
if (_token == KYBER_ETH_ADDRESS) {
payable(walletAddr).transfer(feeAmount);
} else {
ERC20(_token).safeTransfer(walletAddr, feeAmount);
}
}
}
function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) {
require(bs.length >= start + 32, "slicing out of range");
uint256 x;
assembly {
x := mload(add(bs, add(0x20, start)))
}
return x;
}
function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure {
if (_b.length < _index + 32) {
revert(ERR_OFFCHAIN_DATA_INVALID);
}
bytes32 input = bytes32(_input);
_index += 32;
// Read the bytes32 from array memory
assembly {
mstore(add(_b, _index), input)
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? EXCHANGE_WETH_ADDRESS : _src;
}
}
pragma solidity ^0.6.0;
import "../auth/AdminAuth.sol";
contract SaverExchangeRegistry is AdminAuth {
mapping(address => bool) private wrappers;
constructor() public {
wrappers[0x880A845A85F843a5c67DB2061623c6Fc3bB4c511] = true;
wrappers[0x4c9B55f2083629A1F7aDa257ae984E03096eCD25] = true;
wrappers[0x42A9237b872368E1bec4Ca8D26A928D7d39d338C] = true;
}
function addWrapper(address _wrapper) public onlyOwner {
wrappers[_wrapper] = true;
}
function removeWrapper(address _wrapper) public onlyOwner {
wrappers[_wrapper] = false;
}
function isWrapper(address _wrapper) public view returns(bool) {
return wrappers[_wrapper];
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../exchangeV3/DFSExchangeData.sol";
abstract contract OffchainWrapperInterface is DFSExchangeData {
function takeOrder(
ExchangeData memory _exData,
ActionType _type
) virtual public payable returns (bool success, uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
abstract contract IFeeRecipient {
function getFeeAddr() public view virtual returns (address);
function changeWalletAddr(address _newWallet) public virtual;
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../saver/MCDSaverProxy.sol";
import "../../exchangeV3/DFSExchangeData.sol";
import "../../utils/GasBurner.sol";
import "../../interfaces/ILendingPool.sol";
contract MCDSaverTaker is MCDSaverProxy, GasBurner {
address payable public constant MCD_SAVER_FLASH_LOAN = 0x9222c4f253bD0bdb387Fc97D44e5A6b90cDF4389;
address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
function boostWithLoan(
ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr,
ManagerType _managerType
) public payable burnGas(25) {
address managerAddr = getManagerAddr(_managerType);
uint256 maxDebt = getMaxDebt(managerAddr, _cdpId, Manager(managerAddr).ilks(_cdpId));
uint maxLiq = getAvailableLiquidity(DAI_JOIN_ADDRESS);
if (maxDebt >= _exchangeData.srcAmount || maxLiq == 0) {
if (_exchangeData.srcAmount > maxDebt) {
_exchangeData.srcAmount = maxDebt;
}
boost(_exchangeData, _cdpId, _gasCost, _joinAddr, _managerType);
return;
}
uint256 loanAmount = sub(_exchangeData.srcAmount, maxDebt);
loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount;
MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee
Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1);
bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, false, uint8(_managerType));
lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, DAI_ADDRESS, loanAmount, paramsData);
Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0);
}
function repayWithLoan(
ExchangeData memory _exchangeData,
uint _cdpId,
uint _gasCost,
address _joinAddr,
ManagerType _managerType
) public payable burnGas(25) {
address managerAddr = getManagerAddr(_managerType);
uint256 maxColl = getMaxCollateral(managerAddr, _cdpId, Manager(managerAddr).ilks(_cdpId), _joinAddr);
uint maxLiq = getAvailableLiquidity(_joinAddr);
if (maxColl >= _exchangeData.srcAmount || maxLiq == 0) {
if (_exchangeData.srcAmount > maxColl) {
_exchangeData.srcAmount = maxColl;
}
repay(_exchangeData, _cdpId, _gasCost, _joinAddr, _managerType);
return;
}
uint256 loanAmount = sub(_exchangeData.srcAmount, maxColl);
loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount;
MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee
Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1);
bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, true, uint8(_managerType));
lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, getAaveCollAddr(_joinAddr), loanAmount, paramsData);
Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0);
}
/// @notice Gets the maximum amount of debt available to generate
/// @param _managerAddr Address of the CDP Manager
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getMaxDebt(address _managerAddr, uint256 _cdpId, bytes32 _ilk) public override view returns (uint256) {
uint256 price = getPrice(_ilk);
(, uint256 mat) = spotter.ilks(_ilk);
(uint256 collateral, uint256 debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk);
return sub(wdiv(wmul(collateral, price), mat), debt);
}
function getAaveCollAddr(address _joinAddr) internal view returns (address) {
if (isEthJoinAddr(_joinAddr)
|| _joinAddr == 0x775787933e92b709f2a3C70aa87999696e74A9F8) {
return KYBER_ETH_ADDRESS;
} else if (_joinAddr == DAI_JOIN_ADDRESS) {
return DAI_ADDRESS;
} else
{
return getCollateralAddr(_joinAddr);
}
}
function getAvailableLiquidity(address _joinAddr) internal view returns (uint liquidity) {
address tokenAddr = getAaveCollAddr(_joinAddr);
if (tokenAddr == KYBER_ETH_ADDRESS) {
liquidity = AAVE_POOL_CORE.balance;
} else {
liquidity = ERC20(tokenAddr).balanceOf(AAVE_POOL_CORE);
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../ProtocolInterface.sol";
import "../../interfaces/IAToken.sol";
import "../../interfaces/ILendingPool.sol";
import "../../interfaces/ERC20.sol";
import "../../DS/DSAuth.sol";
contract AaveSavingsProtocol is ProtocolInterface, DSAuth {
address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d;
address public constant AAVE_LENDING_POOL = 0x398eC7346DcD622eDc5ae82352F02bE94C62d119;
address public constant AAVE_LENDING_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
function deposit(address _user, uint _amount) public override {
require(msg.sender == _user);
// get dai from user
require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount));
ERC20(DAI_ADDRESS).approve(AAVE_LENDING_POOL_CORE, uint(-1));
ILendingPool(AAVE_LENDING_POOL).deposit(DAI_ADDRESS, _amount, 0);
ERC20(ADAI_ADDRESS).transfer(_user, ERC20(ADAI_ADDRESS).balanceOf(address(this)));
}
function withdraw(address _user, uint _amount) public override {
require(msg.sender == _user);
require(ERC20(ADAI_ADDRESS).transferFrom(_user, address(this), _amount));
IAToken(ADAI_ADDRESS).redeem(_amount);
// return dai we have to user
ERC20(DAI_ADDRESS).transfer(_user, _amount);
}
}
pragma solidity ^0.6.0;
abstract contract ProtocolInterface {
function deposit(address _user, uint256 _amount) public virtual;
function withdraw(address _user, uint256 _amount) public virtual;
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../ProtocolInterface.sol";
import "../../interfaces/ERC20.sol";
import "../../interfaces/ITokenInterface.sol";
import "../../DS/DSAuth.sol";
contract FulcrumSavingsProtocol is ProtocolInterface, DSAuth {
address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public savingsProxy;
uint public decimals = 10 ** 18;
function addSavingsProxy(address _savingsProxy) public auth {
savingsProxy = _savingsProxy;
}
function deposit(address _user, uint _amount) public override {
require(msg.sender == _user);
// get dai from user
require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount));
// approve dai to Fulcrum
ERC20(DAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1));
// mint iDai
ITokenInterface(NEW_IDAI_ADDRESS).mint(_user, _amount);
}
function withdraw(address _user, uint _amount) public override {
require(msg.sender == _user);
// transfer all users tokens to our contract
require(ERC20(NEW_IDAI_ADDRESS).transferFrom(_user, address(this), ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(_user)));
// approve iDai to that contract
ERC20(NEW_IDAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1));
uint tokenPrice = ITokenInterface(NEW_IDAI_ADDRESS).tokenPrice();
// get dai from iDai contract
ITokenInterface(NEW_IDAI_ADDRESS).burn(_user, _amount * decimals / tokenPrice);
// return all remaining tokens back to user
require(ERC20(NEW_IDAI_ADDRESS).transfer(_user, ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(address(this))));
}
}
pragma solidity ^0.6.0;
import "./ERC20.sol";
abstract contract ITokenInterface is ERC20 {
function assetBalanceOf(address _owner) public virtual view returns (uint256);
function mint(address receiver, uint256 depositAmount) external virtual returns (uint256 mintAmount);
function burn(address receiver, uint256 burnAmount) external virtual returns (uint256 loanAmountPaid);
function tokenPrice() public virtual view returns (uint256 price);
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./ProtocolInterface.sol";
import "../interfaces/ERC20.sol";
import "../interfaces/ITokenInterface.sol";
import "../interfaces/ComptrollerInterface.sol";
import "./dydx/ISoloMargin.sol";
import "./SavingsLogger.sol";
import "./dsr/DSRSavingsProtocol.sol";
import "./compound/CompoundSavingsProtocol.sol";
contract SavingsProxy is DSRSavingsProtocol, CompoundSavingsProtocol {
address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d;
address public constant SAVINGS_DYDX_ADDRESS = 0x03b1565e070df392e48e7a8e01798C4B00E534A5;
address public constant SAVINGS_AAVE_ADDRESS = 0x535B9035E9bA8D7efe0FeAEac885fb65b303E37C;
address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081;
address public constant COMP_ADDRESS = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
address public constant SAVINGS_LOGGER_ADDRESS = 0x89b3635BD2bAD145C6f92E82C9e83f06D5654984;
address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
enum SavingsProtocol {Compound, Dydx, Fulcrum, Dsr, Aave}
function deposit(SavingsProtocol _protocol, uint256 _amount) public {
if (_protocol == SavingsProtocol.Dsr) {
dsrDeposit(_amount, true);
} else if (_protocol == SavingsProtocol.Compound) {
compDeposit(msg.sender, _amount);
} else {
_deposit(_protocol, _amount, true);
}
SavingsLogger(SAVINGS_LOGGER_ADDRESS).logDeposit(msg.sender, uint8(_protocol), _amount);
}
function withdraw(SavingsProtocol _protocol, uint256 _amount) public {
if (_protocol == SavingsProtocol.Dsr) {
dsrWithdraw(_amount, true);
} else if (_protocol == SavingsProtocol.Compound) {
compWithdraw(msg.sender, _amount);
} else {
_withdraw(_protocol, _amount, true);
}
SavingsLogger(SAVINGS_LOGGER_ADDRESS).logWithdraw(msg.sender, uint8(_protocol), _amount);
}
function swap(SavingsProtocol _from, SavingsProtocol _to, uint256 _amount) public {
if (_from == SavingsProtocol.Dsr) {
dsrWithdraw(_amount, false);
} else if (_from == SavingsProtocol.Compound) {
compWithdraw(msg.sender, _amount);
} else {
_withdraw(_from, _amount, false);
}
// possible to withdraw 1-2 wei less than actual amount due to division precision
// so we deposit all amount on DSProxy
uint256 amountToDeposit = ERC20(DAI_ADDRESS).balanceOf(address(this));
if (_to == SavingsProtocol.Dsr) {
dsrDeposit(amountToDeposit, false);
} else if (_from == SavingsProtocol.Compound) {
compDeposit(msg.sender, _amount);
} else {
_deposit(_to, amountToDeposit, false);
}
SavingsLogger(SAVINGS_LOGGER_ADDRESS).logSwap(
msg.sender,
uint8(_from),
uint8(_to),
_amount
);
}
function withdrawDai() public {
ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this)));
}
function claimComp() public {
ComptrollerInterface(COMP_ADDRESS).claimComp(address(this));
}
function getAddress(SavingsProtocol _protocol) public pure returns (address) {
if (_protocol == SavingsProtocol.Dydx) {
return SAVINGS_DYDX_ADDRESS;
}
if (_protocol == SavingsProtocol.Aave) {
return SAVINGS_AAVE_ADDRESS;
}
}
function _deposit(SavingsProtocol _protocol, uint256 _amount, bool _fromUser) internal {
if (_fromUser) {
ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), _amount);
}
approveDeposit(_protocol);
ProtocolInterface(getAddress(_protocol)).deposit(address(this), _amount);
endAction(_protocol);
}
function _withdraw(SavingsProtocol _protocol, uint256 _amount, bool _toUser) public {
approveWithdraw(_protocol);
ProtocolInterface(getAddress(_protocol)).withdraw(address(this), _amount);
endAction(_protocol);
if (_toUser) {
withdrawDai();
}
}
function endAction(SavingsProtocol _protocol) internal {
if (_protocol == SavingsProtocol.Dydx) {
setDydxOperator(false);
}
}
function approveDeposit(SavingsProtocol _protocol) internal {
if (_protocol == SavingsProtocol.Compound || _protocol == SavingsProtocol.Fulcrum || _protocol == SavingsProtocol.Aave) {
ERC20(DAI_ADDRESS).approve(getAddress(_protocol), uint256(-1));
}
if (_protocol == SavingsProtocol.Dydx) {
ERC20(DAI_ADDRESS).approve(SOLO_MARGIN_ADDRESS, uint256(-1));
setDydxOperator(true);
}
}
function approveWithdraw(SavingsProtocol _protocol) internal {
if (_protocol == SavingsProtocol.Compound) {
ERC20(NEW_CDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1));
}
if (_protocol == SavingsProtocol.Dydx) {
setDydxOperator(true);
}
if (_protocol == SavingsProtocol.Fulcrum) {
ERC20(NEW_IDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1));
}
if (_protocol == SavingsProtocol.Aave) {
ERC20(ADAI_ADDRESS).approve(getAddress(_protocol), uint256(-1));
}
}
function setDydxOperator(bool _trusted) internal {
ISoloMargin.OperatorArg[] memory operatorArgs = new ISoloMargin.OperatorArg[](1);
operatorArgs[0] = ISoloMargin.OperatorArg({
operator: getAddress(SavingsProtocol.Dydx),
trusted: _trusted
});
ISoloMargin(SOLO_MARGIN_ADDRESS).setOperators(operatorArgs);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
abstract contract ComptrollerInterface {
struct CompMarketState {
uint224 index;
uint32 block;
}
function claimComp(address holder) public virtual;
function claimComp(address holder, address[] memory cTokens) public virtual;
function claimComp(address[] memory holders, address[] memory cTokens, bool borrowers, bool suppliers) public virtual;
function compSupplyState(address) public view virtual returns (CompMarketState memory);
function compSupplierIndex(address,address) public view virtual returns (uint);
function compAccrued(address) public view virtual returns (uint);
function compBorrowState(address) public view virtual returns (CompMarketState memory);
function compBorrowerIndex(address,address) public view virtual returns (uint);
function enterMarkets(address[] calldata cTokens) external virtual returns (uint256[] memory);
function exitMarket(address cToken) external virtual returns (uint256);
function getAssetsIn(address account) external virtual view returns (address[] memory);
function markets(address account) public virtual view returns (bool, uint256);
function getAccountLiquidity(address account) external virtual view returns (uint256, uint256, uint256);
function oracle() public virtual view returns (address);
function borrowCaps(address) external virtual returns (uint256);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
library Account {
enum Status {Normal, Liquid, Vapor}
struct Info {
address owner; // The address that owns the account
uint256 number; // A nonce that allows a single address to control many accounts
}
struct Storage {
mapping(uint256 => Types.Par) balances; // Mapping from marketId to principal
Status status;
}
}
library Actions {
enum ActionType {
Deposit, // supply tokens
Withdraw, // borrow tokens
Transfer, // transfer balance between accounts
Buy, // buy an amount of some token (public virtually)
Sell, // sell an amount of some token (public virtually)
Trade, // trade tokens against another account
Liquidate, // liquidate an undercollateralized or expiring account
Vaporize, // use excess tokens to zero-out a completely negative account
Call // send arbitrary data to an address
}
enum AccountLayout {OnePrimary, TwoPrimary, PrimaryAndSecondary}
enum MarketLayout {ZeroMarkets, OneMarket, TwoMarkets}
struct ActionArgs {
ActionType actionType;
uint256 accountId;
Types.AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
struct DepositArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 market;
address from;
}
struct WithdrawArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 market;
address to;
}
struct TransferArgs {
Types.AssetAmount amount;
Account.Info accountOne;
Account.Info accountTwo;
uint256 market;
}
struct BuyArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 makerMarket;
uint256 takerMarket;
address exchangeWrapper;
bytes orderData;
}
struct SellArgs {
Types.AssetAmount amount;
Account.Info account;
uint256 takerMarket;
uint256 makerMarket;
address exchangeWrapper;
bytes orderData;
}
struct TradeArgs {
Types.AssetAmount amount;
Account.Info takerAccount;
Account.Info makerAccount;
uint256 inputMarket;
uint256 outputMarket;
address autoTrader;
bytes tradeData;
}
struct LiquidateArgs {
Types.AssetAmount amount;
Account.Info solidAccount;
Account.Info liquidAccount;
uint256 owedMarket;
uint256 heldMarket;
}
struct VaporizeArgs {
Types.AssetAmount amount;
Account.Info solidAccount;
Account.Info vaporAccount;
uint256 owedMarket;
uint256 heldMarket;
}
struct CallArgs {
Account.Info account;
address callee;
bytes data;
}
}
library Decimal {
struct D256 {
uint256 value;
}
}
library Interest {
struct Rate {
uint256 value;
}
struct Index {
uint96 borrow;
uint96 supply;
uint32 lastUpdate;
}
}
library Monetary {
struct Price {
uint256 value;
}
struct Value {
uint256 value;
}
}
library Storage {
// All information necessary for tracking a market
struct Market {
// Contract address of the associated ERC20 token
address token;
// Total aggregated supply and borrow amount of the entire market
Types.TotalPar totalPar;
// Interest index of the market
Interest.Index index;
// Contract address of the price oracle for this market
address priceOracle;
// Contract address of the interest setter for this market
address interestSetter;
// Multiplier on the marginRatio for this market
Decimal.D256 marginPremium;
// Multiplier on the liquidationSpread for this market
Decimal.D256 spreadPremium;
// Whether additional borrows are allowed for this market
bool isClosing;
}
// The global risk parameters that govern the health and security of the system
struct RiskParams {
// Required ratio of over-collateralization
Decimal.D256 marginRatio;
// Percentage penalty incurred by liquidated accounts
Decimal.D256 liquidationSpread;
// Percentage of the borrower's interest fee that gets passed to the suppliers
Decimal.D256 earningsRate;
// The minimum absolute borrow value of an account
// There must be sufficient incentivize to liquidate undercollateralized accounts
Monetary.Value minBorrowedValue;
}
// The maximum RiskParam values that can be set
struct RiskLimits {
uint64 marginRatioMax;
uint64 liquidationSpreadMax;
uint64 earningsRateMax;
uint64 marginPremiumMax;
uint64 spreadPremiumMax;
uint128 minBorrowedValueMax;
}
// The entire storage state of Solo
struct State {
// number of markets
uint256 numMarkets;
// marketId => Market
mapping(uint256 => Market) markets;
// owner => account number => Account
mapping(address => mapping(uint256 => Account.Storage)) accounts;
// Addresses that can control other users accounts
mapping(address => mapping(address => bool)) operators;
// Addresses that can control all users accounts
mapping(address => bool) globalOperators;
// mutable risk parameters of the system
RiskParams riskParams;
// immutable risk limits of the system
RiskLimits riskLimits;
}
}
library Types {
enum AssetDenomination {
Wei, // the amount is denominated in wei
Par // the amount is denominated in par
}
enum AssetReference {
Delta, // the amount is given as a delta from the current value
Target // the amount is given as an exact number to end up at
}
struct AssetAmount {
bool sign; // true if positive
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
struct TotalPar {
uint128 borrow;
uint128 supply;
}
struct Par {
bool sign; // true if positive
uint128 value;
}
struct Wei {
bool sign; // true if positive
uint256 value;
}
}
abstract contract ISoloMargin {
struct OperatorArg {
address operator;
bool trusted;
}
function ownerSetSpreadPremium(
uint256 marketId,
Decimal.D256 memory spreadPremium
) public virtual;
function getIsGlobalOperator(address operator) public virtual view returns (bool);
function getMarketTokenAddress(uint256 marketId)
public virtual
view
returns (address);
function ownerSetInterestSetter(uint256 marketId, address interestSetter)
public virtual;
function getAccountValues(Account.Info memory account)
public virtual
view
returns (Monetary.Value memory, Monetary.Value memory);
function getMarketPriceOracle(uint256 marketId)
public virtual
view
returns (address);
function getMarketInterestSetter(uint256 marketId)
public virtual
view
returns (address);
function getMarketSpreadPremium(uint256 marketId)
public virtual
view
returns (Decimal.D256 memory);
function getNumMarkets() public virtual view returns (uint256);
function ownerWithdrawUnsupportedTokens(address token, address recipient)
public virtual
returns (uint256);
function ownerSetMinBorrowedValue(Monetary.Value memory minBorrowedValue)
public virtual;
function ownerSetLiquidationSpread(Decimal.D256 memory spread) public virtual;
function ownerSetEarningsRate(Decimal.D256 memory earningsRate) public virtual;
function getIsLocalOperator(address owner, address operator)
public virtual
view
returns (bool);
function getAccountPar(Account.Info memory account, uint256 marketId)
public virtual
view
returns (Types.Par memory);
function ownerSetMarginPremium(
uint256 marketId,
Decimal.D256 memory marginPremium
) public virtual;
function getMarginRatio() public virtual view returns (Decimal.D256 memory);
function getMarketCurrentIndex(uint256 marketId)
public virtual
view
returns (Interest.Index memory);
function getMarketIsClosing(uint256 marketId) public virtual view returns (bool);
function getRiskParams() public virtual view returns (Storage.RiskParams memory);
function getAccountBalances(Account.Info memory account)
public virtual
view
returns (address[] memory, Types.Par[] memory, Types.Wei[] memory);
function renounceOwnership() public virtual;
function getMinBorrowedValue() public virtual view returns (Monetary.Value memory);
function setOperators(OperatorArg[] memory args) public virtual;
function getMarketPrice(uint256 marketId) public virtual view returns (address);
function owner() public virtual view returns (address);
function isOwner() public virtual view returns (bool);
function ownerWithdrawExcessTokens(uint256 marketId, address recipient)
public virtual
returns (uint256);
function ownerAddMarket(
address token,
address priceOracle,
address interestSetter,
Decimal.D256 memory marginPremium,
Decimal.D256 memory spreadPremium
) public virtual;
function operate(
Account.Info[] memory accounts,
Actions.ActionArgs[] memory actions
) public virtual;
function getMarketWithInfo(uint256 marketId)
public virtual
view
returns (
Storage.Market memory,
Interest.Index memory,
Monetary.Price memory,
Interest.Rate memory
);
function ownerSetMarginRatio(Decimal.D256 memory ratio) public virtual;
function getLiquidationSpread() public virtual view returns (Decimal.D256 memory);
function getAccountWei(Account.Info memory account, uint256 marketId)
public virtual
view
returns (Types.Wei memory);
function getMarketTotalPar(uint256 marketId)
public virtual
view
returns (Types.TotalPar memory);
function getLiquidationSpreadForPair(
uint256 heldMarketId,
uint256 owedMarketId
) public virtual view returns (Decimal.D256 memory);
function getNumExcessTokens(uint256 marketId)
public virtual
view
returns (Types.Wei memory);
function getMarketCachedIndex(uint256 marketId)
public virtual
view
returns (Interest.Index memory);
function getAccountStatus(Account.Info memory account)
public virtual
view
returns (uint8);
function getEarningsRate() public virtual view returns (Decimal.D256 memory);
function ownerSetPriceOracle(uint256 marketId, address priceOracle) public virtual;
function getRiskLimits() public virtual view returns (Storage.RiskLimits memory);
function getMarket(uint256 marketId)
public virtual
view
returns (Storage.Market memory);
function ownerSetIsClosing(uint256 marketId, bool isClosing) public virtual;
function ownerSetGlobalOperator(address operator, bool approved) public virtual;
function transferOwnership(address newOwner) public virtual;
function getAdjustedAccountValues(Account.Info memory account)
public virtual
view
returns (Monetary.Value memory, Monetary.Value memory);
function getMarketMarginPremium(uint256 marketId)
public virtual
view
returns (Decimal.D256 memory);
function getMarketInterestRate(uint256 marketId)
public virtual
view
returns (Interest.Rate memory);
}
pragma solidity ^0.6.0;
contract SavingsLogger {
event Deposit(address indexed sender, uint8 protocol, uint256 amount);
event Withdraw(address indexed sender, uint8 protocol, uint256 amount);
event Swap(address indexed sender, uint8 fromProtocol, uint8 toProtocol, uint256 amount);
function logDeposit(address _sender, uint8 _protocol, uint256 _amount) external {
emit Deposit(_sender, _protocol, _amount);
}
function logWithdraw(address _sender, uint8 _protocol, uint256 _amount) external {
emit Withdraw(_sender, _protocol, _amount);
}
function logSwap(address _sender, uint8 _protocolFrom, uint8 _protocolTo, uint256 _amount)
external
{
emit Swap(_sender, _protocolFrom, _protocolTo, _amount);
}
}
pragma solidity ^0.6.0;
import "../../interfaces/Join.sol";
import "../../DS/DSMath.sol";
abstract contract VatLike {
function can(address, address) virtual public view returns (uint);
function ilks(bytes32) virtual public view returns (uint, uint, uint, uint, uint);
function dai(address) virtual public view returns (uint);
function urns(bytes32, address) virtual public view returns (uint, uint);
function frob(bytes32, address, address, address, int, int) virtual public;
function hope(address) virtual public;
function move(address, address, uint) virtual public;
}
abstract contract PotLike {
function pie(address) virtual public view returns (uint);
function drip() virtual public returns (uint);
function join(uint) virtual public;
function exit(uint) virtual public;
}
abstract contract GemLike {
function approve(address, uint) virtual public;
function transfer(address, uint) virtual public;
function transferFrom(address, address, uint) virtual public;
function deposit() virtual public payable;
function withdraw(uint) virtual public;
}
abstract contract DaiJoinLike {
function vat() virtual public returns (VatLike);
function dai() virtual public returns (GemLike);
function join(address, uint) virtual public payable;
function exit(address, uint) virtual public;
}
contract DSRSavingsProtocol is DSMath {
// Mainnet
address public constant POT_ADDRESS = 0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7;
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
function dsrDeposit(uint _amount, bool _fromUser) internal {
VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat();
uint chi = PotLike(POT_ADDRESS).drip();
daiJoin_join(DAI_JOIN_ADDRESS, address(this), _amount, _fromUser);
if (vat.can(address(this), address(POT_ADDRESS)) == 0) {
vat.hope(POT_ADDRESS);
}
PotLike(POT_ADDRESS).join(mul(_amount, RAY) / chi);
}
function dsrWithdraw(uint _amount, bool _toUser) internal {
VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat();
uint chi = PotLike(POT_ADDRESS).drip();
uint pie = mul(_amount, RAY) / chi;
PotLike(POT_ADDRESS).exit(pie);
uint balance = DaiJoinLike(DAI_JOIN_ADDRESS).vat().dai(address(this));
if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) {
vat.hope(DAI_JOIN_ADDRESS);
}
address to;
if (_toUser) {
to = msg.sender;
} else {
to = address(this);
}
if (_amount == uint(-1)) {
DaiJoinLike(DAI_JOIN_ADDRESS).exit(to, mul(chi, pie) / RAY);
} else {
DaiJoinLike(DAI_JOIN_ADDRESS).exit(
to,
balance >= mul(_amount, RAY) ? _amount : balance / RAY
);
}
}
function daiJoin_join(address apt, address urn, uint wad, bool _fromUser) internal {
if (_fromUser) {
DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad);
}
DaiJoinLike(apt).dai().approve(apt, wad);
DaiJoinLike(apt).join(urn, wad);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../ProtocolInterface.sol";
import "../../interfaces/CTokenInterface.sol";
import "../../compound/helpers/Exponential.sol";
import "../../interfaces/ERC20.sol";
contract CompoundSavingsProtocol {
address public constant NEW_CDAI_ADDRESS = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
CTokenInterface public constant cDaiContract = CTokenInterface(NEW_CDAI_ADDRESS);
function compDeposit(address _user, uint _amount) internal {
// get dai from user
require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount));
// mainnet only
ERC20(DAI_ADDRESS).approve(NEW_CDAI_ADDRESS, uint(-1));
// mint cDai
require(cDaiContract.mint(_amount) == 0, "Failed Mint");
}
function compWithdraw(address _user, uint _amount) internal {
// transfer all users balance to this contract
require(cDaiContract.transferFrom(_user, address(this), ERC20(NEW_CDAI_ADDRESS).balanceOf(_user)));
// approve cDai to compound contract
cDaiContract.approve(NEW_CDAI_ADDRESS, uint(-1));
// get dai from cDai contract
require(cDaiContract.redeemUnderlying(_amount) == 0, "Reedem Failed");
// return to user balance we didn't spend
uint cDaiBalance = cDaiContract.balanceOf(address(this));
if (cDaiBalance > 0) {
cDaiContract.transfer(_user, cDaiBalance);
}
// return dai we have to user
ERC20(DAI_ADDRESS).transfer(_user, _amount);
}
}
pragma solidity ^0.6.0;
import "./CarefulMath.sol";
contract Exponential is CarefulMath {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
}
pragma solidity ^0.6.0;
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../ProtocolInterface.sol";
import "./ISoloMargin.sol";
import "../../interfaces/ERC20.sol";
import "../../DS/DSAuth.sol";
contract DydxSavingsProtocol is ProtocolInterface, DSAuth {
address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
ISoloMargin public soloMargin;
address public savingsProxy;
uint daiMarketId = 3;
constructor() public {
soloMargin = ISoloMargin(SOLO_MARGIN_ADDRESS);
}
function addSavingsProxy(address _savingsProxy) public auth {
savingsProxy = _savingsProxy;
}
function deposit(address _user, uint _amount) public override {
require(msg.sender == _user);
Account.Info[] memory accounts = new Account.Info[](1);
accounts[0] = getAccount(_user, 0);
Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1);
Types.AssetAmount memory amount = Types.AssetAmount({
sign: true,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: _amount
});
actions[0] = Actions.ActionArgs({
actionType: Actions.ActionType.Deposit,
accountId: 0,
amount: amount,
primaryMarketId: daiMarketId,
otherAddress: _user,
secondaryMarketId: 0, //not used
otherAccountId: 0, //not used
data: "" //not used
});
soloMargin.operate(accounts, actions);
}
function withdraw(address _user, uint _amount) public override {
require(msg.sender == _user);
Account.Info[] memory accounts = new Account.Info[](1);
accounts[0] = getAccount(_user, 0);
Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1);
Types.AssetAmount memory amount = Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: _amount
});
actions[0] = Actions.ActionArgs({
actionType: Actions.ActionType.Withdraw,
accountId: 0,
amount: amount,
primaryMarketId: daiMarketId,
otherAddress: _user,
secondaryMarketId: 0, //not used
otherAccountId: 0, //not used
data: "" //not used
});
soloMargin.operate(accounts, actions);
}
function getWeiBalance(address _user, uint _index) public view returns(Types.Wei memory) {
Types.Wei[] memory weiBalances;
(,,weiBalances) = soloMargin.getAccountBalances(getAccount(_user, _index));
return weiBalances[daiMarketId];
}
function getParBalance(address _user, uint _index) public view returns(Types.Par memory) {
Types.Par[] memory parBalances;
(,parBalances,) = soloMargin.getAccountBalances(getAccount(_user, _index));
return parBalances[daiMarketId];
}
function getAccount(address _user, uint _index) public pure returns(Account.Info memory) {
Account.Info memory account = Account.Info({
owner: _user,
number: _index
});
return account;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../savings/dydx/ISoloMargin.sol";
import "../../utils/SafeERC20.sol";
import "../../interfaces/TokenInterface.sol";
import "../../DS/DSProxy.sol";
import "../AaveHelperV2.sol";
import "../../auth/AdminAuth.sol";
import "../../exchangeV3/DFSExchangeData.sol";
/// @title Import Aave position from account to wallet
contract AaveSaverReceiverV2 is AaveHelperV2, AdminAuth, DFSExchangeData {
using SafeERC20 for ERC20;
address public constant AAVE_SAVER_PROXY = 0xBBCD23145Ab10C369c9e5D3b1D58506B0cD2ab44;
address public constant AAVE_BASIC_PROXY = 0xc17c8eB12Ba24D62E69fd57cbd504EEf418867f9;
address public constant AETH_ADDRESS = 0x030bA81f1c18d280636F32af80b9AAd02Cf0854e;
function callFunction(
address sender,
Account.Info memory account,
bytes memory data
) public {
(
bytes memory exchangeDataBytes,
address market,
uint256 rateMode,
uint256 gasCost,
bool isRepay,
uint256 ethAmount,
uint256 txValue,
address user,
address proxy
)
= abi.decode(data, (bytes,address,uint256,uint256,bool,uint256,uint256,address,address));
// withdraw eth
TokenInterface(WETH_ADDRESS).withdraw(ethAmount);
// deposit eth on behalf of proxy
DSProxy(payable(proxy)).execute{value: ethAmount}(AAVE_BASIC_PROXY, abi.encodeWithSignature("deposit(address,address,uint256)", market, ETH_ADDR, ethAmount));
bytes memory functionData = packFunctionCall(market, exchangeDataBytes, rateMode, gasCost, isRepay);
DSProxy(payable(proxy)).execute{value: txValue}(AAVE_SAVER_PROXY, functionData);
// withdraw deposited eth
DSProxy(payable(proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256)", market, ETH_ADDR, ethAmount));
// deposit eth, get weth and return to sender
TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)();
ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2);
}
function packFunctionCall(address _market, bytes memory _exchangeDataBytes, uint256 _rateMode, uint256 _gasCost, bool _isRepay) internal returns (bytes memory) {
ExchangeData memory exData = unpackExchangeData(_exchangeDataBytes);
bytes memory functionData;
if (_isRepay) {
functionData = abi.encodeWithSignature("repay(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256)", _market, exData, _rateMode, _gasCost);
} else {
functionData = abi.encodeWithSignature("boost(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256)", _market, exData, _rateMode, _gasCost);
}
return functionData;
}
/// @dev if contract receive eth, convert it to WETH
receive() external payable {
// deposit eth and get weth
if (msg.sender == owner) {
TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)();
}
}
}
pragma solidity ^0.6.0;
import "../DS/DSMath.sol";
import "../DS/DSProxy.sol";
import "../utils/Discount.sol";
import "../interfaces/IFeeRecipient.sol";
import "../interfaces/IAToken.sol";
import "../interfaces/ILendingPoolV2.sol";
import "../interfaces/IPriceOracleGetterAave.sol";
import "../interfaces/IAaveProtocolDataProviderV2.sol";
import "../utils/SafeERC20.sol";
import "../utils/BotRegistry.sol";
contract AaveHelperV2 is DSMath {
using SafeERC20 for ERC20;
IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A);
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // mainnet
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint public constant NINETY_NINE_PERCENT_WEI = 990000000000000000;
uint16 public constant AAVE_REFERRAL_CODE = 64;
uint public constant STABLE_ID = 1;
uint public constant VARIABLE_ID = 2;
/// @notice Calculates the gas cost for transaction
/// @param _oracleAddress address of oracle used
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _tokenAddr token addr. of token we are getting for the fee
/// @return gasCost The amount we took for the gas cost
function getGasCost(address _oracleAddress, uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint gasCost) {
if (_gasCost == 0) return 0;
uint256 price = IPriceOracleGetterAave(_oracleAddress).getAssetPrice(_tokenAddr);
_gasCost = wdiv(_gasCost, price) / (10 ** (18 - _getDecimals(_tokenAddr)));
gasCost = _gasCost;
// gas cost can't go over 10% of the whole amount
if (gasCost > (_amount / 10)) {
gasCost = _amount / 10;
}
address walletAddr = feeRecipient.getFeeAddr();
if (_tokenAddr == ETH_ADDR) {
payable(walletAddr).transfer(gasCost);
} else {
ERC20(_tokenAddr).safeTransfer(walletAddr, gasCost);
}
}
/// @notice Returns the owner of the DSProxy that called the contract
function getUserAddress() internal view returns (address) {
DSProxy proxy = DSProxy(payable(address(this)));
return proxy.owner();
}
/// @notice Approves token contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _caller Address which will gain the approval
function approveToken(address _tokenAddr, address _caller) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_caller, uint256(-1));
}
}
/// @notice Send specific amount from contract to specific user
/// @param _token Token we are trying to send
/// @param _user User that should receive funds
/// @param _amount Amount that should be sent
function sendContractBalance(address _token, address _user, uint _amount) internal {
if (_amount == 0) return;
if (_token == ETH_ADDR) {
payable(_user).transfer(_amount);
} else {
ERC20(_token).safeTransfer(_user, _amount);
}
}
function sendFullContractBalance(address _token, address _user) internal {
if (_token == ETH_ADDR) {
sendContractBalance(_token, _user, address(this).balance);
} else {
sendContractBalance(_token, _user, ERC20(_token).balanceOf(address(this)));
}
}
function _getDecimals(address _token) internal view returns (uint256) {
if (_token == ETH_ADDR) return 18;
return ERC20(_token).decimals();
}
function getDataProvider(address _market) internal view returns(IAaveProtocolDataProviderV2) {
return IAaveProtocolDataProviderV2(ILendingPoolAddressesProviderV2(_market).getAddress(0x0100000000000000000000000000000000000000000000000000000000000000));
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/**
* @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 ILendingPoolAddressesProviderV2 {
event LendingPoolUpdated(address indexed newAddress);
event ConfigurationAdminUpdated(address indexed newAddress);
event EmergencyAdminUpdated(address indexed newAddress);
event LendingPoolConfiguratorUpdated(address indexed newAddress);
event LendingPoolCollateralManagerUpdated(address indexed newAddress);
event PriceOracleUpdated(address indexed newAddress);
event LendingRateOracleUpdated(address indexed newAddress);
event ProxyCreated(bytes32 id, address indexed newAddress);
event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy);
function setAddress(bytes32 id, address newAddress) external;
function setAddressAsProxy(bytes32 id, address impl) external;
function getAddress(bytes32 id) external view returns (address);
function getLendingPool() external view returns (address);
function setLendingPoolImpl(address pool) external;
function getLendingPoolConfigurator() external view returns (address);
function setLendingPoolConfiguratorImpl(address configurator) external;
function getLendingPoolCollateralManager() external view returns (address);
function setLendingPoolCollateralManager(address manager) external;
function getPoolAdmin() external view returns (address);
function setPoolAdmin(address admin) external;
function getEmergencyAdmin() external view returns (address);
function setEmergencyAdmin(address admin) external;
function getPriceOracle() external view returns (address);
function setPriceOracle(address priceOracle) external;
function getLendingRateOracle() external view returns (address);
function setLendingRateOracle(address lendingRateOracle) external;
}
library DataTypes {
// refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties.
struct ReserveData {
//stores the reserve configuration
ReserveConfigurationMap configuration;
//the liquidity index. Expressed in ray
uint128 liquidityIndex;
//variable borrow index. Expressed in ray
uint128 variableBorrowIndex;
//the current supply rate. Expressed in ray
uint128 currentLiquidityRate;
//the current variable borrow rate. Expressed in ray
uint128 currentVariableBorrowRate;
//the current stable borrow rate. Expressed in ray
uint128 currentStableBorrowRate;
uint40 lastUpdateTimestamp;
//tokens addresses
address aTokenAddress;
address stableDebtTokenAddress;
address variableDebtTokenAddress;
//address of the interest rate strategy
address interestRateStrategyAddress;
//the id of the reserve. Represents the position in the list of the active reserves
uint8 id;
}
struct ReserveConfigurationMap {
//bit 0-15: LTV
//bit 16-31: Liq. threshold
//bit 32-47: Liq. bonus
//bit 48-55: Decimals
//bit 56: Reserve is active
//bit 57: reserve is frozen
//bit 58: borrowing is enabled
//bit 59: stable rate borrowing enabled
//bit 60-63: reserved
//bit 64-79: reserve factor
uint256 data;
}
struct UserConfigurationMap {
uint256 data;
}
enum InterestRateMode {NONE, STABLE, VARIABLE}
}
interface ILendingPoolV2 {
/**
* @dev Emitted on deposit()
* @param reserve The address of the underlying asset of the reserve
* @param user The address initiating the deposit
* @param onBehalfOf The beneficiary of the deposit, receiving the aTokens
* @param amount The amount deposited
* @param referral The referral code used
**/
event Deposit(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount,
uint16 indexed referral
);
/**
* @dev Emitted on withdraw()
* @param reserve The address of the underlyng asset being withdrawn
* @param user The address initiating the withdrawal, owner of aTokens
* @param to Address that will receive the underlying
* @param amount The amount to be withdrawn
**/
event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount);
/**
* @dev Emitted on borrow() and flashLoan() when debt needs to be opened
* @param reserve The address of the underlying asset being borrowed
* @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just
* initiator of the transaction on flashLoan()
* @param onBehalfOf The address that will be getting the debt
* @param amount The amount borrowed out
* @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable
* @param borrowRate The numeric rate at which the user has borrowed
* @param referral The referral code used
**/
event Borrow(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount,
uint256 borrowRateMode,
uint256 borrowRate,
uint16 indexed referral
);
/**
* @dev Emitted on repay()
* @param reserve The address of the underlying asset of the reserve
* @param user The beneficiary of the repayment, getting his debt reduced
* @param repayer The address of the user initiating the repay(), providing the funds
* @param amount The amount repaid
**/
event Repay(
address indexed reserve,
address indexed user,
address indexed repayer,
uint256 amount
);
/**
* @dev Emitted on swapBorrowRateMode()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user swapping his rate mode
* @param rateMode The rate mode that the user wants to swap to
**/
event Swap(address indexed reserve, address indexed user, uint256 rateMode);
/**
* @dev Emitted on setUserUseReserveAsCollateral()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user enabling the usage as collateral
**/
event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user);
/**
* @dev Emitted on setUserUseReserveAsCollateral()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user enabling the usage as collateral
**/
event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user);
/**
* @dev Emitted on rebalanceStableBorrowRate()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user for which the rebalance has been executed
**/
event RebalanceStableBorrowRate(address indexed reserve, address indexed user);
/**
* @dev Emitted on flashLoan()
* @param target The address of the flash loan receiver contract
* @param initiator The address initiating the flash loan
* @param asset The address of the asset being flash borrowed
* @param amount The amount flash borrowed
* @param premium The fee flash borrowed
* @param referralCode The referral code used
**/
event FlashLoan(
address indexed target,
address indexed initiator,
address indexed asset,
uint256 amount,
uint256 premium,
uint16 referralCode
);
/**
* @dev Emitted when the pause is triggered.
*/
event Paused();
/**
* @dev Emitted when the pause is lifted.
*/
event Unpaused();
/**
* @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via
* LendingPoolCollateral manager using a DELEGATECALL
* This allows to have the events in the generated ABI for LendingPool.
* @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
* @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
* @param user The address of the borrower getting liquidated
* @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
* @param liquidatedCollateralAmount The amount of collateral received by the liiquidator
* @param liquidator The address of the liquidator
* @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants
* to receive the underlying collateral asset directly
**/
event LiquidationCall(
address indexed collateralAsset,
address indexed debtAsset,
address indexed user,
uint256 debtToCover,
uint256 liquidatedCollateralAmount,
address liquidator,
bool receiveAToken
);
/**
* @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared
* in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal,
* the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it
* gets added to the LendingPool ABI
* @param reserve The address of the underlying asset of the reserve
* @param liquidityRate The new liquidity rate
* @param stableBorrowRate The new stable borrow rate
* @param variableBorrowRate The new variable borrow rate
* @param liquidityIndex The new liquidity index
* @param variableBorrowIndex The new variable borrow index
**/
event ReserveDataUpdated(
address indexed reserve,
uint256 liquidityRate,
uint256 stableBorrowRate,
uint256 variableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex
);
/**
* @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
**/
function withdraw(
address asset,
uint256 amount,
address to
) external;
/**
* @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower
* already deposited enough collateral, or he was given enough allowance by a credit delegator on the
* corresponding debt token (StableDebtToken or VariableDebtToken)
* - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet
* and 100 stable/variable debt tokens, depending on the `interestRateMode`
* @param asset The address of the underlying asset to borrow
* @param amount The amount to be borrowed
* @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable
* @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
* @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself
* calling the function if he wants to borrow against his own collateral, or the address of the credit delegator
* if he has been given credit delegation allowance
**/
function borrow(
address asset,
uint256 amount,
uint256 interestRateMode,
uint16 referralCode,
address onBehalfOf
) external;
/**
* @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned
* - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address
* @param asset The address of the borrowed underlying asset previously borrowed
* @param amount The amount to repay
* - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`
* @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable
* @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the
* user calling the function if he wants to reduce/remove his own debt, or the address of any other
* other borrower whose debt should be removed
**/
function repay(
address asset,
uint256 amount,
uint256 rateMode,
address onBehalfOf
) external;
/**
* @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa
* @param asset The address of the underlying asset borrowed
* @param rateMode The rate mode that the user wants to swap to
**/
function swapBorrowRateMode(address asset, uint256 rateMode) external;
/**
* @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve.
* - Users can be rebalanced if the following conditions are satisfied:
* 1. Usage ratio is above 95%
* 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been
* borrowed at a stable rate and depositors are not earning enough
* @param asset The address of the underlying asset borrowed
* @param user The address of the user to be rebalanced
**/
function rebalanceStableBorrowRate(address asset, address user) external;
/**
* @dev Allows depositors to enable/disable a specific deposited asset as collateral
* @param asset The address of the underlying asset deposited
* @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise
**/
function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external;
/**
* @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1
* - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives
* a proportionally amount of the `collateralAsset` plus a bonus to cover market risk
* @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
* @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
* @param user The address of the borrower getting liquidated
* @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
* @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants
* to receive the underlying collateral asset directly
**/
function liquidationCall(
address collateralAsset,
address debtAsset,
address user,
uint256 debtToCover,
bool receiveAToken
) external;
/**
* @dev Allows smartcontracts to access the liquidity of the pool within one transaction,
* as long as the amount taken plus a fee is returned.
* IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration.
* For further details please visit https://developers.aave.com
* @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface
* @param assets The addresses of the assets being flash-borrowed
* @param amounts The amounts amounts being flash-borrowed
* @param modes Types of the debt to open if the flash loan is not returned:
* 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver
* 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
* 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
* @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2
* @param params Variadic packed params to pass to the receiver as extra information
* @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 flashLoan(
address receiverAddress,
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata modes,
address onBehalfOf,
bytes calldata params,
uint16 referralCode
) external;
/**
* @dev Returns the user account data across all the reserves
* @param user The address of the user
* @return totalCollateralETH the total collateral in ETH of the user
* @return totalDebtETH the total debt in ETH of the user
* @return availableBorrowsETH the borrowing power left of the user
* @return currentLiquidationThreshold the liquidation threshold of the user
* @return ltv the loan to value of the user
* @return healthFactor the current health factor of the user
**/
function getUserAccountData(address user)
external
view
returns (
uint256 totalCollateralETH,
uint256 totalDebtETH,
uint256 availableBorrowsETH,
uint256 currentLiquidationThreshold,
uint256 ltv,
uint256 healthFactor
);
function initReserve(
address reserve,
address aTokenAddress,
address stableDebtAddress,
address variableDebtAddress,
address interestRateStrategyAddress
) external;
function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress)
external;
function setConfiguration(address reserve, uint256 configuration) external;
/**
* @dev Returns the configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The configuration of the reserve
**/
function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory);
/**
* @dev Returns the configuration of the user across all the reserves
* @param user The user address
* @return The configuration of the user
**/
function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory);
/**
* @dev Returns the normalized income normalized income of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The reserve's normalized income
*/
function getReserveNormalizedIncome(address asset) external view returns (uint256);
/**
* @dev Returns the normalized variable debt per unit of asset
* @param asset The address of the underlying asset of the reserve
* @return The reserve normalized variable debt
*/
function getReserveNormalizedVariableDebt(address asset) external view returns (uint256);
/**
* @dev Returns the state and configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The state of the reserve
**/
function getReserveData(address asset) external view returns (DataTypes.ReserveData memory);
function finalizeTransfer(
address asset,
address from,
address to,
uint256 amount,
uint256 balanceFromAfter,
uint256 balanceToBefore
) external;
function getReservesList() external view returns (address[] memory);
function getAddressesProvider() external view returns (ILendingPoolAddressesProviderV2);
function setPause(bool val) external;
function paused() external view returns (bool);
}
pragma solidity ^0.6.0;
/************
@title IPriceOracleGetterAave interface
@notice Interface for the Aave price oracle.*/
abstract contract IPriceOracleGetterAave {
function getAssetPrice(address _asset) external virtual view returns (uint256);
function getAssetsPrices(address[] calldata _assets) external virtual view returns(uint256[] memory);
function getSourceOfAsset(address _asset) external virtual view returns(address);
function getFallbackOracle() external virtual view returns(address);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.6.8;
pragma experimental ABIEncoderV2;
abstract contract IAaveProtocolDataProviderV2 {
struct TokenData {
string symbol;
address tokenAddress;
}
function getAllReservesTokens() external virtual view returns (TokenData[] memory);
function getAllATokens() external virtual view returns (TokenData[] memory);
function getReserveConfigurationData(address asset)
external virtual
view
returns (
uint256 decimals,
uint256 ltv,
uint256 liquidationThreshold,
uint256 liquidationBonus,
uint256 reserveFactor,
bool usageAsCollateralEnabled,
bool borrowingEnabled,
bool stableBorrowRateEnabled,
bool isActive,
bool isFrozen
);
function getReserveData(address asset)
external virtual
view
returns (
uint256 availableLiquidity,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 stableBorrowRate,
uint256 averageStableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
uint40 lastUpdateTimestamp
);
function getUserReserveData(address asset, address user)
external virtual
view
returns (
uint256 currentATokenBalance,
uint256 currentStableDebt,
uint256 currentVariableDebt,
uint256 principalStableDebt,
uint256 scaledVariableDebt,
uint256 stableBorrowRate,
uint256 liquidityRate,
uint40 stableRateLastUpdated,
bool usageAsCollateralEnabled
);
function getReserveTokensAddresses(address asset)
external virtual
view
returns (
address aTokenAddress,
address stableDebtTokenAddress,
address variableDebtTokenAddress
);
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../mcd/saver/MCDSaverProxy.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../interfaces/ILendingPool.sol";
import "../../exchangeV3/DFSExchangeData.sol";
import "../../utils/GasBurner.sol";
abstract contract IMCDSubscriptions {
function unsubscribe(uint256 _cdpId) external virtual ;
function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool);
}
contract MCDCloseTaker is MCDSaverProxyHelper, GasBurner {
address public constant SUBSCRIPTION_ADDRESS_NEW = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(DEFISAVER_LOGGER);
struct CloseData {
uint cdpId;
address joinAddr;
uint collAmount;
uint daiAmount;
uint minAccepted;
bool wholeDebt;
bool toDai;
ManagerType managerType;
}
Vat public constant vat = Vat(VAT_ADDRESS);
Spotter public constant spotter = Spotter(SPOTTER_ADDRESS);
function closeWithLoan(
DFSExchangeData.ExchangeData memory _exchangeData,
CloseData memory _closeData,
address payable mcdCloseFlashLoan
) public payable burnGas(20) {
mcdCloseFlashLoan.transfer(msg.value); // 0x fee
address managerAddr = getManagerAddr(_closeData.managerType);
if (_closeData.wholeDebt) {
_closeData.daiAmount = getAllDebt(
VAT_ADDRESS,
Manager(managerAddr).urns(_closeData.cdpId),
Manager(managerAddr).urns(_closeData.cdpId),
Manager(managerAddr).ilks(_closeData.cdpId)
);
(_closeData.collAmount, )
= getCdpInfo(Manager(managerAddr), _closeData.cdpId, Manager(managerAddr).ilks(_closeData.cdpId));
}
Manager(managerAddr).cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 1);
bytes memory packedData = _packData(_closeData, _exchangeData);
bytes memory paramsData = abi.encode(address(this), packedData);
lendingPool.flashLoan(mcdCloseFlashLoan, DAI_ADDRESS, _closeData.daiAmount, paramsData);
Manager(managerAddr).cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 0);
// If sub. to automatic protection unsubscribe
unsubscribe(SUBSCRIPTION_ADDRESS_NEW, _closeData.cdpId);
logger.Log(address(this), msg.sender, "MCDClose", abi.encode(_closeData.cdpId, _closeData.collAmount, _closeData.daiAmount, _closeData.toDai));
}
/// @notice Gets the maximum amount of debt available to generate
/// @param _managerAddr Address of the CDP Manager
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getMaxDebt(address _managerAddr, uint256 _cdpId, bytes32 _ilk) public view returns (uint256) {
uint256 price = getPrice(_ilk);
(, uint256 mat) = spotter.ilks(_ilk);
(uint256 collateral, uint256 debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk);
return sub(wdiv(wmul(collateral, price), mat), debt);
}
/// @notice Gets a price of the asset
/// @param _ilk Ilk of the CDP
function getPrice(bytes32 _ilk) public view returns (uint256) {
(, uint256 mat) = spotter.ilks(_ilk);
(, , uint256 spot, , ) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
function unsubscribe(address _subContract, uint _cdpId) internal {
(, bool isSubscribed) = IMCDSubscriptions(_subContract).subscribersPos(_cdpId);
if (isSubscribed) {
IMCDSubscriptions(_subContract).unsubscribe(_cdpId);
}
}
function _packData(
CloseData memory _closeData,
DFSExchangeData.ExchangeData memory _exchangeData
) internal pure returns (bytes memory) {
return abi.encode(_closeData, _exchangeData);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../interfaces/ILoanShifter.sol";
import "../../mcd/saver/MCDSaverProxy.sol";
import "../../mcd/create/MCDCreateProxyActions.sol";
contract McdShifter is MCDSaverProxy {
using SafeERC20 for ERC20;
Manager manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
address public constant OPEN_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305;
function getLoanAmount(uint _cdpId, address _joinAddr) public view virtual returns(uint loanAmount) {
bytes32 ilk = manager.ilks(_cdpId);
(, uint rate,,,) = vat.ilks(ilk);
(, uint art) = vat.urns(ilk, manager.urns(_cdpId));
uint dai = vat.dai(manager.urns(_cdpId));
uint rad = sub(mul(art, rate), dai);
loanAmount = rad / RAY;
loanAmount = mul(loanAmount, RAY) < rad ? loanAmount + 1 : loanAmount;
}
function close(
uint _cdpId,
address _joinAddr,
uint _loanAmount,
uint _collateral
) public {
address owner = getOwner(manager, _cdpId);
bytes32 ilk = manager.ilks(_cdpId);
(uint maxColl, ) = getCdpInfo(manager, _cdpId, ilk);
// repay dai debt cdp
paybackDebt(address(manager), _cdpId, ilk, _loanAmount, owner);
maxColl = _collateral > maxColl ? maxColl : _collateral;
// withdraw collateral from cdp
drawCollateral(address(manager), _cdpId, _joinAddr, maxColl);
// send back to msg.sender
if (isEthJoinAddr(_joinAddr)) {
msg.sender.transfer(address(this).balance);
} else {
ERC20 collToken = ERC20(getCollateralAddr(_joinAddr));
collToken.safeTransfer(msg.sender, collToken.balanceOf(address(this)));
}
}
function open(
uint _cdpId,
address _joinAddr,
uint _debtAmount
) public {
uint collAmount = 0;
if (isEthJoinAddr(_joinAddr)) {
collAmount = address(this).balance;
} else {
collAmount = ERC20(address(Join(_joinAddr).gem())).balanceOf(address(this));
}
if (_cdpId == 0) {
openAndWithdraw(collAmount, _debtAmount, address(this), _joinAddr);
} else {
// add collateral
addCollateral(address(manager), _cdpId, _joinAddr, collAmount);
// draw debt
drawDai(address(manager), _cdpId, manager.ilks(_cdpId), _debtAmount);
}
// transfer to repay FL
ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this)));
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
function openAndWithdraw(uint _collAmount, uint _debtAmount, address _proxy, address _joinAddrTo) internal {
bytes32 ilk = Join(_joinAddrTo).ilk();
if (isEthJoinAddr(_joinAddrTo)) {
MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}(
address(manager),
JUG_ADDRESS,
_joinAddrTo,
DAI_JOIN_ADDRESS,
ilk,
_debtAmount,
_proxy
);
} else {
ERC20(getCollateralAddr(_joinAddrTo)).approve(OPEN_PROXY_ACTIONS, uint256(-1));
MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockGemAndDraw(
address(manager),
JUG_ADDRESS,
_joinAddrTo,
DAI_JOIN_ADDRESS,
ilk,
_collAmount,
_debtAmount,
true,
_proxy
);
}
}
}
pragma solidity ^0.6.0;
abstract contract GemLike {
function approve(address, uint256) public virtual;
function transfer(address, uint256) public virtual;
function transferFrom(address, address, uint256) public virtual;
function deposit() public virtual payable;
function withdraw(uint256) public virtual;
}
abstract contract ManagerLike {
function cdpCan(address, uint256, address) public virtual view returns (uint256);
function ilks(uint256) public virtual view returns (bytes32);
function owns(uint256) public virtual view returns (address);
function urns(uint256) public virtual view returns (address);
function vat() public virtual view returns (address);
function open(bytes32, address) public virtual returns (uint256);
function give(uint256, address) public virtual;
function cdpAllow(uint256, address, uint256) public virtual;
function urnAllow(address, uint256) public virtual;
function frob(uint256, int256, int256) public virtual;
function flux(uint256, address, uint256) public virtual;
function move(uint256, address, uint256) public virtual;
function exit(address, uint256, address, uint256) public virtual;
function quit(uint256, address) public virtual;
function enter(address, uint256) public virtual;
function shift(uint256, uint256) public virtual;
}
abstract contract VatLike {
function can(address, address) public virtual view returns (uint256);
function ilks(bytes32) public virtual view returns (uint256, uint256, uint256, uint256, uint256);
function dai(address) public virtual view returns (uint256);
function urns(bytes32, address) public virtual view returns (uint256, uint256);
function frob(bytes32, address, address, address, int256, int256) public virtual;
function hope(address) public virtual;
function move(address, address, uint256) public virtual;
}
abstract contract GemJoinLike {
function dec() public virtual returns (uint256);
function gem() public virtual returns (GemLike);
function join(address, uint256) public virtual payable;
function exit(address, uint256) public virtual;
}
abstract contract GNTJoinLike {
function bags(address) public virtual view returns (address);
function make(address) public virtual returns (address);
}
abstract contract DaiJoinLike {
function vat() public virtual returns (VatLike);
function dai() public virtual returns (GemLike);
function join(address, uint256) public virtual payable;
function exit(address, uint256) public virtual;
}
abstract contract HopeLike {
function hope(address) public virtual;
function nope(address) public virtual;
}
abstract contract ProxyRegistryInterface {
function build(address) public virtual returns (address);
}
abstract contract EndLike {
function fix(bytes32) public virtual view returns (uint256);
function cash(bytes32, uint256) public virtual;
function free(bytes32) public virtual;
function pack(uint256) public virtual;
function skim(bytes32, address) public virtual;
}
abstract contract JugLike {
function drip(bytes32) public virtual returns (uint256);
}
abstract contract PotLike {
function pie(address) public virtual view returns (uint256);
function drip() public virtual returns (uint256);
function join(uint256) public virtual;
function exit(uint256) public virtual;
}
abstract contract ProxyRegistryLike {
function proxies(address) public virtual view returns (address);
function build(address) public virtual returns (address);
}
abstract contract ProxyLike {
function owner() public virtual view returns (address);
}
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// WARNING: These functions meant to be used as a a library for a DSProxy. Some are unsafe if you call them directly.
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
contract Common {
uint256 constant RAY = 10**27;
// Internal functions
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "mul-overflow");
}
// Public functions
// solhint-disable-next-line func-name-mixedcase
function daiJoin_join(address apt, address urn, uint256 wad) public {
// Gets DAI from the user's wallet
DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad);
// Approves adapter to take the DAI amount
DaiJoinLike(apt).dai().approve(apt, wad);
// Joins DAI into the vat
DaiJoinLike(apt).join(urn, wad);
}
}
contract MCDCreateProxyActions is Common {
// Internal functions
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "sub-overflow");
}
function toInt(uint256 x) internal pure returns (int256 y) {
y = int256(x);
require(y >= 0, "int-overflow");
}
function toRad(uint256 wad) internal pure returns (uint256 rad) {
rad = mul(wad, 10**27);
}
function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) {
// For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function
// Adapters will automatically handle the difference of precision
wad = mul(amt, 10**(18 - GemJoinLike(gemJoin).dec()));
}
function _getDrawDart(address vat, address jug, address urn, bytes32 ilk, uint256 wad)
internal
returns (int256 dart)
{
// Updates stability fee rate
uint256 rate = JugLike(jug).drip(ilk);
// Gets DAI balance of the urn in the vat
uint256 dai = VatLike(vat).dai(urn);
// If there was already enough DAI in the vat balance, just exits it without adding more debt
if (dai < mul(wad, RAY)) {
// Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens
dart = toInt(sub(mul(wad, RAY), dai) / rate);
// This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount)
dart = mul(uint256(dart), rate) < mul(wad, RAY) ? dart + 1 : dart;
}
}
function _getWipeDart(address vat, uint256 dai, address urn, bytes32 ilk)
internal
view
returns (int256 dart)
{
// Gets actual rate from the vat
(, uint256 rate, , , ) = VatLike(vat).ilks(ilk);
// Gets actual art value of the urn
(, uint256 art) = VatLike(vat).urns(ilk, urn);
// Uses the whole dai balance in the vat to reduce the debt
dart = toInt(dai / rate);
// Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value
dart = uint256(dart) <= art ? -dart : -toInt(art);
}
function _getWipeAllWad(address vat, address usr, address urn, bytes32 ilk)
internal
view
returns (uint256 wad)
{
// Gets actual rate from the vat
(, uint256 rate, , , ) = VatLike(vat).ilks(ilk);
// Gets actual art value of the urn
(, uint256 art) = VatLike(vat).urns(ilk, urn);
// Gets actual dai amount in the urn
uint256 dai = VatLike(vat).dai(usr);
uint256 rad = sub(mul(art, rate), dai);
wad = rad / RAY;
// If the rad precision has some dust, it will need to request for 1 extra wad wei
wad = mul(wad, RAY) < rad ? wad + 1 : wad;
}
// Public functions
function transfer(address gem, address dst, uint256 wad) public {
GemLike(gem).transfer(dst, wad);
}
// solhint-disable-next-line func-name-mixedcase
function ethJoin_join(address apt, address urn) public payable {
// Wraps ETH in WETH
GemJoinLike(apt).gem().deposit{value: msg.value}();
// Approves adapter to take the WETH amount
GemJoinLike(apt).gem().approve(address(apt), msg.value);
// Joins WETH collateral into the vat
GemJoinLike(apt).join(urn, msg.value);
}
// solhint-disable-next-line func-name-mixedcase
function gemJoin_join(address apt, address urn, uint256 wad, bool transferFrom) public {
// Only executes for tokens that have approval/transferFrom implementation
if (transferFrom) {
// Gets token from the user's wallet
GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), wad);
// Approves adapter to take the token amount
GemJoinLike(apt).gem().approve(apt, 0);
GemJoinLike(apt).gem().approve(apt, wad);
}
// Joins token collateral into the vat
GemJoinLike(apt).join(urn, wad);
}
function hope(address obj, address usr) public {
HopeLike(obj).hope(usr);
}
function nope(address obj, address usr) public {
HopeLike(obj).nope(usr);
}
function open(address manager, bytes32 ilk, address usr) public returns (uint256 cdp) {
cdp = ManagerLike(manager).open(ilk, usr);
}
function give(address manager, uint256 cdp, address usr) public {
ManagerLike(manager).give(cdp, usr);
}
function move(address manager, uint256 cdp, address dst, uint256 rad) public {
ManagerLike(manager).move(cdp, dst, rad);
}
function frob(address manager, uint256 cdp, int256 dink, int256 dart) public {
ManagerLike(manager).frob(cdp, dink, dart);
}
function lockETH(address manager, address ethJoin, uint256 cdp) public payable {
// Receives ETH amount, converts it to WETH and joins it into the vat
ethJoin_join(ethJoin, address(this));
// Locks WETH amount into the CDP
VatLike(ManagerLike(manager).vat()).frob(
ManagerLike(manager).ilks(cdp),
ManagerLike(manager).urns(cdp),
address(this),
address(this),
toInt(msg.value),
0
);
}
function lockGem(address manager, address gemJoin, uint256 cdp, uint256 wad, bool transferFrom)
public
{
// Takes token amount from user's wallet and joins into the vat
gemJoin_join(gemJoin, address(this), wad, transferFrom);
// Locks token amount into the CDP
VatLike(ManagerLike(manager).vat()).frob(
ManagerLike(manager).ilks(cdp),
ManagerLike(manager).urns(cdp),
address(this),
address(this),
toInt(convertTo18(gemJoin, wad)),
0
);
}
function draw(address manager, address jug, address daiJoin, uint256 cdp, uint256 wad) public {
address urn = ManagerLike(manager).urns(cdp);
address vat = ManagerLike(manager).vat();
bytes32 ilk = ManagerLike(manager).ilks(cdp);
// Generates debt in the CDP
frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad));
// Moves the DAI amount (balance in the vat in rad) to proxy's address
move(manager, cdp, address(this), toRad(wad));
// Allows adapter to access to proxy's DAI balance in the vat
if (VatLike(vat).can(address(this), address(daiJoin)) == 0) {
VatLike(vat).hope(daiJoin);
}
// Exits DAI to the user's wallet as a token
DaiJoinLike(daiJoin).exit(msg.sender, wad);
}
function lockETHAndDraw(
address manager,
address jug,
address ethJoin,
address daiJoin,
uint256 cdp,
uint256 wadD
) public payable {
address urn = ManagerLike(manager).urns(cdp);
address vat = ManagerLike(manager).vat();
bytes32 ilk = ManagerLike(manager).ilks(cdp);
// Receives ETH amount, converts it to WETH and joins it into the vat
ethJoin_join(ethJoin, urn);
// Locks WETH amount into the CDP and generates debt
frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD));
// Moves the DAI amount (balance in the vat in rad) to proxy's address
move(manager, cdp, address(this), toRad(wadD));
// Allows adapter to access to proxy's DAI balance in the vat
if (VatLike(vat).can(address(this), address(daiJoin)) == 0) {
VatLike(vat).hope(daiJoin);
}
// Exits DAI to the user's wallet as a token
DaiJoinLike(daiJoin).exit(msg.sender, wadD);
}
function openLockETHAndDraw(
address manager,
address jug,
address ethJoin,
address daiJoin,
bytes32 ilk,
uint256 wadD,
address owner
) public payable returns (uint256 cdp) {
cdp = open(manager, ilk, address(this));
lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD);
give(manager, cdp, owner);
}
function lockGemAndDraw(
address manager,
address jug,
address gemJoin,
address daiJoin,
uint256 cdp,
uint256 wadC,
uint256 wadD,
bool transferFrom
) public {
address urn = ManagerLike(manager).urns(cdp);
address vat = ManagerLike(manager).vat();
bytes32 ilk = ManagerLike(manager).ilks(cdp);
// Takes token amount from user's wallet and joins into the vat
gemJoin_join(gemJoin, urn, wadC, transferFrom);
// Locks token amount into the CDP and generates debt
frob(
manager,
cdp,
toInt(convertTo18(gemJoin, wadC)),
_getDrawDart(vat, jug, urn, ilk, wadD)
);
// Moves the DAI amount (balance in the vat in rad) to proxy's address
move(manager, cdp, address(this), toRad(wadD));
// Allows adapter to access to proxy's DAI balance in the vat
if (VatLike(vat).can(address(this), address(daiJoin)) == 0) {
VatLike(vat).hope(daiJoin);
}
// Exits DAI to the user's wallet as a token
DaiJoinLike(daiJoin).exit(msg.sender, wadD);
}
function openLockGemAndDraw(
address manager,
address jug,
address gemJoin,
address daiJoin,
bytes32 ilk,
uint256 wadC,
uint256 wadD,
bool transferFrom,
address owner
) public returns (uint256 cdp) {
cdp = open(manager, ilk, address(this));
lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, wadC, wadD, transferFrom);
give(manager, cdp, owner);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../exchangeV3/DFSExchangeCore.sol";
import "./MCDCreateProxyActions.sol";
import "../../utils/FlashLoanReceiverBase.sol";
import "../../interfaces/Manager.sol";
import "../../interfaces/Join.sol";
import "../../DS/DSProxy.sol";
import "./MCDCreateTaker.sol";
contract MCDCreateFlashLoan is DFSExchangeCore, AdminAuth, FlashLoanReceiverBase {
address public constant CREATE_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305;
uint public constant SERVICE_FEE = 400; // 0.25% Fee
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1;
address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {}
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
//check the contract has the specified balance
require(_amount <= getBalanceInternal(address(this), _reserve),
"Invalid balance for the contract");
(address proxy, bytes memory packedData) = abi.decode(_params, (address,bytes));
(MCDCreateTaker.CreateData memory createData, ExchangeData memory exchangeData) = abi.decode(packedData, (MCDCreateTaker.CreateData,ExchangeData));
exchangeData.dfsFeeDivider = SERVICE_FEE;
exchangeData.user = DSProxy(payable(proxy)).owner();
openAndLeverage(createData.collAmount, createData.daiAmount + _fee, createData.joinAddr, proxy, exchangeData);
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
function openAndLeverage(
uint _collAmount,
uint _daiAmountAndFee,
address _joinAddr,
address _proxy,
ExchangeData memory _exchangeData
) public {
(, uint256 collSwaped) = _sell(_exchangeData);
bytes32 ilk = Join(_joinAddr).ilk();
if (isEthJoinAddr(_joinAddr)) {
MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}(
MANAGER_ADDRESS,
JUG_ADDRESS,
_joinAddr,
DAI_JOIN_ADDRESS,
ilk,
_daiAmountAndFee,
_proxy
);
} else {
ERC20(address(Join(_joinAddr).gem())).safeApprove(CREATE_PROXY_ACTIONS, (_collAmount + collSwaped));
MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockGemAndDraw(
MANAGER_ADDRESS,
JUG_ADDRESS,
_joinAddr,
DAI_JOIN_ADDRESS,
ilk,
(_collAmount + collSwaped),
_daiAmountAndFee,
true,
_proxy
);
}
}
/// @notice Checks if the join address is one of the Ether coll. types
/// @param _joinAddr Join address to check
function isEthJoinAddr(address _joinAddr) internal view returns (bool) {
// if it's dai_join_addr don't check gem() it will fail
if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false;
// if coll is weth it's and eth type coll
if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) {
return true;
}
return false;
}
receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {}
}
pragma solidity ^0.6.0;
import "./SafeERC20.sol";
interface IFlashLoanReceiver {
function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external;
}
abstract contract ILendingPoolAddressesProvider {
function getLendingPool() public view virtual returns (address);
function setLendingPoolImpl(address _pool) public virtual;
function getLendingPoolCore() public virtual view returns (address payable);
function setLendingPoolCoreImpl(address _lendingPoolCore) public virtual;
function getLendingPoolConfigurator() public virtual view returns (address);
function setLendingPoolConfiguratorImpl(address _configurator) public virtual;
function getLendingPoolDataProvider() public virtual view returns (address);
function setLendingPoolDataProviderImpl(address _provider) public virtual;
function getLendingPoolParametersProvider() public virtual view returns (address);
function setLendingPoolParametersProviderImpl(address _parametersProvider) public virtual;
function getTokenDistributor() public virtual view returns (address);
function setTokenDistributor(address _tokenDistributor) public virtual;
function getFeeProvider() public virtual view returns (address);
function setFeeProviderImpl(address _feeProvider) public virtual;
function getLendingPoolLiquidationManager() public virtual view returns (address);
function setLendingPoolLiquidationManager(address _manager) public virtual;
function getLendingPoolManager() public virtual view returns (address);
function setLendingPoolManager(address _lendingPoolManager) public virtual;
function getPriceOracle() public virtual view returns (address);
function setPriceOracle(address _priceOracle) public virtual;
function getLendingRateOracle() public view virtual returns (address);
function setLendingRateOracle(address _lendingRateOracle) public virtual;
}
library EthAddressLib {
function ethAddress() internal pure returns(address) {
return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
}
}
abstract contract FlashLoanReceiverBase is IFlashLoanReceiver {
using SafeERC20 for ERC20;
using SafeMath for uint256;
ILendingPoolAddressesProvider public addressesProvider;
constructor(ILendingPoolAddressesProvider _provider) public {
addressesProvider = _provider;
}
receive () external virtual payable {}
function transferFundsBackToPoolInternal(address _reserve, uint256 _amount) internal {
address payable core = addressesProvider.getLendingPoolCore();
transferInternal(core,_reserve, _amount);
}
function transferInternal(address payable _destination, address _reserve, uint256 _amount) internal {
if(_reserve == EthAddressLib.ethAddress()) {
//solium-disable-next-line
_destination.call{value: _amount}("");
return;
}
ERC20(_reserve).safeTransfer(_destination, _amount);
}
function getBalanceInternal(address _target, address _reserve) internal view returns(uint256) {
if(_reserve == EthAddressLib.ethAddress()) {
return _target.balance;
}
return ERC20(_reserve).balanceOf(_target);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./saver/MCDSaverProxyHelper.sol";
import "../interfaces/Spotter.sol";
contract MCDLoanInfo is MCDSaverProxyHelper {
Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
Vat public constant vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B);
Spotter public constant spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3);
struct VaultInfo {
address owner;
uint256 ratio;
uint256 collateral;
uint256 debt;
bytes32 ilk;
address urn;
}
/// @notice Gets a price of the asset
/// @param _ilk Ilk of the CDP
function getPrice(bytes32 _ilk) public view returns (uint) {
(, uint mat) = spotter.ilks(_ilk);
(,,uint spot,,) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
/// @notice Gets CDP ratio
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getRatio(uint _cdpId, bytes32 _ilk) public view returns (uint) {
uint price = getPrice( _ilk);
(uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk);
if (debt == 0) return 0;
return rdiv(wmul(collateral, price), debt);
}
/// @notice Gets CDP info (collateral, debt, price, ilk)
/// @param _cdpId Id of the CDP
function getVaultInfo(uint _cdpId) public view returns (VaultInfo memory vaultInfo) {
address urn = manager.urns(_cdpId);
bytes32 ilk = manager.ilks(_cdpId);
(uint256 collateral, uint256 debt) = vat.urns(ilk, urn);
(,uint rate,,,) = vat.ilks(ilk);
debt = rmul(debt, rate);
vaultInfo = VaultInfo({
owner: manager.owns(_cdpId),
ratio: getRatio(_cdpId, ilk),
collateral: collateral,
debt: debt,
ilk: ilk,
urn: urn
});
}
function getVaultInfos(uint256[] memory _cdps) public view returns (VaultInfo[] memory vaultInfos) {
vaultInfos = new VaultInfo[](_cdps.length);
for (uint256 i = 0; i < _cdps.length; i++) {
vaultInfos[i] = getVaultInfo(_cdps[i]);
}
}
function getRatios(uint256[] memory _cdps) public view returns (uint[] memory ratios) {
ratios = new uint256[](_cdps.length);
for (uint256 i = 0; i<_cdps.length; i++) {
bytes32 ilk = manager.ilks(_cdps[i]);
ratios[i] = getRatio(_cdps[i], ilk);
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../interfaces/Manager.sol";
import "./StaticV2.sol";
import "../saver/MCDSaverProxy.sol";
import "../../interfaces/Vat.sol";
import "../../interfaces/Spotter.sol";
import "../../auth/AdminAuth.sol";
/// @title Handles subscriptions for automatic monitoring
contract SubscriptionsV2 is AdminAuth, StaticV2 {
bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000;
bytes32 internal constant BAT_ILK = 0x4241542d41000000000000000000000000000000000000000000000000000000;
address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
CdpHolder[] public subscribers;
mapping (uint => SubPosition) public subscribersPos;
mapping (bytes32 => uint) public minLimits;
uint public changeIndex;
Manager public manager = Manager(MANAGER_ADDRESS);
Vat public vat = Vat(VAT_ADDRESS);
Spotter public spotter = Spotter(SPOTTER_ADDRESS);
MCDSaverProxy public saverProxy;
event Subscribed(address indexed owner, uint cdpId);
event Unsubscribed(address indexed owner, uint cdpId);
event Updated(address indexed owner, uint cdpId);
event ParamUpdates(address indexed owner, uint cdpId, uint128, uint128, uint128, uint128, bool boostEnabled);
/// @param _saverProxy Address of the MCDSaverProxy contract
constructor(address _saverProxy) public {
saverProxy = MCDSaverProxy(payable(_saverProxy));
minLimits[ETH_ILK] = 1700000000000000000;
minLimits[BAT_ILK] = 1700000000000000000;
}
/// @dev Called by the DSProxy contract which owns the CDP
/// @notice Adds the users CDP in the list of subscriptions so it can be monitored
/// @param _cdpId Id of the CDP
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalBoost Ratio amount which boost should target
/// @param _optimalRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
/// @param _nextPriceEnabled Boolean determing if we can use nextPrice for this cdp
function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {
require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner");
// if boost is not enabled, set max ratio to max uint
uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1);
require(checkParams(manager.ilks(_cdpId), _minRatio, localMaxRatio), "Must be correct params");
SubPosition storage subInfo = subscribersPos[_cdpId];
CdpHolder memory subscription = CdpHolder({
minRatio: _minRatio,
maxRatio: localMaxRatio,
optimalRatioBoost: _optimalBoost,
optimalRatioRepay: _optimalRepay,
owner: msg.sender,
cdpId: _cdpId,
boostEnabled: _boostEnabled,
nextPriceEnabled: _nextPriceEnabled
});
changeIndex++;
if (subInfo.subscribed) {
subscribers[subInfo.arrPos] = subscription;
emit Updated(msg.sender, _cdpId);
emit ParamUpdates(msg.sender, _cdpId, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled);
} else {
subscribers.push(subscription);
subInfo.arrPos = subscribers.length - 1;
subInfo.subscribed = true;
emit Subscribed(msg.sender, _cdpId);
}
}
/// @notice Called by the users DSProxy
/// @dev Owner who subscribed cancels his subscription
function unsubscribe(uint _cdpId) external {
require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner");
_unsubscribe(_cdpId);
}
/// @dev Checks if the _owner is the owner of the CDP
function isOwner(address _owner, uint _cdpId) internal view returns (bool) {
return getOwner(_cdpId) == _owner;
}
/// @dev Checks limit for minimum ratio and if minRatio is bigger than max
function checkParams(bytes32 _ilk, uint128 _minRatio, uint128 _maxRatio) internal view returns (bool) {
if (_minRatio < minLimits[_ilk]) {
return false;
}
if (_minRatio > _maxRatio) {
return false;
}
return true;
}
/// @dev Internal method to remove a subscriber from the list
function _unsubscribe(uint _cdpId) internal {
require(subscribers.length > 0, "Must have subscribers in the list");
SubPosition storage subInfo = subscribersPos[_cdpId];
require(subInfo.subscribed, "Must first be subscribed");
uint lastCdpId = subscribers[subscribers.length - 1].cdpId;
SubPosition storage subInfo2 = subscribersPos[lastCdpId];
subInfo2.arrPos = subInfo.arrPos;
subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1];
subscribers.pop();
changeIndex++;
subInfo.subscribed = false;
subInfo.arrPos = 0;
emit Unsubscribed(msg.sender, _cdpId);
}
/// @notice Returns an address that owns the CDP
/// @param _cdpId Id of the CDP
function getOwner(uint _cdpId) public view returns(address) {
return manager.owns(_cdpId);
}
/// @notice Helper method for the front to get all the info about the subscribed CDP
function getSubscribedInfo(uint _cdpId) public view returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt) {
SubPosition memory subInfo = subscribersPos[_cdpId];
if (!subInfo.subscribed) return (false, 0, 0, 0, 0, address(0), 0, 0);
(coll, debt) = saverProxy.getCdpInfo(manager, _cdpId, manager.ilks(_cdpId));
CdpHolder memory subscriber = subscribers[subInfo.arrPos];
return (
true,
subscriber.minRatio,
subscriber.maxRatio,
subscriber.optimalRatioRepay,
subscriber.optimalRatioBoost,
subscriber.owner,
coll,
debt
);
}
function getCdpHolder(uint _cdpId) public view returns (bool subscribed, CdpHolder memory) {
SubPosition memory subInfo = subscribersPos[_cdpId];
if (!subInfo.subscribed) return (false, CdpHolder(0, 0, 0, 0, address(0), 0, false, false));
CdpHolder memory subscriber = subscribers[subInfo.arrPos];
return (true, subscriber);
}
/// @notice Helper method for the front to get the information about the ilk of a CDP
function getIlkInfo(bytes32 _ilk, uint _cdpId) public view returns(bytes32 ilk, uint art, uint rate, uint spot, uint line, uint dust, uint mat, uint par) {
// send either ilk or cdpId
if (_ilk == bytes32(0)) {
_ilk = manager.ilks(_cdpId);
}
ilk = _ilk;
(,mat) = spotter.ilks(_ilk);
par = spotter.par();
(art, rate, spot, line, dust) = vat.ilks(_ilk);
}
/// @notice Helper method to return all the subscribed CDPs
function getSubscribers() public view returns (CdpHolder[] memory) {
return subscribers;
}
/// @notice Helper method to return all the subscribed CDPs
function getSubscribersByPage(uint _page, uint _perPage) public view returns (CdpHolder[] memory) {
CdpHolder[] memory holders = new CdpHolder[](_perPage);
uint start = _page * _perPage;
uint end = start + _perPage;
uint count = 0;
for (uint i=start; i<end; i++) {
holders[count] = subscribers[i];
count++;
}
return holders;
}
////////////// ADMIN METHODS ///////////////////
/// @notice Admin function to change a min. limit for an asset
function changeMinRatios(bytes32 _ilk, uint _newRatio) public onlyOwner {
minLimits[_ilk] = _newRatio;
}
/// @notice Admin function to unsubscribe a CDP
function unsubscribeByAdmin(uint _cdpId) public onlyOwner {
SubPosition storage subInfo = subscribersPos[_cdpId];
if (subInfo.subscribed) {
_unsubscribe(_cdpId);
}
}
}
pragma solidity ^0.6.0;
/// @title Implements enum Method
abstract contract StaticV2 {
enum Method { Boost, Repay }
struct CdpHolder {
uint128 minRatio;
uint128 maxRatio;
uint128 optimalRatioBoost;
uint128 optimalRatioRepay;
address owner;
uint cdpId;
bool boostEnabled;
bool nextPriceEnabled;
}
struct SubPosition {
uint arrPos;
bool subscribed;
}
}
pragma solidity ^0.6.0;
import "../../interfaces/Join.sol";
import "../../interfaces/ERC20.sol";
import "../../interfaces/Vat.sol";
import "../../interfaces/Flipper.sol";
import "../../interfaces/Gem.sol";
contract BidProxy {
address public constant DAI_JOIN = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
function daiBid(uint _bidId, uint _amount, address _flipper) public {
uint tendAmount = _amount * (10 ** 27);
joinDai(_amount);
(, uint lot, , , , , , ) = Flipper(_flipper).bids(_bidId);
Vat(VAT_ADDRESS).hope(_flipper);
Flipper(_flipper).tend(_bidId, lot, tendAmount);
}
function collateralBid(uint _bidId, uint _amount, address _flipper) public {
(uint bid, , , , , , , ) = Flipper(_flipper).bids(_bidId);
joinDai(bid / (10**27));
Vat(VAT_ADDRESS).hope(_flipper);
Flipper(_flipper).dent(_bidId, _amount, bid);
}
function closeBid(uint _bidId, address _flipper, address _joinAddr) public {
bytes32 ilk = Join(_joinAddr).ilk();
Flipper(_flipper).deal(_bidId);
uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this));
Vat(VAT_ADDRESS).hope(_joinAddr);
Gem(_joinAddr).exit(msg.sender, amount);
}
function exitCollateral(address _joinAddr) public {
bytes32 ilk = Join(_joinAddr).ilk();
uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this));
if(Join(_joinAddr).dec() != 18) {
amount = amount / (10**(18 - Join(_joinAddr).dec()));
}
Vat(VAT_ADDRESS).hope(_joinAddr);
Gem(_joinAddr).exit(msg.sender, amount);
}
function exitDai() public {
uint amount = Vat(VAT_ADDRESS).dai(address(this)) / (10**27);
Vat(VAT_ADDRESS).hope(DAI_JOIN);
Gem(DAI_JOIN).exit(msg.sender, amount);
}
function withdrawToken(address _token) public {
uint balance = ERC20(_token).balanceOf(address(this));
ERC20(_token).transfer(msg.sender, balance);
}
function withdrawEth() public {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
function joinDai(uint _amount) internal {
uint amountInVat = Vat(VAT_ADDRESS).dai(address(this)) / (10**27);
if (_amount > amountInVat) {
uint amountDiff = (_amount - amountInVat) + 1;
ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), amountDiff);
ERC20(DAI_ADDRESS).approve(DAI_JOIN, amountDiff);
Join(DAI_JOIN).join(address(this), amountDiff);
}
}
}
pragma solidity ^0.6.0;
abstract contract Flipper {
function bids(uint _bidId) public virtual returns (uint256, uint256, address, uint48, uint48, address, address, uint256);
function tend(uint id, uint lot, uint bid) virtual external;
function dent(uint id, uint lot, uint bid) virtual external;
function deal(uint id) virtual external;
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../interfaces/Manager.sol";
import "../../interfaces/Vat.sol";
import "../../interfaces/Spotter.sol";
import "../../DS/DSMath.sol";
import "../../auth/AdminAuth.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../utils/GasBurner.sol";
import "../../utils/BotRegistry.sol";
import "../../exchangeV3/DFSExchangeData.sol";
import "./ISubscriptionsV2.sol";
import "./StaticV2.sol";
import "./MCDMonitorProxyV2.sol";
/// @title Implements logic that allows bots to call Boost and Repay
contract MCDMonitorV2 is DSMath, AdminAuth, GasBurner, StaticV2 {
uint public REPAY_GAS_TOKEN = 25;
uint public BOOST_GAS_TOKEN = 25;
uint public MAX_GAS_PRICE = 500000000000; // 500 gwei
uint public REPAY_GAS_COST = 1000000;
uint public BOOST_GAS_COST = 1000000;
bytes4 public REPAY_SELECTOR = 0xf360ce20;
bytes4 public BOOST_SELECTOR = 0x8ec2ae25;
MCDMonitorProxyV2 public monitorProxyContract;
ISubscriptionsV2 public subscriptionsContract;
address public mcdSaverTakerAddress;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
address public constant PROXY_PERMISSION_ADDR = 0x5a4f877CA808Cca3cB7c2A194F80Ab8588FAE26B;
Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
Vat public vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B);
Spotter public spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3);
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
modifier onlyApproved() {
require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot");
_;
}
constructor(address _monitorProxy, address _subscriptions, address _mcdSaverTakerAddress) public {
monitorProxyContract = MCDMonitorProxyV2(_monitorProxy);
subscriptionsContract = ISubscriptionsV2(_subscriptions);
mcdSaverTakerAddress = _mcdSaverTakerAddress;
}
/// @notice Bots call this method to repay for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
function repayFor(
DFSExchangeData.ExchangeData memory _exchangeData,
uint _cdpId,
uint _nextPrice,
address _joinAddr
) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _cdpId, _nextPrice);
require(isAllowed);
uint gasCost = calcGasCost(REPAY_GAS_COST);
address owner = subscriptionsContract.getOwner(_cdpId);
monitorProxyContract.callExecute{value: msg.value}(
owner,
mcdSaverTakerAddress,
abi.encodeWithSelector(REPAY_SELECTOR, _exchangeData, _cdpId, gasCost, _joinAddr, 0));
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _cdpId, _nextPrice);
require(isGoodRatio);
returnEth();
logger.Log(address(this), owner, "AutomaticMCDRepay", abi.encode(ratioBefore, ratioAfter));
}
/// @notice Bots call this method to boost for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
function boostFor(
DFSExchangeData.ExchangeData memory _exchangeData,
uint _cdpId,
uint _nextPrice,
address _joinAddr
) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _cdpId, _nextPrice);
require(isAllowed);
uint gasCost = calcGasCost(BOOST_GAS_COST);
address owner = subscriptionsContract.getOwner(_cdpId);
monitorProxyContract.callExecute{value: msg.value}(
owner,
mcdSaverTakerAddress,
abi.encodeWithSelector(BOOST_SELECTOR, _exchangeData, _cdpId, gasCost, _joinAddr, 0));
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _cdpId, _nextPrice);
require(isGoodRatio);
returnEth();
logger.Log(address(this), owner, "AutomaticMCDBoost", abi.encode(ratioBefore, ratioAfter));
}
/******************* INTERNAL METHODS ********************************/
function returnEth() internal {
// return if some eth left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/******************* STATIC METHODS ********************************/
/// @notice Returns an address that owns the CDP
/// @param _cdpId Id of the CDP
function getOwner(uint _cdpId) public view returns(address) {
return manager.owns(_cdpId);
}
/// @notice Gets CDP info (collateral, debt)
/// @param _cdpId Id of the CDP
/// @param _ilk Ilk of the CDP
function getCdpInfo(uint _cdpId, bytes32 _ilk) public view returns (uint, uint) {
address urn = manager.urns(_cdpId);
(uint collateral, uint debt) = vat.urns(_ilk, urn);
(,uint rate,,,) = vat.ilks(_ilk);
return (collateral, rmul(debt, rate));
}
/// @notice Gets a price of the asset
/// @param _ilk Ilk of the CDP
function getPrice(bytes32 _ilk) public view returns (uint) {
(, uint mat) = spotter.ilks(_ilk);
(,,uint spot,,) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
/// @notice Gets CDP ratio
/// @param _cdpId Id of the CDP
/// @param _nextPrice Next price for user
function getRatio(uint _cdpId, uint _nextPrice) public view returns (uint) {
bytes32 ilk = manager.ilks(_cdpId);
uint price = (_nextPrice == 0) ? getPrice(ilk) : _nextPrice;
(uint collateral, uint debt) = getCdpInfo(_cdpId, ilk);
if (debt == 0) return 0;
return rdiv(wmul(collateral, price), debt) / (10 ** 18);
}
/// @notice Checks if Boost/Repay could be triggered for the CDP
/// @dev Called by MCDMonitor to enforce the min/max check
function canCall(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) {
bool subscribed;
CdpHolder memory holder;
(subscribed, holder) = subscriptionsContract.getCdpHolder(_cdpId);
// check if cdp is subscribed
if (!subscribed) return (false, 0);
// check if using next price is allowed
if (_nextPrice > 0 && !holder.nextPriceEnabled) return (false, 0);
// check if boost and boost allowed
if (_method == Method.Boost && !holder.boostEnabled) return (false, 0);
// check if owner is still owner
if (getOwner(_cdpId) != holder.owner) return (false, 0);
uint currRatio = getRatio(_cdpId, _nextPrice);
if (_method == Method.Repay) {
return (currRatio < holder.minRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.maxRatio, currRatio);
}
}
/// @dev After the Boost/Repay check if the ratio doesn't trigger another call
function ratioGoodAfter(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) {
CdpHolder memory holder;
(, holder) = subscriptionsContract.getCdpHolder(_cdpId);
uint currRatio = getRatio(_cdpId, _nextPrice);
if (_method == Method.Repay) {
return (currRatio < holder.maxRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.minRatio, currRatio);
}
}
/// @notice Calculates gas cost (in Eth) of tx
/// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP
/// @param _gasAmount Amount of gas used for the tx
function calcGasCost(uint _gasAmount) public view returns (uint) {
uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE;
return mul(gasPrice, _gasAmount);
}
/******************* OWNER ONLY OPERATIONS ********************************/
/// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions
/// @param _gasCost New gas cost for boost method
function changeBoostGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
BOOST_GAS_COST = _gasCost;
}
/// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions
/// @param _gasCost New gas cost for repay method
function changeRepayGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
REPAY_GAS_COST = _gasCost;
}
/// @notice Allows owner to change max gas price
/// @param _maxGasPrice New max gas price
function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner {
require(_maxGasPrice < 500000000000);
MAX_GAS_PRICE = _maxGasPrice;
}
/// @notice Allows owner to change the amount of gas token burned per function call
/// @param _gasAmount Amount of gas token
/// @param _isRepay Flag to know for which function we are setting the gas token amount
function changeGasTokenAmount(uint _gasAmount, bool _isRepay) public onlyOwner {
if (_isRepay) {
REPAY_GAS_TOKEN = _gasAmount;
} else {
BOOST_GAS_TOKEN = _gasAmount;
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./StaticV2.sol";
abstract contract ISubscriptionsV2 is StaticV2 {
function getOwner(uint _cdpId) external view virtual returns(address);
function getSubscribedInfo(uint _cdpId) public view virtual returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt);
function getCdpHolder(uint _cdpId) public view virtual returns (bool subscribed, CdpHolder memory);
}
pragma solidity ^0.6.0;
import "../../interfaces/DSProxyInterface.sol";
import "../../interfaces/ERC20.sol";
import "../../auth/AdminAuth.sol";
/// @title Implements logic for calling MCDSaverProxy always from same contract
contract MCDMonitorProxyV2 is AdminAuth {
uint public CHANGE_PERIOD;
uint public MIN_CHANGE_PERIOD = 6 * 1 hours;
address public monitor;
address public newMonitor;
address public lastMonitor;
uint public changeRequestedTimestamp;
event MonitorChangeInitiated(address oldMonitor, address newMonitor);
event MonitorChangeCanceled();
event MonitorChangeFinished(address monitor);
event MonitorChangeReverted(address monitor);
modifier onlyMonitor() {
require (msg.sender == monitor);
_;
}
constructor(uint _changePeriod) public {
CHANGE_PERIOD = _changePeriod * 1 hours;
}
/// @notice Only monitor contract is able to call execute on users proxy
/// @param _owner Address of cdp owner (users DSProxy address)
/// @param _saverProxy Address of MCDSaverProxy
/// @param _data Data to send to MCDSaverProxy
function callExecute(address _owner, address _saverProxy, bytes memory _data) public payable onlyMonitor {
// execute reverts if calling specific method fails
DSProxyInterface(_owner).execute{value: msg.value}(_saverProxy, _data);
// return if anything left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Allowed users are able to set Monitor contract without any waiting period first time
/// @param _monitor Address of Monitor contract
function setMonitor(address _monitor) public onlyOwner {
require(monitor == address(0));
monitor = _monitor;
}
/// @notice Allowed users are able to start procedure for changing monitor
/// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change
/// @param _newMonitor address of new monitor
function changeMonitor(address _newMonitor) public onlyOwner {
require(changeRequestedTimestamp == 0);
changeRequestedTimestamp = now;
lastMonitor = monitor;
newMonitor = _newMonitor;
emit MonitorChangeInitiated(lastMonitor, newMonitor);
}
/// @notice At any point allowed users are able to cancel monitor change
function cancelMonitorChange() public onlyOwner {
require(changeRequestedTimestamp > 0);
changeRequestedTimestamp = 0;
newMonitor = address(0);
emit MonitorChangeCanceled();
}
/// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started
function confirmNewMonitor() public onlyOwner {
require((changeRequestedTimestamp + CHANGE_PERIOD) < now);
require(changeRequestedTimestamp != 0);
require(newMonitor != address(0));
monitor = newMonitor;
newMonitor = address(0);
changeRequestedTimestamp = 0;
emit MonitorChangeFinished(monitor);
}
/// @notice Its possible to revert monitor to last used monitor
function revertMonitor() public onlyOwner {
require(lastMonitor != address(0));
monitor = lastMonitor;
emit MonitorChangeReverted(monitor);
}
function setChangePeriod(uint _periodInHours) public onlyOwner {
require(_periodInHours * 1 hours > MIN_CHANGE_PERIOD);
CHANGE_PERIOD = _periodInHours * 1 hours;
}
}
pragma solidity ^0.6.0;
import "../../interfaces/CEtherInterface.sol";
import "../../interfaces/CompoundOracleInterface.sol";
import "../../interfaces/CTokenInterface.sol";
import "../../interfaces/ComptrollerInterface.sol";
import "../../interfaces/IFeeRecipient.sol";
import "../../utils/Discount.sol";
import "../../DS/DSMath.sol";
import "../../DS/DSProxy.sol";
import "../../compound/helpers/Exponential.sol";
import "../../utils/BotRegistry.sol";
import "../../utils/SafeERC20.sol";
/// @title Utlity functions for cream contracts
contract CreamSaverHelper is DSMath, Exponential {
using SafeERC20 for ERC20;
IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A);
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE;
address public constant COMPTROLLER = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
/// @notice Helper method to payback the cream debt
/// @dev If amount is bigger it will repay the whole debt and send the extra to the _user
/// @param _amount Amount of tokens we want to repay
/// @param _cBorrowToken Ctoken address we are repaying
/// @param _borrowToken Token address we are repaying
/// @param _user Owner of the cream position we are paying back
function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal {
uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this));
if (_amount > wholeDebt) {
if (_borrowToken == ETH_ADDRESS) {
_user.transfer((_amount - wholeDebt));
} else {
ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt));
}
_amount = wholeDebt;
}
approveCToken(_borrowToken, _cBorrowToken);
if (_borrowToken == ETH_ADDRESS) {
CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}();
} else {
require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0);
}
}
/// @notice Calculates the fee amount
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _cTokenAddr CToken addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) {
uint fee = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
fee = AUTOMATIC_SERVICE_FEE;
}
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) {
fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
if (_gasCost != 0) {
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);
_gasCost = wdiv(_gasCost, ethTokenPrice);
feeAmount = add(feeAmount, _gasCost);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
address walletAddr = feeRecipient.getFeeAddr();
if (tokenAddr == ETH_ADDRESS) {
payable(walletAddr).transfer(feeAmount);
} else {
ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount);
}
}
/// @notice Calculates the gas cost of transaction and send it to wallet
/// @param _amount Amount that is converted
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _cTokenAddr CToken addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) {
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
if (_gasCost != 0) {
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);
feeAmount = wdiv(_gasCost, ethTokenPrice);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
address walletAddr = feeRecipient.getFeeAddr();
if (tokenAddr == ETH_ADDRESS) {
payable(walletAddr).transfer(feeAmount);
} else {
ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount);
}
}
/// @notice Enters the market for the collatera and borrow tokens
/// @param _cTokenAddrColl Collateral address we are entering the market in
/// @param _cTokenAddrBorrow Borrow address we are entering the market in
function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal {
address[] memory markets = new address[](2);
markets[0] = _cTokenAddrColl;
markets[1] = _cTokenAddrBorrow;
ComptrollerInterface(COMPTROLLER).enterMarkets(markets);
}
/// @notice Approves CToken contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _cTokenAddr Address which will gain the approval
function approveCToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
/// @notice Returns the underlying address of the cToken asset
/// @param _cTokenAddress cToken address
/// @return Token address of the cToken specified
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
/// @notice Returns the owner of the DSProxy that called the contract
function getUserAddress() internal view returns (address) {
DSProxy proxy = DSProxy(uint160(address(this)));
return proxy.owner();
}
/// @notice Returns the maximum amount of collateral available to withdraw
/// @dev Due to rounding errors the result is - 1% wei from the exact amount
/// @param _cCollAddress Collateral we are getting the max value of
/// @param _account Users account
/// @return Returns the max. collateral amount in that token
function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) {
(, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account);
uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account);
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
if (liquidityInEth == 0) return usersBalance;
CTokenInterface(_cCollAddress).accrueInterest();
if (_cCollAddress == CETH_ADDRESS) {
if (liquidityInEth > usersBalance) return usersBalance;
return sub(liquidityInEth, (liquidityInEth / 100));
}
uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress);
uint liquidityInToken = wdiv(liquidityInEth, ethPrice);
if (liquidityInToken > usersBalance) return usersBalance;
return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues
}
/// @notice Returns the maximum amount of borrow amount available
/// @dev Due to rounding errors the result is - 1% wei from the exact amount
/// @param _cBorrowAddress Borrow token we are getting the max value of
/// @param _account Users account
/// @return Returns the max. borrow amount in that token
function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) {
(, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account);
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
CTokenInterface(_cBorrowAddress).accrueInterest();
if (_cBorrowAddress == CETH_ADDRESS) return sub(liquidityInEth, (liquidityInEth / 100));
uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress);
uint liquidityInToken = wdiv(liquidityInEth, ethPrice);
return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues
}
}
pragma solidity ^0.6.0;
abstract contract CEtherInterface {
function mint() external virtual payable;
function repayBorrow() external virtual payable;
}
pragma solidity ^0.6.0;
abstract contract CompoundOracleInterface {
function getUnderlyingPrice(address cToken) external view virtual returns (uint);
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/SafeERC20.sol";
import "../../exchange/SaverExchangeCore.sol";
import "../../interfaces/CTokenInterface.sol";
import "../../utils/Discount.sol";
import "../helpers/CreamSaverHelper.sol";
import "../../loggers/DefisaverLogger.sol";
/// @title Implements the actual logic of Repay/Boost with FL
contract CreamSaverFlashProxy is SaverExchangeCore, CreamSaverHelper {
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
using SafeERC20 for ERC20;
/// @notice Repays the position and sends tokens back for FL
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for transaction
/// @param _flashLoanData Data about FL [amount, fee]
function flashRepay(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost,
uint[2] memory _flashLoanData // amount, fee
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1];
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
// draw max coll
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
// swap max coll + loanAmount
_exData.srcAmount = maxColl + _flashLoanData[0];
(,swapAmount) = _sell(_exData);
// get fee
swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]);
} else {
swapAmount = (maxColl + _flashLoanData[0]);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
// payback debt
paybackDebt(swapAmount, _cAddresses[1], borrowToken, user);
// draw collateral for loanAmount + loanFee
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0);
// repay flash loan
returnFlashLoan(collToken, flashBorrowed);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Boosts the position and sends tokens back for FL
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
/// @param _flashLoanData Data about FL [amount, fee]
function flashBoost(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost,
uint[2] memory _flashLoanData // amount, fee
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1];
// borrow max amount
uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this));
require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
// get dfs fee
borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]);
_exData.srcAmount = (borrowAmount + _flashLoanData[0]);
(,swapAmount) = _sell(_exData);
} else {
swapAmount = (borrowAmount + _flashLoanData[0]);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
// deposit swaped collateral
depositCollateral(collToken, _cAddresses[0], swapAmount);
// borrow token to repay flash loan
require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0);
// repay flash loan
returnFlashLoan(borrowToken, flashBorrowed);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Helper method to deposit tokens in Compound
/// @param _collToken Token address of the collateral
/// @param _cCollToken CToken address of the collateral
/// @param _depositAmount Amount to deposit
function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal {
approveCToken(_collToken, _cCollToken);
if (_collToken != ETH_ADDRESS) {
require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0);
} else {
CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail
}
}
/// @notice Returns the tokens/ether to the msg.sender which is the FL contract
/// @param _tokenAddr Address of token which we return
/// @param _amount Amount to return
function returnFlashLoan(address _tokenAddr, uint _amount) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeTransfer(msg.sender, _amount);
}
msg.sender.transfer(address(this).balance);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../DS/DSMath.sol";
import "../interfaces/TokenInterface.sol";
import "../interfaces/ExchangeInterfaceV2.sol";
import "../utils/ZrxAllowlist.sol";
import "./SaverExchangeHelper.sol";
import "./SaverExchangeRegistry.sol";
contract SaverExchangeCore is SaverExchangeHelper, DSMath {
// first is empty to keep the legacy order in place
enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX }
enum ActionType { SELL, BUY }
struct ExchangeData {
address srcAddr;
address destAddr;
uint srcAmount;
uint destAmount;
uint minPrice;
address wrapper;
address exchangeAddr;
bytes callData;
uint256 price0x;
}
/// @notice Internal method that preforms a sell on 0x/on-chain
/// @dev Usefull for other DFS contract to integrate for exchanging
/// @param exData Exchange data struct
/// @return (address, uint) Address of the wrapper used and destAmount
function _sell(ExchangeData memory exData) internal returns (address, uint) {
address wrapper;
uint swapedTokens;
bool success;
uint tokensLeft = exData.srcAmount;
// if selling eth, convert to weth
if (exData.srcAddr == KYBER_ETH_ADDRESS) {
exData.srcAddr = ethToWethAddr(exData.srcAddr);
TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)();
}
// Try 0x first and then fallback on specific wrapper
if (exData.price0x > 0) {
approve0xProxy(exData.srcAddr, exData.srcAmount);
uint ethAmount = getProtocolFee(exData.srcAddr, exData.srcAmount);
(success, swapedTokens, tokensLeft) = takeOrder(exData, ethAmount, ActionType.SELL);
if (success) {
wrapper = exData.exchangeAddr;
}
}
// fallback to desired wrapper if 0x failed
if (!success) {
swapedTokens = saverSwap(exData, ActionType.SELL);
wrapper = exData.wrapper;
}
require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), "Final amount isn't correct");
// if anything is left in weth, pull it to user as eth
if (getBalance(WETH_ADDRESS) > 0) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
return (wrapper, swapedTokens);
}
/// @notice Internal method that preforms a buy on 0x/on-chain
/// @dev Usefull for other DFS contract to integrate for exchanging
/// @param exData Exchange data struct
/// @return (address, uint) Address of the wrapper used and srcAmount
function _buy(ExchangeData memory exData) internal returns (address, uint) {
address wrapper;
uint swapedTokens;
bool success;
require(exData.destAmount != 0, "Dest amount must be specified");
// if selling eth, convert to weth
if (exData.srcAddr == KYBER_ETH_ADDRESS) {
exData.srcAddr = ethToWethAddr(exData.srcAddr);
TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)();
}
if (exData.price0x > 0) {
approve0xProxy(exData.srcAddr, exData.srcAmount);
uint ethAmount = getProtocolFee(exData.srcAddr, exData.srcAmount);
(success, swapedTokens,) = takeOrder(exData, ethAmount, ActionType.BUY);
if (success) {
wrapper = exData.exchangeAddr;
}
}
// fallback to desired wrapper if 0x failed
if (!success) {
swapedTokens = saverSwap(exData, ActionType.BUY);
wrapper = exData.wrapper;
}
require(getBalance(exData.destAddr) >= exData.destAmount, "Final amount isn't correct");
// if anything is left in weth, pull it to user as eth
if (getBalance(WETH_ADDRESS) > 0) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
return (wrapper, getBalance(exData.destAddr));
}
/// @notice Takes order from 0x and returns bool indicating if it is successful
/// @param _exData Exchange data
/// @param _ethAmount Ether fee needed for 0x order
function takeOrder(
ExchangeData memory _exData,
uint256 _ethAmount,
ActionType _type
) private returns (bool success, uint256, uint256) {
// write in the exact amount we are selling/buing in an order
if (_type == ActionType.SELL) {
writeUint256(_exData.callData, 36, _exData.srcAmount);
} else {
writeUint256(_exData.callData, 36, _exData.destAmount);
}
if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isNonPayableAddr(_exData.exchangeAddr)) {
_ethAmount = 0;
}
uint256 tokensBefore = getBalance(_exData.destAddr);
if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.exchangeAddr)) {
(success, ) = _exData.exchangeAddr.call{value: _ethAmount}(_exData.callData);
} else {
success = false;
}
uint256 tokensSwaped = 0;
uint256 tokensLeft = _exData.srcAmount;
if (success) {
// check to see if any _src tokens are left over after exchange
tokensLeft = getBalance(_exData.srcAddr);
// convert weth -> eth if needed
if (_exData.destAddr == KYBER_ETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(
TokenInterface(WETH_ADDRESS).balanceOf(address(this))
);
}
// get the current balance of the swaped tokens
tokensSwaped = getBalance(_exData.destAddr) - tokensBefore;
}
return (success, tokensSwaped, tokensLeft);
}
/// @notice Calls wraper contract for exchage to preform an on-chain swap
/// @param _exData Exchange data struct
/// @param _type Type of action SELL|BUY
/// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount
function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) {
require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), "Wrapper is not valid");
uint ethValue = 0;
ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount);
if (_type == ActionType.SELL) {
swapedTokens = ExchangeInterfaceV2(_exData.wrapper).
sell{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.srcAmount);
} else {
swapedTokens = ExchangeInterfaceV2(_exData.wrapper).
buy{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.destAmount);
}
}
function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure {
if (_b.length < _index + 32) {
revert("Incorrent lengt while writting bytes32");
}
bytes32 input = bytes32(_input);
_index += 32;
// Read the bytes32 from array memory
assembly {
mstore(add(_b, _index), input)
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
/// @notice Calculates protocol fee
/// @param _srcAddr selling token address (if eth should be WETH)
/// @param _srcAmount amount we are selling
function getProtocolFee(address _srcAddr, uint256 _srcAmount) internal view returns(uint256) {
// if we are not selling ETH msg value is always the protocol fee
if (_srcAddr != WETH_ADDRESS) return address(this).balance;
// if msg value is larger than srcAmount, that means that msg value is protocol fee + srcAmount, so we subsctract srcAmount from msg value
// we have an edge case here when protocol fee is higher than selling amount
if (address(this).balance > _srcAmount) return address(this).balance - _srcAmount;
// if msg value is lower than src amount, that means that srcAmount isn't included in msg value, so we return msg value
return address(this).balance;
}
function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) {
// splitting in two different bytes and encoding all because of stack too deep in decoding part
bytes memory part1 = abi.encode(
_exData.srcAddr,
_exData.destAddr,
_exData.srcAmount,
_exData.destAmount
);
bytes memory part2 = abi.encode(
_exData.minPrice,
_exData.wrapper,
_exData.exchangeAddr,
_exData.callData,
_exData.price0x
);
return abi.encode(part1, part2);
}
function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) {
(
bytes memory part1,
bytes memory part2
) = abi.decode(_data, (bytes,bytes));
(
_exData.srcAddr,
_exData.destAddr,
_exData.srcAmount,
_exData.destAmount
) = abi.decode(part1, (address,address,uint256,uint256));
(
_exData.minPrice,
_exData.wrapper,
_exData.exchangeAddr,
_exData.callData,
_exData.price0x
)
= abi.decode(part2, (uint256,address,address,bytes,uint256));
}
// solhint-disable-next-line no-empty-blocks
receive() external virtual payable {}
}
pragma solidity ^0.6.0;
interface ExchangeInterfaceV2 {
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable returns (uint);
function buy(address _srcAddr, address _destAddr, uint _destAmount) external payable returns(uint);
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint);
function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint);
}
pragma solidity ^0.6.0;
import "../utils/SafeERC20.sol";
import "../utils/Discount.sol";
contract SaverExchangeHelper {
using SafeERC20 for ERC20;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D;
address public constant ERC20_PROXY_0X = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF;
address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F;
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
function getBalance(address _tokenAddr) internal view returns (uint balance) {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
balance = address(this).balance;
} else {
balance = ERC20(_tokenAddr).balanceOf(address(this));
}
}
function approve0xProxy(address _tokenAddr, uint _amount) internal {
if (_tokenAddr != KYBER_ETH_ADDRESS) {
ERC20(_tokenAddr).safeApprove(address(ERC20_PROXY_0X), _amount);
}
}
function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal {
// send back any leftover ether or tokens
if (address(this).balance > 0) {
_to.transfer(address(this).balance);
}
if (getBalance(_srcAddr) > 0) {
ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr));
}
if (getBalance(_destAddr) > 0) {
ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr));
}
}
function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) {
require(bs.length >= start + 32, "slicing out of range");
uint256 x;
assembly {
x := mload(add(bs, add(0x20, start)))
}
return x;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/SafeERC20.sol";
import "../../exchangeV3/DFSExchangeCore.sol";
import "../../interfaces/CTokenInterface.sol";
import "../../utils/Discount.sol";
import "../helpers/CompoundSaverHelper.sol";
import "../../loggers/DefisaverLogger.sol";
/// @title Implements the actual logic of Repay/Boost with FL
contract CompoundSaverFlashProxy is DFSExchangeCore, CompoundSaverHelper {
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
using SafeERC20 for ERC20;
/// @notice Repays the position and sends tokens back for FL
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for transaction
/// @param _flashLoanData Data about FL [amount, fee]
function flashRepay(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost,
uint[2] memory _flashLoanData // amount, fee
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1];
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
// draw max coll
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
// swap max coll + loanAmount
_exData.srcAmount = maxColl + _flashLoanData[0];
_exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
_exData.user = user;
(,swapAmount) = _sell(_exData);
// get fee
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
} else {
swapAmount = (maxColl + _flashLoanData[0]);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
// payback debt
paybackDebt(swapAmount, _cAddresses[1], borrowToken, user);
// draw collateral for loanAmount + loanFee
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0);
// repay flash loan
returnFlashLoan(collToken, flashBorrowed);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Boosts the position and sends tokens back for FL
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
/// @param _flashLoanData Data about FL [amount, fee]
function flashBoost(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost,
uint[2] memory _flashLoanData // amount, fee
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1];
// borrow max amount
uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this));
require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
// get dfs fee
_exData.srcAmount = (borrowAmount + _flashLoanData[0]);
_exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
_exData.user = user;
(, swapAmount) = _sell(_exData);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
} else {
swapAmount = (borrowAmount + _flashLoanData[0]);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
// deposit swaped collateral
depositCollateral(collToken, _cAddresses[0], swapAmount);
// borrow token to repay flash loan
require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0);
// repay flash loan
returnFlashLoan(borrowToken, flashBorrowed);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Helper method to deposit tokens in Compound
/// @param _collToken Token address of the collateral
/// @param _cCollToken CToken address of the collateral
/// @param _depositAmount Amount to deposit
function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal {
approveCToken(_collToken, _cCollToken);
if (_collToken != ETH_ADDRESS) {
require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0);
} else {
CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail
}
}
/// @notice Returns the tokens/ether to the msg.sender which is the FL contract
/// @param _tokenAddr Address of token which we return
/// @param _amount Amount to return
function returnFlashLoan(address _tokenAddr, uint _amount) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeTransfer(msg.sender, _amount);
}
msg.sender.transfer(address(this).balance);
}
}
pragma solidity ^0.6.0;
import "../../interfaces/CEtherInterface.sol";
import "../../interfaces/CompoundOracleInterface.sol";
import "../../interfaces/CTokenInterface.sol";
import "../../interfaces/ComptrollerInterface.sol";
import "../../interfaces/IFeeRecipient.sol";
import "../../utils/Discount.sol";
import "../../DS/DSMath.sol";
import "../../DS/DSProxy.sol";
import "./Exponential.sol";
import "../../utils/BotRegistry.sol";
import "../../utils/SafeERC20.sol";
/// @title Utlity functions for Compound contracts
contract CompoundSaverHelper is DSMath, Exponential {
using SafeERC20 for ERC20;
IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A);
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
/// @notice Helper method to payback the Compound debt
/// @dev If amount is bigger it will repay the whole debt and send the extra to the _user
/// @param _amount Amount of tokens we want to repay
/// @param _cBorrowToken Ctoken address we are repaying
/// @param _borrowToken Token address we are repaying
/// @param _user Owner of the compound position we are paying back
function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal {
uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this));
if (_amount > wholeDebt) {
if (_borrowToken == ETH_ADDRESS) {
_user.transfer((_amount - wholeDebt));
} else {
ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt));
}
_amount = wholeDebt;
}
approveCToken(_borrowToken, _cBorrowToken);
if (_borrowToken == ETH_ADDRESS) {
CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}();
} else {
require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0);
}
}
/// @notice Calculates the fee amount
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _cTokenAddr CToken addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) {
uint fee = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
fee = AUTOMATIC_SERVICE_FEE;
}
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) {
fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
if (_gasCost != 0) {
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);
uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS);
uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice);
_gasCost = wdiv(_gasCost, tokenPriceInEth);
feeAmount = add(feeAmount, _gasCost);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
address walletAddr = feeRecipient.getFeeAddr();
if (tokenAddr == ETH_ADDRESS) {
payable(walletAddr).transfer(feeAmount);
} else {
ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount);
}
}
/// @notice Calculates the gas cost of transaction and send it to wallet
/// @param _amount Amount that is converted
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _cTokenAddr CToken addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) {
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
if (_gasCost != 0) {
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr);
uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS);
uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice);
feeAmount = wdiv(_gasCost, tokenPriceInEth);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
address walletAddr = feeRecipient.getFeeAddr();
if (tokenAddr == ETH_ADDRESS) {
payable(walletAddr).transfer(feeAmount);
} else {
ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount);
}
}
/// @notice Enters the market for the collatera and borrow tokens
/// @param _cTokenAddrColl Collateral address we are entering the market in
/// @param _cTokenAddrBorrow Borrow address we are entering the market in
function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal {
address[] memory markets = new address[](2);
markets[0] = _cTokenAddrColl;
markets[1] = _cTokenAddrBorrow;
ComptrollerInterface(COMPTROLLER).enterMarkets(markets);
}
/// @notice Approves CToken contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _cTokenAddr Address which will gain the approval
function approveCToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
/// @notice Returns the underlying address of the cToken asset
/// @param _cTokenAddress cToken address
/// @return Token address of the cToken specified
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
/// @notice Returns the owner of the DSProxy that called the contract
function getUserAddress() internal view returns (address) {
DSProxy proxy = DSProxy(uint160(address(this)));
return proxy.owner();
}
/// @notice Returns the maximum amount of collateral available to withdraw
/// @dev Due to rounding errors the result is - 1% wei from the exact amount
/// @param _cCollAddress Collateral we are getting the max value of
/// @param _account Users account
/// @return Returns the max. collateral amount in that token
function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) {
(, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account);
uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account);
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
if (liquidityInUsd == 0) return usersBalance;
CTokenInterface(_cCollAddress).accrueInterest();
(, uint collFactorMantissa) = ComptrollerInterface(COMPTROLLER).markets(_cCollAddress);
Exp memory collateralFactor = Exp({mantissa: collFactorMantissa});
(, uint tokensToUsd) = divScalarByExpTruncate(liquidityInUsd, collateralFactor);
uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress);
uint liqInToken = wdiv(tokensToUsd, usdPrice);
if (liqInToken > usersBalance) return usersBalance;
return sub(liqInToken, (liqInToken / 100)); // cut off 1% due to rounding issues
}
/// @notice Returns the maximum amount of borrow amount available
/// @dev Due to rounding errors the result is - 1% wei from the exact amount
/// @param _cBorrowAddress Borrow token we are getting the max value of
/// @param _account Users account
/// @return Returns the max. borrow amount in that token
function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) {
(, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account);
address oracle = ComptrollerInterface(COMPTROLLER).oracle();
CTokenInterface(_cBorrowAddress).accrueInterest();
uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress);
uint liquidityInToken = wdiv(liquidityInUsd, usdPrice);
return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues
}
function isAutomation() internal view returns(bool) {
return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin);
}
}
pragma solidity ^0.6.0;
import "../../compound/helpers/CompoundSaverHelper.sol";
contract CompShifter is CompoundSaverHelper {
using SafeERC20 for ERC20;
address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
function getLoanAmount(uint _cdpId, address _joinAddr) public returns(uint loanAmount) {
return getWholeDebt(_cdpId, _joinAddr);
}
function getWholeDebt(uint _cdpId, address _joinAddr) public returns(uint loanAmount) {
return CTokenInterface(_joinAddr).borrowBalanceCurrent(msg.sender);
}
function close(
address _cCollAddr,
address _cBorrowAddr,
uint _collAmount,
uint _debtAmount
) public {
address collAddr = getUnderlyingAddr(_cCollAddr);
// payback debt
paybackDebt(_debtAmount, _cBorrowAddr, getUnderlyingAddr(_cBorrowAddr), tx.origin);
require(CTokenInterface(_cCollAddr).redeemUnderlying(_collAmount) == 0);
// Send back money to repay FL
if (collAddr == ETH_ADDRESS) {
msg.sender.transfer(address(this).balance);
} else {
ERC20(collAddr).safeTransfer(msg.sender, ERC20(collAddr).balanceOf(address(this)));
}
}
function changeDebt(
address _cBorrowAddrOld,
address _cBorrowAddrNew,
uint _debtAmountOld,
uint _debtAmountNew
) public {
address borrowAddrNew = getUnderlyingAddr(_cBorrowAddrNew);
// payback debt in one token
paybackDebt(_debtAmountOld, _cBorrowAddrOld, getUnderlyingAddr(_cBorrowAddrOld), tx.origin);
// draw debt in another one
borrowCompound(_cBorrowAddrNew, _debtAmountNew);
// Send back money to repay FL
if (borrowAddrNew == ETH_ADDRESS) {
msg.sender.transfer(address(this).balance);
} else {
ERC20(borrowAddrNew).safeTransfer(msg.sender, ERC20(borrowAddrNew).balanceOf(address(this)));
}
}
function open(
address _cCollAddr,
address _cBorrowAddr,
uint _debtAmount
) public {
address collAddr = getUnderlyingAddr(_cCollAddr);
address borrowAddr = getUnderlyingAddr(_cBorrowAddr);
uint collAmount = 0;
if (collAddr == ETH_ADDRESS) {
collAmount = address(this).balance;
} else {
collAmount = ERC20(collAddr).balanceOf(address(this));
}
depositCompound(collAddr, _cCollAddr, collAmount);
// draw debt
borrowCompound(_cBorrowAddr, _debtAmount);
// Send back money to repay FL
if (borrowAddr == ETH_ADDRESS) {
msg.sender.transfer(address(this).balance);
} else {
ERC20(borrowAddr).safeTransfer(msg.sender, ERC20(borrowAddr).balanceOf(address(this)));
}
}
function repayAll(address _cTokenAddr) public {
address tokenAddr = getUnderlyingAddr(_cTokenAddr);
uint amount = ERC20(tokenAddr).balanceOf(address(this));
if (amount != 0) {
paybackDebt(amount, _cTokenAddr, tokenAddr, tx.origin);
}
}
function depositCompound(address _tokenAddr, address _cTokenAddr, uint _amount) internal {
approveCToken(_tokenAddr, _cTokenAddr);
enterMarket(_cTokenAddr);
if (_tokenAddr != ETH_ADDRESS) {
require(CTokenInterface(_cTokenAddr).mint(_amount) == 0, "mint error");
} else {
CEtherInterface(_cTokenAddr).mint{value: _amount}();
}
}
function borrowCompound(address _cTokenAddr, uint _amount) internal {
enterMarket(_cTokenAddr);
require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0);
}
function enterMarket(address _cTokenAddr) public {
address[] memory markets = new address[](1);
markets[0] = _cTokenAddr;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../exchangeV3/DFSExchangeCore.sol";
import "../../loggers/DefisaverLogger.sol";
import "../helpers/CompoundSaverHelper.sol";
/// @title Contract that implements repay/boost functionality
contract CompoundSaverProxy is CompoundSaverHelper, DFSExchangeCore {
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Withdraws collateral, converts to borrowed token and repays debt
/// @dev Called through the DSProxy
/// @param _exData Exchange data
/// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
function repay(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount;
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
_exData.srcAmount = collAmount;
_exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
_exData.user = user;
(, swapAmount) = _sell(_exData);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
} else {
swapAmount = collAmount;
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
paybackDebt(swapAmount, _cAddresses[1], borrowToken, user);
// handle 0x fee
tx.origin.transfer(address(this).balance);
// log amount, collToken, borrowToken
logger.Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Borrows token, converts to collateral, and adds to position
/// @dev Called through the DSProxy
/// @param _exData Exchange data
/// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
function boost(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this));
uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount;
require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
_exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
_exData.user = user;
_exData.srcAmount = borrowAmount;
(, swapAmount) = _sell(_exData);
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
} else {
swapAmount = borrowAmount;
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
approveCToken(collToken, _cAddresses[0]);
if (collToken != ETH_ADDRESS) {
require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0);
} else {
CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail
}
// handle 0x fee
tx.origin.transfer(address(this).balance);
// log amount, collToken, borrowToken
logger.Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../auth/AdminAuth.sol";
import "../utils/FlashLoanReceiverBase.sol";
import "../interfaces/DSProxyInterface.sol";
import "../exchangeV3/DFSExchangeCore.sol";
import "./ShifterRegistry.sol";
import "./LoanShifterTaker.sol";
/// @title LoanShifterReceiver Recevies the Aave flash loan and calls actions through users DSProxy
contract LoanShifterReceiver is DFSExchangeCore, FlashLoanReceiverBase, AdminAuth {
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER =
ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint public constant SERVICE_FEE = 400; // 0.25% Fee
ShifterRegistry public constant shifterRegistry =
ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e);
struct ParamData {
bytes proxyData1;
bytes proxyData2;
address proxy;
address debtAddr;
uint8 protocol1;
uint8 protocol2;
uint8 swapType;
}
constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {}
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params
) external override {
// Format the call data for DSProxy
(ParamData memory paramData, ExchangeData memory exchangeData) =
packFunctionCall(_amount, _fee, _params);
address protocolAddr1 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol1));
address protocolAddr2 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol2));
// Send Flash loan amount to DSProxy
sendTokenToProxy(payable(paramData.proxy), _reserve, _amount);
// Execute the Close/Change debt operation
DSProxyInterface(paramData.proxy).execute(protocolAddr1, paramData.proxyData1);
exchangeData.dfsFeeDivider = SERVICE_FEE;
exchangeData.user = DSProxyInterface(paramData.proxy).owner();
if (paramData.swapType == 1) {
// COLL_SWAP
(, uint256 amount) = _sell(exchangeData);
sendTokenAndEthToProxy(payable(paramData.proxy), exchangeData.destAddr, amount);
} else if (paramData.swapType == 2) {
// DEBT_SWAP
exchangeData.destAmount = (_amount + _fee);
_buy(exchangeData);
// Send extra to DSProxy
sendTokenToProxy(
payable(paramData.proxy),
exchangeData.srcAddr,
ERC20(exchangeData.srcAddr).balanceOf(address(this))
);
} else {
// NO_SWAP just send tokens to proxy
sendTokenAndEthToProxy(
payable(paramData.proxy),
exchangeData.srcAddr,
getBalance(exchangeData.srcAddr)
);
}
// Execute the Open operation
DSProxyInterface(paramData.proxy).execute(protocolAddr2, paramData.proxyData2);
// Repay FL
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
function packFunctionCall(
uint256 _amount,
uint256 _fee,
bytes memory _params
)
internal
pure
returns (ParamData memory paramData, ExchangeData memory exchangeData)
{
LoanShifterTaker.LoanShiftData memory shiftData;
address proxy;
(shiftData, exchangeData, proxy) = abi.decode(
_params,
(LoanShifterTaker.LoanShiftData, ExchangeData, address)
);
bytes memory proxyData1;
bytes memory proxyData2;
uint256 openDebtAmount = (_amount + _fee);
if (shiftData.fromProtocol == LoanShifterTaker.Protocols.MCD) {
// MAKER FROM
proxyData1 = abi.encodeWithSignature(
"close(uint256,address,uint256,uint256)",
shiftData.id1,
shiftData.addrLoan1,
_amount,
shiftData.collAmount
);
} else if (shiftData.fromProtocol == LoanShifterTaker.Protocols.COMPOUND) {
// COMPOUND FROM
if (shiftData.swapType == LoanShifterTaker.SwapType.DEBT_SWAP) {
// DEBT_SWAP
proxyData1 = abi.encodeWithSignature(
"changeDebt(address,address,uint256,uint256)",
shiftData.debtAddr1,
shiftData.debtAddr2,
_amount,
exchangeData.srcAmount
);
} else {
proxyData1 = abi.encodeWithSignature(
"close(address,address,uint256,uint256)",
shiftData.addrLoan1,
shiftData.debtAddr1,
shiftData.collAmount,
shiftData.debtAmount
);
}
}
if (shiftData.toProtocol == LoanShifterTaker.Protocols.MCD) {
// MAKER TO
proxyData2 = abi.encodeWithSignature(
"open(uint256,address,uint256)",
shiftData.id2,
shiftData.addrLoan2,
openDebtAmount
);
} else if (shiftData.toProtocol == LoanShifterTaker.Protocols.COMPOUND) {
// COMPOUND TO
if (shiftData.swapType == LoanShifterTaker.SwapType.DEBT_SWAP) {
// DEBT_SWAP
proxyData2 = abi.encodeWithSignature("repayAll(address)", shiftData.debtAddr2);
} else {
proxyData2 = abi.encodeWithSignature(
"open(address,address,uint256)",
shiftData.addrLoan2,
shiftData.debtAddr2,
openDebtAmount
);
}
}
paramData = ParamData({
proxyData1: proxyData1,
proxyData2: proxyData2,
proxy: proxy,
debtAddr: shiftData.debtAddr1,
protocol1: uint8(shiftData.fromProtocol),
protocol2: uint8(shiftData.toProtocol),
swapType: uint8(shiftData.swapType)
});
}
function sendTokenAndEthToProxy(
address payable _proxy,
address _reserve,
uint256 _amount
) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, _amount);
}
_proxy.transfer(address(this).balance);
}
function sendTokenToProxy(
address payable _proxy,
address _reserve,
uint256 _amount
) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, _amount);
} else {
_proxy.transfer(address(this).balance);
}
}
function getNameByProtocol(uint8 _proto) internal pure returns (string memory) {
if (_proto == 0) {
return "MCD_SHIFTER";
} else if (_proto == 1) {
return "COMP_SHIFTER";
}
}
receive() external payable override(FlashLoanReceiverBase, DFSExchangeCore) {}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../DS/DSProxy.sol";
import "../../utils/FlashLoanReceiverBase.sol";
import "../../interfaces/DSProxyInterface.sol";
import "../../exchangeV3/DFSExchangeCore.sol";
import "../../shifter/ShifterRegistry.sol";
import "./CompoundCreateTaker.sol";
/// @title Contract that receives the FL from Aave for Creating loans
contract CompoundCreateReceiver is FlashLoanReceiverBase, DFSExchangeCore {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x2E82103bD91053C781aaF39da17aE58ceE39d0ab);
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
uint public constant SERVICE_FEE = 400; // 0.25% Fee
// solhint-disable-next-line no-empty-blocks
constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {}
struct CompCreateData {
address payable proxyAddr;
bytes proxyData;
address cCollAddr;
address cDebtAddr;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
// Format the call data for DSProxy
(CompCreateData memory compCreate, ExchangeData memory exchangeData)
= packFunctionCall(_amount, _fee, _params);
address leveragedAsset = _reserve;
// If the assets are different
if (compCreate.cCollAddr != compCreate.cDebtAddr) {
exchangeData.dfsFeeDivider = SERVICE_FEE;
exchangeData.user = DSProxyInterface(compCreate.proxyAddr).owner();
_sell(exchangeData);
leveragedAsset = exchangeData.destAddr;
}
// Send amount to DSProxy
sendToProxy(compCreate.proxyAddr, leveragedAsset);
address compOpenProxy = shifterRegistry.getAddr("COMP_SHIFTER");
// Execute the DSProxy call
DSProxyInterface(compCreate.proxyAddr).execute(compOpenProxy, compCreate.proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
// solhint-disable-next-line avoid-tx-origin
tx.origin.transfer(address(this).balance);
}
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _amount Amount of FL
/// @param _fee Fee of the FL
/// @param _params Saver proxy params
function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (CompCreateData memory compCreate, ExchangeData memory exchangeData) {
CompoundCreateTaker.CreateInfo memory createData;
address proxy;
(createData , exchangeData, proxy)= abi.decode(_params, (CompoundCreateTaker.CreateInfo, ExchangeData, address));
bytes memory proxyData = abi.encodeWithSignature(
"open(address,address,uint256)",
createData.cCollAddress, createData.cBorrowAddress, (_amount + _fee));
compCreate = CompCreateData({
proxyAddr: payable(proxy),
proxyData: proxyData,
cCollAddr: createData.cCollAddress,
cDebtAddr: createData.cBorrowAddress
});
return (compCreate, exchangeData);
}
/// @notice Send the FL funds received to DSProxy
/// @param _proxy DSProxy address
/// @param _reserve Token address
function sendToProxy(address payable _proxy, address _reserve) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, ERC20(_reserve).balanceOf(address(this)));
} else {
_proxy.transfer(address(this).balance);
}
}
// solhint-disable-next-line no-empty-blocks
receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../interfaces/ILendingPool.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../auth/ProxyPermission.sol";
import "../../exchangeV3/DFSExchangeData.sol";
import "../../utils/SafeERC20.sol";
/// @title Opens compound positions with a leverage
contract CompoundCreateTaker is ProxyPermission {
using SafeERC20 for ERC20;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
struct CreateInfo {
address cCollAddress;
address cBorrowAddress;
uint depositAmount;
}
/// @notice Main function which will take a FL and open a leverage position
/// @dev Call through DSProxy, if _exchangeData.destAddr is a token approve DSProxy
/// @param _createInfo [cCollAddress, cBorrowAddress, depositAmount]
/// @param _exchangeData Exchange data struct
function openLeveragedLoan(
CreateInfo memory _createInfo,
DFSExchangeData.ExchangeData memory _exchangeData,
address payable _compReceiver
) public payable {
uint loanAmount = _exchangeData.srcAmount;
// Pull tokens from user
if (_exchangeData.destAddr != ETH_ADDRESS) {
ERC20(_exchangeData.destAddr).safeTransferFrom(msg.sender, address(this), _createInfo.depositAmount);
} else {
require(msg.value >= _createInfo.depositAmount, "Must send correct amount of eth");
}
// Send tokens to FL receiver
sendDeposit(_compReceiver, _exchangeData.destAddr);
bytes memory paramsData = abi.encode(_createInfo, _exchangeData, address(this));
givePermission(_compReceiver);
lendingPool.flashLoan(_compReceiver, _exchangeData.srcAddr, loanAmount, paramsData);
removePermission(_compReceiver);
logger.Log(address(this), msg.sender, "CompoundLeveragedLoan",
abi.encode(_exchangeData.srcAddr, _exchangeData.destAddr, _exchangeData.srcAmount, _exchangeData.destAmount));
}
function sendDeposit(address payable _compoundReceiver, address _token) internal {
if (_token != ETH_ADDRESS) {
ERC20(_token).safeTransfer(_compoundReceiver, ERC20(_token).balanceOf(address(this)));
}
_compoundReceiver.transfer(address(this).balance);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../auth/ProxyPermission.sol";
import "../utils/DydxFlashLoanBase.sol";
import "../loggers/DefisaverLogger.sol";
import "../interfaces/ERC20.sol";
/// @title Takes flash loan
contract DyDxFlashLoanTaker is DydxFlashLoanBase, ProxyPermission {
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
/// @notice Takes flash loan for _receiver
/// @dev Receiver must send back WETH + 2 wei after executing transaction
/// @dev Method is meant to be called from proxy and proxy will give authorization to _receiver
/// @param _receiver Address of funds receiver
/// @param _ethAmount ETH amount that needs to be pulled from dydx
/// @param _encodedData Bytes with packed data
function takeLoan(address _receiver, uint256 _ethAmount, bytes memory _encodedData) public {
ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS);
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR);
// Calculate repay amount (_amount + (2 wei))
// Approve transfer from
uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount);
ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount);
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, _ethAmount, _receiver);
operations[1] = _getCallAction(
_encodedData,
_receiver
);
operations[2] = _getDepositAction(marketId, repayAmount, address(this));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
givePermission(_receiver);
solo.operate(accountInfos, operations);
removePermission(_receiver);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "DyDxFlashLoanTaken", abi.encode(_receiver, _ethAmount, _encodedData));
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../utils/SafeMath.sol";
import "../savings/dydx/ISoloMargin.sol";
contract DydxFlashLoanBase {
using SafeMath for uint256;
address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
function _getMarketIdFromTokenAddress(address token)
internal
view
returns (uint256)
{
return 0;
}
function _getRepaymentAmountInternal(uint256 amount)
internal
view
returns (uint256)
{
// Needs to be overcollateralize
// Needs to provide +2 wei to be safe
return amount.add(2);
}
function _getAccountInfo() internal view returns (Account.Info memory) {
return Account.Info({owner: address(this), number: 1});
}
function _getWithdrawAction(uint marketId, uint256 amount, address contractAddr)
internal
view
returns (Actions.ActionArgs memory)
{
return
Actions.ActionArgs({
actionType: Actions.ActionType.Withdraw,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: contractAddr,
otherAccountId: 0,
data: ""
});
}
function _getCallAction(bytes memory data, address contractAddr)
internal
view
returns (Actions.ActionArgs memory)
{
return
Actions.ActionArgs({
actionType: Actions.ActionType.Call,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: 0
}),
primaryMarketId: 0,
secondaryMarketId: 0,
otherAddress: contractAddr,
otherAccountId: 0,
data: data
});
}
function _getDepositAction(uint marketId, uint256 amount, address contractAddr)
internal
view
returns (Actions.ActionArgs memory)
{
return
Actions.ActionArgs({
actionType: Actions.ActionType.Deposit,
accountId: 0,
amount: Types.AssetAmount({
sign: true,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: contractAddr,
otherAccountId: 0,
data: ""
});
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../AaveHelperV2.sol";
import "../../../utils/GasBurner.sol";
import "../../../auth/AdminAuth.sol";
import "../../../auth/ProxyPermission.sol";
import "../../../utils/DydxFlashLoanBase.sol";
import "../../../loggers/DefisaverLogger.sol";
import "../../../interfaces/ProxyRegistryInterface.sol";
import "../../../interfaces/TokenInterface.sol";
import "../../../interfaces/ERC20.sol";
import "../../../exchangeV3/DFSExchangeData.sol";
/// @title Import Aave position from account to wallet
/// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction)
contract AaveSaverTakerOV2 is ProxyPermission, GasBurner, DFSExchangeData, AaveHelperV2 {
address payable public constant AAVE_RECEIVER = 0xB33BBa30b6d276167C42d14fF3500FD24b4766D2;
// leaving _flAmount to be the same as the older version
function repay(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable burnGas(10) {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
// send msg.value for exchange to the receiver
AAVE_RECEIVER.transfer(msg.value);
address[] memory assets = new address[](1);
assets[0] = _data.srcAddr;
uint256[] memory amounts = new uint256[](1);
amounts[0] = _data.srcAmount;
// for repay we are using regular flash loan with paying back the flash loan + premium
uint256[] memory modes = new uint256[](1);
modes[0] = 0;
// create data
bytes memory encodedData = packExchangeData(_data);
bytes memory data = abi.encode(encodedData, _market, _gasCost, _rateMode, true, address(this));
// give permission to receiver and execute tx
givePermission(AAVE_RECEIVER);
ILendingPoolV2(lendingPool).flashLoan(AAVE_RECEIVER, assets, amounts, modes, address(this), data, AAVE_REFERRAL_CODE);
removePermission(AAVE_RECEIVER);
}
// leaving _flAmount to be the same as the older version
function boost(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable burnGas(10) {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
// send msg.value for exchange to the receiver
AAVE_RECEIVER.transfer(msg.value);
address[] memory assets = new address[](1);
assets[0] = _data.srcAddr;
uint256[] memory amounts = new uint256[](1);
amounts[0] = _data.srcAmount;
uint256[] memory modes = new uint256[](1);
modes[0] = _rateMode;
// create data
bytes memory encodedData = packExchangeData(_data);
bytes memory data = abi.encode(encodedData, _market, _gasCost, _rateMode, false, address(this));
// give permission to receiver and execute tx
givePermission(AAVE_RECEIVER);
ILendingPoolV2(lendingPool).flashLoan(AAVE_RECEIVER, assets, amounts, modes, address(this), data, AAVE_REFERRAL_CODE);
removePermission(AAVE_RECEIVER);
}
}
pragma solidity ^0.6.0;
import "./DSProxyInterface.sol";
abstract contract ProxyRegistryInterface {
function proxies(address _owner) public virtual view returns (address);
function build(address) public virtual returns (address);
}
pragma solidity ^0.6.0;
import "../../interfaces/ExchangeInterfaceV3.sol";
import "../../interfaces/OasisInterface.sol";
import "../../interfaces/TokenInterface.sol";
import "../../DS/DSMath.sol";
import "../../utils/SafeERC20.sol";
import "../../auth/AdminAuth.sol";
contract OasisTradeWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth {
using SafeERC20 for ERC20;
address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @notice Sells a _srcAmount of tokens at Oasis
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external override payable returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount);
uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0);
// convert weth -> eth and send back
if (destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(destAmount);
msg.sender.transfer(destAmount);
} else {
ERC20(destAddr).safeTransfer(msg.sender, destAmount);
}
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Oasis
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1));
uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1));
// convert weth -> eth and send back
if (destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(_destAmount);
msg.sender.transfer(_destAmount);
} else {
ERC20(destAddr).safeTransfer(msg.sender, _destAmount);
}
// Send the leftover from the source token back
sendLeftOver(srcAddr);
return srcAmount;
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount);
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
return wdiv(1 ether, wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount));
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
receive() payable external {}
}
pragma solidity ^0.6.0;
abstract contract OasisInterface {
function getBuyAmount(address tokenToBuy, address tokenToPay, uint256 amountToPay)
external
virtual
view
returns (uint256 amountBought);
function getPayAmount(address tokenToPay, address tokenToBuy, uint256 amountToBuy)
public virtual
view
returns (uint256 amountPaid);
function sellAllAmount(address pay_gem, uint256 pay_amt, address buy_gem, uint256 min_fill_amount)
public virtual
returns (uint256 fill_amt);
function buyAllAmount(address buy_gem, uint256 buy_amt, address pay_gem, uint256 max_fill_amount)
public virtual
returns (uint256 fill_amt);
}
pragma solidity ^0.6.0;
import "../../interfaces/ExchangeInterfaceV2.sol";
import "../../interfaces/OasisInterface.sol";
import "../../interfaces/TokenInterface.sol";
import "../../DS/DSMath.sol";
import "../../utils/SafeERC20.sol";
import "../../auth/AdminAuth.sol";
contract OasisTradeWrapper is DSMath, ExchangeInterfaceV2, AdminAuth {
using SafeERC20 for ERC20;
address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @notice Sells a _srcAmount of tokens at Oasis
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount);
uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0);
// convert weth -> eth and send back
if (destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(destAmount);
msg.sender.transfer(destAmount);
} else {
ERC20(destAddr).safeTransfer(msg.sender, destAmount);
}
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Oasis
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1));
uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1));
// convert weth -> eth and send back
if (destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).withdraw(_destAmount);
msg.sender.transfer(_destAmount);
} else {
ERC20(destAddr).safeTransfer(msg.sender, _destAmount);
}
// Send the leftover from the source token back
sendLeftOver(srcAddr);
return srcAmount;
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount);
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) {
address srcAddr = ethToWethAddr(_srcAddr);
address destAddr = ethToWethAddr(_destAddr);
return wdiv(1 ether, wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount));
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
receive() payable external {}
}
pragma solidity ^0.6.0;
import "../../utils/SafeERC20.sol";
import "../../interfaces/KyberNetworkProxyInterface.sol";
import "../../interfaces/ExchangeInterfaceV2.sol";
import "../../interfaces/UniswapExchangeInterface.sol";
import "../../interfaces/UniswapFactoryInterface.sol";
import "../../DS/DSMath.sol";
import "../../auth/AdminAuth.sol";
contract UniswapWrapper is DSMath, ExchangeInterfaceV2, AdminAuth {
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant UNISWAP_FACTORY = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95;
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at Uniswap
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) {
address uniswapExchangeAddr;
uint destAmount;
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount);
destAmount = UniswapExchangeInterface(uniswapExchangeAddr).
tokenToEthTransferInput(_srcAmount, 1, block.timestamp + 1, msg.sender);
}
// if we are selling token to token
else {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount);
destAmount = UniswapExchangeInterface(uniswapExchangeAddr).
tokenToTokenTransferInput(_srcAmount, 1, 1, block.timestamp + 1, msg.sender, _destAddr);
}
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Uniswap
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) {
address uniswapExchangeAddr;
uint srcAmount;
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1));
srcAmount = UniswapExchangeInterface(uniswapExchangeAddr).
tokenToEthTransferOutput(_destAmount, uint(-1), block.timestamp + 1, msg.sender);
}
// if we are buying token to token
else {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1));
srcAmount = UniswapExchangeInterface(uniswapExchangeAddr).
tokenToTokenTransferOutput(_destAmount, uint(-1), uint(-1), block.timestamp + 1, msg.sender, _destAddr);
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return srcAmount;
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
if(_srcAddr == WETH_ADDRESS) {
address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr);
return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenInputPrice(_srcAmount), _srcAmount);
} else if (_destAddr == WETH_ADDRESS) {
address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthInputPrice(_srcAmount), _srcAmount);
} else {
uint ethBought = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getTokenToEthInputPrice(_srcAmount);
return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getEthToTokenInputPrice(ethBought), _srcAmount);
}
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
if(_srcAddr == WETH_ADDRESS) {
address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr);
return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenOutputPrice(_destAmount), _destAmount));
} else if (_destAddr == WETH_ADDRESS) {
address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthOutputPrice(_destAmount), _destAmount));
} else {
uint ethNeeded = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getTokenToEthOutputPrice(_destAmount);
return wdiv(1 ether, wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getEthToTokenOutputPrice(ethNeeded), _destAmount));
}
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
receive() payable external {}
}
pragma solidity ^0.6.0;
import "./ERC20.sol";
abstract contract KyberNetworkProxyInterface {
function maxGasPrice() external virtual view returns (uint256);
function getUserCapInWei(address user) external virtual view returns (uint256);
function getUserCapInTokenWei(address user, ERC20 token) external virtual view returns (uint256);
function enabled() external virtual view returns (bool);
function info(bytes32 id) external virtual view returns (uint256);
function getExpectedRate(ERC20 src, ERC20 dest, uint256 srcQty)
public virtual
view
returns (uint256 expectedRate, uint256 slippageRate);
function tradeWithHint(
ERC20 src,
uint256 srcAmount,
ERC20 dest,
address destAddress,
uint256 maxDestAmount,
uint256 minConversionRate,
address walletId,
bytes memory hint
) public virtual payable returns (uint256);
function trade(
ERC20 src,
uint256 srcAmount,
ERC20 dest,
address destAddress,
uint256 maxDestAmount,
uint256 minConversionRate,
address walletId
) public virtual payable returns (uint256);
function swapEtherToToken(ERC20 token, uint256 minConversionRate)
external virtual
payable
returns (uint256);
function swapTokenToEther(ERC20 token, uint256 tokenQty, uint256 minRate)
external virtual
payable
returns (uint256);
function swapTokenToToken(ERC20 src, uint256 srcAmount, ERC20 dest, uint256 minConversionRate)
public virtual
returns (uint256);
}
pragma solidity ^0.6.0;
abstract contract UniswapExchangeInterface {
function getEthToTokenInputPrice(uint256 eth_sold)
external virtual
view
returns (uint256 tokens_bought);
function getEthToTokenOutputPrice(uint256 tokens_bought)
external virtual
view
returns (uint256 eth_sold);
function getTokenToEthInputPrice(uint256 tokens_sold)
external virtual
view
returns (uint256 eth_bought);
function getTokenToEthOutputPrice(uint256 eth_bought)
external virtual
view
returns (uint256 tokens_sold);
function tokenToEthTransferInput(
uint256 tokens_sold,
uint256 min_eth,
uint256 deadline,
address recipient
) external virtual returns (uint256 eth_bought);
function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient)
external virtual
payable
returns (uint256 tokens_bought);
function tokenToTokenTransferInput(
uint256 tokens_sold,
uint256 min_tokens_bought,
uint256 min_eth_bought,
uint256 deadline,
address recipient,
address token_addr
) external virtual returns (uint256 tokens_bought);
function ethToTokenTransferOutput(
uint256 tokens_bought,
uint256 deadline,
address recipient
) external virtual payable returns (uint256 eth_sold);
function tokenToEthTransferOutput(
uint256 eth_bought,
uint256 max_tokens,
uint256 deadline,
address recipient
) external virtual returns (uint256 tokens_sold);
function tokenToTokenTransferOutput(
uint256 tokens_bought,
uint256 max_tokens_sold,
uint256 max_eth_sold,
uint256 deadline,
address recipient,
address token_addr
) external virtual returns (uint256 tokens_sold);
}
pragma solidity ^0.6.0;
abstract contract UniswapFactoryInterface {
function getExchange(address token) external view virtual returns (address exchange);
}
pragma solidity ^0.6.0;
import "../../utils/SafeERC20.sol";
import "../../interfaces/KyberNetworkProxyInterface.sol";
import "../../interfaces/IFeeRecipient.sol";
import "../../interfaces/ExchangeInterfaceV3.sol";
import "../../DS/DSMath.sol";
import "../../auth/AdminAuth.sol";
contract KyberWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth {
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e;
IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A);
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at Kyber
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external override payable returns (uint) {
ERC20 srcToken = ERC20(_srcAddr);
ERC20 destToken = ERC20(_destAddr);
address walletAddr = feeRecipient.getFeeAddr();
KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE);
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount);
}
uint destAmount = kyberNetworkProxy.trade{value: msg.value}(
srcToken,
_srcAmount,
destToken,
msg.sender,
uint(-1),
0,
walletAddr
);
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Kyber
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) {
ERC20 srcToken = ERC20(_srcAddr);
ERC20 destToken = ERC20(_destAddr);
address walletAddr = feeRecipient.getFeeAddr();
uint srcAmount = 0;
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcAmount = srcToken.balanceOf(address(this));
} else {
srcAmount = msg.value;
}
KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE);
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcToken.safeApprove(address(kyberNetworkProxy), srcAmount);
}
uint destAmount = kyberNetworkProxy.trade{value: msg.value}(
srcToken,
srcAmount,
destToken,
msg.sender,
_destAmount,
0,
walletAddr
);
require(destAmount == _destAmount, "Wrong dest amount");
uint srcAmountAfter = 0;
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcAmountAfter = srcToken.balanceOf(address(this));
} else {
srcAmountAfter = address(this).balance;
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return (srcAmount - srcAmountAfter);
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return rate Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint rate) {
(rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE)
.getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount);
// multiply with decimal difference in src token
rate = rate * (10**(18 - getDecimals(_srcAddr)));
// divide with decimal difference in dest token
rate = rate / (10**(18 - getDecimals(_destAddr)));
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return rate Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint rate) {
uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount, _additionalData);
uint256 srcAmount = wmul(srcRate, _destAmount);
rate = getSellRate(_srcAddr, _destAddr, srcAmount, _additionalData);
// increase rate by 3% too account for inaccuracy between sell/buy conversion
rate = rate + (rate / 30);
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
receive() payable external {}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
}
pragma solidity ^0.6.0;
import "../../utils/SafeERC20.sol";
import "../../interfaces/ExchangeInterfaceV3.sol";
import "../../interfaces/UniswapRouterInterface.sol";
import "../../DS/DSMath.sol";
import "../../auth/AdminAuth.sol";
/// @title DFS exchange wrapper for UniswapV2
contract UniswapWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth {
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at UniswapV2
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external payable override returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
uint[] memory amounts;
address[] memory path = abi.decode(_additionalData, (address[]));
ERC20(_srcAddr).safeApprove(address(router), _srcAmount);
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1);
}
// if we are selling token to token
else {
amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1);
}
return amounts[amounts.length - 1];
}
/// @notice Buys a _destAmount of tokens at UniswapV2
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
uint[] memory amounts;
address[] memory path = abi.decode(_additionalData, (address[]));
ERC20(_srcAddr).safeApprove(address(router), uint(-1));
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1);
}
// if we are buying token to token
else {
amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1);
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return amounts[0];
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
address[] memory path = abi.decode(_additionalData, (address[]));
uint[] memory amounts = router.getAmountsOut(_srcAmount, path);
return wdiv(amounts[amounts.length - 1], _srcAmount);
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
address[] memory path = abi.decode(_additionalData, (address[]));
uint[] memory amounts = router.getAmountsIn(_destAmount, path);
return wdiv(_destAmount, amounts[0]);
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
receive() payable external {}
}
pragma solidity ^0.6.0;
abstract contract UniswapRouterInterface {
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
returns (uint[] memory amounts);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external virtual
returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external virtual returns (uint[] memory amounts);
function getAmountsOut(uint amountIn, address[] memory path) public virtual view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] memory path) public virtual view returns (uint[] memory amounts);
}
pragma solidity ^0.6.0;
import "../../utils/SafeERC20.sol";
import "../../interfaces/ExchangeInterfaceV2.sol";
import "../../interfaces/UniswapRouterInterface.sol";
import "../../DS/DSMath.sol";
import "../../auth/AdminAuth.sol";
/// @title DFS exchange wrapper for UniswapV2
contract UniswapV2Wrapper is DSMath, ExchangeInterfaceV2, AdminAuth {
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at UniswapV2
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
uint[] memory amounts;
address[] memory path = new address[](2);
path[0] = _srcAddr;
path[1] = _destAddr;
ERC20(_srcAddr).safeApprove(address(router), _srcAmount);
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1);
}
// if we are selling token to token
else {
amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1);
}
return amounts[amounts.length - 1];
}
/// @notice Buys a _destAmount of tokens at UniswapV2
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
uint[] memory amounts;
address[] memory path = new address[](2);
path[0] = _srcAddr;
path[1] = _destAddr;
ERC20(_srcAddr).safeApprove(address(router), uint(-1));
// if we are buying ether
if (_destAddr == WETH_ADDRESS) {
amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1);
}
// if we are buying token to token
else {
amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1);
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return amounts[0];
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
address[] memory path = new address[](2);
path[0] = _srcAddr;
path[1] = _destAddr;
uint[] memory amounts = router.getAmountsOut(_srcAmount, path);
return wdiv(amounts[amounts.length - 1], _srcAmount);
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) {
_srcAddr = ethToWethAddr(_srcAddr);
_destAddr = ethToWethAddr(_destAddr);
address[] memory path = new address[](2);
path[0] = _srcAddr;
path[1] = _destAddr;
uint[] memory amounts = router.getAmountsIn(_destAmount, path);
return wdiv(_destAmount, amounts[0]);
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
/// @notice Converts Kybers Eth address -> Weth
/// @param _src Input address
function ethToWethAddr(address _src) internal pure returns (address) {
return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src;
}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
receive() payable external {}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../DS/DSMath.sol";
import "../interfaces/TokenInterface.sol";
import "../interfaces/ExchangeInterfaceV3.sol";
import "../utils/SafeERC20.sol";
contract DFSPrices is DSMath {
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
enum ActionType { SELL, BUY }
/// @notice Returns the best estimated price from 2 exchanges
/// @param _amount Amount of source tokens you want to exchange
/// @param _srcToken Address of the source token
/// @param _destToken Address of the destination token
/// @param _type Type of action SELL|BUY
/// @param _wrappers Array of wrapper addresses to compare
/// @return (address, uint) The address of the best exchange and the exchange price
function getBestPrice(
uint256 _amount,
address _srcToken,
address _destToken,
ActionType _type,
address[] memory _wrappers,
bytes[] memory _additionalData
) public returns (address, uint256) {
uint256[] memory rates = new uint256[](_wrappers.length);
for (uint i=0; i<_wrappers.length; i++) {
rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type, _additionalData[i]);
}
return getBiggestRate(_wrappers, rates);
}
/// @notice Return the expected rate from the exchange wrapper
/// @dev In case of Oasis/Uniswap handles the different precision tokens
/// @param _wrapper Address of exchange wrapper
/// @param _srcToken From token
/// @param _destToken To token
/// @param _amount Amount to be exchanged
/// @param _type Type of action SELL|BUY
function getExpectedRate(
address _wrapper,
address _srcToken,
address _destToken,
uint256 _amount,
ActionType _type,
bytes memory _additionalData
) public returns (uint256) {
bool success;
bytes memory result;
if (_type == ActionType.SELL) {
(success, result) = _wrapper.call(abi.encodeWithSignature(
"getSellRate(address,address,uint256,bytes)",
_srcToken,
_destToken,
_amount,
_additionalData
));
} else {
(success, result) = _wrapper.call(abi.encodeWithSignature(
"getBuyRate(address,address,uint256,bytes)",
_srcToken,
_destToken,
_amount,
_additionalData
));
}
if (success) {
return sliceUint(result, 0);
}
return 0;
}
/// @notice Finds the biggest rate between exchanges, needed for sell rate
/// @param _wrappers Array of wrappers to compare
/// @param _rates Array of rates to compare
function getBiggestRate(
address[] memory _wrappers,
uint256[] memory _rates
) internal pure returns (address, uint) {
uint256 maxIndex = 0;
// starting from 0 in case there is only one rate in array
for (uint256 i=0; i<_rates.length; i++) {
if (_rates[i] > _rates[maxIndex]) {
maxIndex = i;
}
}
return (_wrappers[maxIndex], _rates[maxIndex]);
}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) {
require(bs.length >= start + 32, "slicing out of range");
uint256 x;
assembly {
x := mload(add(bs, add(0x20, start)))
}
return x;
}
}
pragma solidity ^0.6.0;
import "../../utils/SafeERC20.sol";
import "../../interfaces/KyberNetworkProxyInterface.sol";
import "../../interfaces/ExchangeInterfaceV2.sol";
import "../../interfaces/IFeeRecipient.sol";
import "../../DS/DSMath.sol";
import "../../auth/AdminAuth.sol";
contract KyberWrapper is DSMath, ExchangeInterfaceV2, AdminAuth {
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e;
IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A);
using SafeERC20 for ERC20;
/// @notice Sells a _srcAmount of tokens at Kyber
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return uint Destination amount
function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) {
ERC20 srcToken = ERC20(_srcAddr);
ERC20 destToken = ERC20(_destAddr);
address walletAddr = feeRecipient.getFeeAddr();
KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE);
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount);
}
uint destAmount = kyberNetworkProxy.trade{value: msg.value}(
srcToken,
_srcAmount,
destToken,
msg.sender,
uint(-1),
0,
walletAddr
);
return destAmount;
}
/// @notice Buys a _destAmount of tokens at Kyber
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return uint srcAmount
function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) {
ERC20 srcToken = ERC20(_srcAddr);
ERC20 destToken = ERC20(_destAddr);
address walletAddr = feeRecipient.getFeeAddr();
uint srcAmount = 0;
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcAmount = srcToken.balanceOf(address(this));
} else {
srcAmount = msg.value;
}
KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE);
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcToken.safeApprove(address(kyberNetworkProxy), srcAmount);
}
uint destAmount = kyberNetworkProxy.trade{value: msg.value}(
srcToken,
srcAmount,
destToken,
msg.sender,
_destAmount,
0,
walletAddr
);
require(destAmount == _destAmount, "Wrong dest amount");
uint srcAmountAfter = 0;
if (_srcAddr != KYBER_ETH_ADDRESS) {
srcAmountAfter = srcToken.balanceOf(address(this));
} else {
srcAmountAfter = address(this).balance;
}
// Send the leftover from the source token back
sendLeftOver(_srcAddr);
return (srcAmount - srcAmountAfter);
}
/// @notice Return a rate for which we can sell an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _srcAmount From amount
/// @return rate Rate
function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint rate) {
(rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE)
.getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount);
// multiply with decimal difference in src token
rate = rate * (10**(18 - getDecimals(_srcAddr)));
// divide with decimal difference in dest token
rate = rate / (10**(18 - getDecimals(_destAddr)));
}
/// @notice Return a rate for which we can buy an amount of tokens
/// @param _srcAddr From token
/// @param _destAddr To token
/// @param _destAmount To amount
/// @return rate Rate
function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint rate) {
uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount);
uint256 srcAmount = wmul(srcRate, _destAmount);
rate = getSellRate(_srcAddr, _destAddr, srcAmount);
// increase rate by 3% too account for inaccuracy between sell/buy conversion
rate = rate + (rate / 30);
}
/// @notice Send any leftover tokens, we use to clear out srcTokens after buy
/// @param _srcAddr Source token address
function sendLeftOver(address _srcAddr) internal {
msg.sender.transfer(address(this).balance);
if (_srcAddr != KYBER_ETH_ADDRESS) {
ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this)));
}
}
receive() payable external {}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../interfaces/GasTokenInterface.sol";
import "../interfaces/IFeeRecipient.sol";
import "./SaverExchangeCore.sol";
import "../DS/DSMath.sol";
import "../loggers/DefisaverLogger.sol";
import "../auth/AdminAuth.sol";
import "../utils/GasBurner.sol";
import "../utils/SafeERC20.sol";
contract SaverExchange is SaverExchangeCore, AdminAuth, GasBurner {
using SafeERC20 for ERC20;
uint256 public constant SERVICE_FEE = 800; // 0.125% Fee
IFeeRecipient public constant _feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A);
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
uint public burnAmount = 10;
/// @notice Takes a src amount of tokens and converts it into the dest token
/// @dev Takes fee from the _srcAmount before the exchange
/// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x]
/// @param _user User address who called the exchange
function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) {
// take fee
uint dfsFee = getFee(exData.srcAmount, exData.srcAddr);
exData.srcAmount = sub(exData.srcAmount, dfsFee);
// Perform the exchange
(address wrapper, uint destAmount) = _sell(exData);
// send back any leftover ether or tokens
sendLeftover(exData.srcAddr, exData.destAddr, _user);
// log the event
logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount));
}
/// @notice Takes a dest amount of tokens and converts it from the src token
/// @dev Send always more than needed for the swap, extra will be returned
/// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x]
/// @param _user User address who called the exchange
function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){
uint dfsFee = getFee(exData.srcAmount, exData.srcAddr);
exData.srcAmount = sub(exData.srcAmount, dfsFee);
// Perform the exchange
(address wrapper, uint srcAmount) = _buy(exData);
// send back any leftover ether or tokens
sendLeftover(exData.srcAddr, exData.destAddr, _user);
// log the event
logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount));
}
/// @notice Takes a feePercentage and sends it to wallet
/// @param _amount Dai amount of the whole trade
/// @param _token Address of the token
/// @return feeAmount Amount in Dai owner earned on the fee
function getFee(uint256 _amount, address _token) internal returns (uint256 feeAmount) {
uint256 fee = SERVICE_FEE;
if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(msg.sender)) {
fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(msg.sender);
}
if (fee == 0) {
feeAmount = 0;
} else {
address walletAddr = _feeRecipient.getFeeAddr();
feeAmount = _amount / fee;
if (_token == KYBER_ETH_ADDRESS) {
payable(walletAddr).transfer(feeAmount);
} else {
ERC20(_token).safeTransfer(walletAddr, feeAmount);
}
}
}
/// @notice Changes the amount of gas token we burn for each call
/// @dev Only callable by the owner
/// @param _newBurnAmount New amount of gas tokens to be burned
function changeBurnAmount(uint _newBurnAmount) public {
require(owner == msg.sender);
burnAmount = _newBurnAmount;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../exchange/SaverExchangeCore.sol";
contract ExchangeDataParser {
function decodeExchangeData(
SaverExchangeCore.ExchangeData memory exchangeData
) internal pure returns (address[4] memory, uint[4] memory, bytes memory) {
return (
[exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper],
[exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x],
exchangeData.callData
);
}
function encodeExchangeData(
address[4] memory exAddr, uint[4] memory exNum, bytes memory callData
) internal pure returns (SaverExchangeCore.ExchangeData memory) {
return SaverExchangeCore.ExchangeData({
srcAddr: exAddr[0],
destAddr: exAddr[1],
srcAmount: exNum[0],
destAmount: exNum[1],
minPrice: exNum[2],
wrapper: exAddr[3],
exchangeAddr: exAddr[2],
callData: callData,
price0x: exNum[3]
});
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/FlashLoanReceiverBase.sol";
import "../../interfaces/DSProxyInterface.sol";
import "../../exchange/SaverExchangeCore.sol";
/// @title Contract that receives the FL from Aave for Repays/Boost
contract CreamSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address payable public COMPOUND_SAVER_FLASH_PROXY = 0x1e012554891d271eDc80ba8eB146EA5FF596fA51;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public owner;
using SafeERC20 for ERC20;
constructor()
FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER)
public {
owner = msg.sender;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
// Format the call data for DSProxy
(bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params);
// Send Flash loan amount to DSProxy
sendLoanToProxy(proxyAddr, _reserve, _amount);
// Execute the DSProxy call
DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _amount Amount of FL
/// @param _fee Fee of the FL
/// @param _params Saver proxy params
/// @return proxyData Formated function call data
function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) {
(
bytes memory exDataBytes,
address[2] memory cAddresses, // cCollAddress, cBorrowAddress
uint256 gasCost,
bool isRepay,
address payable proxyAddr
)
= abi.decode(_params, (bytes,address[2],uint256,bool,address));
ExchangeData memory _exData = unpackExchangeData(exDataBytes);
uint[2] memory flashLoanData = [_amount, _fee];
if (isRepay) {
proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData);
} else {
proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData);
}
return (proxyData, proxyAddr);
}
/// @notice Send the FL funds received to DSProxy
/// @param _proxy DSProxy address
/// @param _reserve Token address
/// @param _amount Amount of tokens
function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, _amount);
}
_proxy.transfer(address(this).balance);
}
receive() external override(SaverExchangeCore, FlashLoanReceiverBase) payable {}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../mcd/saver/MCDSaverProxy.sol";
import "../../utils/FlashLoanReceiverBase.sol";
import "../../exchangeV3/DFSExchangeCore.sol";
contract MCDSaverFlashLoan is MCDSaverProxy, AdminAuth, FlashLoanReceiverBase {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {}
struct SaverData {
uint cdpId;
uint gasCost;
uint loanAmount;
uint fee;
address joinAddr;
ManagerType managerType;
}
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
//check the contract has the specified balance
require(_amount <= getBalanceInternal(address(this), _reserve),
"Invalid balance for the contract");
(
bytes memory exDataBytes,
uint cdpId,
uint gasCost,
address joinAddr,
bool isRepay,
uint8 managerType
)
= abi.decode(_params, (bytes,uint256,uint256,address,bool,uint8));
ExchangeData memory exchangeData = unpackExchangeData(exDataBytes);
SaverData memory saverData = SaverData({
cdpId: cdpId,
gasCost: gasCost,
loanAmount: _amount,
fee: _fee,
joinAddr: joinAddr,
managerType: ManagerType(managerType)
});
if (isRepay) {
repayWithLoan(exchangeData, saverData);
} else {
boostWithLoan(exchangeData, saverData);
}
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
function boostWithLoan(
ExchangeData memory _exchangeData,
SaverData memory _saverData
) internal {
address managerAddr = getManagerAddr(_saverData.managerType);
address user = getOwner(Manager(managerAddr), _saverData.cdpId);
// Draw users Dai
uint maxDebt = getMaxDebt(managerAddr, _saverData.cdpId, Manager(managerAddr).ilks(_saverData.cdpId));
uint daiDrawn = drawDai(managerAddr, _saverData.cdpId, Manager(managerAddr).ilks(_saverData.cdpId), maxDebt);
// Swap
_exchangeData.srcAmount = daiDrawn + _saverData.loanAmount - takeFee(_saverData.gasCost, daiDrawn + _saverData.loanAmount);
_exchangeData.user = user;
_exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
(, uint swapedAmount) = _sell(_exchangeData);
// Return collateral
addCollateral(managerAddr, _saverData.cdpId, _saverData.joinAddr, swapedAmount);
// Draw Dai to repay the flash loan
drawDai(managerAddr, _saverData.cdpId, Manager(managerAddr).ilks(_saverData.cdpId), (_saverData.loanAmount + _saverData.fee));
logger.Log(address(this), msg.sender, "MCDFlashBoost", abi.encode(_saverData.cdpId, user, _exchangeData.srcAmount, swapedAmount));
}
function repayWithLoan(
ExchangeData memory _exchangeData,
SaverData memory _saverData
) internal {
address managerAddr = getManagerAddr(_saverData.managerType);
address user = getOwner(Manager(managerAddr), _saverData.cdpId);
bytes32 ilk = Manager(managerAddr).ilks(_saverData.cdpId);
// Draw collateral
uint maxColl = getMaxCollateral(managerAddr, _saverData.cdpId, ilk, _saverData.joinAddr);
uint collDrawn = drawCollateral(managerAddr, _saverData.cdpId, _saverData.joinAddr, maxColl);
// Swap
_exchangeData.srcAmount = (_saverData.loanAmount + collDrawn);
_exchangeData.user = user;
_exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
(, uint paybackAmount) = _sell(_exchangeData);
paybackAmount -= takeFee(_saverData.gasCost, paybackAmount);
paybackAmount = limitLoanAmount(managerAddr, _saverData.cdpId, ilk, paybackAmount, user);
// Payback the debt
paybackDebt(managerAddr, _saverData.cdpId, ilk, paybackAmount, user);
// Draw collateral to repay the flash loan
drawCollateral(managerAddr, _saverData.cdpId, _saverData.joinAddr, (_saverData.loanAmount + _saverData.fee));
logger.Log(address(this), msg.sender, "MCDFlashRepay", abi.encode(_saverData.cdpId, user, _exchangeData.srcAmount, paybackAmount));
}
/// @notice Handles that the amount is not bigger than cdp debt and not dust
function limitLoanAmount(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _paybackAmount, address _owner) internal returns (uint256) {
uint debt = getAllDebt(address(vat), Manager(_managerAddr).urns(_cdpId), Manager(_managerAddr).urns(_cdpId), _ilk);
if (_paybackAmount > debt) {
ERC20(DAI_ADDRESS).transfer(_owner, (_paybackAmount - debt));
return debt;
}
uint debtLeft = debt - _paybackAmount;
(,,,, uint dust) = vat.ilks(_ilk);
dust = dust / 10**27;
// Less than dust value
if (debtLeft < dust) {
uint amountOverDust = (dust - debtLeft);
ERC20(DAI_ADDRESS).transfer(_owner, amountOverDust);
return (_paybackAmount - amountOverDust);
}
return _paybackAmount;
}
receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../mcd/saver/MCDSaverProxy.sol";
import "../../utils/FlashLoanReceiverBase.sol";
import "../../auth/AdminAuth.sol";
import "../../exchangeV3/DFSExchangeCore.sol";
import "../../mcd/saver/MCDSaverProxyHelper.sol";
import "./MCDCloseTaker.sol";
contract MCDCloseFlashLoan is DFSExchangeCore, MCDSaverProxyHelper, FlashLoanReceiverBase, AdminAuth {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
uint public constant SERVICE_FEE = 400; // 0.25% Fee
bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS);
Spotter public constant spotter = Spotter(SPOTTER_ADDRESS);
Vat public constant vat = Vat(VAT_ADDRESS);
struct CloseData {
uint cdpId;
uint collAmount;
uint daiAmount;
uint minAccepted;
address joinAddr;
address proxy;
uint flFee;
bool toDai;
address reserve;
uint amount;
}
constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {}
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
(address proxy, bytes memory packedData) = abi.decode(_params, (address,bytes));
(MCDCloseTaker.CloseData memory closeDataSent, ExchangeData memory exchangeData) = abi.decode(packedData, (MCDCloseTaker.CloseData,ExchangeData));
CloseData memory closeData = CloseData({
cdpId: closeDataSent.cdpId,
collAmount: closeDataSent.collAmount,
daiAmount: closeDataSent.daiAmount,
minAccepted: closeDataSent.minAccepted,
joinAddr: closeDataSent.joinAddr,
proxy: proxy,
flFee: _fee,
toDai: closeDataSent.toDai,
reserve: _reserve,
amount: _amount
});
address user = DSProxy(payable(closeData.proxy)).owner();
exchangeData.dfsFeeDivider = SERVICE_FEE;
exchangeData.user = user;
address managerAddr = getManagerAddr(closeDataSent.managerType);
closeCDP(closeData, exchangeData, user, managerAddr);
}
function closeCDP(
CloseData memory _closeData,
ExchangeData memory _exchangeData,
address _user,
address _managerAddr
) internal {
paybackDebt(_managerAddr, _closeData.cdpId, Manager(_managerAddr).ilks(_closeData.cdpId), _closeData.daiAmount); // payback whole debt
uint drawnAmount = drawMaxCollateral(_managerAddr, _closeData.cdpId, _closeData.joinAddr, _closeData.collAmount); // draw whole collateral
uint daiSwaped = 0;
if (_closeData.toDai) {
_exchangeData.srcAmount = drawnAmount;
(, daiSwaped) = _sell(_exchangeData);
} else {
_exchangeData.destAmount = (_closeData.daiAmount + _closeData.flFee);
(, daiSwaped) = _buy(_exchangeData);
}
address tokenAddr = getVaultCollAddr(_closeData.joinAddr);
if (_closeData.toDai) {
tokenAddr = DAI_ADDRESS;
}
require(getBalance(tokenAddr) >= _closeData.minAccepted, "Below min. number of eth specified");
transferFundsBackToPoolInternal(_closeData.reserve, _closeData.amount.add(_closeData.flFee));
sendLeftover(tokenAddr, DAI_ADDRESS, payable(_user));
}
function drawMaxCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) {
Manager(_managerAddr).frob(_cdpId, -toPositiveInt(_amount), 0);
Manager(_managerAddr).flux(_cdpId, address(this), _amount);
uint joinAmount = _amount;
if (Join(_joinAddr).dec() != 18) {
joinAmount = _amount / (10 ** (18 - Join(_joinAddr).dec()));
}
Join(_joinAddr).exit(address(this), joinAmount);
if (isEthJoinAddr(_joinAddr)) {
Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth
}
return joinAmount;
}
function paybackDebt(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount) internal {
address urn = Manager(_managerAddr).urns(_cdpId);
daiJoin.dai().approve(DAI_JOIN_ADDRESS, _daiAmount);
daiJoin.join(urn, _daiAmount);
Manager(_managerAddr).frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk));
}
function getVaultCollAddr(address _joinAddr) internal view returns (address) {
address tokenAddr = address(Join(_joinAddr).gem());
if (tokenAddr == EXCHANGE_WETH_ADDRESS) {
return KYBER_ETH_ADDRESS;
}
return tokenAddr;
}
function getPrice(bytes32 _ilk) public view returns (uint256) {
(, uint256 mat) = spotter.ilks(_ilk);
(, , uint256 spot, , ) = vat.ilks(_ilk);
return rmul(rmul(spot, spotter.par()), mat);
}
receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {}
}
pragma solidity ^0.6.0;
import "../../utils/FlashLoanReceiverBase.sol";
import "../../interfaces/ProxyRegistryInterface.sol";
import "../../interfaces/CTokenInterface.sol";
import "../../utils/SafeERC20.sol";
/// @title Receives FL from Aave and imports the position to DSProxy
contract CreamImportFlashLoan is FlashLoanReceiverBase {
using SafeERC20 for ERC20;
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address public constant CREAM_BORROW_PROXY = 0x87F198Ef6116CdBC5f36B581d212ad950b7e2Ddd;
address public owner;
constructor()
FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER)
public {
owner = msg.sender;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
(
address cCollateralToken,
address cBorrowToken,
address user,
address proxy
)
= abi.decode(_params, (address,address,address,address));
// approve FL tokens so we can repay them
ERC20(_reserve).safeApprove(cBorrowToken, uint(-1));
// repay cream debt
require(CTokenInterface(cBorrowToken).repayBorrowBehalf(user, uint(-1)) == 0, "Repay borrow behalf fail");
// transfer cTokens to proxy
uint cTokenBalance = CTokenInterface(cCollateralToken).balanceOf(user);
require(CTokenInterface(cCollateralToken).transferFrom(user, proxy, cTokenBalance));
// borrow
bytes memory proxyData = getProxyData(cCollateralToken, cBorrowToken, _reserve, (_amount + _fee));
DSProxyInterface(proxy).execute(CREAM_BORROW_PROXY, proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _cCollToken CToken address of collateral
/// @param _cBorrowToken CToken address we will borrow
/// @param _borrowToken Token address we will borrow
/// @param _amount Amount that will be borrowed
/// @return proxyData Formated function call data
function getProxyData(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) internal pure returns (bytes memory proxyData) {
proxyData = abi.encodeWithSignature(
"borrow(address,address,address,uint256)",
_cCollToken, _cBorrowToken, _borrowToken, _amount);
}
function withdrawStuckFunds(address _tokenAddr, uint _amount) public {
require(owner == msg.sender, "Must be owner");
if (_tokenAddr == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
msg.sender.transfer(_amount);
} else {
ERC20(_tokenAddr).safeTransfer(owner, _amount);
}
}
}
pragma solidity ^0.6.0;
import "../../utils/GasBurner.sol";
import "../../auth/ProxyPermission.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../interfaces/ILendingPool.sol";
import "../../interfaces/CTokenInterface.sol";
import "../../interfaces/ProxyRegistryInterface.sol";
import "../helpers/CreamSaverHelper.sol";
/// @title Imports cream position from the account to DSProxy
contract CreamImportTaker is CreamSaverHelper, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address payable public constant CREAM_IMPORT_FLASH_LOAN = 0x24F4aC0Fe758c45cf8425D8Fbdd608cca9A7dBf8;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must approve cream_IMPORT_FLASH_LOAN to pull _cCollateralToken
/// @param _cCollateralToken Collateral we are moving to DSProxy
/// @param _cBorrowToken Borrow token we are moving to DSProxy
function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) {
address proxy = getProxy();
uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender);
bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy);
givePermission(CREAM_IMPORT_FLASH_LOAN);
lendingPool.flashLoan(CREAM_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData);
removePermission(CREAM_IMPORT_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CreamImport", abi.encode(loanAmount, 0, _cCollateralToken));
}
/// @notice Gets proxy address, if user doesn't has DSProxy build it
/// @return proxy DsProxy address
function getProxy() internal returns (address proxy) {
proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender);
if (proxy == address(0)) {
proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender);
}
}
}
pragma solidity ^0.6.0;
import "../../utils/GasBurner.sol";
import "../../auth/ProxyPermission.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../interfaces/ILendingPool.sol";
import "../../interfaces/CTokenInterface.sol";
import "../../interfaces/ProxyRegistryInterface.sol";
import "../helpers/CompoundSaverHelper.sol";
/// @title Imports Compound position from the account to DSProxy
contract CompoundImportTaker is CompoundSaverHelper, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address payable public constant COMPOUND_IMPORT_FLASH_LOAN = 0x1DB68Ba0B85800FD323387E8B69d9AE867e00B94;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must approve DSProxy to pull _cCollateralToken
/// @param _cCollateralToken Collateral we are moving to DSProxy
/// @param _cBorrowToken Borrow token we are moving to DSProxy
function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) {
uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender);
bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, address(this));
givePermission(COMPOUND_IMPORT_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData);
removePermission(COMPOUND_IMPORT_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CompoundImport", abi.encode(loanAmount, 0, _cCollateralToken));
}
}
pragma solidity ^0.6.0;
import "../../auth/AdminAuth.sol";
import "../../utils/FlashLoanReceiverBase.sol";
import "../../interfaces/ProxyRegistryInterface.sol";
import "../../interfaces/CTokenInterface.sol";
import "../../utils/SafeERC20.sol";
/// @title Receives FL from Aave and imports the position to DSProxy
contract CompoundImportFlashLoan is FlashLoanReceiverBase, AdminAuth {
using SafeERC20 for ERC20;
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER =
ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address public constant COMPOUND_BORROW_PROXY = 0xb7EDC39bE76107e2Cc645f0f6a3D164f5e173Ee2;
address public constant PULL_TOKENS_PROXY = 0x45431b79F783e0BF0fe7eF32D06A3e061780bfc4;
// solhint-disable-next-line no-empty-blocks
constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params
) external override {
(address cCollAddr, address cBorrowAddr, address proxy) =
abi.decode(_params, (address, address, address));
address user = DSProxyInterface(proxy).owner();
uint256 usersCTokenBalance = CTokenInterface(cCollAddr).balanceOf(user);
// approve FL tokens so we can repay them
ERC20(_reserve).safeApprove(cBorrowAddr, _amount);
// repay compound debt on behalf of the user
require(
CTokenInterface(cBorrowAddr).repayBorrowBehalf(user, uint256(-1)) == 0,
"Repay borrow behalf fail"
);
bytes memory depositProxyCallData = formatDSProxyPullTokensCall(cCollAddr, usersCTokenBalance);
DSProxyInterface(proxy).execute(PULL_TOKENS_PROXY, depositProxyCallData);
// borrow debt now on ds proxy
bytes memory borrowProxyCallData =
formatDSProxyBorrowCall(cCollAddr, cBorrowAddr, _reserve, (_amount + _fee));
DSProxyInterface(proxy).execute(COMPOUND_BORROW_PROXY, borrowProxyCallData);
// repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
}
/// @notice Formats function data call to pull tokens to DSProxy
/// @param _cTokenAddr CToken address of the collateral
/// @param _amount Amount of cTokens to pull
function formatDSProxyPullTokensCall(
address _cTokenAddr,
uint256 _amount
) internal pure returns (bytes memory) {
return abi.encodeWithSignature(
"pullTokens(address,uint256)",
_cTokenAddr,
_amount
);
}
/// @notice Formats function data call borrow through DSProxy
/// @param _cCollToken CToken address of collateral
/// @param _cBorrowToken CToken address we will borrow
/// @param _borrowToken Token address we will borrow
/// @param _amount Amount that will be borrowed
function formatDSProxyBorrowCall(
address _cCollToken,
address _cBorrowToken,
address _borrowToken,
uint256 _amount
) internal pure returns (bytes memory) {
return abi.encodeWithSignature(
"borrow(address,address,address,uint256)",
_cCollToken,
_cBorrowToken,
_borrowToken,
_amount
);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/GasBurner.sol";
import "../../auth/AdminAuth.sol";
import "../../auth/ProxyPermission.sol";
import "../../utils/DydxFlashLoanBase.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../interfaces/ProxyRegistryInterface.sol";
import "../../interfaces/TokenInterface.sol";
import "../../interfaces/ERC20.sol";
import "../../exchangeV3/DFSExchangeData.sol";
/// @title Import Aave position from account to wallet
/// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction)
contract AaveSaverTakerV2 is DydxFlashLoanBase, ProxyPermission, GasBurner, DFSExchangeData {
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public constant AAVE_RECEIVER = 0x5a7689F1452d57E92878e0c0Be47cA3525e8Fcc9;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
function repay(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable {
_flashLoan(_market, _data, _rateMode,_gasCost, true, _flAmount);
}
function boost(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable {
_flashLoan(_market, _data, _rateMode, _gasCost, false, _flAmount);
}
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must send 2 wei with this transaction
function _flashLoan(address _market, ExchangeData memory _data, uint _rateMode, uint _gasCost, bool _isRepay, uint _flAmount) internal {
ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS);
uint256 ethAmount = _flAmount;
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR);
// Calculate repay amount (_amount + (2 wei))
// Approve transfer from
uint256 repayAmount = _getRepaymentAmountInternal(ethAmount);
ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount);
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, ethAmount, AAVE_RECEIVER);
AAVE_RECEIVER.transfer(msg.value);
bytes memory encodedData = packExchangeData(_data);
operations[1] = _getCallAction(
abi.encode(encodedData, _market, _rateMode, _gasCost, _isRepay, ethAmount, msg.value, proxyOwner(), address(this)),
AAVE_RECEIVER
);
operations[2] = _getDepositAction(marketId, repayAmount, address(this));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
givePermission(AAVE_RECEIVER);
solo.operate(accountInfos, operations);
removePermission(AAVE_RECEIVER);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/GasBurner.sol";
import "../../auth/AdminAuth.sol";
import "../../auth/ProxyPermission.sol";
import "../../utils/DydxFlashLoanBase.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../interfaces/ProxyRegistryInterface.sol";
import "../../interfaces/TokenInterface.sol";
import "../../interfaces/ERC20.sol";
/// @title Import Aave position from account to wallet
/// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction)
contract AaveImportTakerV2 is DydxFlashLoanBase, ProxyPermission {
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public constant AAVE_IMPORT = 0x1C9B7FBD410Adcd213C5d6CBA12e651300061eaD;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must send 2 wei with this transaction
/// @dev User must approve DSProxy to pull _aCollateralToken
/// @param _market Market in which we want to import
/// @param _collateralToken Collateral token we are moving to DSProxy
/// @param _borrowToken Borrow token we are moving to DSProxy
/// @param _ethAmount ETH amount that needs to be pulled from dydx
function importLoan(address _market, address _collateralToken, address _borrowToken, uint _ethAmount) public {
ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS);
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR);
// Calculate repay amount (_amount + (2 wei))
// Approve transfer from
uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount);
ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount);
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, _ethAmount, AAVE_IMPORT);
operations[1] = _getCallAction(
abi.encode(_market, _collateralToken, _borrowToken, _ethAmount, address(this)),
AAVE_IMPORT
);
operations[2] = _getDepositAction(marketId, repayAmount, address(this));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
givePermission(AAVE_IMPORT);
solo.operate(accountInfos, operations);
removePermission(AAVE_IMPORT);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveImport", abi.encode(_collateralToken, _borrowToken));
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/GasBurner.sol";
import "../../auth/AdminAuth.sol";
import "../../auth/ProxyPermission.sol";
import "../../utils/DydxFlashLoanBase.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../interfaces/ProxyRegistryInterface.sol";
import "../../interfaces/TokenInterface.sol";
import "../../interfaces/ERC20.sol";
import "../../exchange/SaverExchangeCore.sol";
/// @title Import Aave position from account to wallet
/// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction)
contract AaveSaverTaker is DydxFlashLoanBase, ProxyPermission, GasBurner, SaverExchangeCore {
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public constant AAVE_RECEIVER = 0x969DfE84ac318531f13B731c7f21af9918802B94;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
function repay(ExchangeData memory _data, uint256 _gasCost) public payable {
_flashLoan(_data, _gasCost, true);
}
function boost(ExchangeData memory _data, uint256 _gasCost) public payable {
_flashLoan(_data, _gasCost, false);
}
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must send 2 wei with this transaction
function _flashLoan(ExchangeData memory _data, uint _gasCost, bool _isRepay) internal {
ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS);
uint256 ethAmount = ERC20(WETH_ADDR).balanceOf(SOLO_MARGIN_ADDRESS);
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR);
// Calculate repay amount (_amount + (2 wei))
// Approve transfer from
uint256 repayAmount = _getRepaymentAmountInternal(ethAmount);
ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount);
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, ethAmount, AAVE_RECEIVER);
AAVE_RECEIVER.transfer(msg.value);
bytes memory encodedData = packExchangeData(_data);
operations[1] = _getCallAction(
abi.encode(encodedData, _gasCost, _isRepay, ethAmount, msg.value, proxyOwner(), address(this)),
AAVE_RECEIVER
);
operations[2] = _getDepositAction(marketId, repayAmount, address(this));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
givePermission(AAVE_RECEIVER);
solo.operate(accountInfos, operations);
removePermission(AAVE_RECEIVER);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/GasBurner.sol";
import "../../auth/AdminAuth.sol";
import "../../auth/ProxyPermission.sol";
import "../../utils/DydxFlashLoanBase.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../interfaces/ProxyRegistryInterface.sol";
import "../../interfaces/TokenInterface.sol";
import "../../interfaces/ERC20.sol";
/// @title Import Aave position from account to wallet
/// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction)
contract AaveImportTaker is DydxFlashLoanBase, ProxyPermission {
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public constant AAVE_IMPORT = 0x5cD4239D2AA5b487bA87c3715127eA53685B4926;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
/// @notice Starts the process to move users position 1 collateral and 1 borrow
/// @dev User must send 2 wei with this transaction
/// @dev User must approve DSProxy to pull _aCollateralToken
/// @param _collateralToken Collateral token we are moving to DSProxy
/// @param _borrowToken Borrow token we are moving to DSProxy
/// @param _ethAmount ETH amount that needs to be pulled from dydx
function importLoan(address _collateralToken, address _borrowToken, uint _ethAmount) public {
ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS);
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR);
// Calculate repay amount (_amount + (2 wei))
// Approve transfer from
uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount);
ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount);
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, _ethAmount, AAVE_IMPORT);
operations[1] = _getCallAction(
abi.encode(_collateralToken, _borrowToken, _ethAmount, address(this)),
AAVE_IMPORT
);
operations[2] = _getDepositAction(marketId, repayAmount, address(this));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
givePermission(AAVE_IMPORT);
solo.operate(accountInfos, operations);
removePermission(AAVE_IMPORT);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveImport", abi.encode(_collateralToken, _borrowToken));
}
}
pragma solidity ^0.6.0;
import "../../interfaces/CTokenInterface.sol";
import "../../interfaces/ComptrollerInterface.sol";
import "../../utils/SafeERC20.sol";
contract CreamBorrowProxy {
using SafeERC20 for ERC20;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258;
function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public {
address[] memory markets = new address[](2);
markets[0] = _cCollToken;
markets[1] = _cBorrowToken;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0);
// withdraw funds to msg.sender
if (_borrowToken != ETH_ADDR) {
ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
}
pragma solidity ^0.6.0;
import "../DS/DSMath.sol";
import "../interfaces/CompoundOracleInterface.sol";
import "../interfaces/ComptrollerInterface.sol";
import "../interfaces/CTokenInterface.sol";
import "../compound/helpers/Exponential.sol";
contract CreamSafetyRatio is Exponential, DSMath {
// solhint-disable-next-line const-name-snakecase
ComptrollerInterface public constant comp = ComptrollerInterface(0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258);
/// @notice Calcualted the ratio of debt / adjusted collateral
/// @param _user Address of the user
function getSafetyRatio(address _user) public view returns (uint) {
// For each asset the account is in
address[] memory assets = comp.getAssetsIn(_user);
address oracleAddr = comp.oracle();
uint sumCollateral = 0;
uint sumBorrow = 0;
for (uint i = 0; i < assets.length; i++) {
address asset = assets[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory oraclePrice;
if (cTokenBalance != 0 || borrowBalance != 0) {
oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)});
}
// Sum up collateral in Eth
if (cTokenBalance != 0) {
(, uint collFactorMantissa) = comp.markets(address(asset));
Exp memory collateralFactor = Exp({mantissa: collFactorMantissa});
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, Exp memory tokensToEther) = mulExp3(collateralFactor, exchangeRate, oraclePrice);
(, sumCollateral) = mulScalarTruncateAddUInt(tokensToEther, cTokenBalance, sumCollateral);
}
// Sum up debt in Eth
if (borrowBalance != 0) {
(, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow);
}
}
if (sumBorrow == 0) return uint(-1);
uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral;
return wdiv(1e18, borrowPowerUsed);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../helpers/Exponential.sol";
import "../../utils/SafeERC20.sol";
import "../../utils/GasBurner.sol";
import "../../interfaces/CTokenInterface.sol";
import "../../interfaces/ComptrollerInterface.sol";
contract CompBalance is Exponential, GasBurner {
ComptrollerInterface public constant comp = ComptrollerInterface(
0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B
);
address public constant COMP_ADDR = 0xc00e94Cb662C3520282E6f5717214004A7f26888;
uint224 public constant compInitialIndex = 1e36;
function claimComp(
address _user,
address[] memory _cTokensSupply,
address[] memory _cTokensBorrow
) public burnGas(8) {
_claim(_user, _cTokensSupply, _cTokensBorrow);
ERC20(COMP_ADDR).transfer(msg.sender, ERC20(COMP_ADDR).balanceOf(address(this)));
}
function _claim(
address _user,
address[] memory _cTokensSupply,
address[] memory _cTokensBorrow
) internal {
address[] memory u = new address[](1);
u[0] = _user;
comp.claimComp(u, _cTokensSupply, false, true);
comp.claimComp(u, _cTokensBorrow, true, false);
}
function getBalance(address _user, address[] memory _cTokens) public view returns (uint256) {
uint256 compBalance = 0;
for (uint256 i = 0; i < _cTokens.length; ++i) {
compBalance += getSuppyBalance(_cTokens[i], _user);
compBalance += getBorrowBalance(_cTokens[i], _user);
}
compBalance = add_(comp.compAccrued(_user), compBalance);
compBalance += ERC20(COMP_ADDR).balanceOf(_user);
return compBalance;
}
function getClaimableAssets(address[] memory _cTokens, address _user)
public
view
returns (bool[] memory supplyClaims, bool[] memory borrowClaims)
{
supplyClaims = new bool[](_cTokens.length);
borrowClaims = new bool[](_cTokens.length);
for (uint256 i = 0; i < _cTokens.length; ++i) {
supplyClaims[i] = getSuppyBalance(_cTokens[i], _user) > 0;
borrowClaims[i] = getBorrowBalance(_cTokens[i], _user) > 0;
}
}
function getSuppyBalance(address _cToken, address _supplier)
public
view
returns (uint256 supplierAccrued)
{
ComptrollerInterface.CompMarketState memory supplyState = comp.compSupplyState(_cToken);
Double memory supplyIndex = Double({mantissa: supplyState.index});
Double memory supplierIndex = Double({
mantissa: comp.compSupplierIndex(_cToken, _supplier)
});
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = compInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint256 supplierTokens = CTokenInterface(_cToken).balanceOf(_supplier);
uint256 supplierDelta = mul_(supplierTokens, deltaIndex);
supplierAccrued = supplierDelta;
}
function getBorrowBalance(address _cToken, address _borrower)
public
view
returns (uint256 borrowerAccrued)
{
ComptrollerInterface.CompMarketState memory borrowState = comp.compBorrowState(_cToken);
Double memory borrowIndex = Double({mantissa: borrowState.index});
Double memory borrowerIndex = Double({
mantissa: comp.compBorrowerIndex(_cToken, _borrower)
});
Exp memory marketBorrowIndex = Exp({mantissa: CTokenInterface(_cToken).borrowIndex()});
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint256 borrowerAmount = div_(
CTokenInterface(_cToken).borrowBalanceStored(_borrower),
marketBorrowIndex
);
uint256 borrowerDelta = mul_(borrowerAmount, deltaIndex);
borrowerAccrued = borrowerDelta;
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./CompBalance.sol";
import "../../exchangeV3/DFSExchangeCore.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../interfaces/DSProxyInterface.sol";
import "../CompoundBasicProxy.sol";
contract CompLeverage is DFSExchangeCore, CompBalance {
address public constant C_COMP_ADDR = 0x70e36f6BF80a52b3B46b3aF8e106CC0ed743E8e4;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Should claim COMP and sell it to the specified token and deposit it back
/// @param exchangeData Standard Exchange struct
/// @param _cTokensSupply List of cTokens user is supplying
/// @param _cTokensBorrow List of cTokens user is borrowing
/// @param _cDepositAddr The cToken address of the asset you want to deposit
/// @param _inMarket Flag if the cToken is used as collateral
function claimAndSell(
ExchangeData memory exchangeData,
address[] memory _cTokensSupply,
address[] memory _cTokensBorrow,
address _cDepositAddr,
bool _inMarket
) public payable {
// Claim COMP token
_claim(address(this), _cTokensSupply, _cTokensBorrow);
uint compBalance = ERC20(COMP_ADDR).balanceOf(address(this));
uint depositAmount = 0;
// Exchange COMP
if (exchangeData.srcAddr != address(0)) {
exchangeData.user = msg.sender;
exchangeData.dfsFeeDivider = 400; // 0.25%
exchangeData.srcAmount = compBalance;
(, depositAmount) = _sell(exchangeData);
// if we have no deposit after, send back tokens to the user
if (_cDepositAddr == address(0)) {
if (exchangeData.destAddr != ETH_ADDRESS) {
ERC20(exchangeData.destAddr).safeTransfer(msg.sender, depositAmount);
} else {
msg.sender.transfer(address(this).balance);
}
}
}
// Deposit back a token
if (_cDepositAddr != address(0)) {
// if we are just depositing COMP without a swap
if (_cDepositAddr == C_COMP_ADDR) {
depositAmount = compBalance;
}
address tokenAddr = getUnderlyingAddr(_cDepositAddr);
deposit(tokenAddr, _cDepositAddr, depositAmount, _inMarket);
}
logger.Log(address(this), msg.sender, "CompLeverage", abi.encode(compBalance, depositAmount, _cDepositAddr, exchangeData.destAmount));
}
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable {
approveToken(_tokenAddr, _cTokenAddr);
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
if (_tokenAddr != ETH_ADDRESS) {
require(CTokenInterface(_cTokenAddr).mint(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).mint{value: _amount}(); // reverts on fail
}
}
function enterMarket(address _cTokenAddr) public {
address[] memory markets = new address[](1);
markets[0] = _cTokenAddr;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
}
function approveToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDRESS) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
}
pragma solidity ^0.6.0;
import "../utils/GasBurner.sol";
import "../utils/SafeERC20.sol";
import "../interfaces/CTokenInterface.sol";
import "../interfaces/CEtherInterface.sol";
import "../interfaces/ComptrollerInterface.sol";
/// @title Basic compound interactions through the DSProxy
contract CompoundBasicProxy is GasBurner {
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
using SafeERC20 for ERC20;
/// @notice User deposits tokens to the Compound protocol
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @param _tokenAddr The address of the token to be deposited
/// @param _cTokenAddr CTokens to be deposited
/// @param _amount Amount of tokens to be deposited
/// @param _inMarket True if the token is already in market for that address
function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
}
approveToken(_tokenAddr, _cTokenAddr);
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
if (_tokenAddr != ETH_ADDR) {
require(CTokenInterface(_cTokenAddr).mint(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail
}
}
/// @notice User withdraws tokens to the Compound protocol
/// @param _tokenAddr The address of the token to be withdrawn
/// @param _cTokenAddr CTokens to be withdrawn
/// @param _amount Amount of tokens to be withdrawn
/// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens
function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) {
if (_isCAmount) {
require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0);
} else {
require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0);
}
// withdraw funds to msg.sender
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @notice User borrows tokens to the Compound protocol
/// @param _tokenAddr The address of the token to be borrowed
/// @param _cTokenAddr CTokens to be borrowed
/// @param _amount Amount of tokens to be borrowed
/// @param _inMarket True if the token is already in market for that address
function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) {
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0);
// withdraw funds to msg.sender
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the Compound protocol
/// @param _tokenAddr The address of the token to be paybacked
/// @param _cTokenAddr CTokens to be paybacked
/// @param _amount Amount of tokens to be payedback
/// @param _wholeDebt If true the _amount will be set to the whole amount of the debt
function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable {
approveToken(_tokenAddr, _cTokenAddr);
if (_wholeDebt) {
_amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this));
}
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}();
msg.sender.transfer(address(this).balance); // send back the extra eth
}
}
/// @notice Helper method to withdraw tokens from the DSProxy
/// @param _tokenAddr Address of the token to be withdrawn
function withdrawTokens(address _tokenAddr) public {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Enters the Compound market so it can be deposited/borrowed
/// @param _cTokenAddr CToken address of the token
function enterMarket(address _cTokenAddr) public {
address[] memory markets = new address[](1);
markets[0] = _cTokenAddr;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
}
/// @notice Exits the Compound market so it can't be deposited/borrowed
/// @param _cTokenAddr CToken address of the token
function exitMarket(address _cTokenAddr) public {
ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr);
}
/// @notice Approves CToken contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _cTokenAddr Address which will gain the approval
function approveToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
}
pragma solidity ^0.6.0;
import "../utils/GasBurner.sol";
import "../utils/SafeERC20.sol";
import "../interfaces/CTokenInterface.sol";
import "../interfaces/CEtherInterface.sol";
import "../interfaces/ComptrollerInterface.sol";
/// @title Basic cream interactions through the DSProxy
contract CreamBasicProxy is GasBurner {
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258;
using SafeERC20 for ERC20;
/// @notice User deposits tokens to the cream protocol
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @param _tokenAddr The address of the token to be deposited
/// @param _cTokenAddr CTokens to be deposited
/// @param _amount Amount of tokens to be deposited
/// @param _inMarket True if the token is already in market for that address
function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
}
approveToken(_tokenAddr, _cTokenAddr);
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
if (_tokenAddr != ETH_ADDR) {
require(CTokenInterface(_cTokenAddr).mint(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail
}
}
/// @notice User withdraws tokens to the cream protocol
/// @param _tokenAddr The address of the token to be withdrawn
/// @param _cTokenAddr CTokens to be withdrawn
/// @param _amount Amount of tokens to be withdrawn
/// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens
function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) {
if (_isCAmount) {
require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0);
} else {
require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0);
}
// withdraw funds to msg.sender
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @notice User borrows tokens to the cream protocol
/// @param _tokenAddr The address of the token to be borrowed
/// @param _cTokenAddr CTokens to be borrowed
/// @param _amount Amount of tokens to be borrowed
/// @param _inMarket True if the token is already in market for that address
function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) {
if (!_inMarket) {
enterMarket(_cTokenAddr);
}
require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0);
// withdraw funds to msg.sender
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the cream protocol
/// @param _tokenAddr The address of the token to be paybacked
/// @param _cTokenAddr CTokens to be paybacked
/// @param _amount Amount of tokens to be payedback
/// @param _wholeDebt If true the _amount will be set to the whole amount of the debt
function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable {
approveToken(_tokenAddr, _cTokenAddr);
if (_wholeDebt) {
_amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this));
}
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0);
} else {
CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}();
msg.sender.transfer(address(this).balance); // send back the extra eth
}
}
/// @notice Helper method to withdraw tokens from the DSProxy
/// @param _tokenAddr Address of the token to be withdrawn
function withdrawTokens(address _tokenAddr) public {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Enters the cream market so it can be deposited/borrowed
/// @param _cTokenAddr CToken address of the token
function enterMarket(address _cTokenAddr) public {
address[] memory markets = new address[](1);
markets[0] = _cTokenAddr;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
}
/// @notice Exits the cream market so it can't be deposited/borrowed
/// @param _cTokenAddr CToken address of the token
function exitMarket(address _cTokenAddr) public {
ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr);
}
/// @notice Approves CToken contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _cTokenAddr Address which will gain the approval
function approveToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
}
pragma solidity ^0.6.0;
import "../DS/DSMath.sol";
import "../interfaces/CompoundOracleInterface.sol";
import "../interfaces/ComptrollerInterface.sol";
import "../interfaces/CTokenInterface.sol";
import "./helpers/Exponential.sol";
contract CompoundSafetyRatio is Exponential, DSMath {
// solhint-disable-next-line const-name-snakecase
ComptrollerInterface public constant comp = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
/// @notice Calcualted the ratio of debt / adjusted collateral
/// @param _user Address of the user
function getSafetyRatio(address _user) public view returns (uint) {
// For each asset the account is in
address[] memory assets = comp.getAssetsIn(_user);
address oracleAddr = comp.oracle();
uint sumCollateral = 0;
uint sumBorrow = 0;
for (uint i = 0; i < assets.length; i++) {
address asset = assets[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory oraclePrice;
if (cTokenBalance != 0 || borrowBalance != 0) {
oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)});
}
// Sum up collateral in Usd
if (cTokenBalance != 0) {
(, uint collFactorMantissa) = comp.markets(address(asset));
Exp memory collateralFactor = Exp({mantissa: collFactorMantissa});
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, Exp memory tokensToUsd) = mulExp3(collateralFactor, exchangeRate, oraclePrice);
(, sumCollateral) = mulScalarTruncateAddUInt(tokensToUsd, cTokenBalance, sumCollateral);
}
// Sum up debt in Usd
if (borrowBalance != 0) {
(, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow);
}
}
if (sumBorrow == 0) return uint(-1);
uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral;
return wdiv(1e18, borrowPowerUsed);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./CompoundSafetyRatio.sol";
import "./helpers/CompoundSaverHelper.sol";
/// @title Gets data about Compound positions
contract CompoundLoanInfo is CompoundSafetyRatio {
struct LoanData {
address user;
uint128 ratio;
address[] collAddr;
address[] borrowAddr;
uint[] collAmounts;
uint[] borrowAmounts;
}
struct TokenInfo {
address cTokenAddress;
address underlyingTokenAddress;
uint collateralFactor;
uint price;
}
struct TokenInfoFull {
address underlyingTokenAddress;
uint supplyRate;
uint borrowRate;
uint exchangeRate;
uint marketLiquidity;
uint totalSupply;
uint totalBorrow;
uint collateralFactor;
uint price;
uint borrowCap;
}
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
/// @notice Calcualted the ratio of coll/debt for a compound user
/// @param _user Address of the user
function getRatio(address _user) public view returns (uint) {
// For each asset the account is in
return getSafetyRatio(_user);
}
/// @notice Fetches Compound prices for tokens
/// @param _cTokens Arr. of cTokens for which to get the prices
/// @return prices Array of prices
function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) {
prices = new uint[](_cTokens.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokens.length; ++i) {
prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]);
}
}
/// @notice Fetches Compound collateral factors for tokens
/// @param _cTokens Arr. of cTokens for which to get the coll. factors
/// @return collFactors Array of coll. factors
function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) {
collFactors = new uint[](_cTokens.length);
for (uint i = 0; i < _cTokens.length; ++i) {
(, collFactors[i]) = comp.markets(_cTokens[i]);
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in usd
/// @param _user Address of the user
/// @return data LoanData information
function getLoanData(address _user) public view returns (LoanData memory data) {
address[] memory assets = comp.getAssetsIn(_user);
address oracleAddr = comp.oracle();
data = LoanData({
user: _user,
ratio: 0,
collAddr: new address[](assets.length),
borrowAddr: new address[](assets.length),
collAmounts: new uint[](assets.length),
borrowAmounts: new uint[](assets.length)
});
uint collPos = 0;
uint borrowPos = 0;
for (uint i = 0; i < assets.length; i++) {
address asset = assets[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory oraclePrice;
if (cTokenBalance != 0 || borrowBalance != 0) {
oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)});
}
// Sum up collateral in Usd
if (cTokenBalance != 0) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, Exp memory tokensToUsd) = mulExp(exchangeRate, oraclePrice);
data.collAddr[collPos] = asset;
(, data.collAmounts[collPos]) = mulScalarTruncate(tokensToUsd, cTokenBalance);
collPos++;
}
// Sum up debt in Usd
if (borrowBalance != 0) {
data.borrowAddr[borrowPos] = asset;
(, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance);
borrowPos++;
}
}
data.ratio = uint128(getSafetyRatio(_user));
return data;
}
function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) {
balances = new uint[](_cTokens.length);
borrows = new uint[](_cTokens.length);
for (uint i = 0; i < _cTokens.length; i++) {
address asset = _cTokens[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance);
borrows[i] = borrowBalance;
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in usd
/// @param _users Addresses of the user
/// @return loans Array of LoanData information
function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) {
loans = new LoanData[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
loans[i] = getLoanData(_users[i]);
}
}
/// @notice Calcualted the ratio of coll/debt for a compound user
/// @param _users Addresses of the user
/// @return ratios Array of ratios
function getRatios(address[] memory _users) public view returns (uint[] memory ratios) {
ratios = new uint[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
ratios[i] = getSafetyRatio(_users[i]);
}
}
/// @notice Information about cTokens
/// @param _cTokenAddresses Array of cTokens addresses
/// @return tokens Array of cTokens infomartion
function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) {
tokens = new TokenInfo[](_cTokenAddresses.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokenAddresses.length; ++i) {
(, uint collFactor) = comp.markets(_cTokenAddresses[i]);
tokens[i] = TokenInfo({
cTokenAddress: _cTokenAddresses[i],
underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]),
collateralFactor: collFactor,
price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i])
});
}
}
/// @notice Information about cTokens
/// @param _cTokenAddresses Array of cTokens addresses
/// @return tokens Array of cTokens infomartion
function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) {
tokens = new TokenInfoFull[](_cTokenAddresses.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokenAddresses.length; ++i) {
(, uint collFactor) = comp.markets(_cTokenAddresses[i]);
CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]);
tokens[i] = TokenInfoFull({
underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]),
supplyRate: cToken.supplyRatePerBlock(),
borrowRate: cToken.borrowRatePerBlock(),
exchangeRate: cToken.exchangeRateCurrent(),
marketLiquidity: cToken.getCash(),
totalSupply: cToken.totalSupply(),
totalBorrow: cToken.totalBorrowsCurrent(),
collateralFactor: collFactor,
price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]),
borrowCap: comp.borrowCaps(_cTokenAddresses[i])
});
}
}
/// @notice Returns the underlying address of the cToken asset
/// @param _cTokenAddress cToken address
/// @return Token address of the cToken specified
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/BotRegistry.sol";
import "../../utils/GasBurner.sol";
import "./CompoundMonitorProxy.sol";
import "./CompoundSubscriptions.sol";
import "../../interfaces/GasTokenInterface.sol";
import "../../DS/DSMath.sol";
import "../../auth/AdminAuth.sol";
import "../../loggers/DefisaverLogger.sol";
import "../CompoundSafetyRatio.sol";
import "../../exchange/SaverExchangeCore.sol";
/// @title Contract implements logic of calling boost/repay in the automatic system
contract CompoundMonitor is AdminAuth, DSMath, CompoundSafetyRatio, GasBurner {
using SafeERC20 for ERC20;
enum Method { Boost, Repay }
uint public REPAY_GAS_TOKEN = 20;
uint public BOOST_GAS_TOKEN = 20;
uint constant public MAX_GAS_PRICE = 500000000000; // 500 gwei
uint public REPAY_GAS_COST = 1500000;
uint public BOOST_GAS_COST = 1000000;
address public constant GAS_TOKEN_INTERFACE_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
CompoundMonitorProxy public compoundMonitorProxy;
CompoundSubscriptions public subscriptionsContract;
address public compoundFlashLoanTakerAddress;
DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER);
modifier onlyApproved() {
require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot");
_;
}
/// @param _compoundMonitorProxy Proxy contracts that actually is authorized to call DSProxy
/// @param _subscriptions Subscriptions contract for Compound positions
/// @param _compoundFlashLoanTaker Contract that actually performs Repay/Boost
constructor(address _compoundMonitorProxy, address _subscriptions, address _compoundFlashLoanTaker) public {
compoundMonitorProxy = CompoundMonitorProxy(_compoundMonitorProxy);
subscriptionsContract = CompoundSubscriptions(_subscriptions);
compoundFlashLoanTakerAddress = _compoundFlashLoanTaker;
}
/// @notice Bots call this method to repay for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _user The actual address that owns the Compound position
function repayFor(
SaverExchangeCore.ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
address _user
) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(REPAY_GAS_COST);
compoundMonitorProxy.callExecute{value: msg.value}(
_user,
compoundFlashLoanTakerAddress,
abi.encodeWithSignature(
"repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)",
_exData,
_cAddresses,
gasCost
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticCompoundRepay", abi.encode(ratioBefore, ratioAfter));
}
/// @notice Bots call this method to boost for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _user The actual address that owns the Compound position
function boostFor(
SaverExchangeCore.ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
address _user
) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(BOOST_GAS_COST);
compoundMonitorProxy.callExecute{value: msg.value}(
_user,
compoundFlashLoanTakerAddress,
abi.encodeWithSignature(
"boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)",
_exData,
_cAddresses,
gasCost
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticCompoundBoost", abi.encode(ratioBefore, ratioAfter));
}
/******************* INTERNAL METHODS ********************************/
function returnEth() internal {
// return if some eth left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/******************* STATIC METHODS ********************************/
/// @notice Checks if Boost/Repay could be triggered for the CDP
/// @dev Called by MCDMonitor to enforce the min/max check
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Compound position
/// @return Boolean if it can be called and the ratio
function canCall(Method _method, address _user) public view returns(bool, uint) {
bool subscribed = subscriptionsContract.isSubscribed(_user);
CompoundSubscriptions.CompoundHolder memory holder = subscriptionsContract.getHolder(_user);
// check if cdp is subscribed
if (!subscribed) return (false, 0);
// check if boost and boost allowed
if (_method == Method.Boost && !holder.boostEnabled) return (false, 0);
uint currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
return (currRatio < holder.minRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.maxRatio, currRatio);
}
}
/// @dev After the Boost/Repay check if the ratio doesn't trigger another call
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Compound position
/// @return Boolean if the recent action preformed correctly and the ratio
function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) {
CompoundSubscriptions.CompoundHolder memory holder;
holder= subscriptionsContract.getHolder(_user);
uint currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
return (currRatio < holder.maxRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.minRatio, currRatio);
}
}
/// @notice Calculates gas cost (in Eth) of tx
/// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP
/// @param _gasAmount Amount of gas used for the tx
function calcGasCost(uint _gasAmount) public view returns (uint) {
uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE;
return mul(gasPrice, _gasAmount);
}
/******************* OWNER ONLY OPERATIONS ********************************/
/// @notice As the code is new, have a emergancy admin saver proxy change
function changeCompoundFlashLoanTaker(address _newCompoundFlashLoanTakerAddress) public onlyAdmin {
compoundFlashLoanTakerAddress = _newCompoundFlashLoanTakerAddress;
}
/// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions
/// @param _gasCost New gas cost for boost method
function changeBoostGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
BOOST_GAS_COST = _gasCost;
}
/// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions
/// @param _gasCost New gas cost for repay method
function changeRepayGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
REPAY_GAS_COST = _gasCost;
}
/// @notice If any tokens gets stuck in the contract owner can withdraw it
/// @param _tokenAddress Address of the ERC20 token
/// @param _to Address of the receiver
/// @param _amount The amount to be sent
function transferERC20(address _tokenAddress, address _to, uint _amount) public onlyOwner {
ERC20(_tokenAddress).safeTransfer(_to, _amount);
}
/// @notice If any Eth gets stuck in the contract owner can withdraw it
/// @param _to Address of the receiver
/// @param _amount The amount to be sent
function transferEth(address payable _to, uint _amount) public onlyOwner {
_to.transfer(_amount);
}
}
pragma solidity ^0.6.0;
import "../../interfaces/DSProxyInterface.sol";
import "../../utils/SafeERC20.sol";
import "../../auth/AdminAuth.sol";
/// @title Contract with the actuall DSProxy permission calls the automation operations
contract CompoundMonitorProxy is AdminAuth {
using SafeERC20 for ERC20;
uint public CHANGE_PERIOD;
address public monitor;
address public newMonitor;
address public lastMonitor;
uint public changeRequestedTimestamp;
mapping(address => bool) public allowed;
event MonitorChangeInitiated(address oldMonitor, address newMonitor);
event MonitorChangeCanceled();
event MonitorChangeFinished(address monitor);
event MonitorChangeReverted(address monitor);
// if someone who is allowed become malicious, owner can't be changed
modifier onlyAllowed() {
require(allowed[msg.sender] || msg.sender == owner);
_;
}
modifier onlyMonitor() {
require (msg.sender == monitor);
_;
}
constructor(uint _changePeriod) public {
CHANGE_PERIOD = _changePeriod * 1 days;
}
/// @notice Only monitor contract is able to call execute on users proxy
/// @param _owner Address of cdp owner (users DSProxy address)
/// @param _compoundSaverProxy Address of CompoundSaverProxy
/// @param _data Data to send to CompoundSaverProxy
function callExecute(address _owner, address _compoundSaverProxy, bytes memory _data) public payable onlyMonitor {
// execute reverts if calling specific method fails
DSProxyInterface(_owner).execute{value: msg.value}(_compoundSaverProxy, _data);
// return if anything left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Allowed users are able to set Monitor contract without any waiting period first time
/// @param _monitor Address of Monitor contract
function setMonitor(address _monitor) public onlyAllowed {
require(monitor == address(0));
monitor = _monitor;
}
/// @notice Allowed users are able to start procedure for changing monitor
/// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change
/// @param _newMonitor address of new monitor
function changeMonitor(address _newMonitor) public onlyAllowed {
require(changeRequestedTimestamp == 0);
changeRequestedTimestamp = now;
lastMonitor = monitor;
newMonitor = _newMonitor;
emit MonitorChangeInitiated(lastMonitor, newMonitor);
}
/// @notice At any point allowed users are able to cancel monitor change
function cancelMonitorChange() public onlyAllowed {
require(changeRequestedTimestamp > 0);
changeRequestedTimestamp = 0;
newMonitor = address(0);
emit MonitorChangeCanceled();
}
/// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started
function confirmNewMonitor() public onlyAllowed {
require((changeRequestedTimestamp + CHANGE_PERIOD) < now);
require(changeRequestedTimestamp != 0);
require(newMonitor != address(0));
monitor = newMonitor;
newMonitor = address(0);
changeRequestedTimestamp = 0;
emit MonitorChangeFinished(monitor);
}
/// @notice Its possible to revert monitor to last used monitor
function revertMonitor() public onlyAllowed {
require(lastMonitor != address(0));
monitor = lastMonitor;
emit MonitorChangeReverted(monitor);
}
/// @notice Allowed users are able to add new allowed user
/// @param _user Address of user that will be allowed
function addAllowed(address _user) public onlyAllowed {
allowed[_user] = true;
}
/// @notice Allowed users are able to remove allowed user
/// @dev owner is always allowed even if someone tries to remove it from allowed mapping
/// @param _user Address of allowed user
function removeAllowed(address _user) public onlyAllowed {
allowed[_user] = false;
}
function setChangePeriod(uint _periodInDays) public onlyAllowed {
require(_periodInDays * 1 days > CHANGE_PERIOD);
CHANGE_PERIOD = _periodInDays * 1 days;
}
/// @notice In case something is left in contract, owner is able to withdraw it
/// @param _token address of token to withdraw balance
function withdrawToken(address _token) public onlyOwner {
uint balance = ERC20(_token).balanceOf(address(this));
ERC20(_token).safeTransfer(msg.sender, balance);
}
/// @notice In case something is left in contract, owner is able to withdraw it
function withdrawEth() public onlyOwner {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../auth/AdminAuth.sol";
/// @title Stores subscription information for Compound automatization
contract CompoundSubscriptions is AdminAuth {
struct CompoundHolder {
address user;
uint128 minRatio;
uint128 maxRatio;
uint128 optimalRatioBoost;
uint128 optimalRatioRepay;
bool boostEnabled;
}
struct SubPosition {
uint arrPos;
bool subscribed;
}
CompoundHolder[] public subscribers;
mapping (address => SubPosition) public subscribersPos;
uint public changeIndex;
event Subscribed(address indexed user);
event Unsubscribed(address indexed user);
event Updated(address indexed user);
event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool);
/// @dev Called by the DSProxy contract which owns the Compound position
/// @notice Adds the users Compound poistion in the list of subscriptions so it can be monitored
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalBoost Ratio amount which boost should target
/// @param _optimalRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external {
// if boost is not enabled, set max ratio to max uint
uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1);
require(checkParams(_minRatio, localMaxRatio), "Must be correct params");
SubPosition storage subInfo = subscribersPos[msg.sender];
CompoundHolder memory subscription = CompoundHolder({
minRatio: _minRatio,
maxRatio: localMaxRatio,
optimalRatioBoost: _optimalBoost,
optimalRatioRepay: _optimalRepay,
user: msg.sender,
boostEnabled: _boostEnabled
});
changeIndex++;
if (subInfo.subscribed) {
subscribers[subInfo.arrPos] = subscription;
emit Updated(msg.sender);
emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled);
} else {
subscribers.push(subscription);
subInfo.arrPos = subscribers.length - 1;
subInfo.subscribed = true;
emit Subscribed(msg.sender);
}
}
/// @notice Called by the users DSProxy
/// @dev Owner who subscribed cancels his subscription
function unsubscribe() external {
_unsubscribe(msg.sender);
}
/// @dev Checks limit if minRatio is bigger than max
/// @param _minRatio Minimum ratio, bellow which repay can be triggered
/// @param _maxRatio Maximum ratio, over which boost can be triggered
/// @return Returns bool if the params are correct
function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) {
if (_minRatio > _maxRatio) {
return false;
}
return true;
}
/// @dev Internal method to remove a subscriber from the list
/// @param _user The actual address that owns the Compound position
function _unsubscribe(address _user) internal {
require(subscribers.length > 0, "Must have subscribers in the list");
SubPosition storage subInfo = subscribersPos[_user];
require(subInfo.subscribed, "Must first be subscribed");
address lastOwner = subscribers[subscribers.length - 1].user;
SubPosition storage subInfo2 = subscribersPos[lastOwner];
subInfo2.arrPos = subInfo.arrPos;
subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1];
subscribers.pop(); // remove last element and reduce arr length
changeIndex++;
subInfo.subscribed = false;
subInfo.arrPos = 0;
emit Unsubscribed(msg.sender);
}
/// @dev Checks if the user is subscribed
/// @param _user The actual address that owns the Compound position
/// @return If the user is subscribed
function isSubscribed(address _user) public view returns (bool) {
SubPosition storage subInfo = subscribersPos[_user];
return subInfo.subscribed;
}
/// @dev Returns subscribtion information about a user
/// @param _user The actual address that owns the Compound position
/// @return Subscription information about the user if exists
function getHolder(address _user) public view returns (CompoundHolder memory) {
SubPosition storage subInfo = subscribersPos[_user];
return subscribers[subInfo.arrPos];
}
/// @notice Helper method to return all the subscribed CDPs
/// @return List of all subscribers
function getSubscribers() public view returns (CompoundHolder[] memory) {
return subscribers;
}
/// @notice Helper method for the frontend, returns all the subscribed CDPs paginated
/// @param _page What page of subscribers you want
/// @param _perPage Number of entries per page
/// @return List of all subscribers for that page
function getSubscribersByPage(uint _page, uint _perPage) public view returns (CompoundHolder[] memory) {
CompoundHolder[] memory holders = new CompoundHolder[](_perPage);
uint start = _page * _perPage;
uint end = start + _perPage;
end = (end > holders.length) ? holders.length : end;
uint count = 0;
for (uint i = start; i < end; i++) {
holders[count] = subscribers[i];
count++;
}
return holders;
}
////////////// ADMIN METHODS ///////////////////
/// @notice Admin function to unsubscribe a CDP
/// @param _user The actual address that owns the Compound position
function unsubscribeByAdmin(address _user) public onlyOwner {
SubPosition storage subInfo = subscribersPos[_user];
if (subInfo.subscribed) {
_unsubscribe(_user);
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../interfaces/GasTokenInterface.sol";
import "./DFSExchangeCore.sol";
import "../DS/DSMath.sol";
import "../loggers/DefisaverLogger.sol";
import "../auth/AdminAuth.sol";
import "../utils/GasBurner.sol";
import "../utils/SafeERC20.sol";
contract DFSExchange is DFSExchangeCore, AdminAuth, GasBurner {
using SafeERC20 for ERC20;
uint256 public constant SERVICE_FEE = 800; // 0.125% Fee
// solhint-disable-next-line const-name-snakecase
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
uint public burnAmount = 10;
/// @notice Takes a src amount of tokens and converts it into the dest token
/// @dev Takes fee from the _srcAmount before the exchange
/// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x]
/// @param _user User address who called the exchange
function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) {
exData.dfsFeeDivider = SERVICE_FEE;
exData.user = _user;
// Perform the exchange
(address wrapper, uint destAmount) = _sell(exData);
// send back any leftover ether or tokens
sendLeftover(exData.srcAddr, exData.destAddr, _user);
// log the event
logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount));
}
/// @notice Takes a dest amount of tokens and converts it from the src token
/// @dev Send always more than needed for the swap, extra will be returned
/// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x]
/// @param _user User address who called the exchange
function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){
exData.dfsFeeDivider = SERVICE_FEE;
exData.user = _user;
// Perform the exchange
(address wrapper, uint srcAmount) = _buy(exData);
// send back any leftover ether or tokens
sendLeftover(exData.srcAddr, exData.destAddr, _user);
// log the event
logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount));
}
/// @notice Changes the amount of gas token we burn for each call
/// @dev Only callable by the owner
/// @param _newBurnAmount New amount of gas tokens to be burned
function changeBurnAmount(uint _newBurnAmount) public {
require(owner == msg.sender);
burnAmount = _newBurnAmount;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../auth/AdminAuth.sol";
import "./DFSExchange.sol";
import "../utils/SafeERC20.sol";
contract AllowanceProxy is AdminAuth {
using SafeERC20 for ERC20;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
DFSExchange dfsExchange = DFSExchange(0xc2Ce04e2FB4DD20964b4410FcE718b95963a1587);
function callSell(DFSExchangeCore.ExchangeData memory exData) public payable {
pullAndSendTokens(exData.srcAddr, exData.srcAmount);
dfsExchange.sell{value: msg.value}(exData, msg.sender);
}
function callBuy(DFSExchangeCore.ExchangeData memory exData) public payable {
pullAndSendTokens(exData.srcAddr, exData.srcAmount);
dfsExchange.buy{value: msg.value}(exData, msg.sender);
}
function pullAndSendTokens(address _tokenAddr, uint _amount) internal {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
require(msg.value >= _amount, "msg.value smaller than amount");
} else {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(dfsExchange), _amount);
}
}
function ownerChangeExchange(address payable _newExchange) public onlyOwner {
dfsExchange = DFSExchange(_newExchange);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./CreamSafetyRatio.sol";
import "./helpers/CreamSaverHelper.sol";
/// @title Gets data about cream positions
contract CreamLoanInfo is CreamSafetyRatio {
struct LoanData {
address user;
uint128 ratio;
address[] collAddr;
address[] borrowAddr;
uint[] collAmounts;
uint[] borrowAmounts;
}
struct TokenInfo {
address cTokenAddress;
address underlyingTokenAddress;
uint collateralFactor;
uint price;
}
struct TokenInfoFull {
address underlyingTokenAddress;
uint supplyRate;
uint borrowRate;
uint exchangeRate;
uint marketLiquidity;
uint totalSupply;
uint totalBorrow;
uint collateralFactor;
uint price;
}
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE;
/// @notice Calcualted the ratio of coll/debt for a cream user
/// @param _user Address of the user
function getRatio(address _user) public view returns (uint) {
// For each asset the account is in
return getSafetyRatio(_user);
}
/// @notice Fetches cream prices for tokens
/// @param _cTokens Arr. of cTokens for which to get the prices
/// @return prices Array of prices
function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) {
prices = new uint[](_cTokens.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokens.length; ++i) {
prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]);
}
}
/// @notice Fetches cream collateral factors for tokens
/// @param _cTokens Arr. of cTokens for which to get the coll. factors
/// @return collFactors Array of coll. factors
function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) {
collFactors = new uint[](_cTokens.length);
for (uint i = 0; i < _cTokens.length; ++i) {
(, collFactors[i]) = comp.markets(_cTokens[i]);
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in eth
/// @param _user Address of the user
/// @return data LoanData information
function getLoanData(address _user) public view returns (LoanData memory data) {
address[] memory assets = comp.getAssetsIn(_user);
address oracleAddr = comp.oracle();
data = LoanData({
user: _user,
ratio: 0,
collAddr: new address[](assets.length),
borrowAddr: new address[](assets.length),
collAmounts: new uint[](assets.length),
borrowAmounts: new uint[](assets.length)
});
uint collPos = 0;
uint borrowPos = 0;
for (uint i = 0; i < assets.length; i++) {
address asset = assets[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory oraclePrice;
if (cTokenBalance != 0 || borrowBalance != 0) {
oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)});
}
// Sum up collateral in eth
if (cTokenBalance != 0) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, Exp memory tokensToEth) = mulExp(exchangeRate, oraclePrice);
data.collAddr[collPos] = asset;
(, data.collAmounts[collPos]) = mulScalarTruncate(tokensToEth, cTokenBalance);
collPos++;
}
// Sum up debt in eth
if (borrowBalance != 0) {
data.borrowAddr[borrowPos] = asset;
(, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance);
borrowPos++;
}
}
data.ratio = uint128(getSafetyRatio(_user));
return data;
}
function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) {
balances = new uint[](_cTokens.length);
borrows = new uint[](_cTokens.length);
for (uint i = 0; i < _cTokens.length; i++) {
address asset = _cTokens[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance);
borrows[i] = borrowBalance;
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in eth
/// @param _users Addresses of the user
/// @return loans Array of LoanData information
function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) {
loans = new LoanData[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
loans[i] = getLoanData(_users[i]);
}
}
/// @notice Calcualted the ratio of coll/debt for a cream user
/// @param _users Addresses of the user
/// @return ratios Array of ratios
function getRatios(address[] memory _users) public view returns (uint[] memory ratios) {
ratios = new uint[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
ratios[i] = getSafetyRatio(_users[i]);
}
}
/// @notice Information about cTokens
/// @param _cTokenAddresses Array of cTokens addresses
/// @return tokens Array of cTokens infomartion
function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) {
tokens = new TokenInfo[](_cTokenAddresses.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokenAddresses.length; ++i) {
(, uint collFactor) = comp.markets(_cTokenAddresses[i]);
tokens[i] = TokenInfo({
cTokenAddress: _cTokenAddresses[i],
underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]),
collateralFactor: collFactor,
price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i])
});
}
}
/// @notice Information about cTokens
/// @param _cTokenAddresses Array of cTokens addresses
/// @return tokens Array of cTokens infomartion
function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) {
tokens = new TokenInfoFull[](_cTokenAddresses.length);
address oracleAddr = comp.oracle();
for (uint i = 0; i < _cTokenAddresses.length; ++i) {
(, uint collFactor) = comp.markets(_cTokenAddresses[i]);
CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]);
tokens[i] = TokenInfoFull({
underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]),
supplyRate: cToken.supplyRatePerBlock(),
borrowRate: cToken.borrowRatePerBlock(),
exchangeRate: cToken.exchangeRateCurrent(),
marketLiquidity: cToken.getCash(),
totalSupply: cToken.totalSupply(),
totalBorrow: cToken.totalBorrowsCurrent(),
collateralFactor: collFactor,
price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i])
});
}
}
/// @notice Returns the underlying address of the cToken asset
/// @param _cTokenAddress cToken address
/// @return Token address of the cToken specified
function getUnderlyingAddr(address _cTokenAddress) internal returns (address) {
if (_cTokenAddress == CETH_ADDRESS) {
return ETH_ADDRESS;
} else {
return CTokenInterface(_cTokenAddress).underlying();
}
}
}
pragma solidity ^0.6.0;
import "../../interfaces/ERC20.sol";
import "../../interfaces/CTokenInterface.sol";
import "../../interfaces/ComptrollerInterface.sol";
import "../../utils/SafeERC20.sol";
contract CompoundBorrowProxy {
using SafeERC20 for ERC20;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public {
address[] memory markets = new address[](2);
markets[0] = _cCollToken;
markets[1] = _cBorrowToken;
ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets);
require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0);
// withdraw funds to msg.sender
if (_borrowToken != ETH_ADDR) {
ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this)));
} else {
msg.sender.transfer(address(this).balance);
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/FlashLoanReceiverBase.sol";
import "../../interfaces/DSProxyInterface.sol";
import "../../exchangeV3/DFSExchangeData.sol";
/// @title Contract that receives the FL from Aave for Repays/Boost
contract CompoundSaverFlashLoan is FlashLoanReceiverBase, DFSExchangeData {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
address payable public COMPOUND_SAVER_FLASH_PROXY = 0xcaB974d1702a056e6FF16f1DaA34646E41Ef485E;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public owner;
using SafeERC20 for ERC20;
constructor()
FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER)
public {
owner = msg.sender;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
// Format the call data for DSProxy
(bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params);
// Send Flash loan amount to DSProxy
sendLoanToProxy(proxyAddr, _reserve, _amount);
// Execute the DSProxy call
DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _amount Amount of FL
/// @param _fee Fee of the FL
/// @param _params Saver proxy params
/// @return proxyData Formated function call data
function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) {
(
bytes memory exDataBytes,
address[2] memory cAddresses, // cCollAddress, cBorrowAddress
uint256 gasCost,
bool isRepay,
address payable proxyAddr
)
= abi.decode(_params, (bytes,address[2],uint256,bool,address));
ExchangeData memory _exData = unpackExchangeData(exDataBytes);
uint[2] memory flashLoanData = [_amount, _fee];
if (isRepay) {
proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData);
} else {
proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData);
}
return (proxyData, proxyAddr);
}
/// @notice Send the FL funds received to DSProxy
/// @param _proxy DSProxy address
/// @param _reserve Token address
/// @param _amount Amount of tokens
function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, _amount);
}
_proxy.transfer(address(this).balance);
}
receive() external override(FlashLoanReceiverBase) payable {}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../exchange/SaverExchangeCore.sol";
import "../../loggers/DefisaverLogger.sol";
import "../helpers/CreamSaverHelper.sol";
/// @title Contract that implements repay/boost functionality
contract CreamSaverProxy is CreamSaverHelper, SaverExchangeCore {
DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126);
/// @notice Withdraws collateral, converts to borrowed token and repays debt
/// @dev Called through the DSProxy
/// @param _exData Exchange data
/// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
function repay(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount;
require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
(, swapAmount) = _sell(_exData);
swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]);
} else {
swapAmount = collAmount;
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
paybackDebt(swapAmount, _cAddresses[1], borrowToken, user);
// handle 0x fee
tx.origin.transfer(address(this).balance);
// log amount, collToken, borrowToken
logger.Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
/// @notice Borrows token, converts to collateral, and adds to position
/// @dev Called through the DSProxy
/// @param _exData Exchange data
/// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress]
/// @param _gasCost Gas cost for specific transaction
function boost(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable {
enterMarket(_cAddresses[0], _cAddresses[1]);
address payable user = payable(getUserAddress());
uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this));
uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount;
require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0);
address collToken = getUnderlyingAddr(_cAddresses[0]);
address borrowToken = getUnderlyingAddr(_cAddresses[1]);
uint swapAmount = 0;
if (collToken != borrowToken) {
borrowAmount -= getFee(borrowAmount, user, _gasCost, _cAddresses[1]);
_exData.srcAmount = borrowAmount;
(,swapAmount) = _sell(_exData);
} else {
swapAmount = borrowAmount;
swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]);
}
approveCToken(collToken, _cAddresses[0]);
if (collToken != ETH_ADDRESS) {
require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0);
} else {
CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail
}
// handle 0x fee
tx.origin.transfer(address(this).balance);
// log amount, collToken, borrowToken
logger.Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken));
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/GasBurner.sol";
import "../../interfaces/ILendingPool.sol";
import "./CreamSaverProxy.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../auth/ProxyPermission.sol";
/// @title Entry point for the FL Repay Boosts, called by DSProxy
contract CreamFlashLoanTaker is CreamSaverProxy, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0x3ceD2067c0B057611e4E2686Dbe40028962Cc625;
address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
/// @notice Repays the position with it's own fund or with FL if needed
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _gasCost Gas cost for specific transaction
function repayWithLoan(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable burnGas(25) {
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr);
if (_exData.srcAmount <= maxColl || availableLiquidity == 0) {
repay(_exData, _cAddresses, _gasCost);
} else {
// 0x fee
COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value);
uint loanAmount = (_exData.srcAmount - maxColl);
bytes memory encoded = packExchangeData(_exData);
bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this));
givePermission(COMPOUND_SAVER_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData);
removePermission(COMPOUND_SAVER_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CreamFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0]));
}
}
/// @notice Boosts the position with it's own fund or with FL if needed
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _gasCost Gas cost for specific transaction
function boostWithLoan(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable burnGas(20) {
uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this));
uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr);
if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) {
boost(_exData, _cAddresses, _gasCost);
} else {
// 0x fee
COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value);
uint loanAmount = (_exData.srcAmount - maxBorrow);
bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this));
givePermission(COMPOUND_SAVER_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData);
removePermission(COMPOUND_SAVER_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CreamFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1]));
}
}
function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
liquidity = AAVE_POOL_CORE.balance;
} else {
liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE);
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../savings/dydx/ISoloMargin.sol";
import "../../utils/SafeERC20.sol";
import "../../interfaces/TokenInterface.sol";
import "../../DS/DSProxy.sol";
import "../AaveHelper.sol";
import "../../auth/AdminAuth.sol";
import "../../exchange/SaverExchangeCore.sol";
/// @title Import Aave position from account to wallet
contract AaveSaverReceiver is AaveHelper, AdminAuth, SaverExchangeCore {
using SafeERC20 for ERC20;
address public constant AAVE_SAVER_PROXY = 0xCab7ce9148499E0dD8228c3c8cDb9B56Ac2bb57a;
address public constant AAVE_BASIC_PROXY = 0xd042D4E9B4186c545648c7FfFe87125c976D110B;
address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04;
function callFunction(
address sender,
Account.Info memory account,
bytes memory data
) public {
(
bytes memory exchangeDataBytes,
uint256 gasCost,
bool isRepay,
uint256 ethAmount,
uint256 txValue,
address user,
address proxy
)
= abi.decode(data, (bytes,uint256,bool,uint256,uint256,address,address));
// withdraw eth
TokenInterface(WETH_ADDRESS).withdraw(ethAmount);
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
// deposit eth on behalf of proxy
DSProxy(payable(proxy)).execute{value: ethAmount}(AAVE_BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount));
bytes memory functionData = packFunctionCall(exchangeDataBytes, gasCost, isRepay);
DSProxy(payable(proxy)).execute{value: txValue}(AAVE_SAVER_PROXY, functionData);
// withdraw deposited eth
DSProxy(payable(proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false));
// deposit eth, get weth and return to sender
TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)();
ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2);
}
function packFunctionCall(bytes memory _exchangeDataBytes, uint256 _gasCost, bool _isRepay) internal returns (bytes memory) {
ExchangeData memory exData = unpackExchangeData(_exchangeDataBytes);
bytes memory functionData;
if (_isRepay) {
functionData = abi.encodeWithSignature("repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost);
} else {
functionData = abi.encodeWithSignature("boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost);
}
return functionData;
}
/// @dev if contract receive eth, convert it to WETH
receive() external override payable {
// deposit eth and get weth
if (msg.sender == owner) {
TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)();
}
}
}
pragma solidity ^0.6.0;
import "../DS/DSMath.sol";
import "../DS/DSProxy.sol";
import "../utils/Discount.sol";
import "../interfaces/IFeeRecipient.sol";
import "../interfaces/IAToken.sol";
import "../interfaces/ILendingPool.sol";
import "../interfaces/ILendingPoolAddressesProvider.sol";
import "../interfaces/IPriceOracleGetterAave.sol";
import "../utils/SafeERC20.sol";
import "../utils/BotRegistry.sol";
contract AaveHelper is DSMath {
using SafeERC20 for ERC20;
IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A);
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee
uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8;
uint public constant NINETY_NINE_PERCENT_WEI = 990000000000000000;
uint16 public constant AAVE_REFERRAL_CODE = 64;
/// @param _collateralAddress underlying token address
/// @param _user users address
function getMaxCollateral(address _collateralAddress, address _user) public view returns (uint256) {
address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider();
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
uint256 pow10 = 10 ** (18 - _getDecimals(_collateralAddress));
// fetch all needed data
(,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user);
(,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress);
uint256 collateralPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_collateralAddress);
uint256 userTokenBalance = ILendingPool(lendingPoolCoreAddress).getUserUnderlyingAssetBalance(_collateralAddress, _user);
uint256 userTokenBalanceEth = wmul(userTokenBalance * pow10, collateralPrice);
// if borrow is 0, return whole user balance
if (totalBorrowsETH == 0) {
return userTokenBalance;
}
uint256 maxCollateralEth = div(sub(mul(currentLTV, totalCollateralETH), mul(totalBorrowsETH, 100)), currentLTV);
/// @dev final amount can't be higher than users token balance
maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth;
// might happen due to wmul precision
if (maxCollateralEth >= totalCollateralETH) {
return wdiv(totalCollateralETH, collateralPrice) / pow10;
}
// get sum of all other reserves multiplied with their liquidation thresholds by reversing formula
uint256 a = sub(wmul(currentLTV, totalCollateralETH), wmul(tokenLTV, userTokenBalanceEth));
// add new collateral amount multiplied by its threshold, and then divide with new total collateral
uint256 newLiquidationThreshold = wdiv(add(a, wmul(sub(userTokenBalanceEth, maxCollateralEth), tokenLTV)), sub(totalCollateralETH, maxCollateralEth));
// if new threshold is lower than first one, calculate new max collateral with newLiquidationThreshold
if (newLiquidationThreshold < currentLTV) {
maxCollateralEth = div(sub(mul(newLiquidationThreshold, totalCollateralETH), mul(totalBorrowsETH, 100)), newLiquidationThreshold);
maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth;
}
return wmul(wdiv(maxCollateralEth, collateralPrice) / pow10, NINETY_NINE_PERCENT_WEI);
}
/// @param _borrowAddress underlying token address
/// @param _user users address
function getMaxBorrow(address _borrowAddress, address _user) public view returns (uint256) {
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
(,,,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user);
uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress);
return wmul(wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress))), NINETY_NINE_PERCENT_WEI);
}
function getMaxBoost(address _borrowAddress, address _collateralAddress, address _user) public view returns (uint256) {
address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider();
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
(,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user);
(,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress);
totalCollateralETH = div(mul(totalCollateralETH, currentLTV), 100);
uint256 availableBorrowsETH = wmul(mul(div(sub(totalCollateralETH, totalBorrowsETH), sub(100, tokenLTV)), 100), NINETY_NINE_PERCENT_WEI);
uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress);
return wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress)));
}
/// @notice Calculates the fee amount
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _tokenAddr token addr. of token we are getting for the fee
/// @return feeAmount The amount we took for the fee
function getFee(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint feeAmount) {
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
uint fee = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
fee = AUTOMATIC_SERVICE_FEE;
}
if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) {
fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
if (_gasCost != 0) {
uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr);
_gasCost = wdiv(_gasCost, price) / (10 ** (18 - _getDecimals(_tokenAddr)));
feeAmount = add(feeAmount, _gasCost);
}
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
address walletAddr = feeRecipient.getFeeAddr();
if (_tokenAddr == ETH_ADDR) {
payable(walletAddr).transfer(feeAmount);
} else {
ERC20(_tokenAddr).safeTransfer(walletAddr, feeAmount);
}
}
/// @notice Calculates the gas cost for transaction
/// @param _amount Amount that is converted
/// @param _user Actuall user addr not DSProxy
/// @param _gasCost Ether amount of gas we are spending for tx
/// @param _tokenAddr token addr. of token we are getting for the fee
/// @return gasCost The amount we took for the gas cost
function getGasCost(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint gasCost) {
if (_gasCost == 0) return 0;
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr);
_gasCost = wmul(_gasCost, price);
gasCost = _gasCost;
// fee can't go over 20% of the whole amount
if (gasCost > (_amount / 5)) {
gasCost = _amount / 5;
}
address walletAddr = feeRecipient.getFeeAddr();
if (_tokenAddr == ETH_ADDR) {
payable(walletAddr).transfer(gasCost);
} else {
ERC20(_tokenAddr).safeTransfer(walletAddr, gasCost);
}
}
/// @notice Returns the owner of the DSProxy that called the contract
function getUserAddress() internal view returns (address) {
DSProxy proxy = DSProxy(payable(address(this)));
return proxy.owner();
}
/// @notice Approves token contract to pull underlying tokens from the DSProxy
/// @param _tokenAddr Token we are trying to approve
/// @param _caller Address which will gain the approval
function approveToken(address _tokenAddr, address _caller) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_caller, uint256(-1));
}
}
/// @notice Send specific amount from contract to specific user
/// @param _token Token we are trying to send
/// @param _user User that should receive funds
/// @param _amount Amount that should be sent
function sendContractBalance(address _token, address _user, uint _amount) public {
if (_amount == 0) return;
if (_token == ETH_ADDR) {
payable(_user).transfer(_amount);
} else {
ERC20(_token).safeTransfer(_user, _amount);
}
}
function sendFullContractBalance(address _token, address _user) public {
if (_token == ETH_ADDR) {
sendContractBalance(_token, _user, address(this).balance);
} else {
sendContractBalance(_token, _user, ERC20(_token).balanceOf(address(this)));
}
}
function _getDecimals(address _token) internal view returns (uint256) {
if (_token == ETH_ADDR) return 18;
return ERC20(_token).decimals();
}
function isAutomation() internal view returns(bool) {
return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../AaveHelper.sol";
import "../../exchangeV3/DFSExchangeCore.sol";
import "../../interfaces/IAToken.sol";
import "../../interfaces/ILendingPool.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../utils/GasBurner.sol";
contract AaveSaverProxy is GasBurner, DFSExchangeCore, AaveHelper {
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
uint public constant VARIABLE_RATE = 2;
function repay(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address payable user = payable(getUserAddress());
// redeem collateral
address aTokenCollateral = ILendingPool(lendingPoolCore).getReserveATokenAddress(_data.srcAddr);
// uint256 maxCollateral = IAToken(aTokenCollateral).balanceOf(address(this));
// don't swap more than maxCollateral
// _data.srcAmount = _data.srcAmount > maxCollateral ? maxCollateral : _data.srcAmount;
IAToken(aTokenCollateral).redeem(_data.srcAmount);
uint256 destAmount = _data.srcAmount;
if (_data.srcAddr != _data.destAddr) {
_data.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
_data.user = user;
// swap
(, destAmount) = _sell(_data);
destAmount -= getGasCost(destAmount, user, _gasCost, _data.destAddr);
} else {
destAmount -= getGasCost(destAmount, user, _gasCost, _data.destAddr);
}
// payback
if (_data.destAddr == ETH_ADDR) {
ILendingPool(lendingPool).repay{value: destAmount}(_data.destAddr, destAmount, payable(address(this)));
} else {
approveToken(_data.destAddr, lendingPoolCore);
ILendingPool(lendingPool).repay(_data.destAddr, destAmount, payable(address(this)));
}
// first return 0x fee to msg.sender as it is the address that actually sent 0x fee
sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value));
// send all leftovers from dest addr to proxy owner
sendFullContractBalance(_data.destAddr, user);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveRepay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount));
}
function boost(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) {
address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
(,,,uint256 borrowRateMode,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_data.destAddr, address(this));
address payable user = payable(getUserAddress());
// skipping this check as its too expensive
// uint256 maxBorrow = getMaxBoost(_data.srcAddr, _data.destAddr, address(this));
// _data.srcAmount = _data.srcAmount > maxBorrow ? maxBorrow : _data.srcAmount;
// borrow amount
ILendingPool(lendingPool).borrow(_data.srcAddr, _data.srcAmount, borrowRateMode == 0 ? VARIABLE_RATE : borrowRateMode, AAVE_REFERRAL_CODE);
uint256 destAmount;
if (_data.destAddr != _data.srcAddr) {
_data.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE;
_data.user = user;
// swap
(, destAmount) = _sell(_data);
destAmount -= getGasCost(_data.destAmount, user, _gasCost, _data.destAddr);
} else {
destAmount = _data.srcAmount;
destAmount -= getGasCost(_data.destAmount, user, _gasCost, _data.destAddr);
}
if (_data.destAddr == ETH_ADDR) {
ILendingPool(lendingPool).deposit{value: destAmount}(_data.destAddr, destAmount, AAVE_REFERRAL_CODE);
} else {
approveToken(_data.destAddr, lendingPoolCore);
ILendingPool(lendingPool).deposit(_data.destAddr, destAmount, AAVE_REFERRAL_CODE);
}
if (!collateralEnabled) {
ILendingPool(lendingPool).setUserUseReserveAsCollateral(_data.destAddr, true);
}
// returning to msg.sender as it is the address that actually sent 0x fee
sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value));
// send all leftovers from dest addr to proxy owner
sendFullContractBalance(_data.destAddr, user);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveBoost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount));
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../AaveHelperV2.sol";
import "../../exchangeV3/DFSExchangeCore.sol";
import "../../interfaces/IAToken.sol";
import "../../interfaces/TokenInterface.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../utils/GasBurner.sol";
contract AaveSaverProxyV2 is DFSExchangeCore, AaveHelperV2, GasBurner {
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
function repay(address _market, ExchangeData memory _data, uint _rateMode, uint _gasCost) public payable burnGas(20) {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market);
address payable user = payable(getUserAddress());
ILendingPoolV2(lendingPool).withdraw(_data.srcAddr, _data.srcAmount, address(this));
uint256 destAmount = _data.srcAmount;
if (_data.srcAddr != _data.destAddr) {
_data.user = user;
_data.dfsFeeDivider = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
_data.dfsFeeDivider = AUTOMATIC_SERVICE_FEE;
}
// swap
(, destAmount) = _sell(_data);
}
// take gas cost at the end
destAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), destAmount, user, _gasCost, _data.destAddr);
// payback
if (_data.destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).deposit.value(destAmount)();
}
approveToken(_data.destAddr, lendingPool);
// if destAmount higher than borrow repay whole debt
uint borrow;
if (_rateMode == STABLE_ID) {
(,borrow,,,,,,,) = dataProvider.getUserReserveData(_data.destAddr, address(this));
} else {
(,,borrow,,,,,,) = dataProvider.getUserReserveData(_data.destAddr, address(this));
}
ILendingPoolV2(lendingPool).repay(_data.destAddr, destAmount > borrow ? borrow : destAmount, _rateMode, payable(address(this)));
// first return 0x fee to tx.origin as it is the address that actually sent 0x fee
sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value));
// send all leftovers from dest addr to proxy owner
sendFullContractBalance(_data.destAddr, user);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveV2Repay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount));
}
function boost(address _market, ExchangeData memory _data, uint _rateMode, uint _gasCost) public payable burnGas(20) {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market);
address payable user = payable(getUserAddress());
// borrow amount
ILendingPoolV2(lendingPool).borrow(_data.srcAddr, _data.srcAmount, _rateMode, AAVE_REFERRAL_CODE, address(this));
// take gas cost at the beginning
_data.srcAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), _data.srcAmount, user, _gasCost, _data.srcAddr);
uint256 destAmount;
if (_data.destAddr != _data.srcAddr) {
_data.user = user;
_data.dfsFeeDivider = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
_data.dfsFeeDivider = AUTOMATIC_SERVICE_FEE;
}
(, destAmount) = _sell(_data);
} else {
destAmount = _data.srcAmount;
}
if (_data.destAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).deposit.value(destAmount)();
}
approveToken(_data.destAddr, lendingPool);
ILendingPoolV2(lendingPool).deposit(_data.destAddr, destAmount, address(this), AAVE_REFERRAL_CODE);
(,,,,,,,,bool collateralEnabled) = dataProvider.getUserReserveData(_data.destAddr, address(this));
if (!collateralEnabled) {
ILendingPoolV2(lendingPool).setUserUseReserveAsCollateral(_data.destAddr, true);
}
// returning to msg.sender as it is the address that actually sent 0x fee
sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value));
// send all leftovers from dest addr to proxy owner
sendFullContractBalance(_data.destAddr, user);
DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveV2Boost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount));
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../../utils/SafeERC20.sol";
import "../../../interfaces/TokenInterface.sol";
import "../../../DS/DSProxy.sol";
import "../../AaveHelperV2.sol";
import "../../../auth/AdminAuth.sol";
import "../../../exchangeV3/DFSExchangeCore.sol";
/// @title Import Aave position from account to wallet
contract AaveSaverReceiverOV2 is AaveHelperV2, AdminAuth, DFSExchangeCore {
using SafeERC20 for ERC20;
address public constant AAVE_BASIC_PROXY = 0xc17c8eB12Ba24D62E69fd57cbd504EEf418867f9;
function boost(ExchangeData memory _exchangeData, address _market, uint256 _gasCost, address _proxy) internal {
(, uint swappedAmount) = _sell(_exchangeData);
address user = DSAuth(_proxy).owner();
swappedAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), swappedAmount, user, _gasCost, _exchangeData.destAddr);
// if its eth we need to send it to the basic proxy, if not, we need to approve users proxy to pull tokens
uint256 msgValue = 0;
address token = _exchangeData.destAddr;
// sell always return eth, but deposit differentiate eth vs weth, so we change weth address to eth when we are depoisting
if (_exchangeData.destAddr == ETH_ADDR || _exchangeData.destAddr == WETH_ADDRESS) {
msgValue = swappedAmount;
token = ETH_ADDR;
} else {
ERC20(_exchangeData.destAddr).safeApprove(_proxy, swappedAmount);
}
// deposit collateral on behalf of user
DSProxy(payable(_proxy)).execute{value: msgValue}(
AAVE_BASIC_PROXY,
abi.encodeWithSignature(
"deposit(address,address,uint256)",
_market,
token,
swappedAmount
)
);
}
function repay(ExchangeData memory _exchangeData, address _market, uint256 _gasCost, address _proxy, uint256 _rateMode, uint _aaveFlashlLoanFee) internal {
// we will withdraw exactly the srcAmount, as fee we keep before selling
uint valueToWithdraw = _exchangeData.srcAmount;
// take out the fee wee need to pay and sell the rest
_exchangeData.srcAmount = _exchangeData.srcAmount - _aaveFlashlLoanFee;
(, uint swappedAmount) = _sell(_exchangeData);
// set protocol fee left to eth balance of this address
// but if destAddr is eth or weth, this also includes that value so we need to substract it
uint protocolFeeLeft = address(this).balance;
address user = DSAuth(_proxy).owner();
swappedAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), swappedAmount, user, _gasCost, _exchangeData.destAddr);
// if its eth we need to send it to the basic proxy, if not, we need to approve basic proxy to pull tokens
uint256 msgValue = 0;
if (_exchangeData.destAddr == ETH_ADDR || _exchangeData.destAddr == WETH_ADDRESS) {
protocolFeeLeft -= swappedAmount;
msgValue = swappedAmount;
} else {
ERC20(_exchangeData.destAddr).safeApprove(_proxy, swappedAmount);
}
// first payback the loan with swapped amount
DSProxy(payable(_proxy)).execute{value: msgValue}(
AAVE_BASIC_PROXY,
abi.encodeWithSignature(
"payback(address,address,uint256,uint256)",
_market,
_exchangeData.destAddr,
swappedAmount,
_rateMode
)
);
// if some tokens left after payback (full repay) we need to return it back to the proxy owner
require(user != address(0)); // be sure that we fetched the user correctly
if (_exchangeData.destAddr == ETH_ADDR || _exchangeData.destAddr == WETH_ADDRESS) {
// keep protocol fee for tx.origin, but the rest of the balance return to the user
payable(user).transfer(address(this).balance - protocolFeeLeft);
} else {
// in case its a token, just return whole value back to the user, as protocol fee is always in eth
uint amount = ERC20(_exchangeData.destAddr).balanceOf(user);
ERC20(_exchangeData.destAddr).safeTransfer(user, amount);
}
// pull the amount we flash loaned in collateral to be able to payback the debt
DSProxy(payable(_proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256)", _market, _exchangeData.srcAddr, valueToWithdraw));
}
function executeOperation(
address[] calldata,
uint256[] calldata amounts,
uint256[] calldata premiums,
address initiator,
bytes calldata params
) public returns (bool) {
(
bytes memory exchangeDataBytes,
address market,
uint256 gasCost,
uint256 rateMode,
bool isRepay,
address proxy
)
= abi.decode(params, (bytes,address,uint256,uint256,bool,address));
require(initiator == proxy, "initiator isn't proxy");
ExchangeData memory exData = unpackExchangeData(exchangeDataBytes);
exData.user = DSAuth(proxy).owner();
exData.dfsFeeDivider = MANUAL_SERVICE_FEE;
if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) {
exData.dfsFeeDivider = AUTOMATIC_SERVICE_FEE;
}
// this is to avoid stack too deep
uint fee = premiums[0];
uint totalValueToReturn = exData.srcAmount + fee;
// if its repay, we are using regular flash loan and payback the premiums
if (isRepay) {
repay(exData, market, gasCost, proxy, rateMode, fee);
address token = exData.srcAddr;
if (token == ETH_ADDR || token == WETH_ADDRESS) {
// deposit eth, get weth and return to sender
TokenInterface(WETH_ADDRESS).deposit.value(totalValueToReturn)();
token = WETH_ADDRESS;
}
ERC20(token).safeApprove(ILendingPoolAddressesProviderV2(market).getLendingPool(), totalValueToReturn);
} else {
boost(exData, market, gasCost, proxy);
}
tx.origin.transfer(address(this).balance);
return true;
}
/// @dev allow contract to receive eth from sell
receive() external override payable {}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../savings/dydx/ISoloMargin.sol";
import "../../utils/SafeERC20.sol";
import "../../interfaces/TokenInterface.sol";
import "../../DS/DSProxy.sol";
import "../AaveHelperV2.sol";
import "../../auth/AdminAuth.sol";
// weth->eth
// deposit eth for users proxy
// borrow users token from proxy
// repay on behalf of user
// pull user supply
// take eth amount from supply (if needed more, borrow it?)
// return eth to sender
/// @title Import Aave position from account to wallet
contract AaveImportV2 is AaveHelperV2, AdminAuth {
using SafeERC20 for ERC20;
address public constant BASIC_PROXY = 0xc17c8eB12Ba24D62E69fd57cbd504EEf418867f9;
address public constant PULL_TOKENS_PROXY = 0x45431b79F783e0BF0fe7eF32D06A3e061780bfc4;
function callFunction(
address,
Account.Info memory,
bytes memory data
) public {
(
address market,
address collateralToken,
address borrowToken,
uint256 ethAmount,
address proxy
)
= abi.decode(data, (address,address,address,uint256,address));
address user = DSProxy(payable(proxy)).owner();
// withdraw eth
TokenInterface(WETH_ADDRESS).withdraw(ethAmount);
IAaveProtocolDataProviderV2 dataProvider = getDataProvider(market);
uint256 globalBorrowAmountStable = 0;
uint256 globalBorrowAmountVariable = 0;
{ // avoid stack too deep
// deposit eth on behalf of proxy
DSProxy(payable(proxy)).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,address,uint256)", market, ETH_ADDR, ethAmount));
// borrow needed amount to repay users borrow
(, uint256 borrowsStable, uint256 borrowsVariable,,,,,,) = dataProvider.getUserReserveData(borrowToken, user);
if (borrowsStable > 0) {
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,address,uint256,uint256)", market, borrowToken, borrowsStable, STABLE_ID));
globalBorrowAmountStable = borrowsStable;
}
if (borrowsVariable > 0) {
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,address,uint256,uint256)", market, borrowToken, borrowsVariable, VARIABLE_ID));
globalBorrowAmountVariable = borrowsVariable;
}
}
if (globalBorrowAmountVariable > 0) {
paybackOnBehalf(market, proxy, globalBorrowAmountVariable, borrowToken, user, VARIABLE_ID);
}
if (globalBorrowAmountStable > 0) {
paybackOnBehalf(market, proxy, globalBorrowAmountStable, borrowToken, user, STABLE_ID);
}
(address aToken,,) = dataProvider.getReserveTokensAddresses(collateralToken);
// pull coll tokens
DSProxy(payable(proxy)).execute(PULL_TOKENS_PROXY, abi.encodeWithSignature("pullTokens(address,uint256)", aToken, ERC20(aToken).balanceOf(user)));
// enable as collateral
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateralIfNeeded(address,address)", market, collateralToken));
// withdraw deposited eth
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256)", market, ETH_ADDR, ethAmount));
// deposit eth, get weth and return to sender
TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}();
ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2);
}
function paybackOnBehalf(address _market, address _proxy, uint _amount, address _token, address _onBehalf, uint _rateMode) internal {
// payback on behalf of user
if (_token != ETH_ADDR) {
ERC20(_token).safeApprove(_proxy, _amount);
DSProxy(payable(_proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,uint256,address)", _market, _token, _amount, _rateMode, _onBehalf));
} else {
DSProxy(payable(_proxy)).execute{value: _amount}(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,uint256,address)", _market, _token, _amount, _rateMode, _onBehalf));
}
}
/// @dev if contract receive eth, convert it to WETH
receive() external payable {
// deposit eth and get weth
if (msg.sender == owner) {
TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}();
}
}
}
pragma solidity ^0.6.0;
import "./AaveHelperV2.sol";
import "../interfaces/ILendingPoolV2.sol";
contract AaveSafetyRatioV2 is AaveHelperV2 {
function getSafetyRatio(address _market, address _user) public view returns(uint256) {
ILendingPoolV2 lendingPool = ILendingPoolV2(ILendingPoolAddressesProviderV2(_market).getLendingPool());
(,uint256 totalDebtETH,uint256 availableBorrowsETH,,,) = lendingPool.getUserAccountData(_user);
if (totalDebtETH == 0) return uint256(0);
return wdiv(add(totalDebtETH, availableBorrowsETH), totalDebtETH);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/GasBurner.sol";
import "../../DS/DSMath.sol";
import "../../auth/AdminAuth.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../exchangeV3/DFSExchangeData.sol";
import "./AaveMonitorProxyV2.sol";
import "./AaveSubscriptionsV2.sol";
import "../AaveSafetyRatioV2.sol";
/// @title Contract implements logic of calling boost/repay in the automatic system
contract AaveMonitorV2 is AdminAuth, DSMath, AaveSafetyRatioV2, GasBurner {
using SafeERC20 for ERC20;
string public constant NAME = "AaveMonitorV2";
enum Method { Boost, Repay }
uint public REPAY_GAS_TOKEN = 20;
uint public BOOST_GAS_TOKEN = 20;
uint public MAX_GAS_PRICE = 400000000000; // 400 gwei
uint public REPAY_GAS_COST = 2000000;
uint public BOOST_GAS_COST = 2000000;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant AAVE_MARKET_ADDRESS = 0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5;
AaveMonitorProxyV2 public aaveMonitorProxy;
AaveSubscriptionsV2 public subscriptionsContract;
address public aaveSaverProxy;
DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER);
modifier onlyApproved() {
require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot");
_;
}
/// @param _aaveMonitorProxy Proxy contracts that actually is authorized to call DSProxy
/// @param _subscriptions Subscriptions contract for Aave positions
/// @param _aaveSaverProxy Contract that actually performs Repay/Boost
constructor(address _aaveMonitorProxy, address _subscriptions, address _aaveSaverProxy) public {
aaveMonitorProxy = AaveMonitorProxyV2(_aaveMonitorProxy);
subscriptionsContract = AaveSubscriptionsV2(_subscriptions);
aaveSaverProxy = _aaveSaverProxy;
}
/// @notice Bots call this method to repay for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _user The actual address that owns the Aave position
function repayFor(
DFSExchangeData.ExchangeData memory _exData,
address _user,
uint256 _rateMode,
uint256 _flAmount
) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(REPAY_GAS_COST);
aaveMonitorProxy.callExecute{value: msg.value}(
_user,
aaveSaverProxy,
abi.encodeWithSignature(
"repay(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256,uint256)",
AAVE_MARKET_ADDRESS,
_exData,
_rateMode,
gasCost,
_flAmount
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticAaveRepayV2", abi.encode(ratioBefore, ratioAfter));
}
/// @notice Bots call this method to boost for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _user The actual address that owns the Aave position
function boostFor(
DFSExchangeData.ExchangeData memory _exData,
address _user,
uint256 _rateMode,
uint256 _flAmount
) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(BOOST_GAS_COST);
aaveMonitorProxy.callExecute{value: msg.value}(
_user,
aaveSaverProxy,
abi.encodeWithSignature(
"boost(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256,uint256)",
AAVE_MARKET_ADDRESS,
_exData,
_rateMode,
gasCost,
_flAmount
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticAaveBoostV2", abi.encode(ratioBefore, ratioAfter));
}
/******************* INTERNAL METHODS ********************************/
function returnEth() internal {
// return if some eth left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/******************* STATIC METHODS ********************************/
/// @notice Checks if Boost/Repay could be triggered for the CDP
/// @dev Called by AaveMonitor to enforce the min/max check
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Aave position
/// @return Boolean if it can be called and the ratio
function canCall(Method _method, address _user) public view returns(bool, uint) {
bool subscribed = subscriptionsContract.isSubscribed(_user);
AaveSubscriptionsV2.AaveHolder memory holder = subscriptionsContract.getHolder(_user);
// check if cdp is subscribed
if (!subscribed) return (false, 0);
// check if boost and boost allowed
if (_method == Method.Boost && !holder.boostEnabled) return (false, 0);
uint currRatio = getSafetyRatio(AAVE_MARKET_ADDRESS, _user);
if (_method == Method.Repay) {
return (currRatio < holder.minRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.maxRatio, currRatio);
}
}
/// @dev After the Boost/Repay check if the ratio doesn't trigger another call
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Aave position
/// @return Boolean if the recent action preformed correctly and the ratio
function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) {
AaveSubscriptionsV2.AaveHolder memory holder;
holder = subscriptionsContract.getHolder(_user);
uint currRatio = getSafetyRatio(AAVE_MARKET_ADDRESS, _user);
if (_method == Method.Repay) {
return (currRatio < holder.maxRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.minRatio, currRatio);
}
}
/// @notice Calculates gas cost (in Eth) of tx
/// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP
/// @param _gasAmount Amount of gas used for the tx
function calcGasCost(uint _gasAmount) public view returns (uint) {
uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE;
return mul(gasPrice, _gasAmount);
}
/******************* OWNER ONLY OPERATIONS ********************************/
/// @notice As the code is new, have a emergancy admin saver proxy change
function changeAaveSaverProxy(address _newAaveSaverProxy) public onlyAdmin {
aaveSaverProxy = _newAaveSaverProxy;
}
/// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions
/// @param _gasCost New gas cost for boost method
function changeBoostGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
BOOST_GAS_COST = _gasCost;
}
/// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions
/// @param _gasCost New gas cost for repay method
function changeRepayGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
REPAY_GAS_COST = _gasCost;
}
/// @notice Allows owner to change max gas price
/// @param _maxGasPrice New max gas price
function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner {
require(_maxGasPrice < 500000000000);
MAX_GAS_PRICE = _maxGasPrice;
}
/// @notice Allows owner to change gas token amount
/// @param _gasTokenAmount New gas token amount
/// @param _repay true if repay gas token, false if boost gas token
function changeGasTokenAmount(uint _gasTokenAmount, bool _repay) public onlyOwner {
if (_repay) {
REPAY_GAS_TOKEN = _gasTokenAmount;
} else {
BOOST_GAS_TOKEN = _gasTokenAmount;
}
}
}
pragma solidity ^0.6.0;
import "../../interfaces/DSProxyInterface.sol";
import "../../utils/SafeERC20.sol";
import "../../auth/AdminAuth.sol";
/// @title Contract with the actuall DSProxy permission calls the automation operations
contract AaveMonitorProxyV2 is AdminAuth {
using SafeERC20 for ERC20;
string public constant NAME = "AaveMonitorProxyV2";
uint public CHANGE_PERIOD;
address public monitor;
address public newMonitor;
address public lastMonitor;
uint public changeRequestedTimestamp;
event MonitorChangeInitiated(address oldMonitor, address newMonitor);
event MonitorChangeCanceled();
event MonitorChangeFinished(address monitor);
event MonitorChangeReverted(address monitor);
modifier onlyMonitor() {
require (msg.sender == monitor);
_;
}
constructor(uint _changePeriod) public {
CHANGE_PERIOD = _changePeriod * 1 hours;
}
/// @notice Only monitor contract is able to call execute on users proxy
/// @param _owner Address of cdp owner (users DSProxy address)
/// @param _aaveSaverProxy Address of AaveSaverProxy
/// @param _data Data to send to AaveSaverProxy
function callExecute(address _owner, address _aaveSaverProxy, bytes memory _data) public payable onlyMonitor {
// execute reverts if calling specific method fails
DSProxyInterface(_owner).execute{value: msg.value}(_aaveSaverProxy, _data);
// return if anything left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Owner is able to set Monitor contract without any waiting period first time
/// @param _monitor Address of Monitor contract
function setMonitor(address _monitor) public onlyOwner {
require(monitor == address(0));
monitor = _monitor;
}
/// @notice Owner is able to start procedure for changing monitor
/// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change
/// @param _newMonitor address of new monitor
function changeMonitor(address _newMonitor) public onlyOwner {
require(changeRequestedTimestamp == 0);
changeRequestedTimestamp = now;
lastMonitor = monitor;
newMonitor = _newMonitor;
emit MonitorChangeInitiated(lastMonitor, newMonitor);
}
/// @notice At any point owner is able to cancel monitor change
function cancelMonitorChange() public onlyOwner {
require(changeRequestedTimestamp > 0);
changeRequestedTimestamp = 0;
newMonitor = address(0);
emit MonitorChangeCanceled();
}
/// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started
function confirmNewMonitor() public onlyOwner {
require((changeRequestedTimestamp + CHANGE_PERIOD) < now);
require(changeRequestedTimestamp != 0);
require(newMonitor != address(0));
monitor = newMonitor;
newMonitor = address(0);
changeRequestedTimestamp = 0;
emit MonitorChangeFinished(monitor);
}
/// @notice Its possible to revert monitor to last used monitor
function revertMonitor() public onlyOwner {
require(lastMonitor != address(0));
monitor = lastMonitor;
emit MonitorChangeReverted(monitor);
}
function setChangePeriod(uint _periodInHours) public onlyOwner {
require(_periodInHours * 1 hours > CHANGE_PERIOD);
CHANGE_PERIOD = _periodInHours * 1 hours;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../auth/AdminAuth.sol";
/// @title Stores subscription information for Aave automatization
contract AaveSubscriptionsV2 is AdminAuth {
string public constant NAME = "AaveSubscriptionsV2";
struct AaveHolder {
address user;
uint128 minRatio;
uint128 maxRatio;
uint128 optimalRatioBoost;
uint128 optimalRatioRepay;
bool boostEnabled;
}
struct SubPosition {
uint arrPos;
bool subscribed;
}
AaveHolder[] public subscribers;
mapping (address => SubPosition) public subscribersPos;
uint public changeIndex;
event Subscribed(address indexed user);
event Unsubscribed(address indexed user);
event Updated(address indexed user);
event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool);
/// @dev Called by the DSProxy contract which owns the Aave position
/// @notice Adds the users Aave poistion in the list of subscriptions so it can be monitored
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalBoost Ratio amount which boost should target
/// @param _optimalRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external {
// if boost is not enabled, set max ratio to max uint
uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1);
require(checkParams(_minRatio, localMaxRatio), "Must be correct params");
SubPosition storage subInfo = subscribersPos[msg.sender];
AaveHolder memory subscription = AaveHolder({
minRatio: _minRatio,
maxRatio: localMaxRatio,
optimalRatioBoost: _optimalBoost,
optimalRatioRepay: _optimalRepay,
user: msg.sender,
boostEnabled: _boostEnabled
});
changeIndex++;
if (subInfo.subscribed) {
subscribers[subInfo.arrPos] = subscription;
emit Updated(msg.sender);
emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled);
} else {
subscribers.push(subscription);
subInfo.arrPos = subscribers.length - 1;
subInfo.subscribed = true;
emit Subscribed(msg.sender);
}
}
/// @notice Called by the users DSProxy
/// @dev Owner who subscribed cancels his subscription
function unsubscribe() external {
_unsubscribe(msg.sender);
}
/// @dev Checks limit if minRatio is bigger than max
/// @param _minRatio Minimum ratio, bellow which repay can be triggered
/// @param _maxRatio Maximum ratio, over which boost can be triggered
/// @return Returns bool if the params are correct
function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) {
if (_minRatio > _maxRatio) {
return false;
}
return true;
}
/// @dev Internal method to remove a subscriber from the list
/// @param _user The actual address that owns the Aave position
function _unsubscribe(address _user) internal {
require(subscribers.length > 0, "Must have subscribers in the list");
SubPosition storage subInfo = subscribersPos[_user];
require(subInfo.subscribed, "Must first be subscribed");
address lastOwner = subscribers[subscribers.length - 1].user;
SubPosition storage subInfo2 = subscribersPos[lastOwner];
subInfo2.arrPos = subInfo.arrPos;
subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1];
subscribers.pop(); // remove last element and reduce arr length
changeIndex++;
subInfo.subscribed = false;
subInfo.arrPos = 0;
emit Unsubscribed(msg.sender);
}
/// @dev Checks if the user is subscribed
/// @param _user The actual address that owns the Aave position
/// @return If the user is subscribed
function isSubscribed(address _user) public view returns (bool) {
SubPosition storage subInfo = subscribersPos[_user];
return subInfo.subscribed;
}
/// @dev Returns subscribtion information about a user
/// @param _user The actual address that owns the Aave position
/// @return Subscription information about the user if exists
function getHolder(address _user) public view returns (AaveHolder memory) {
SubPosition storage subInfo = subscribersPos[_user];
return subscribers[subInfo.arrPos];
}
/// @notice Helper method to return all the subscribed CDPs
/// @return List of all subscribers
function getSubscribers() public view returns (AaveHolder[] memory) {
return subscribers;
}
/// @notice Helper method for the frontend, returns all the subscribed CDPs paginated
/// @param _page What page of subscribers you want
/// @param _perPage Number of entries per page
/// @return List of all subscribers for that page
function getSubscribersByPage(uint _page, uint _perPage) public view returns (AaveHolder[] memory) {
AaveHolder[] memory holders = new AaveHolder[](_perPage);
uint start = _page * _perPage;
uint end = start + _perPage;
end = (end > holders.length) ? holders.length : end;
uint count = 0;
for (uint i = start; i < end; i++) {
holders[count] = subscribers[i];
count++;
}
return holders;
}
////////////// ADMIN METHODS ///////////////////
/// @notice Admin function to unsubscribe a position
/// @param _user The actual address that owns the Aave position
function unsubscribeByAdmin(address _user) public onlyOwner {
SubPosition storage subInfo = subscribersPos[_user];
if (subInfo.subscribed) {
_unsubscribe(_user);
}
}
}
pragma solidity ^0.6.0;
import "../utils/GasBurner.sol";
import "../interfaces/TokenInterface.sol";
import "../interfaces/IAToken.sol";
import "../interfaces/ILendingPoolV2.sol";
import "./AaveHelperV2.sol";
import "../utils/SafeERC20.sol";
/// @title Basic compound interactions through the DSProxy
contract AaveBasicProxyV2 is GasBurner, AaveHelperV2 {
using SafeERC20 for ERC20;
/// @notice User deposits tokens to the Aave protocol
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @param _market address provider for specific market
/// @param _tokenAddr The address of the token to be deposited
/// @param _amount Amount of tokens to be deposited
function deposit(address _market, address _tokenAddr, uint256 _amount) public burnGas(5) payable {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
if (_tokenAddr == ETH_ADDR) {
require(msg.value == _amount);
TokenInterface(WETH_ADDRESS).deposit{value: _amount}();
_tokenAddr = WETH_ADDRESS;
} else {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount);
}
approveToken(_tokenAddr, lendingPool);
ILendingPoolV2(lendingPool).deposit(_tokenAddr, _amount, address(this), AAVE_REFERRAL_CODE);
setUserUseReserveAsCollateralIfNeeded(_market, _tokenAddr);
}
/// @notice User withdraws tokens from the Aave protocol
/// @param _market address provider for specific market
/// @param _tokenAddr The address of the token to be withdrawn
/// @param _amount Amount of tokens to be withdrawn -> send -1 for whole amount
function withdraw(address _market, address _tokenAddr, uint256 _amount) public burnGas(8) {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
_tokenAddr = changeToWeth(_tokenAddr);
if (_tokenAddr == WETH_ADDRESS) {
// if weth, pull to proxy and return ETH to user
ILendingPoolV2(lendingPool).withdraw(_tokenAddr, _amount, address(this));
// needs to use balance of in case that amount is -1 for whole debt
TokenInterface(WETH_ADDRESS).withdraw(TokenInterface(WETH_ADDRESS).balanceOf(address(this)));
msg.sender.transfer(address(this).balance);
} else {
// if not eth send directly to user
ILendingPoolV2(lendingPool).withdraw(_tokenAddr, _amount, msg.sender);
}
}
/// @notice User borrows tokens to the Aave protocol
/// @param _market address provider for specific market
/// @param _tokenAddr The address of the token to be borrowed
/// @param _amount Amount of tokens to be borrowed
/// @param _type Send 1 for stable rate and 2 for variable
function borrow(address _market, address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
_tokenAddr = changeToWeth(_tokenAddr);
ILendingPoolV2(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE, address(this));
if (_tokenAddr == WETH_ADDRESS) {
// we do this so the user gets eth instead of weth
TokenInterface(WETH_ADDRESS).withdraw(_amount);
_tokenAddr = ETH_ADDR;
}
withdrawTokens(_tokenAddr);
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the Aave protocol
/// @param _market address provider for specific market
/// @param _tokenAddr The address of the token to be paybacked
/// @param _amount Amount of tokens to be payed back
function payback(address _market, address _tokenAddr, uint256 _amount, uint256 _rateMode) public burnGas(3) payable {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
_tokenAddr = changeToWeth(_tokenAddr);
if (_tokenAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).deposit{value: msg.value}();
} else {
uint amountToPull = min(_amount, ERC20(_tokenAddr).balanceOf(msg.sender));
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amountToPull);
}
approveToken(_tokenAddr, lendingPool);
ILendingPoolV2(lendingPool).repay(_tokenAddr, _amount, _rateMode, payable(address(this)));
if (_tokenAddr == WETH_ADDRESS) {
// Pull if we have any eth leftover
TokenInterface(WETH_ADDRESS).withdraw(ERC20(WETH_ADDRESS).balanceOf(address(this)));
_tokenAddr = ETH_ADDR;
}
withdrawTokens(_tokenAddr);
}
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @notice User paybacks tokens to the Aave protocol
/// @param _market address provider for specific market
/// @param _tokenAddr The address of the token to be paybacked
/// @param _amount Amount of tokens to be payed back
function paybackOnBehalf(address _market, address _tokenAddr, uint256 _amount, uint256 _rateMode, address _onBehalf) public burnGas(3) payable {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
_tokenAddr = changeToWeth(_tokenAddr);
if (_tokenAddr == WETH_ADDRESS) {
TokenInterface(WETH_ADDRESS).deposit{value: msg.value}();
} else {
uint amountToPull = min(_amount, ERC20(_tokenAddr).allowance(msg.sender, address(this)));
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amountToPull);
}
approveToken(_tokenAddr, lendingPool);
ILendingPoolV2(lendingPool).repay(_tokenAddr, _amount, _rateMode, _onBehalf);
if (_tokenAddr == WETH_ADDRESS) {
// we do this so the user gets eth instead of weth
TokenInterface(WETH_ADDRESS).withdraw(_amount);
_tokenAddr = ETH_ADDR;
}
withdrawTokens(_tokenAddr);
}
/// @notice Helper method to withdraw tokens from the DSProxy
/// @param _tokenAddr Address of the token to be withdrawn
function withdrawTokens(address _tokenAddr) public {
uint256 amount = _tokenAddr == ETH_ADDR ? address(this).balance : ERC20(_tokenAddr).balanceOf(address(this));
if (amount > 0) {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeTransfer(msg.sender, amount);
} else {
msg.sender.transfer(amount);
}
}
}
function setUserUseReserveAsCollateralIfNeeded(address _market, address _tokenAddr) public {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market);
(,,,,,,,,bool collateralEnabled) = dataProvider.getUserReserveData(_tokenAddr, address(this));
if (!collateralEnabled) {
ILendingPoolV2(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true);
}
}
function setUserUseReserveAsCollateral(address _market, address _tokenAddr, bool _true) public {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
ILendingPoolV2(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true);
}
// stable = 1, variable = 2
function swapBorrowRateMode(address _market, address _reserve, uint _rateMode) public {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
ILendingPoolV2(lendingPool).swapBorrowRateMode(_reserve, _rateMode);
}
function changeToWeth(address _token) private view returns(address) {
if (_token == ETH_ADDR) {
return WETH_ADDRESS;
}
return _token;
}
// solhint-disable-next-line no-empty-blocks
receive() external virtual payable {}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./AaveSafetyRatioV2.sol";
import "../interfaces/IAaveProtocolDataProviderV2.sol";
contract AaveLoanInfoV2 is AaveSafetyRatioV2 {
struct LoanData {
address user;
uint128 ratio;
address[] collAddr;
address[] borrowAddr;
uint256[] collAmounts;
uint256[] borrowStableAmounts;
uint256[] borrowVariableAmounts;
}
struct TokenInfo {
address aTokenAddress;
address underlyingTokenAddress;
uint256 collateralFactor;
uint256 price;
}
struct TokenInfoFull {
address aTokenAddress;
address underlyingTokenAddress;
uint256 supplyRate;
uint256 borrowRateVariable;
uint256 borrowRateStable;
uint256 totalSupply;
uint256 availableLiquidity;
uint256 totalBorrow;
uint256 collateralFactor;
uint256 liquidationRatio;
uint256 price;
bool usageAsCollateralEnabled;
bool borrowinEnabled;
bool stableBorrowRateEnabled;
}
struct ReserveData {
uint256 availableLiquidity;
uint256 totalStableDebt;
uint256 totalVariableDebt;
uint256 liquidityRate;
uint256 variableBorrowRate;
uint256 stableBorrowRate;
}
struct UserToken {
address token;
uint256 balance;
uint256 borrowsStable;
uint256 borrowsVariable;
uint256 stableBorrowRate;
bool enabledAsCollateral;
}
/// @notice Calcualted the ratio of coll/debt for a compound user
/// @param _market Address of LendingPoolAddressesProvider for specific market
/// @param _user Address of the user
function getRatio(address _market, address _user) public view returns (uint256) {
// For each asset the account is in
return getSafetyRatio(_market, _user);
}
/// @notice Fetches Aave prices for tokens
/// @param _market Address of LendingPoolAddressesProvider for specific market
/// @param _tokens Arr. of tokens for which to get the prices
/// @return prices Array of prices
function getPrices(address _market, address[] memory _tokens) public view returns (uint256[] memory prices) {
address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle();
prices = IPriceOracleGetterAave(priceOracleAddress).getAssetsPrices(_tokens);
}
/// @notice Fetches Aave collateral factors for tokens
/// @param _market Address of LendingPoolAddressesProvider for specific market
/// @param _tokens Arr. of tokens for which to get the coll. factors
/// @return collFactors Array of coll. factors
function getCollFactors(address _market, address[] memory _tokens) public view returns (uint256[] memory collFactors) {
IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market);
collFactors = new uint256[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; ++i) {
(,collFactors[i],,,,,,,,) = dataProvider.getReserveConfigurationData(_tokens[i]);
}
}
function getTokenBalances(address _market, address _user, address[] memory _tokens) public view returns (UserToken[] memory userTokens) {
IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market);
userTokens = new UserToken[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; i++) {
address asset = _tokens[i];
userTokens[i].token = asset;
(userTokens[i].balance, userTokens[i].borrowsStable, userTokens[i].borrowsVariable,,,userTokens[i].stableBorrowRate,,,userTokens[i].enabledAsCollateral) = dataProvider.getUserReserveData(asset, _user);
}
}
/// @notice Calcualted the ratio of coll/debt for an aave user
/// @param _market Address of LendingPoolAddressesProvider for specific market
/// @param _users Addresses of the user
/// @return ratios Array of ratios
function getRatios(address _market, address[] memory _users) public view returns (uint256[] memory ratios) {
ratios = new uint256[](_users.length);
for (uint256 i = 0; i < _users.length; ++i) {
ratios[i] = getSafetyRatio(_market, _users[i]);
}
}
/// @notice Information about reserves
/// @param _market Address of LendingPoolAddressesProvider for specific market
/// @param _tokenAddresses Array of tokens addresses
/// @return tokens Array of reserves infomartion
function getTokensInfo(address _market, address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) {
IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market);
address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle();
tokens = new TokenInfo[](_tokenAddresses.length);
for (uint256 i = 0; i < _tokenAddresses.length; ++i) {
(,uint256 ltv,,,,,,,,) = dataProvider.getReserveConfigurationData(_tokenAddresses[i]);
(address aToken,,) = dataProvider.getReserveTokensAddresses(_tokenAddresses[i]);
tokens[i] = TokenInfo({
aTokenAddress: aToken,
underlyingTokenAddress: _tokenAddresses[i],
collateralFactor: ltv,
price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i])
});
}
}
function getTokenInfoFull(IAaveProtocolDataProviderV2 _dataProvider, address _priceOracleAddress, address _token) private view returns(TokenInfoFull memory _tokenInfo) {
(
, // uint256 decimals
uint256 ltv,
uint256 liquidationThreshold,
, // uint256 liquidationBonus
, // uint256 reserveFactor
bool usageAsCollateralEnabled,
bool borrowinEnabled,
bool stableBorrowRateEnabled,
, // bool isActive
// bool isFrozen
) = _dataProvider.getReserveConfigurationData(_token);
ReserveData memory t;
(
t.availableLiquidity,
t.totalStableDebt,
t.totalVariableDebt,
t.liquidityRate,
t.variableBorrowRate,
t.stableBorrowRate,
,
,
,
) = _dataProvider.getReserveData(_token);
(address aToken,,) = _dataProvider.getReserveTokensAddresses(_token);
uint price = IPriceOracleGetterAave(_priceOracleAddress).getAssetPrice(_token);
_tokenInfo = TokenInfoFull({
aTokenAddress: aToken,
underlyingTokenAddress: _token,
supplyRate: t.liquidityRate,
borrowRateVariable: t.variableBorrowRate,
borrowRateStable: t.stableBorrowRate,
totalSupply: ERC20(aToken).totalSupply(),
availableLiquidity: t.availableLiquidity,
totalBorrow: t.totalVariableDebt+t.totalStableDebt,
collateralFactor: ltv,
liquidationRatio: liquidationThreshold,
price: price,
usageAsCollateralEnabled: usageAsCollateralEnabled,
borrowinEnabled: borrowinEnabled,
stableBorrowRateEnabled: stableBorrowRateEnabled
});
}
/// @notice Information about reserves
/// @param _market Address of LendingPoolAddressesProvider for specific market
/// @param _tokenAddresses Array of token addresses
/// @return tokens Array of reserves infomartion
function getFullTokensInfo(address _market, address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) {
IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market);
address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle();
tokens = new TokenInfoFull[](_tokenAddresses.length);
for (uint256 i = 0; i < _tokenAddresses.length; ++i) {
tokens[i] = getTokenInfoFull(dataProvider, priceOracleAddress, _tokenAddresses[i]);
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in ether
/// @param _market Address of LendingPoolAddressesProvider for specific market
/// @param _user Address of the user
/// @return data LoanData information
function getLoanData(address _market, address _user) public view returns (LoanData memory data) {
IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market);
address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle();
IAaveProtocolDataProviderV2.TokenData[] memory reserves = dataProvider.getAllReservesTokens();
data = LoanData({
user: _user,
ratio: 0,
collAddr: new address[](reserves.length),
borrowAddr: new address[](reserves.length),
collAmounts: new uint[](reserves.length),
borrowStableAmounts: new uint[](reserves.length),
borrowVariableAmounts: new uint[](reserves.length)
});
uint64 collPos = 0;
uint64 borrowStablePos = 0;
uint64 borrowVariablePos = 0;
for (uint64 i = 0; i < reserves.length; i++) {
address reserve = reserves[i].tokenAddress;
(uint256 aTokenBalance, uint256 borrowsStable, uint256 borrowsVariable,,,,,,) = dataProvider.getUserReserveData(reserve, _user);
uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserve);
if (aTokenBalance > 0) {
uint256 userTokenBalanceEth = wmul(aTokenBalance, price) * (10 ** (18 - _getDecimals(reserve)));
data.collAddr[collPos] = reserve;
data.collAmounts[collPos] = userTokenBalanceEth;
collPos++;
}
// Sum up debt in Eth
if (borrowsStable > 0) {
uint256 userBorrowBalanceEth = wmul(borrowsStable, price) * (10 ** (18 - _getDecimals(reserve)));
data.borrowAddr[borrowStablePos] = reserve;
data.borrowStableAmounts[borrowStablePos] = userBorrowBalanceEth;
borrowStablePos++;
}
// Sum up debt in Eth
if (borrowsVariable > 0) {
uint256 userBorrowBalanceEth = wmul(borrowsVariable, price) * (10 ** (18 - _getDecimals(reserve)));
data.borrowAddr[borrowVariablePos] = reserve;
data.borrowVariableAmounts[borrowVariablePos] = userBorrowBalanceEth;
borrowVariablePos++;
}
}
data.ratio = uint128(getSafetyRatio(_market, _user));
return data;
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in ether
/// @param _market Address of LendingPoolAddressesProvider for specific market
/// @param _users Addresses of the user
/// @return loans Array of LoanData information
function getLoanDataArr(address _market, address[] memory _users) public view returns (LoanData[] memory loans) {
loans = new LoanData[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
loans[i] = getLoanData(_market, _users[i]);
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../savings/dydx/ISoloMargin.sol";
import "../../utils/SafeERC20.sol";
import "../../interfaces/TokenInterface.sol";
import "../../DS/DSProxy.sol";
import "../AaveHelper.sol";
import "../../auth/AdminAuth.sol";
// weth->eth
// deposit eth for users proxy
// borrow users token from proxy
// repay on behalf of user
// pull user supply
// take eth amount from supply (if needed more, borrow it?)
// return eth to sender
/// @title Import Aave position from account to wallet
contract AaveImport is AaveHelper, AdminAuth {
using SafeERC20 for ERC20;
address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant BASIC_PROXY = 0xF499FB2feb3351aEA373723a6A0e8F6BE6fBF616;
address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04;
address public constant PULL_TOKENS_PROXY = 0x45431b79F783e0BF0fe7eF32D06A3e061780bfc4;
function callFunction(
address,
Account.Info memory,
bytes memory data
) public {
(
address collateralToken,
address borrowToken,
uint256 ethAmount,
address proxy
)
= abi.decode(data, (address,address,uint256,address));
address user = DSProxy(payable(proxy)).owner();
// withdraw eth
TokenInterface(WETH_ADDRESS).withdraw(ethAmount);
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address aCollateralToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(collateralToken);
address aBorrowToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(borrowToken);
uint256 globalBorrowAmount = 0;
{ // avoid stack too deep
// deposit eth on behalf of proxy
DSProxy(payable(proxy)).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount));
// borrow needed amount to repay users borrow
(,uint256 borrowAmount,,uint256 borrowRateMode,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(borrowToken, user);
borrowAmount += originationFee;
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,uint256,uint256)", borrowToken, borrowAmount, borrowRateMode));
globalBorrowAmount = borrowAmount;
}
// payback on behalf of user
if (borrowToken != ETH_ADDR) {
ERC20(borrowToken).safeApprove(proxy, globalBorrowAmount);
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user));
} else {
DSProxy(payable(proxy)).execute{value: globalBorrowAmount}(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user));
}
// pull coll tokens
DSProxy(payable(proxy)).execute(PULL_TOKENS_PROXY, abi.encodeWithSignature("pullTokens(address,uint256)", aCollateralToken, ERC20(aCollateralToken).balanceOf(user)));
// enable as collateral
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateralIfNeeded(address)", collateralToken));
// withdraw deposited eth
DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false));
// deposit eth, get weth and return to sender
TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}();
ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2);
}
/// @dev if contract receive eth, convert it to WETH
receive() external payable {
// deposit eth and get weth
if (msg.sender == owner) {
TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}();
}
}
}
pragma solidity ^0.6.0;
import "./AaveHelper.sol";
contract AaveSafetyRatio is AaveHelper {
function getSafetyRatio(address _user) public view returns(uint256) {
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
(,,uint256 totalBorrowsETH,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user);
if (totalBorrowsETH == 0) return uint256(0);
return wdiv(add(totalBorrowsETH, availableBorrowsETH), totalBorrowsETH);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/GasBurner.sol";
import "./AaveMonitorProxy.sol";
import "./AaveSubscriptions.sol";
import "../../DS/DSMath.sol";
import "../../auth/AdminAuth.sol";
import "../../loggers/DefisaverLogger.sol";
import "../AaveSafetyRatio.sol";
import "../../exchange/SaverExchangeCore.sol";
/// @title Contract implements logic of calling boost/repay in the automatic system
contract AaveMonitor is AdminAuth, DSMath, AaveSafetyRatio, GasBurner {
using SafeERC20 for ERC20;
enum Method { Boost, Repay }
uint public REPAY_GAS_TOKEN = 20;
uint public BOOST_GAS_TOKEN = 20;
uint public MAX_GAS_PRICE = 400000000000; // 400 gwei
uint public REPAY_GAS_COST = 2000000;
uint public BOOST_GAS_COST = 2000000;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
AaveMonitorProxy public aaveMonitorProxy;
AaveSubscriptions public subscriptionsContract;
address public aaveSaverProxy;
DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER);
modifier onlyApproved() {
require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot");
_;
}
/// @param _aaveMonitorProxy Proxy contracts that actually is authorized to call DSProxy
/// @param _subscriptions Subscriptions contract for Aave positions
/// @param _aaveSaverProxy Contract that actually performs Repay/Boost
constructor(address _aaveMonitorProxy, address _subscriptions, address _aaveSaverProxy) public {
aaveMonitorProxy = AaveMonitorProxy(_aaveMonitorProxy);
subscriptionsContract = AaveSubscriptions(_subscriptions);
aaveSaverProxy = _aaveSaverProxy;
}
/// @notice Bots call this method to repay for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _user The actual address that owns the Aave position
function repayFor(
SaverExchangeCore.ExchangeData memory _exData,
address _user
) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(REPAY_GAS_COST);
aaveMonitorProxy.callExecute{value: msg.value}(
_user,
aaveSaverProxy,
abi.encodeWithSignature(
"repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)",
_exData,
gasCost
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticAaveRepay", abi.encode(ratioBefore, ratioAfter));
}
/// @notice Bots call this method to boost for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _user The actual address that owns the Aave position
function boostFor(
SaverExchangeCore.ExchangeData memory _exData,
address _user
) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) {
(bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user);
require(isAllowed); // check if conditions are met
uint256 gasCost = calcGasCost(BOOST_GAS_COST);
aaveMonitorProxy.callExecute{value: msg.value}(
_user,
aaveSaverProxy,
abi.encodeWithSignature(
"boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)",
_exData,
gasCost
)
);
(bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user);
require(isGoodRatio); // check if the after result of the actions is good
returnEth();
logger.Log(address(this), _user, "AutomaticAaveBoost", abi.encode(ratioBefore, ratioAfter));
}
/******************* INTERNAL METHODS ********************************/
function returnEth() internal {
// return if some eth left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/******************* STATIC METHODS ********************************/
/// @notice Checks if Boost/Repay could be triggered for the CDP
/// @dev Called by AaveMonitor to enforce the min/max check
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Aave position
/// @return Boolean if it can be called and the ratio
function canCall(Method _method, address _user) public view returns(bool, uint) {
bool subscribed = subscriptionsContract.isSubscribed(_user);
AaveSubscriptions.AaveHolder memory holder = subscriptionsContract.getHolder(_user);
// check if cdp is subscribed
if (!subscribed) return (false, 0);
// check if boost and boost allowed
if (_method == Method.Boost && !holder.boostEnabled) return (false, 0);
uint currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
return (currRatio < holder.minRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.maxRatio, currRatio);
}
}
/// @dev After the Boost/Repay check if the ratio doesn't trigger another call
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Aave position
/// @return Boolean if the recent action preformed correctly and the ratio
function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) {
AaveSubscriptions.AaveHolder memory holder;
holder= subscriptionsContract.getHolder(_user);
uint currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
return (currRatio < holder.maxRatio, currRatio);
} else if (_method == Method.Boost) {
return (currRatio > holder.minRatio, currRatio);
}
}
/// @notice Calculates gas cost (in Eth) of tx
/// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP
/// @param _gasAmount Amount of gas used for the tx
function calcGasCost(uint _gasAmount) public view returns (uint) {
uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE;
return mul(gasPrice, _gasAmount);
}
/******************* OWNER ONLY OPERATIONS ********************************/
/// @notice As the code is new, have a emergancy admin saver proxy change
function changeAaveSaverProxy(address _newAaveSaverProxy) public onlyAdmin {
aaveSaverProxy = _newAaveSaverProxy;
}
/// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions
/// @param _gasCost New gas cost for boost method
function changeBoostGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
BOOST_GAS_COST = _gasCost;
}
/// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions
/// @param _gasCost New gas cost for repay method
function changeRepayGasCost(uint _gasCost) public onlyOwner {
require(_gasCost < 3000000);
REPAY_GAS_COST = _gasCost;
}
/// @notice Allows owner to change max gas price
/// @param _maxGasPrice New max gas price
function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner {
require(_maxGasPrice < 500000000000);
MAX_GAS_PRICE = _maxGasPrice;
}
/// @notice Allows owner to change gas token amount
/// @param _gasTokenAmount New gas token amount
/// @param _repay true if repay gas token, false if boost gas token
function changeGasTokenAmount(uint _gasTokenAmount, bool _repay) public onlyOwner {
if (_repay) {
REPAY_GAS_TOKEN = _gasTokenAmount;
} else {
BOOST_GAS_TOKEN = _gasTokenAmount;
}
}
}
pragma solidity ^0.6.0;
import "../../interfaces/DSProxyInterface.sol";
import "../../utils/SafeERC20.sol";
import "../../auth/AdminAuth.sol";
/// @title Contract with the actuall DSProxy permission calls the automation operations
contract AaveMonitorProxy is AdminAuth {
using SafeERC20 for ERC20;
uint public CHANGE_PERIOD;
address public monitor;
address public newMonitor;
address public lastMonitor;
uint public changeRequestedTimestamp;
mapping(address => bool) public allowed;
event MonitorChangeInitiated(address oldMonitor, address newMonitor);
event MonitorChangeCanceled();
event MonitorChangeFinished(address monitor);
event MonitorChangeReverted(address monitor);
// if someone who is allowed become malicious, owner can't be changed
modifier onlyAllowed() {
require(allowed[msg.sender] || msg.sender == owner);
_;
}
modifier onlyMonitor() {
require (msg.sender == monitor);
_;
}
constructor(uint _changePeriod) public {
CHANGE_PERIOD = _changePeriod * 1 days;
}
/// @notice Only monitor contract is able to call execute on users proxy
/// @param _owner Address of cdp owner (users DSProxy address)
/// @param _aaveSaverProxy Address of AaveSaverProxy
/// @param _data Data to send to AaveSaverProxy
function callExecute(address _owner, address _aaveSaverProxy, bytes memory _data) public payable onlyMonitor {
// execute reverts if calling specific method fails
DSProxyInterface(_owner).execute{value: msg.value}(_aaveSaverProxy, _data);
// return if anything left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Allowed users are able to set Monitor contract without any waiting period first time
/// @param _monitor Address of Monitor contract
function setMonitor(address _monitor) public onlyAllowed {
require(monitor == address(0));
monitor = _monitor;
}
/// @notice Allowed users are able to start procedure for changing monitor
/// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change
/// @param _newMonitor address of new monitor
function changeMonitor(address _newMonitor) public onlyAllowed {
require(changeRequestedTimestamp == 0);
changeRequestedTimestamp = now;
lastMonitor = monitor;
newMonitor = _newMonitor;
emit MonitorChangeInitiated(lastMonitor, newMonitor);
}
/// @notice At any point allowed users are able to cancel monitor change
function cancelMonitorChange() public onlyAllowed {
require(changeRequestedTimestamp > 0);
changeRequestedTimestamp = 0;
newMonitor = address(0);
emit MonitorChangeCanceled();
}
/// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started
function confirmNewMonitor() public onlyAllowed {
require((changeRequestedTimestamp + CHANGE_PERIOD) < now);
require(changeRequestedTimestamp != 0);
require(newMonitor != address(0));
monitor = newMonitor;
newMonitor = address(0);
changeRequestedTimestamp = 0;
emit MonitorChangeFinished(monitor);
}
/// @notice Its possible to revert monitor to last used monitor
function revertMonitor() public onlyAllowed {
require(lastMonitor != address(0));
monitor = lastMonitor;
emit MonitorChangeReverted(monitor);
}
/// @notice Allowed users are able to add new allowed user
/// @param _user Address of user that will be allowed
function addAllowed(address _user) public onlyAllowed {
allowed[_user] = true;
}
/// @notice Allowed users are able to remove allowed user
/// @dev owner is always allowed even if someone tries to remove it from allowed mapping
/// @param _user Address of allowed user
function removeAllowed(address _user) public onlyAllowed {
allowed[_user] = false;
}
function setChangePeriod(uint _periodInDays) public onlyAllowed {
require(_periodInDays * 1 days > CHANGE_PERIOD);
CHANGE_PERIOD = _periodInDays * 1 days;
}
/// @notice In case something is left in contract, owner is able to withdraw it
/// @param _token address of token to withdraw balance
function withdrawToken(address _token) public onlyOwner {
uint balance = ERC20(_token).balanceOf(address(this));
ERC20(_token).safeTransfer(msg.sender, balance);
}
/// @notice In case something is left in contract, owner is able to withdraw it
function withdrawEth() public onlyOwner {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../auth/AdminAuth.sol";
/// @title Stores subscription information for Aave automatization
contract AaveSubscriptions is AdminAuth {
struct AaveHolder {
address user;
uint128 minRatio;
uint128 maxRatio;
uint128 optimalRatioBoost;
uint128 optimalRatioRepay;
bool boostEnabled;
}
struct SubPosition {
uint arrPos;
bool subscribed;
}
AaveHolder[] public subscribers;
mapping (address => SubPosition) public subscribersPos;
uint public changeIndex;
event Subscribed(address indexed user);
event Unsubscribed(address indexed user);
event Updated(address indexed user);
event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool);
/// @dev Called by the DSProxy contract which owns the Aave position
/// @notice Adds the users Aave poistion in the list of subscriptions so it can be monitored
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalBoost Ratio amount which boost should target
/// @param _optimalRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external {
// if boost is not enabled, set max ratio to max uint
uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1);
require(checkParams(_minRatio, localMaxRatio), "Must be correct params");
SubPosition storage subInfo = subscribersPos[msg.sender];
AaveHolder memory subscription = AaveHolder({
minRatio: _minRatio,
maxRatio: localMaxRatio,
optimalRatioBoost: _optimalBoost,
optimalRatioRepay: _optimalRepay,
user: msg.sender,
boostEnabled: _boostEnabled
});
changeIndex++;
if (subInfo.subscribed) {
subscribers[subInfo.arrPos] = subscription;
emit Updated(msg.sender);
emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled);
} else {
subscribers.push(subscription);
subInfo.arrPos = subscribers.length - 1;
subInfo.subscribed = true;
emit Subscribed(msg.sender);
}
}
/// @notice Called by the users DSProxy
/// @dev Owner who subscribed cancels his subscription
function unsubscribe() external {
_unsubscribe(msg.sender);
}
/// @dev Checks limit if minRatio is bigger than max
/// @param _minRatio Minimum ratio, bellow which repay can be triggered
/// @param _maxRatio Maximum ratio, over which boost can be triggered
/// @return Returns bool if the params are correct
function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) {
if (_minRatio > _maxRatio) {
return false;
}
return true;
}
/// @dev Internal method to remove a subscriber from the list
/// @param _user The actual address that owns the Aave position
function _unsubscribe(address _user) internal {
require(subscribers.length > 0, "Must have subscribers in the list");
SubPosition storage subInfo = subscribersPos[_user];
require(subInfo.subscribed, "Must first be subscribed");
address lastOwner = subscribers[subscribers.length - 1].user;
SubPosition storage subInfo2 = subscribersPos[lastOwner];
subInfo2.arrPos = subInfo.arrPos;
subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1];
subscribers.pop(); // remove last element and reduce arr length
changeIndex++;
subInfo.subscribed = false;
subInfo.arrPos = 0;
emit Unsubscribed(msg.sender);
}
/// @dev Checks if the user is subscribed
/// @param _user The actual address that owns the Aave position
/// @return If the user is subscribed
function isSubscribed(address _user) public view returns (bool) {
SubPosition storage subInfo = subscribersPos[_user];
return subInfo.subscribed;
}
/// @dev Returns subscribtion information about a user
/// @param _user The actual address that owns the Aave position
/// @return Subscription information about the user if exists
function getHolder(address _user) public view returns (AaveHolder memory) {
SubPosition storage subInfo = subscribersPos[_user];
return subscribers[subInfo.arrPos];
}
/// @notice Helper method to return all the subscribed CDPs
/// @return List of all subscribers
function getSubscribers() public view returns (AaveHolder[] memory) {
return subscribers;
}
/// @notice Helper method for the frontend, returns all the subscribed CDPs paginated
/// @param _page What page of subscribers you want
/// @param _perPage Number of entries per page
/// @return List of all subscribers for that page
function getSubscribersByPage(uint _page, uint _perPage) public view returns (AaveHolder[] memory) {
AaveHolder[] memory holders = new AaveHolder[](_perPage);
uint start = _page * _perPage;
uint end = start + _perPage;
end = (end > holders.length) ? holders.length : end;
uint count = 0;
for (uint i = start; i < end; i++) {
holders[count] = subscribers[i];
count++;
}
return holders;
}
////////////// ADMIN METHODS ///////////////////
/// @notice Admin function to unsubscribe a position
/// @param _user The actual address that owns the Aave position
function unsubscribeByAdmin(address _user) public onlyOwner {
SubPosition storage subInfo = subscribersPos[_user];
if (subInfo.subscribed) {
_unsubscribe(_user);
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./AaveSafetyRatio.sol";
contract AaveLoanInfo is AaveSafetyRatio {
struct LoanData {
address user;
uint128 ratio;
address[] collAddr;
address[] borrowAddr;
uint256[] collAmounts;
uint256[] borrowAmounts;
}
struct TokenInfo {
address aTokenAddress;
address underlyingTokenAddress;
uint256 collateralFactor;
uint256 price;
}
struct TokenInfoFull {
address aTokenAddress;
address underlyingTokenAddress;
uint256 supplyRate;
uint256 borrowRate;
uint256 borrowRateStable;
uint256 totalSupply;
uint256 availableLiquidity;
uint256 totalBorrow;
uint256 collateralFactor;
uint256 liquidationRatio;
uint256 price;
bool usageAsCollateralEnabled;
}
struct UserToken {
address token;
uint256 balance;
uint256 borrows;
uint256 borrowRateMode;
uint256 borrowRate;
bool enabledAsCollateral;
}
/// @notice Calcualted the ratio of coll/debt for a compound user
/// @param _user Address of the user
function getRatio(address _user) public view returns (uint256) {
// For each asset the account is in
return getSafetyRatio(_user);
}
/// @notice Fetches Aave prices for tokens
/// @param _tokens Arr. of tokens for which to get the prices
/// @return prices Array of prices
function getPrices(address[] memory _tokens) public view returns (uint256[] memory prices) {
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
prices = new uint[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; ++i) {
prices[i] = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokens[i]);
}
}
/// @notice Fetches Aave collateral factors for tokens
/// @param _tokens Arr. of tokens for which to get the coll. factors
/// @return collFactors Array of coll. factors
function getCollFactors(address[] memory _tokens) public view returns (uint256[] memory collFactors) {
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
collFactors = new uint256[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; ++i) {
(,collFactors[i],,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokens[i]);
}
}
function getTokenBalances(address _user, address[] memory _tokens) public view returns (UserToken[] memory userTokens) {
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
userTokens = new UserToken[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; i++) {
address asset = _tokens[i];
userTokens[i].token = asset;
(userTokens[i].balance, userTokens[i].borrows,,userTokens[i].borrowRateMode,userTokens[i].borrowRate,,,,,userTokens[i].enabledAsCollateral) = ILendingPool(lendingPoolAddress).getUserReserveData(asset, _user);
}
}
/// @notice Calcualted the ratio of coll/debt for an aave user
/// @param _users Addresses of the user
/// @return ratios Array of ratios
function getRatios(address[] memory _users) public view returns (uint256[] memory ratios) {
ratios = new uint256[](_users.length);
for (uint256 i = 0; i < _users.length; ++i) {
ratios[i] = getSafetyRatio(_users[i]);
}
}
/// @notice Information about reserves
/// @param _tokenAddresses Array of tokens addresses
/// @return tokens Array of reserves infomartion
function getTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) {
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
tokens = new TokenInfo[](_tokenAddresses.length);
for (uint256 i = 0; i < _tokenAddresses.length; ++i) {
(,uint256 ltv,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokenAddresses[i]);
tokens[i] = TokenInfo({
aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]),
underlyingTokenAddress: _tokenAddresses[i],
collateralFactor: ltv,
price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i])
});
}
}
/// @notice Information about reserves
/// @param _tokenAddresses Array of token addresses
/// @return tokens Array of reserves infomartion
function getFullTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) {
address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore();
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
tokens = new TokenInfoFull[](_tokenAddresses.length);
for (uint256 i = 0; i < _tokenAddresses.length; ++i) {
(uint256 ltv, uint256 liqRatio,,, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowingEnabled,) = ILendingPool(lendingPoolAddress).getReserveConfigurationData(_tokenAddresses[i]);
tokens[i] = TokenInfoFull({
aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]),
underlyingTokenAddress: _tokenAddresses[i],
supplyRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentLiquidityRate(_tokenAddresses[i]),
borrowRate: borrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentVariableBorrowRate(_tokenAddresses[i]) : 0,
borrowRateStable: stableBorrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentStableBorrowRate(_tokenAddresses[i]) : 0,
totalSupply: ILendingPool(lendingPoolCoreAddress).getReserveTotalLiquidity(_tokenAddresses[i]),
availableLiquidity: ILendingPool(lendingPoolCoreAddress).getReserveAvailableLiquidity(_tokenAddresses[i]),
totalBorrow: ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsVariable(_tokenAddresses[i]) + ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsStable(_tokenAddresses[i]),
collateralFactor: ltv,
liquidationRatio: liqRatio,
price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]),
usageAsCollateralEnabled: usageAsCollateralEnabled
});
}
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in ether
/// @param _user Address of the user
/// @return data LoanData information
function getLoanData(address _user) public view returns (LoanData memory data) {
address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool();
address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle();
address[] memory reserves = ILendingPool(lendingPoolAddress).getReserves();
data = LoanData({
user: _user,
ratio: 0,
collAddr: new address[](reserves.length),
borrowAddr: new address[](reserves.length),
collAmounts: new uint[](reserves.length),
borrowAmounts: new uint[](reserves.length)
});
uint64 collPos = 0;
uint64 borrowPos = 0;
for (uint64 i = 0; i < reserves.length; i++) {
address reserve = reserves[i];
(uint256 aTokenBalance, uint256 borrowBalance,,,,,,,,) = ILendingPool(lendingPoolAddress).getUserReserveData(reserve, _user);
uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserves[i]);
if (aTokenBalance > 0) {
uint256 userTokenBalanceEth = wmul(aTokenBalance, price) * (10 ** (18 - _getDecimals(reserve)));
data.collAddr[collPos] = reserve;
data.collAmounts[collPos] = userTokenBalanceEth;
collPos++;
}
// Sum up debt in Eth
if (borrowBalance > 0) {
uint256 userBorrowBalanceEth = wmul(borrowBalance, price) * (10 ** (18 - _getDecimals(reserve)));
data.borrowAddr[borrowPos] = reserve;
data.borrowAmounts[borrowPos] = userBorrowBalanceEth;
borrowPos++;
}
}
data.ratio = uint128(getSafetyRatio(_user));
return data;
}
/// @notice Fetches all the collateral/debt address and amounts, denominated in ether
/// @param _users Addresses of the user
/// @return loans Array of LoanData information
function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) {
loans = new LoanData[](_users.length);
for (uint i = 0; i < _users.length; ++i) {
loans[i] = getLoanData(_users[i]);
}
}
}
pragma solidity ^0.6.0;
import "../DS/DSMath.sol";
import "../interfaces/TokenInterface.sol";
import "../interfaces/ExchangeInterfaceV2.sol";
import "./SaverExchangeHelper.sol";
contract Prices is DSMath {
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
enum ActionType { SELL, BUY }
/// @notice Returns the best estimated price from 2 exchanges
/// @param _amount Amount of source tokens you want to exchange
/// @param _srcToken Address of the source token
/// @param _destToken Address of the destination token
/// @param _type Type of action SELL|BUY
/// @param _wrappers Array of wrapper addresses to compare
/// @return (address, uint) The address of the best exchange and the exchange price
function getBestPrice(
uint256 _amount,
address _srcToken,
address _destToken,
ActionType _type,
address[] memory _wrappers
) public returns (address, uint256) {
uint256[] memory rates = new uint256[](_wrappers.length);
for (uint i=0; i<_wrappers.length; i++) {
rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type);
}
return getBiggestRate(_wrappers, rates);
}
/// @notice Return the expected rate from the exchange wrapper
/// @dev In case of Oasis/Uniswap handles the different precision tokens
/// @param _wrapper Address of exchange wrapper
/// @param _srcToken From token
/// @param _destToken To token
/// @param _amount Amount to be exchanged
/// @param _type Type of action SELL|BUY
function getExpectedRate(
address _wrapper,
address _srcToken,
address _destToken,
uint256 _amount,
ActionType _type
) public returns (uint256) {
bool success;
bytes memory result;
if (_type == ActionType.SELL) {
(success, result) = _wrapper.call(abi.encodeWithSignature(
"getSellRate(address,address,uint256)",
_srcToken,
_destToken,
_amount
));
} else {
(success, result) = _wrapper.call(abi.encodeWithSignature(
"getBuyRate(address,address,uint256)",
_srcToken,
_destToken,
_amount
));
}
if (success) {
return sliceUint(result, 0);
}
return 0;
}
/// @notice Finds the biggest rate between exchanges, needed for sell rate
/// @param _wrappers Array of wrappers to compare
/// @param _rates Array of rates to compare
function getBiggestRate(
address[] memory _wrappers,
uint256[] memory _rates
) internal pure returns (address, uint) {
uint256 maxIndex = 0;
// starting from 0 in case there is only one rate in array
for (uint256 i=0; i<_rates.length; i++) {
if (_rates[i] > _rates[maxIndex]) {
maxIndex = i;
}
}
return (_wrappers[maxIndex], _rates[maxIndex]);
}
function getDecimals(address _token) internal view returns (uint256) {
if (_token == KYBER_ETH_ADDRESS) return 18;
return ERC20(_token).decimals();
}
function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) {
require(bs.length >= start + 32, "slicing out of range");
uint256 x;
assembly {
x := mload(add(bs, add(0x20, start)))
}
return x;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../auth/AdminAuth.sol";
import "./SaverExchange.sol";
import "../utils/SafeERC20.sol";
contract AllowanceProxy is AdminAuth {
using SafeERC20 for ERC20;
address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
// TODO: Real saver exchange address
SaverExchange saverExchange = SaverExchange(0x235abFAd01eb1BDa28Ef94087FBAA63E18074926);
function callSell(SaverExchangeCore.ExchangeData memory exData) public payable {
pullAndSendTokens(exData.srcAddr, exData.srcAmount);
saverExchange.sell{value: msg.value}(exData, msg.sender);
}
function callBuy(SaverExchangeCore.ExchangeData memory exData) public payable {
pullAndSendTokens(exData.srcAddr, exData.srcAmount);
saverExchange.buy{value: msg.value}(exData, msg.sender);
}
function pullAndSendTokens(address _tokenAddr, uint _amount) internal {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
require(msg.value >= _amount, "msg.value smaller than amount");
} else {
ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(saverExchange), _amount);
}
}
function ownerChangeExchange(address payable _newExchange) public onlyOwner {
saverExchange = SaverExchange(_newExchange);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/SafeERC20.sol";
import "../../DS/DSMath.sol";
import "../../auth/AdminAuth.sol";
import "../DFSExchangeHelper.sol";
import "../../interfaces/OffchainWrapperInterface.sol";
import "../../interfaces/TokenInterface.sol";
contract ZeroxWrapper is OffchainWrapperInterface, DFSExchangeHelper, AdminAuth, DSMath {
string public constant ERR_SRC_AMOUNT = "Not enough funds";
string public constant ERR_PROTOCOL_FEE = "Not enough eth for protcol fee";
string public constant ERR_TOKENS_SWAPED_ZERO = "Order success but amount 0";
using SafeERC20 for ERC20;
/// @notice Takes order from 0x and returns bool indicating if it is successful
/// @param _exData Exchange data
/// @param _type Action type (buy or sell)
function takeOrder(
ExchangeData memory _exData,
ActionType _type
) override public payable returns (bool success, uint256) {
// check that contract have enough balance for exchange and protocol fee
require(getBalance(_exData.srcAddr) >= _exData.srcAmount, ERR_SRC_AMOUNT);
require(getBalance(KYBER_ETH_ADDRESS) >= _exData.offchainData.protocolFee, ERR_PROTOCOL_FEE);
/// @dev 0x always uses max approve in v1, so we approve the exact amount we want to sell
/// @dev safeApprove is modified to always first set approval to 0, then to exact amount
if (_type == ActionType.SELL) {
ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, _exData.srcAmount);
} else {
uint srcAmount = wdiv(_exData.destAmount, _exData.offchainData.price) + 1; // + 1 so we round up
ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, srcAmount);
}
// we know that it will be eth if dest addr is either weth or eth
address destAddr = _exData.destAddr == KYBER_ETH_ADDRESS ? EXCHANGE_WETH_ADDRESS : _exData.destAddr;
uint256 tokensBefore = getBalance(destAddr);
(success, ) = _exData.offchainData.exchangeAddr.call{value: _exData.offchainData.protocolFee}(_exData.offchainData.callData);
uint256 tokensSwaped = 0;
if (success) {
// get the current balance of the swaped tokens
tokensSwaped = getBalance(destAddr) - tokensBefore;
require(tokensSwaped > 0, ERR_TOKENS_SWAPED_ZERO);
}
// returns all funds from src addr, dest addr and eth funds (protocol fee leftovers)
sendLeftover(_exData.srcAddr, destAddr, msg.sender);
return (success, tokensSwaped);
}
// solhint-disable-next-line no-empty-blocks
receive() external virtual payable {}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/SafeERC20.sol";
import "../../DS/DSMath.sol";
import "../../auth/AdminAuth.sol";
import "../DFSExchangeHelper.sol";
import "../../interfaces/OffchainWrapperInterface.sol";
import "../../interfaces/TokenInterface.sol";
contract ScpWrapper is OffchainWrapperInterface, DFSExchangeHelper, AdminAuth, DSMath {
string public constant ERR_SRC_AMOUNT = "Not enough funds";
string public constant ERR_PROTOCOL_FEE = "Not enough eth for protcol fee";
string public constant ERR_TOKENS_SWAPED_ZERO = "Order success but amount 0";
using SafeERC20 for ERC20;
/// @notice Takes order from Scp and returns bool indicating if it is successful
/// @param _exData Exchange data
/// @param _type Action type (buy or sell)
function takeOrder(
ExchangeData memory _exData,
ActionType _type
) override public payable returns (bool success, uint256) {
// check that contract have enough balance for exchange and protocol fee
require(getBalance(_exData.srcAddr) >= _exData.srcAmount, ERR_SRC_AMOUNT);
require(getBalance(KYBER_ETH_ADDRESS) >= _exData.offchainData.protocolFee, ERR_PROTOCOL_FEE);
ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, _exData.srcAmount);
// write in the exact amount we are selling/buing in an order
if (_type == ActionType.SELL) {
writeUint256(_exData.offchainData.callData, 36, _exData.srcAmount);
} else {
uint srcAmount = wdiv(_exData.destAmount, _exData.offchainData.price) + 1; // + 1 so we round up
writeUint256(_exData.offchainData.callData, 36, srcAmount);
}
// we know that it will be eth if dest addr is either weth or eth
address destAddr = _exData.destAddr == KYBER_ETH_ADDRESS ? EXCHANGE_WETH_ADDRESS : _exData.destAddr;
uint256 tokensBefore = getBalance(destAddr);
(success, ) = _exData.offchainData.exchangeAddr.call{value: _exData.offchainData.protocolFee}(_exData.offchainData.callData);
uint256 tokensSwaped = 0;
if (success) {
// get the current balance of the swaped tokens
tokensSwaped = getBalance(destAddr) - tokensBefore;
require(tokensSwaped > 0, ERR_TOKENS_SWAPED_ZERO);
}
// returns all funds from src addr, dest addr and eth funds (protocol fee leftovers)
sendLeftover(_exData.srcAddr, destAddr, msg.sender);
return (success, tokensSwaped);
}
// solhint-disable-next-line no-empty-blocks
receive() external virtual payable {}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../utils/GasBurner.sol";
import "../../interfaces/ILendingPool.sol";
import "./CompoundSaverProxy.sol";
import "../../loggers/DefisaverLogger.sol";
import "../../auth/ProxyPermission.sol";
/// @title Entry point for the FL Repay Boosts, called by DSProxy
contract CompoundFlashLoanTaker is CompoundSaverProxy, ProxyPermission, GasBurner {
ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119);
address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0x819879d4725944b679371cE64474d3B92253cAb6;
address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
/// @notice Repays the position with it's own fund or with FL if needed
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _gasCost Gas cost for specific transaction
function repayWithLoan(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable burnGas(25) {
uint maxColl = getMaxCollateral(_cAddresses[0], address(this));
uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr);
if (_exData.srcAmount <= maxColl || availableLiquidity == 0) {
repay(_exData, _cAddresses, _gasCost);
} else {
// 0x fee
COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value);
uint loanAmount = (_exData.srcAmount - maxColl);
if (loanAmount > availableLiquidity) loanAmount = availableLiquidity;
bytes memory encoded = packExchangeData(_exData);
bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this));
givePermission(COMPOUND_SAVER_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData);
removePermission(COMPOUND_SAVER_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CompoundFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0]));
}
}
/// @notice Boosts the position with it's own fund or with FL if needed
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _gasCost Gas cost for specific transaction
function boostWithLoan(
ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
uint256 _gasCost
) public payable burnGas(20) {
uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this));
uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr);
if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) {
boost(_exData, _cAddresses, _gasCost);
} else {
// 0x fee
COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value);
uint loanAmount = (_exData.srcAmount - maxBorrow);
if (loanAmount > availableLiquidity) loanAmount = availableLiquidity;
bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this));
givePermission(COMPOUND_SAVER_FLASH_LOAN);
lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData);
removePermission(COMPOUND_SAVER_FLASH_LOAN);
logger.Log(address(this), msg.sender, "CompoundFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1]));
}
}
function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) {
if (_tokenAddr == KYBER_ETH_ADDRESS) {
liquidity = AAVE_POOL_CORE.balance;
} else {
liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE);
}
}
}
pragma solidity ^0.6.0;
import "../../auth/ProxyPermission.sol";
import "../../interfaces/ICompoundSubscription.sol";
/// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract
contract CompoundSubscriptionsProxy is ProxyPermission {
address public constant COMPOUND_SUBSCRIPTION_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207;
address public constant COMPOUND_MONITOR_PROXY = 0xB1cF8DE8e791E4Ed1Bd86c03E2fc1f14389Cb10a;
/// @notice Calls subscription contract and creates a DSGuard if non existent
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
givePermission(COMPOUND_MONITOR_PROXY);
ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe(
_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls subscription contract and updated existing parameters
/// @dev If subscription is non existent this will create one
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function update(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls the subscription contract to unsubscribe the caller
function unsubscribe() public {
removePermission(COMPOUND_MONITOR_PROXY);
ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).unsubscribe();
}
}
pragma solidity ^0.6.0;
abstract contract ICompoundSubscription {
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual;
function unsubscribe() public virtual;
}
pragma solidity ^0.6.0;
import "../../auth/ProxyPermission.sol";
import "../../interfaces/IAaveSubscription.sol";
/// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract
contract AaveSubscriptionsProxyV2 is ProxyPermission {
string public constant NAME = "AaveSubscriptionsProxyV2";
address public constant AAVE_SUBSCRIPTION_ADDRESS = 0x6B25043BF08182d8e86056C6548847aF607cd7CD;
address public constant AAVE_MONITOR_PROXY = 0x380982902872836ceC629171DaeAF42EcC02226e;
/// @notice Calls subscription contract and creates a DSGuard if non existent
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
givePermission(AAVE_MONITOR_PROXY);
IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(
_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls subscription contract and updated existing parameters
/// @dev If subscription is non existent this will create one
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function update(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls the subscription contract to unsubscribe the caller
function unsubscribe() public {
removePermission(AAVE_MONITOR_PROXY);
IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).unsubscribe();
}
}
pragma solidity ^0.6.0;
abstract contract IAaveSubscription {
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual;
function unsubscribe() public virtual;
}
pragma solidity ^0.6.0;
import "../../auth/ProxyPermission.sol";
import "../../interfaces/IAaveSubscription.sol";
/// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract
contract AaveSubscriptionsProxy is ProxyPermission {
address public constant AAVE_SUBSCRIPTION_ADDRESS = 0xe08ff7A2BADb634F0b581E675E6B3e583De086FC;
address public constant AAVE_MONITOR_PROXY = 0xfA560Dba3a8D0B197cA9505A2B98120DD89209AC;
/// @notice Calls subscription contract and creates a DSGuard if non existent
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
givePermission(AAVE_MONITOR_PROXY);
IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(
_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls subscription contract and updated existing parameters
/// @dev If subscription is non existent this will create one
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalRatioBoost Ratio amount which boost should target
/// @param _optimalRatioRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function update(
uint128 _minRatio,
uint128 _maxRatio,
uint128 _optimalRatioBoost,
uint128 _optimalRatioRepay,
bool _boostEnabled
) public {
IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled);
}
/// @notice Calls the subscription contract to unsubscribe the caller
function unsubscribe() public {
removePermission(AAVE_MONITOR_PROXY);
IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).unsubscribe();
}
}
pragma solidity ^0.6.0;
import "../../DS/DSGuard.sol";
import "../../DS/DSAuth.sol";
contract SubscriptionsInterfaceV2 {
function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {}
function unsubscribe(uint _cdpId) external {}
}
/// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract
contract SubscriptionsProxyV2 {
address public constant MONITOR_PROXY_ADDRESS = 0x1816A86C4DA59395522a42b871bf11A4E96A1C7a;
address public constant OLD_SUBSCRIPTION = 0x83152CAA0d344a2Fd428769529e2d490A88f4393;
address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7;
function migrate(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public {
SubscriptionsInterfaceV2(OLD_SUBSCRIPTION).unsubscribe(_cdpId);
subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled, _subscriptions);
}
function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public {
address currAuthority = address(DSAuth(address(this)).authority());
DSGuard guard = DSGuard(currAuthority);
if (currAuthority == address(0)) {
guard = DSGuardFactory(FACTORY_ADDRESS).newGuard();
DSAuth(address(this)).setAuthority(DSAuthority(address(guard)));
}
guard.permit(MONITOR_PROXY_ADDRESS, address(this), bytes4(keccak256("execute(address,bytes)")));
SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled);
}
function update(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public {
SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled);
}
function unsubscribe(uint _cdpId, address _subscriptions) public {
SubscriptionsInterfaceV2(_subscriptions).unsubscribe(_cdpId);
}
}
pragma solidity ^0.6.0;
import "../../interfaces/OsmMom.sol";
import "../../interfaces/Osm.sol";
import "../../auth/AdminAuth.sol";
import "../../interfaces/Manager.sol";
contract MCDPriceVerifier is AdminAuth {
OsmMom public osmMom = OsmMom(0x76416A4d5190d071bfed309861527431304aA14f);
Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
mapping(address => bool) public authorized;
function verifyVaultNextPrice(uint _nextPrice, uint _cdpId) public view returns(bool) {
require(authorized[msg.sender]);
bytes32 ilk = manager.ilks(_cdpId);
return verifyNextPrice(_nextPrice, ilk);
}
function verifyNextPrice(uint _nextPrice, bytes32 _ilk) public view returns(bool) {
require(authorized[msg.sender]);
address osmAddress = osmMom.osms(_ilk);
uint whitelisted = Osm(osmAddress).bud(address(this));
// If contracts doesn't have access return true
if (whitelisted != 1) return true;
(bytes32 price, bool has) = Osm(osmAddress).peep();
return has ? uint(price) == _nextPrice : false;
}
function setAuthorized(address _address, bool _allowed) public onlyOwner {
authorized[_address] = _allowed;
}
}
pragma solidity ^0.6.0;
abstract contract OsmMom {
mapping (bytes32 => address) public osms;
}
pragma solidity ^0.6.0;
abstract contract Osm {
mapping(address => uint256) public bud;
function peep() external view virtual returns (bytes32, bool);
}
pragma solidity ^0.6.0;
import "./DSProxy.sol";
abstract contract DSProxyFactoryInterface {
function build(address owner) public virtual returns (DSProxy proxy);
}
pragma solidity ^0.6.0;
import "./ERC20.sol";
//TODO: currenlty only adjusted to kyber, but should be genric interfaces for more dec. exchanges
interface ExchangeInterface {
function swapEtherToToken(uint256 _ethAmount, address _tokenAddress, uint256 _maxAmount)
external
payable
returns (uint256, uint256);
function swapTokenToEther(address _tokenAddress, uint256 _amount, uint256 _maxAmount)
external
returns (uint256);
function swapTokenToToken(address _src, address _dest, uint256 _amount)
external
payable
returns (uint256);
function getExpectedRate(address src, address dest, uint256 srcQty)
external
view
returns (uint256 expectedRate);
}
|
Approves CToken contract to pull underlying tokens from the DSProxy _tokenAddr Token we are trying to approve _cTokenAddr Address which will gain the approval
|
function approveToken(address _tokenAddr, address _cTokenAddr) internal {
if (_tokenAddr != ETH_ADDR) {
ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1));
}
}
| 381,000
|
// File: @openzeppelin/contracts/utils/cryptography/ECDSA.sol
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// File: VaultCoreInterface.sol
pragma solidity 0.8.9;
abstract contract VaultCoreInterface {
function getVersion() public pure virtual returns (uint);
function typeOfContract() public pure virtual returns (bytes32);
function approveToken(
uint256 _tokenId,
address _tokenContractAddress) external virtual;
}
// File: RoyaltyRegistryInterface.sol
pragma solidity 0.8.9;
/**
* Interface to the RoyaltyRegistry responsible for looking payout addresses
*/
abstract contract RoyaltyRegistryInterface {
function getAddress(address custodial) external view virtual returns (address);
function getMediaCustomPercentage(uint256 mediaId, address tokenAddress) external view virtual returns(uint16);
function getExternalTokenPercentage(uint256 tokenId, address tokenAddress) external view virtual returns(uint16, uint16);
function typeOfContract() virtual public pure returns (string calldata);
function VERSION() virtual public pure returns (uint8);
}
// File: ApprovedCreatorRegistryInterface.sol
pragma solidity 0.8.9;
/**
* Interface to the digital media store external contract that is
* responsible for storing the common digital media and collection data.
* This allows for new token contracts to be deployed and continue to reference
* the digital media and collection data.
*/
abstract contract ApprovedCreatorRegistryInterface {
function getVersion() virtual public pure returns (uint);
function typeOfContract() virtual public pure returns (string calldata);
function isOperatorApprovedForCustodialAccount(
address _operator,
address _custodialAddress) virtual public view returns (bool);
}
// File: utils/Collaborator.sol
pragma solidity 0.8.9;
library Collaborator {
bytes32 public constant TYPE_HASH = keccak256("Share(address account,uint48 value,uint48 royalty)");
struct Share {
address payable account;
uint48 value;
uint48 royalty;
}
function hash(Share memory part) internal pure returns (bytes32) {
return keccak256(abi.encode(TYPE_HASH, part.account, part.value, part.royalty));
}
}
// 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/Context.sol
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
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);
}
}
// File: OBOControl.sol
pragma solidity 0.8.9;
contract OBOControl is Ownable {
address public oboAdmin;
uint256 constant public newAddressWaitPeriod = 1 days;
bool public isInitialOBOAdded = false;
// List of approved on behalf of users.
mapping (address => uint256) public approvedOBOs;
event NewOBOAddressEvent(
address OBOAddress,
bool action);
event NewOBOAdminAddressEvent(
address oboAdminAddress);
modifier onlyOBOAdmin() {
require(owner() == _msgSender() || oboAdmin == _msgSender(), "not oboAdmin");
_;
}
function setOBOAdmin(address _oboAdmin) external onlyOwner {
oboAdmin = _oboAdmin;
emit NewOBOAdminAddressEvent(_oboAdmin);
}
/**
* Add a new approvedOBO address. The address can be used after wait period.
*/
function addApprovedOBO(address _oboAddress) external onlyOBOAdmin {
require(_oboAddress != address(0), "cant set to 0x");
require(approvedOBOs[_oboAddress] == 0, "already added");
approvedOBOs[_oboAddress] = block.timestamp;
emit NewOBOAddressEvent(_oboAddress, true);
}
/**
* Removes an approvedOBO immediately.
*/
function removeApprovedOBO(address _oboAddress) external onlyOBOAdmin {
delete approvedOBOs[_oboAddress];
emit NewOBOAddressEvent(_oboAddress, false);
}
/*
* Add OBOAddress for immediate use. This is an internal only Fn that is called
* only when the contract is deployed.
*/
function addApprovedOBOImmediately(address _oboAddress) internal onlyOwner {
require(_oboAddress != address(0), "addr(0)");
// set the date to one in past so that address is active immediately.
approvedOBOs[_oboAddress] = block.timestamp - newAddressWaitPeriod - 1;
emit NewOBOAddressEvent(_oboAddress, true);
}
function addApprovedOBOAfterDeploy(address _oboAddress) external onlyOBOAdmin {
require(isInitialOBOAdded == false, "OBO already added");
addApprovedOBOImmediately(_oboAddress);
isInitialOBOAdded = true;
}
/*
* Helper function to verify is a given address is a valid approvedOBO address.
*/
function isValidApprovedOBO(address _oboAddress) public view returns (bool) {
uint256 createdAt = approvedOBOs[_oboAddress];
if (createdAt == 0) {
return false;
}
return block.timestamp - createdAt > newAddressWaitPeriod;
}
/**
* @dev Modifier to make the obo calls only callable by approved addressess
*/
modifier isApprovedOBO() {
require(isValidApprovedOBO(msg.sender), "unauthorized OBO user");
_;
}
}
// File: @openzeppelin/contracts/security/Pausable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// 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/IERC721Receiver.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
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: DigitalMediaToken.sol
pragma solidity 0.8.9;
contract DigitalMediaToken is ERC721, OBOControl, Pausable {
uint256 public currentSupply = 0;
// creator address has to be set during deploy via constructor only.
address public singleCreatorAddress;
address public signerAddress;
bool public enableExternalMinting;
bool public canRoyaltyRegistryChange = true;
struct DigitalMedia {
uint32 totalSupply; // The total supply of collectibles available
uint32 printIndex; // The current print index
address creator; // The creator of the collectible
uint16 royalty;
bool immutableMedia;
Collaborator.Share[] collaborators;
string metadataPath; // Hash of the media content, with the actual data stored on a secondary
// data store (ideally decentralized)
}
struct DigitalMediaRelease {
uint32 printEdition; // The unique edition number of this digital media release
uint256 digitalMediaId; // Reference ID to the digital media metadata
}
ApprovedCreatorRegistryInterface public creatorRegistryStore;
RoyaltyRegistryInterface public royaltyStore;
VaultCoreInterface public vaultStore;
// Event fired when a new digital media is created. No point in returning printIndex
// since its always zero when created.
event DigitalMediaCreateEvent(
uint256 id,
address creator,
uint32 totalSupply,
uint32 royalty,
bool immutableMedia,
string metadataPath);
event DigitalMediaReleaseCreateEvent(
uint256 id,
address owner,
uint32 printEdition,
string tokenURI,
uint256 digitalMediaId);
// Event fired when a creator assigns a new creator address.
event ChangedCreator(
address creator,
address newCreator);
// Event fired when a digital media is burned
event DigitalMediaBurnEvent(
uint256 id,
address caller);
// Event fired when burning a token
event DigitalMediaReleaseBurnEvent(
uint256 tokenId,
address owner);
event NewSignerEvent(
address signer);
event NewRoyaltyEvent(
uint16 value);
// ID to Digital Media object
mapping (uint256 => DigitalMedia) public idToDigitalMedia;
// Maps internal ERC721 token ID to digital media release object.
mapping (uint256 => DigitalMediaRelease) public tokenIdToDigitalMediaRelease;
// Maps a creator address to a new creator address. Useful if a creator
// changes their address or the previous address gets compromised.
mapping (address => address) public changedCreators;
constructor(string memory _tokenName, string memory _tokenSymbol) ERC721(_tokenName, _tokenSymbol) {}
// Set the creator registry address upon construction. Immutable.
function setCreatorRegistryStore(address _crsAddress) internal {
ApprovedCreatorRegistryInterface candidateCreatorRegistryStore = ApprovedCreatorRegistryInterface(_crsAddress);
// require(candidateCreatorRegistryStore.getVersion() == 1, "registry store is not version 1");
// Simple check to make sure we are adding the registry contract indeed
// https://fravoll.github.io/solidity-patterns/string_equality_comparison.html
bytes32 contractType = keccak256(abi.encodePacked(candidateCreatorRegistryStore.typeOfContract()));
// keccak256(abi.encodePacked("approvedCreatorRegistry")) = 0x74cb6de1099c3d993f336da7af5394f68038a23980424e1ae5723d4110522be4
// keccak256(abi.encodePacked("approvedCreatorRegistryReadOnly")) = 0x9732b26dfb8751e6f1f71e8f21b28a237cfe383953dce7db3dfa1777abdb2791
require(
contractType == 0x74cb6de1099c3d993f336da7af5394f68038a23980424e1ae5723d4110522be4
|| contractType == 0x9732b26dfb8751e6f1f71e8f21b28a237cfe383953dce7db3dfa1777abdb2791,
"not crtrRegistry");
creatorRegistryStore = candidateCreatorRegistryStore;
}
function setRoyaltyRegistryStore(address _royaltyStore) external whenNotPaused onlyOBOAdmin {
require(canRoyaltyRegistryChange == true, "no");
RoyaltyRegistryInterface candidateRoyaltyStore = RoyaltyRegistryInterface(_royaltyStore);
require(candidateRoyaltyStore.VERSION() == 1, "roylty v!= 1");
bytes32 contractType = keccak256(abi.encodePacked(candidateRoyaltyStore.typeOfContract()));
// keccak256(abi.encodePacked("royaltyRegistry")) = 0xb590ff355bf2d720a7e957392d3b76fd1adda1832940640bf5d5a7c387fed323
require(contractType == 0xb590ff355bf2d720a7e957392d3b76fd1adda1832940640bf5d5a7c387fed323,
"not royalty");
royaltyStore = candidateRoyaltyStore;
}
function setRoyaltyRegistryForever() external whenNotPaused onlyOwner {
canRoyaltyRegistryChange = false;
}
function setVaultStore(address _vaultStore) external whenNotPaused onlyOwner {
VaultCoreInterface candidateVaultStore = VaultCoreInterface(_vaultStore);
bytes32 contractType = candidateVaultStore.typeOfContract();
require(contractType == 0x6d707661756c7400000000000000000000000000000000000000000000000000, "invalid mpvault");
vaultStore = candidateVaultStore;
}
/*
* Set signer address on the token contract. Setting signer means we are opening
* the token contract for external accounts to create tokens. Call this to change
* the signer immediately.
*/
function setSignerAddress(address _signerAddress, bool _enableExternalMinting) external whenNotPaused
isApprovedOBO {
require(_signerAddress != address(0), "cant be zero");
signerAddress = _signerAddress;
enableExternalMinting = _enableExternalMinting;
emit NewSignerEvent(signerAddress);
}
/**
* Validates that the Registered store is initialized.
*/
modifier registryInitialized() {
require(address(creatorRegistryStore) != address(0), "registry = 0x0");
_;
}
/**
* Validates that the Vault store is initialized.
*/
modifier vaultInitialized() {
require(address(vaultStore) != address(0), "vault = 0x0");
_;
}
function _setCollaboratorsOnDigitalMedia(DigitalMedia storage _digitalMedia,
Collaborator.Share[] memory _collaborators) internal {
uint total = 0;
uint totalRoyalty = 0;
for (uint i = 0; i < _collaborators.length; i++) {
require(_collaborators[i].account != address(0x0) ||
_collaborators[i].account != _digitalMedia.creator, "collab 0x0/creator");
require(_collaborators[i].value != 0 || _collaborators[i].royalty != 0,
"share/royalty = 0");
_digitalMedia.collaborators.push(_collaborators[i]);
total = total + _collaborators[i].value;
totalRoyalty = totalRoyalty + _collaborators[i].royalty;
}
require(total <= 10000, "total <=10000");
require(totalRoyalty <= 10000, "totalRoyalty <=10000");
}
/**
* Creates a new digital media object.
* @param _creator address the creator of this digital media
* @param _totalSupply uint32 the total supply a creation could have
* @param _metadataPath string the path to the ipfs metadata
* @return uint the new digital media id
*/
function _createDigitalMedia(
address _creator, uint256 _onchainId, uint32 _totalSupply,
string memory _metadataPath, Collaborator.Share[] memory _collaborators,
uint16 _royalty, bool _immutableMedia, uint256 contractSupply)
internal returns (uint) {
// If this is a single creator contract make sure _owner matches single creator
if (singleCreatorAddress != address(0)) {
require(singleCreatorAddress == _creator, "Creator must match single creator address");
}
// If token contract's max supply is reached error out.
if (contractSupply > 0) {
require(currentSupply < contractSupply, "total supply reached");
}
// Verify this media does not exist already
DigitalMedia storage _digitalMedia = idToDigitalMedia[_onchainId];
require(_digitalMedia.creator == address(0), "media already exists");
// TODO: Dannie check this require throughly.
require((_totalSupply > 0) && address(_creator) != address(0) && _royalty <= 10000, "invalid params");
_digitalMedia.printIndex = 0;
_digitalMedia.totalSupply = _totalSupply;
_digitalMedia.creator = _creator;
_digitalMedia.metadataPath = _metadataPath;
_digitalMedia.immutableMedia = _immutableMedia;
_digitalMedia.royalty = _royalty;
_setCollaboratorsOnDigitalMedia(_digitalMedia, _collaborators);
currentSupply = currentSupply + 1;
emit DigitalMediaCreateEvent(
_onchainId, _creator, _totalSupply,
_royalty, _immutableMedia, _metadataPath);
return _onchainId;
}
/**
* Creates _count number of new digital media releases (i.e a token).
* Bumps up the print index by _count.
* @param _owner address the owner of the digital media object
* @param _digitalMediaId uint256 the digital media id
*/
function _createDigitalMediaReleases(
address _owner, uint256 _digitalMediaId, uint256[] memory _releaseIds)
internal {
require(_releaseIds.length > 0 && _releaseIds.length < 10000, "0 < count <= 10000");
DigitalMedia storage _digitalMedia = idToDigitalMedia[_digitalMediaId];
require(_digitalMedia.creator != address(0), "media does not exist");
uint32 currentPrintIndex = _digitalMedia.printIndex;
require(_checkApprovedCreator(_digitalMedia.creator, _owner), "Creator not approved");
require(_releaseIds.length + currentPrintIndex <= _digitalMedia.totalSupply, "Total supply exceeded.");
for (uint32 i=0; i < _releaseIds.length; i++) {
uint256 newDigitalMediaReleaseId = _releaseIds[i];
DigitalMediaRelease storage release = tokenIdToDigitalMediaRelease[newDigitalMediaReleaseId];
require(release.printEdition == 0, "tokenId already used");
uint32 newPrintEdition = currentPrintIndex + 1 + i;
release.printEdition = newPrintEdition;
release.digitalMediaId = _digitalMediaId;
emit DigitalMediaReleaseCreateEvent(
newDigitalMediaReleaseId,
_owner,
newPrintEdition,
_digitalMedia.metadataPath,
_digitalMediaId
);
// This will assign ownership and also emit the Transfer event as per ERC721
_mint(_owner, newDigitalMediaReleaseId);
}
_digitalMedia.printIndex = _digitalMedia.printIndex + uint32(_releaseIds.length);
}
/**
* Checks that a given caller is an approved creator and is allowed to mint or burn
* tokens. If the creator was changed it will check against the updated creator.
* @param _caller the calling address
* @return bool allowed or not
*/
function _checkApprovedCreator(address _creator, address _caller)
internal
view
returns (bool) {
address approvedCreator = changedCreators[_creator];
if (approvedCreator != address(0)) {
return approvedCreator == _caller;
} else {
return _creator == _caller;
}
}
/**
* Burns a token for a given tokenId and caller.
* @param _tokenId the id of the token to burn.
* @param _caller the address of the caller.
*/
function _burnToken(uint256 _tokenId, address _caller) internal {
address owner = ownerOf(_tokenId);
require(_isApprovedOrOwner(_caller, _tokenId), "ERC721: burn caller is not owner nor approved");
_burn(_tokenId);
delete tokenIdToDigitalMediaRelease[_tokenId];
emit DigitalMediaReleaseBurnEvent(_tokenId, owner);
}
/**
* Burns a digital media. Once this function succeeds, this digital media
* will no longer be able to mint any more tokens. Existing tokens need to be
* burned individually though.
* @param _digitalMediaId the id of the digital media to burn
* @param _caller the address of the caller.
*/
function _burnDigitalMedia(uint256 _digitalMediaId, address _caller) internal {
DigitalMedia storage _digitalMedia = idToDigitalMedia[_digitalMediaId];
require(_digitalMedia.creator != address(0), "media does not exist");
require(_checkApprovedCreator(_digitalMedia.creator, _caller) ||
isApprovedForAll(_digitalMedia.creator, _caller),
"Failed digital media burn. Caller not approved.");
_digitalMedia.printIndex = _digitalMedia.totalSupply;
emit DigitalMediaBurnEvent(_digitalMediaId, _caller);
}
/**
* @dev Returns an URI for a given token ID
* @dev Throws if the token ID does not exist. May return an empty string.
* @param _tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
require(_exists(_tokenId));
DigitalMediaRelease storage digitalMediaRelease = tokenIdToDigitalMediaRelease[_tokenId];
uint256 _digitalMediaId = digitalMediaRelease.digitalMediaId;
DigitalMedia storage _digitalMedia = idToDigitalMedia[_digitalMediaId];
string memory prefix = "ipfs://";
return string(abi.encodePacked(prefix, string(_digitalMedia.metadataPath)));
}
/*
* Look up a royalty payout address if royaltyStore is set otherwise we returns
* the same argument.
*/
function _getRoyaltyAddress(address custodial) internal view returns(address) {
return address(royaltyStore) == address(0) ? custodial : royaltyStore.getAddress(custodial);
}
}
// File: DigitalMediaCore.sol
pragma solidity 0.8.9;
contract DigitalMediaCore is DigitalMediaToken {
using ECDSA for bytes32;
uint8 constant public VERSION = 3;
// if the contract can have a total of only 10,000 tokens set the totalMediaSupply
// during the contract deployment. I could nt define a immutable variable in DigitalMediaToken
// So creating the variable here and instantiating it in constructor and passing
// it down to the internal functions.
uint256 public immutable totalMediaSupply;
struct DigitalMediaCreateRequest {
uint256 onchainId; // onchain id for this media
uint32 totalSupply; // The total supply of collectibles available
address creator; // The creator of the collectible
uint16 royalty;
bool immutableMedia;
Collaborator.Share[] collaborators;
string metadataPath; // Hash of the media content
uint256[] releaseIds; // number of releases to mint
}
struct DigitalMediaUpdateRequest {
uint256 onchainId; // onchain id for this media
uint256 metadataId;
uint32 totalSupply; // The total supply of collectibles available
address creator; // The creator of the collectible
uint16 royalty;
Collaborator.Share[] collaborators;
string metadataPath; // Hash of the media content
}
struct DigitalMediaReleaseCreateRequest {
uint256 digitalMediaId;
uint256[] releaseIds; // number of releases to mint
address owner;
}
struct TokenDestinationRequest {
uint256 tokenId;
address destinationAddress;
}
struct ChainSignatureRequest {
uint256 onchainId;
address owner;
}
struct PayoutInfo {
address user;
uint256 amount;
}
event DigitalMediaUpdateEvent(
uint256 id,
uint32 totalSupply,
uint16 royalty,
string metadataPath,
uint256 metadataId);
event MediasImmutableEvent(
uint256[] mediaIds);
event MediaImmutableEvent(
uint256 mediaId);
constructor(string memory _tokenName, string memory _tokenSymbol,
address _crsAddress, uint256 _totalSupply) DigitalMediaToken(_tokenName, _tokenSymbol) {
setCreatorRegistryStore(_crsAddress);
totalMediaSupply = _totalSupply;
}
/**
* Retrieves a Digital Media object.
*/
function getDigitalMedia(uint256 _id)
external
view
returns (DigitalMedia memory) {
DigitalMedia memory _digitalMedia = idToDigitalMedia[_id];
require(_digitalMedia.creator != address(0), "DigitalMedia not found.");
return _digitalMedia;
}
/**
* Ok I am not proud of this function but sale conract needs to getDigitalMedia
* while I tried to write a interface file DigitalMediaBurnInterfaceV3.sol I could
* not include the DigitalMedia struct in that abstract contract. So I am writing
* another endpoint to return just the bare minimum data required for the sale contract.
*/
function getDigitalMediaForSale(uint256 _id) external view returns(
address, bool, uint16) {
DigitalMedia storage _digitalMedia = idToDigitalMedia[_id];
require(_digitalMedia.creator != address(0), "DigitalMedia not found.");
return (_digitalMedia.creator, _digitalMedia.collaborators.length > 0,
_digitalMedia.royalty);
}
/**
* Retrieves a Digital Media Release (i.e a token)
*/
function getDigitalMediaRelease(uint256 _id)
external
view
returns (DigitalMediaRelease memory) {
require(_exists(_id), "release does not exist");
DigitalMediaRelease storage digitalMediaRelease = tokenIdToDigitalMediaRelease[_id];
return digitalMediaRelease;
}
/**
* Creates a new digital media object and mints it's first digital media release token.
* The onchainid and creator has to be signed by signerAddress in order to create.
* No creations of any kind are allowed when the contract is paused.
*/
function createDigitalMediaAndReleases(
DigitalMediaCreateRequest memory request,
bytes calldata signature)
external
whenNotPaused {
require(request.creator == msg.sender, "msgSender != creator");
ChainSignatureRequest memory signatureRequest = ChainSignatureRequest(request.onchainId, request.creator);
_verifyReleaseRequestSignature(signatureRequest, signature);
uint256 digitalMediaId = _createDigitalMedia(msg.sender, request.onchainId, request.totalSupply,
request.metadataPath, request.collaborators, request.royalty, request.immutableMedia,
totalMediaSupply);
_createDigitalMediaReleases(msg.sender, digitalMediaId, request.releaseIds);
}
/**
* Creates a new digital media release (token) for a given digital media id.
* This request needs to be signed by the authorized signerAccount to prevent
* from user stealing media & release ids on chain and frontrunning.
* No creations of any kind are allowed when the contract is paused.
*/
function createDigitalMediaReleases(
DigitalMediaReleaseCreateRequest memory request)
external
whenNotPaused {
// require(request.owner == msg.sender, "owner != msg.sender");
require(signerAddress != address(0), "signer not set");
_createDigitalMediaReleases(msg.sender, request.digitalMediaId, request.releaseIds);
}
/**
* Creates a new digital media object and mints it's digital media release tokens.
* Called on behalf of the _owner. Pass count to mint `n` number of tokens.
*
* Only approved creators are allowed to create Obo.
*
* No creations of any kind are allowed when the contract is paused.
*/
function oboCreateDigitalMediaAndReleases(
DigitalMediaCreateRequest memory request)
external
whenNotPaused
isApprovedOBO {
uint256 digitalMediaId = _createDigitalMedia(request.creator, request.onchainId, request.totalSupply, request.metadataPath,
request.collaborators, request.royalty, request.immutableMedia, totalMediaSupply);
_createDigitalMediaReleases(request.creator, digitalMediaId, request.releaseIds);
}
/**
* Create many digital medias in one call.
*/
function oboCreateManyDigitalMedias(
DigitalMediaCreateRequest[] memory requests) external whenNotPaused isApprovedOBO {
for (uint32 i=0; i < requests.length; i++) {
DigitalMediaCreateRequest memory request = requests[i];
_createDigitalMedia(request.creator, request.onchainId, request.totalSupply,
request.metadataPath, request.collaborators, request.royalty, request.immutableMedia, totalMediaSupply);
}
}
/**
* Creates multiple digital media releases (tokens) for a given digital media id.
* Called on behalf of the _owner.
*
* Only approved creators are allowed to create Obo.
*
* No creations of any kind are allowed when the contract is paused.
*/
function oboCreateDigitalMediaReleases(
DigitalMediaReleaseCreateRequest memory request)
external
whenNotPaused
isApprovedOBO {
_createDigitalMediaReleases(request.owner, request.digitalMediaId, request.releaseIds);
}
/*
* Create multiple digital medias and associated releases (tokens). Called on behalf
* of the _owner. Each media should mint atleast 1 token.
* No creations of any kind are allowed when the contract is paused.
*/
function oboCreateManyDigitalMediasAndReleases(
DigitalMediaCreateRequest[] memory requests) external whenNotPaused isApprovedOBO {
for (uint32 i=0; i < requests.length; i++) {
DigitalMediaCreateRequest memory request = requests[i];
uint256 digitalMediaId = _createDigitalMedia(request.creator, request.onchainId, request.totalSupply,
request.metadataPath, request.collaborators, request.royalty, request.immutableMedia, totalMediaSupply);
_createDigitalMediaReleases(request.creator, digitalMediaId, request.releaseIds);
}
}
/*
* Create multiple releases (tokens) associated with existing medias. Called on behalf
* of the _owner.
* No creations of any kind are allowed when the contract is paused.
*/
function oboCreateManyReleases(
DigitalMediaReleaseCreateRequest[] memory requests) external whenNotPaused isApprovedOBO {
for (uint32 i=0; i < requests.length; i++) {
DigitalMediaReleaseCreateRequest memory request = requests[i];
DigitalMedia storage _digitalMedia = idToDigitalMedia[request.digitalMediaId];
require(_digitalMedia.creator != address(0), "DigitalMedia not found.");
_createDigitalMediaReleases(request.owner, request.digitalMediaId, request.releaseIds);
}
}
/**
* Override the isApprovalForAll to check for a special oboApproval list. Reason for this
* is that we can can easily remove obo operators if they every become compromised.
*/
function isApprovedForAll(address _owner, address _operator) public view override registryInitialized returns (bool) {
if (creatorRegistryStore.isOperatorApprovedForCustodialAccount(_operator, _owner) == true) {
return true;
} else {
return super.isApprovedForAll(_owner, _operator);
}
}
/**
* Changes the creator for the current sender, in the event we
* need to be able to mint new tokens from an existing digital media
* print production. When changing creator, the old creator will
* no longer be able to mint tokens.
*
* A creator may need to be changed:
* 1. If we want to allow a creator to take control over their token minting (i.e go decentralized)
* 2. If we want to re-issue private keys due to a compromise. For this reason, we can call this function
* when the contract is paused.
* @param _creator the creator address
* @param _newCreator the new creator address
*/
function changeCreator(address _creator, address _newCreator) external {
address approvedCreator = changedCreators[_creator];
require(msg.sender != address(0) && _creator != address(0), "Creator must be valid non 0x0 address.");
require(msg.sender == _creator || msg.sender == approvedCreator, "Unauthorized caller.");
if (approvedCreator == address(0)) {
changedCreators[msg.sender] = _newCreator;
} else {
require(msg.sender == approvedCreator, "Unauthorized caller.");
changedCreators[_creator] = _newCreator;
}
emit ChangedCreator(_creator, _newCreator);
}
// standard ERC721 burn interface
function burn(uint256 _tokenId) external {
_burnToken(_tokenId, msg.sender);
}
/**
* Ends the production run of a digital media. Afterwards no more tokens
* will be allowed to be printed for each digital media. Used when a creator
* makes a mistake and wishes to burn and recreate their digital media.
*
* When a contract is paused we do not allow new tokens to be created,
* so stopping the production of a token doesn't have much purpose.
*/
function burnDigitalMedia(uint256 _digitalMediaId) external whenNotPaused {
_burnDigitalMedia(_digitalMediaId, msg.sender);
}
/*
* Batch transfer multiple tokens from their sources to destination
* Owner / ApproveAll user can call this endpoint.
*/
function safeTransferMany(TokenDestinationRequest[] memory requests) external whenNotPaused {
for (uint32 i=0; i < requests.length; i++) {
TokenDestinationRequest memory request = requests[i];
safeTransferFrom(ownerOf(request.tokenId), request.destinationAddress, request.tokenId);
}
}
function _updateDigitalMedia(DigitalMediaUpdateRequest memory request,
DigitalMedia storage _digitalMedia) internal {
require(_digitalMedia.immutableMedia == false, "immutable");
require(_digitalMedia.printIndex <= request.totalSupply, "< currentPrintIndex");
_digitalMedia.totalSupply = request.totalSupply;
_digitalMedia.metadataPath = request.metadataPath;
_digitalMedia.royalty = request.royalty;
delete _digitalMedia.collaborators;
_setCollaboratorsOnDigitalMedia(_digitalMedia, request.collaborators);
emit DigitalMediaUpdateEvent(request.onchainId,
request.totalSupply, request.royalty, request.metadataPath,
request.metadataId);
}
function updateMedia(DigitalMediaUpdateRequest memory request) external whenNotPaused {
require(request.creator == msg.sender, "msgSender != creator");
DigitalMedia storage _digitalMedia = idToDigitalMedia[request.onchainId];
require(_digitalMedia.creator != address(0) && _digitalMedia.creator == msg.sender,
"DM creator issue");
_updateDigitalMedia(request, _digitalMedia);
}
/*
* Update existing digitalMedia's metadata, totalSupply, collaborated, royalty
* and immutable attribute. Once a media is immutable you cannot call this function
*/
function updateManyMedias(DigitalMediaUpdateRequest[] memory requests)
external whenNotPaused isApprovedOBO vaultInitialized {
for (uint32 i=0; i < requests.length; i++) {
DigitalMediaUpdateRequest memory request = requests[i];
DigitalMedia storage _digitalMedia = idToDigitalMedia[request.onchainId];
// Call creator registry to check if the creator gave approveAll to vault
require(_digitalMedia.creator != address(0) && _digitalMedia.creator == request.creator,
"DM creator");
require(isApprovedForAll(_digitalMedia.creator, address(vaultStore)) == true, "approveall missing");
_updateDigitalMedia(request, _digitalMedia);
}
}
function makeMediaImmutable(uint256 mediaId) external whenNotPaused {
DigitalMedia storage _digitalMedia = idToDigitalMedia[mediaId];
require(_digitalMedia.creator != address(0) && _digitalMedia.creator == msg.sender,
"DM creator");
require(_digitalMedia.immutableMedia == false, "DM immutable");
_digitalMedia.immutableMedia = true;
emit MediaImmutableEvent(mediaId);
}
/*
* Once we update media and feel satisfied with the changes, we can render it immutable now.
*/
function makeMediasImmutable(uint256[] memory mediaIds) external whenNotPaused isApprovedOBO vaultInitialized {
for (uint32 i=0; i < mediaIds.length; i++) {
uint256 mediaId = mediaIds[i];
DigitalMedia storage _digitalMedia = idToDigitalMedia[mediaId];
require(_digitalMedia.creator != address(0), "DM not found.");
require(_digitalMedia.immutableMedia == false, "DM immutable");
require(isApprovedForAll(_digitalMedia.creator, address(vaultStore)) == true, "approveall missing");
_digitalMedia.immutableMedia = true;
}
emit MediasImmutableEvent(mediaIds);
}
function _lookUpTokenAndReturnEntries(uint256 _tokenId, uint256 _salePrice,
bool _isRoyalty) internal view returns(PayoutInfo[] memory entries) {
require(_exists(_tokenId), "no token");
DigitalMediaRelease memory digitalMediaRelease = tokenIdToDigitalMediaRelease[_tokenId];
DigitalMedia memory _digitalMedia = idToDigitalMedia[digitalMediaRelease.digitalMediaId];
uint256 size = _digitalMedia.collaborators.length + 1;
entries = new PayoutInfo[](size);
uint totalRoyaltyPercentage = 0;
for (uint256 index = 0; index < _digitalMedia.collaborators.length; index++) {
address payoutAddress = _getRoyaltyAddress(_digitalMedia.collaborators[index].account);
if (_isRoyalty == true) {
entries[index] = PayoutInfo(payoutAddress,
_digitalMedia.collaborators[index].royalty * _digitalMedia.royalty * _salePrice / (10000 * 10000));
totalRoyaltyPercentage = totalRoyaltyPercentage + _digitalMedia.collaborators[index].royalty;
} else {
entries[index] = PayoutInfo(payoutAddress,
_digitalMedia.collaborators[index].value * _salePrice / 10000);
totalRoyaltyPercentage = totalRoyaltyPercentage + _digitalMedia.collaborators[index].value;
}
}
address creatorPayoutAddress = _getRoyaltyAddress(_digitalMedia.creator);
if (_isRoyalty == true) {
entries[size-1]= PayoutInfo(creatorPayoutAddress, _salePrice * (10000 - totalRoyaltyPercentage) * _digitalMedia.royalty / (10000 * 10000));
} else {
entries[size-1]= PayoutInfo(creatorPayoutAddress, _salePrice * (10000 - totalRoyaltyPercentage) / 10000);
}
return entries;
}
/*
* Return royalty for a given Token. Returns an array of PayoutInfo which consists
* of address to pay to and amount.
* Thank you for posting this gist. Helped me to figure out how to return an array of structs.
* https://gist.github.com/minhth1905/4b6208372fc5e7343b5ce1fb6d42c942
*/
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (
PayoutInfo[] memory) {
return _lookUpTokenAndReturnEntries(_tokenId, _salePrice, true);
}
/*
* Given salePrice break down the amount between the creator and collabarators
* according to their percentages.
*/
function saleInfo(uint256 _tokenId, uint256 _totalPayout) external view returns (
PayoutInfo[] memory) {
return _lookUpTokenAndReturnEntries(_tokenId, _totalPayout, false);
}
function pause() external onlyOwner {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
/*
* helper to verify signature signed by non-custodial creator.
*/
function _verifyReleaseRequestSignature(
ChainSignatureRequest memory request,
bytes calldata signature) internal view {
require(enableExternalMinting == true, "ext minting disabled");
bytes32 encodedRequest = keccak256(abi.encode(request));
address addressWhoSigned = encodedRequest.recover(signature);
require(addressWhoSigned == signerAddress, "sig error");
}
}
|
standard ERC721 burn interface
|
function burn(uint256 _tokenId) external {
_burnToken(_tokenId, msg.sender);
}
| 640,521
|
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./interfaces/IUniswapV2Router.sol";
import "./interfaces/IUniswapV2Factory.sol";
contract LiquidityLocker {
using Counters for Counters.Counter;
using SafeERC20 for IERC20;
struct Pair {
IERC20 a;
IERC20 b;
}
struct PairAmounts {
uint256 a;
uint256 b;
}
struct LiquidityAddition {
PairAmounts tokenAmounts;
uint256 liquidity;
}
struct LiquidityLock {
Pair tokens;
uint256 liquidity;
uint256 unlocktime;
address provider;
}
IUniswapV2Router public router;
mapping(uint256 => LiquidityLock) public liquidityLocks;
Counters.Counter public nrOfLiquidityLocks;
modifier Allowance(IERC20 token, uint256 amount) {
require(
token.allowance(msg.sender, address(this)) >= amount,
"Amount not approved"
);
_;
}
event LiquidityLocked(
uint256 lockId,
address indexed provider,
IERC20 indexed tokenA,
IERC20 indexed tokenB,
uint256 liquidity,
uint256 unlocktime
);
event LiquidityUnlocked(
uint256 lockId,
address indexed provider,
IERC20 indexed tokenA,
IERC20 indexed tokenB,
uint256 liquidity
);
constructor(IUniswapV2Router _router) {
router = _router;
}
function addAndLockLiquidity(
Pair memory tokens,
PairAmounts memory desiredAmounts,
PairAmounts memory minAmounts,
uint256 deadline,
uint256 unlocktime
)
public
Allowance(tokens.a, desiredAmounts.a)
Allowance(tokens.b, desiredAmounts.b)
returns (LiquidityAddition memory liquidityAddition)
{
require(unlocktime > block.timestamp, "Unlock time is before current time");
tokens.a.safeTransferFrom(msg.sender, address(this), desiredAmounts.a);
tokens.b.safeTransferFrom(msg.sender, address(this), desiredAmounts.b);
tokens.a.safeIncreaseAllowance(address(router), desiredAmounts.a);
tokens.b.safeIncreaseAllowance(address(router), desiredAmounts.b);
liquidityAddition = _addLiquidityThroughRouter(
tokens,
desiredAmounts,
minAmounts,
deadline
);
uint256 liquidityLockId = nrOfLiquidityLocks.current();
liquidityLocks[liquidityLockId] = LiquidityLock({
tokens: Pair(tokens.a, tokens.b),
liquidity: liquidityAddition.liquidity,
unlocktime: unlocktime,
provider: msg.sender
});
nrOfLiquidityLocks.increment();
if (desiredAmounts.a - liquidityAddition.tokenAmounts.a > 0) {
tokens.a.safeTransfer(
msg.sender,
desiredAmounts.a - liquidityAddition.tokenAmounts.a
);
}
if (desiredAmounts.b - liquidityAddition.tokenAmounts.b > 0) {
tokens.b.safeTransfer(
msg.sender,
desiredAmounts.b - liquidityAddition.tokenAmounts.b
);
}
// emit an event to be able to query all locked liquidity
emit LiquidityLocked(
liquidityLockId,
msg.sender,
tokens.a,
tokens.b,
liquidityAddition.liquidity,
unlocktime
);
}
function removeUnlockedLiquidity(
uint256 liquidityLockID,
uint256 liquidity,
PairAmounts memory minAmounts,
uint256 deadline
) public returns (PairAmounts memory amounts) {
LiquidityLock storage liquidityLock = liquidityLocks[liquidityLockID];
require(
block.timestamp >= liquidityLock.unlocktime,
"Liquidity is still locked"
);
require(
liquidityLock.provider == msg.sender,
"Can only be removed by provider"
);
require(liquidityLock.liquidity >= liquidity, "Not enough left in lock");
liquidityLock.liquidity -= liquidity;
IERC20 pair = IERC20(
IUniswapV2Factory(router.factory()).getPair(
address(liquidityLock.tokens.a),
address(liquidityLock.tokens.b)
)
);
pair.safeIncreaseAllowance(address(router), liquidity);
(amounts.a, amounts.b) = router.removeLiquidity(
address(liquidityLock.tokens.a),
address(liquidityLock.tokens.b),
liquidity,
minAmounts.a,
minAmounts.b,
msg.sender,
deadline
);
// Emit event to query unlock liquidity
emit LiquidityUnlocked(
liquidityLockID,
msg.sender,
liquidityLock.tokens.a,
liquidityLock.tokens.b,
liquidity
);
}
function _addLiquidityThroughRouter(
Pair memory tokens,
PairAmounts memory desiredAmounts,
PairAmounts memory minAmounts,
uint256 deadline
) internal returns (LiquidityAddition memory liquidityAddition) {
(
liquidityAddition.tokenAmounts.a,
liquidityAddition.tokenAmounts.b,
liquidityAddition.liquidity
) = router.addLiquidity(
address(tokens.a),
address(tokens.b),
desiredAmounts.a,
desiredAmounts.b,
minAmounts.a,
minAmounts.b,
address(this),
deadline
);
}
}
|
Emit event to query unlock liquidity
|
function removeUnlockedLiquidity(
uint256 liquidityLockID,
uint256 liquidity,
PairAmounts memory minAmounts,
uint256 deadline
) public returns (PairAmounts memory amounts) {
LiquidityLock storage liquidityLock = liquidityLocks[liquidityLockID];
require(
block.timestamp >= liquidityLock.unlocktime,
"Liquidity is still locked"
);
require(
liquidityLock.provider == msg.sender,
"Can only be removed by provider"
);
require(liquidityLock.liquidity >= liquidity, "Not enough left in lock");
liquidityLock.liquidity -= liquidity;
IERC20 pair = IERC20(
IUniswapV2Factory(router.factory()).getPair(
address(liquidityLock.tokens.a),
address(liquidityLock.tokens.b)
)
);
pair.safeIncreaseAllowance(address(router), liquidity);
(amounts.a, amounts.b) = router.removeLiquidity(
address(liquidityLock.tokens.a),
address(liquidityLock.tokens.b),
liquidity,
minAmounts.a,
minAmounts.b,
msg.sender,
deadline
);
emit LiquidityUnlocked(
liquidityLockID,
msg.sender,
liquidityLock.tokens.a,
liquidityLock.tokens.b,
liquidity
);
}
| 891,685
|
pragma solidity ^0.4.24;
import "../story/story.sol";
import "../register.sol";
import "../world_info.sol";
/// @title Identity
/// @author ["Cryptape Technologies <contact@cryptape.com>"]
contract Identity {
Register register;
address owner;
uint public record;
uint public weapon;
address public scene;
uint8 public job;
address public proxy;
/// Save register's address
constructor(
address _id,
address _scene
)
public
{
register = Register(msg.sender);
owner = _id;
scene = _scene;
}
modifier onlyOperator {
require(msg.sender == register.userOpAddr(), "not operator");
_;
}
modifier onlyOwner(address _owner) {
require(owner == _owner, "not owner");
_;
}
/// @notice Update record
function updateRecord(uint _record, address _owner)
public
onlyOperator
onlyOwner(_owner)
returns (bool)
{
record = _record;
return true;
}
/// @notice Set weapon
function setWeapon(uint _weapon, address _owner)
public
onlyOperator
onlyOwner(_owner)
returns (bool)
{
weapon = _weapon;
return true;
}
// @notice Set scene
// leave old scene enter new scene
function setScene(address _scene, address _owner)
public
onlyOperator
onlyOwner(_owner)
returns (bool)
{
// Update the world info
WorldInfo world = WorldInfo(register.worldInfoAddr());
world.userLeave(scene, owner);
world.userEnter(_scene, owner);
// Update the secene
scene = _scene;
return true;
}
/// @notice Set job
function setJob(uint8 _job, address _owner)
public
onlyOperator
onlyOwner(_owner)
returns (bool)
{
job = _job;
return true;
}
/// @notice Set proxy
function setProxy(address _proxy) public {
proxy = _proxy;
}
// @notice call proxy process function
function process(address _to, uint256 decision, address _owner)
public
onlyOperator
onlyOwner(_owner)
returns (bool)
{
Story(proxy).process(_owner, _to, decision);
}
// call proxy info function
function info() public view returns (bytes32[8]) {
return Story(proxy).info(msg.sender);
}
}
|
Set scene leave old scene enter new scene Update the world info Update the secene
|
function setScene(address _scene, address _owner)
public
onlyOperator
onlyOwner(_owner)
returns (bool)
{
WorldInfo world = WorldInfo(register.worldInfoAddr());
world.userLeave(scene, owner);
world.userEnter(_scene, owner);
scene = _scene;
return true;
}
| 12,965,467
|
./full_match/5/0x3287983f852bd6d56fF175A7BcDDCd0e3008F99B/sources/src/zkbob/utils/ZkBobAccounting.sol
|
for full correctness, next line should use "while" instead of "if" however, in order to keep constant gas usage, "if" is being used this can lead to a longer sliding window (> 1 week) in some cases, but eventually it will converge back to the 1 week target if tail is more than 1 week behind, we move tail pointer to the next snapshot
|
function _recordOperation(
address _user,
int256 _txAmount
)
internal
returns (uint56 maxWeeklyAvgTvl, uint32 maxWeeklyTxCount, uint256 txCount)
{
Slot0 memory s0 = slot0;
Slot1 memory s1 = slot1;
uint24 curSlot = uint24(block.timestamp / SLOT_DURATION);
txCount = uint256(s0.txCount);
if (s0.txCount > 0 && curSlot - s0.tailSlot > WEEK_SLOTS) {
Snapshot memory sn = snapshots[s0.tailSlot];
delete snapshots[s0.tailSlot];
s0.tailSlot = sn.nextSlot;
uint32 weeklyTxCount = s0.txCount - sn.txCount;
if (weeklyTxCount > s0.maxWeeklyTxCount) {
s0.maxWeeklyTxCount = weeklyTxCount;
}
uint56 avgTvl = uint56((s0.cumTvl - sn.cumTvl) / weeklyTxCount);
if (avgTvl > s0.maxWeeklyAvgTvl) {
s0.maxWeeklyAvgTvl = avgTvl;
}
}
if (s0.headSlot < curSlot) {
snapshots[s0.headSlot] = Snapshot(curSlot, s0.txCount, s0.cumTvl);
s0.headSlot = curSlot;
}
s0.txCount++;
if (_txAmount != 0) {
_processTVLChange(s1, _user, _txAmount);
}
slot0 = s0;
return (s0.maxWeeklyAvgTvl, s0.maxWeeklyTxCount, txCount);
}
| 7,063,076
|
pragma solidity ^0.4.15;
// ----------------------------------------------------------------------------
// HAZ 'Hazza Network Token' contract locked tokens
//
// Refer to http://hazza.network for further information.
//
// Enjoy. (c) ANX International and BokkyPooBah / Bok Consulting Pty Ltd 2017.
// The MIT Licence.
// ----------------------------------------------------------------------------
import "./ERC20Interface.sol";
import "./SafeMath.sol";
import "./HazzaNetworkTokenConfig.sol";
// ----------------------------------------------------------------------------
// Contract that holds the locked token information
// ----------------------------------------------------------------------------
contract LockedTokens is HazzaNetworkTokenConfig {
using SafeMath for uint;
// ------------------------------------------------------------------------
// Current totalSupply of locked tokens
// ------------------------------------------------------------------------
uint public totalSupplyLocked6M;
uint public totalSupplyLocked8M;
uint public totalSupplyLocked12M;
// ------------------------------------------------------------------------
// Locked tokens mapping
// ------------------------------------------------------------------------
mapping (address => uint) public balancesLocked6M;
mapping (address => uint) public balancesLocked8M;
mapping (address => uint) public balancesLocked12M;
// ------------------------------------------------------------------------
// Address of Hazza Network token contract
// ------------------------------------------------------------------------
ERC20Interface public tokenContract;
address public tokenContractAddress;
// ------------------------------------------------------------------------
// Constructor - called by token contract
// ------------------------------------------------------------------------
function LockedTokens(address _tokenContract) {
tokenContract = ERC20Interface(_tokenContract);
tokenContractAddress = _tokenContract;
// any locked token balances known in advance of contract deployment can be added here
// add6M(0xaBBa43E7594E3B76afB157989e93c6621497FD4b, 2000000 * DECIMALSFACTOR);
// add8M(0xAddA9B762A00FF12711113bfDc36958B73d7F915, 2000000 * DECIMALSFACTOR);
// add12M(0xAddA9B762A00FF12711113bfDc36958B73d7F915, 2000000 * DECIMALSFACTOR);
}
// ------------------------------------------------------------------------
// Modifier to mark that a function can only be executed by the token contract
// ------------------------------------------------------------------------
modifier onlyTokenContract {
require(msg.sender == tokenContractAddress);
_;
}
// ------------------------------------------------------------------------
// Add to 6m locked balances and totalSupply
// ------------------------------------------------------------------------
function add6M(address account, uint value) onlyTokenContract {
balancesLocked6M[account] = balancesLocked6M[account].add(value);
totalSupplyLocked6M = totalSupplyLocked6M.add(value);
}
// ------------------------------------------------------------------------
// Add to 8m locked balances and totalSupply
// ------------------------------------------------------------------------
function add8M(address account, uint value) onlyTokenContract {
balancesLocked8M[account] = balancesLocked8M[account].add(value);
totalSupplyLocked8M = totalSupplyLocked8M.add(value);
}
// ------------------------------------------------------------------------
// Add to 12m locked balances and totalSupply
// ------------------------------------------------------------------------
function add12M(address account, uint value) onlyTokenContract {
balancesLocked12M[account] = balancesLocked12M[account].add(value);
totalSupplyLocked12M = totalSupplyLocked12M.add(value);
}
// ------------------------------------------------------------------------
// 6m locked balances for an account
// ------------------------------------------------------------------------
function balanceOfLocked6M(address account) constant returns (uint balance) {
return balancesLocked6M[account];
}
// ------------------------------------------------------------------------
// 8m locked balances for an account
// ------------------------------------------------------------------------
function balanceOfLocked8M(address account) constant returns (uint balance) {
return balancesLocked8M[account];
}
// ------------------------------------------------------------------------
// 12m locked balances for an account
// ------------------------------------------------------------------------
function balanceOfLocked12M(address account) constant returns (uint balance) {
return balancesLocked12M[account];
}
// ------------------------------------------------------------------------
// locked balances for an account
// ------------------------------------------------------------------------
function balanceOfLocked(address account) constant returns (uint balance) {
return balancesLocked6M[account].add(balancesLocked8M[account]).add(balancesLocked12M[account]);
}
// ------------------------------------------------------------------------
// locked total supply
// ------------------------------------------------------------------------
function totalSupplyLocked() constant returns (uint) {
return totalSupplyLocked6M + totalSupplyLocked8M + totalSupplyLocked12M;
}
// ------------------------------------------------------------------------
// An account can unlock their 6m locked tokens 6m after token launch date
// ------------------------------------------------------------------------
function unlock6M() {
require(now >= LOCKED_6M_DATE);
uint amount = balancesLocked6M[msg.sender];
require(amount > 0);
balancesLocked6M[msg.sender] = 0;
totalSupplyLocked6M = totalSupplyLocked6M.sub(amount);
require(tokenContract.transfer(msg.sender, amount));
}
// ------------------------------------------------------------------------
// An account can unlock their 8m locked tokens 8m after token launch date
// ------------------------------------------------------------------------
function unlock8M() {
require(now >= LOCKED_8M_DATE);
uint amount = balancesLocked8M[msg.sender];
require(amount > 0);
balancesLocked8M[msg.sender] = 0;
totalSupplyLocked8M = totalSupplyLocked8M.sub(amount);
require(tokenContract.transfer(msg.sender, amount));
}
// ------------------------------------------------------------------------
// An account can unlock their 12m locked tokens 12m after token launch date
// ------------------------------------------------------------------------
function unlock12M() {
require(now >= LOCKED_12M_DATE);
uint amount = balancesLocked12M[msg.sender];
require(amount > 0);
balancesLocked12M[msg.sender] = 0;
totalSupplyLocked12M = totalSupplyLocked12M.sub(amount);
require(tokenContract.transfer(msg.sender, amount));
}
}
|
------------------------------------------------------------------------ locked balances for an account ------------------------------------------------------------------------
|
function balanceOfLocked(address account) constant returns (uint balance) {
return balancesLocked6M[account].add(balancesLocked8M[account]).add(balancesLocked12M[account]);
}
| 1,823,850
|
./full_match/43113/0xc48Be674DE92202d505Ba1ACDa28837b2D96f4Dd/sources/contracts/lens/Quoter.sol
|
@inheritdoc IElkDexV3SwapCallback
|
function ElkDexV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes memory path
) external view override {
(address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool();
CallbackValidation.verifyCallback(factory, tokenIn, tokenOut, fee);
(bool isExactInput, uint256 amountToPay, uint256 amountReceived) =
amount0Delta > 0
? (tokenIn < tokenOut, uint256(amount0Delta), uint256(-amount1Delta))
: (tokenOut < tokenIn, uint256(amount1Delta), uint256(-amount0Delta));
if (isExactInput) {
assembly {
let ptr := mload(0x40)
mstore(ptr, amountReceived)
revert(ptr, 32)
}
assembly {
let ptr := mload(0x40)
mstore(ptr, amountToPay)
revert(ptr, 32)
}
}
}
| 13,187,393
|
./partial_match/1/0x095527F5bEa113E9575B662c5ba01D990A280f2F/sources/TrueFi.sol
|
Writes are allowed only if the accessManager approves
|
function setAttribute(
address _who,
bytes32 _attribute,
uint256 _value,
bytes32 _notes
) public {
require(confirmWrite(_attribute, msg.sender));
attributes[_who][_attribute] = AttributeData(_value, _notes, msg.sender, block.timestamp);
emit SetAttribute(_who, _attribute, _value, _notes, msg.sender);
RegistryClone[] storage targets = subscribers[_attribute];
uint256 index = targets.length;
while (index-- > 0) {
targets[index].syncAttributeValue(_who, _attribute, _value);
}
}
| 3,986,978
|
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
import "./DirectLoanBaseMinimal.sol";
import "../../../utils/ContractKeys.sol";
/**
* @title DirectLoanFixed
* @author NFTfi
* @notice Main contract for NFTfi Direct Loans Fixed Type. This contract manages the ability to create NFT-backed
* peer-to-peer loans of type Fixed (agreed to be a fixed-repayment loan) where the borrower pays the
* maximumRepaymentAmount regardless of whether they repay early or not.
*
* There are two ways to commence an NFT-backed loan:
*
* a. The borrower accepts a lender's offer by calling `acceptOffer`.
* 1. the borrower calls nftContract.approveAll(NFTfi), approving the NFTfi contract to move their NFT's on their
* be1alf.
* 2. the lender calls erc20Contract.approve(NFTfi), allowing NFTfi to move the lender's ERC20 tokens on their
* behalf.
* 3. the lender signs an off-chain message, proposing its offer terms.
* 4. the borrower calls `acceptOffer` to accept these terms and enter into the loan. The NFT is stored in
* the contract, the borrower receives the loan principal in the specified ERC20 currency, the lender receives an
* NFTfi promissory note (in ERC721 form) that represents the rights to either the principal-plus-interest, or the
* underlying NFT collateral if the borrower does not pay back in time, and the borrower receives obligation receipt
* (in ERC721 form) that gives them the right to pay back the loan and get the collateral back.
*
* b. The lender accepts a borrowe's binding terms by calling `acceptListing`.
* 1. the borrower calls nftContract.approveAll(NFTfi), approving the NFTfi contract to move their NFT's on their
* be1alf.
* 2. the lender calls erc20Contract.approve(NFTfi), allowing NFTfi to move the lender's ERC20 tokens on their
* behalf.
* 3. the borrower signs an off-chain message, proposing its binding terms.
* 4. the lender calls `acceptListing` with an offer matching the binding terms and enter into the loan. The NFT is
* stored in the contract, the borrower receives the loan principal in the specified ERC20 currency, the lender
* receives an NFTfi promissory note (in ERC721 form) that represents the rights to either the principal-plus-interest,
* or the underlying NFT collateral if the borrower does not pay back in time, and the borrower receives obligation
* receipt (in ERC721 form) that gives them the right to pay back the loan and get the collateral back.
*
* The lender can freely transfer and trade this ERC721 promissory note as they wish, with the knowledge that
* transferring the ERC721 promissory note tranfsers the rights to principal-plus-interest and/or collateral, and that
* they will no longer have a claim on the loan. The ERC721 promissory note itself represents that claim.
*
* The borrower can freely transfer and trade this ERC721 obligaiton receipt as they wish, with the knowledge that
* transferring the ERC721 obligaiton receipt tranfsers the rights right to pay back the loan and get the collateral
* back.
*
*
* A loan may end in one of two ways:
* - First, a borrower may call NFTfi.payBackLoan() and pay back the loan plus interest at any time, in which case they
* receive their NFT back in the same transaction.
* - Second, if the loan's duration has passed and the loan has not been paid back yet, a lender can call
* NFTfi.liquidateOverdueLoan(), in which case they receive the underlying NFT collateral and forfeit the rights to the
* principal-plus-interest, which the borrower now keeps.
*/
contract DirectLoanFixedOffer is DirectLoanBaseMinimal {
/* ********** */
/* DATA TYPES */
/* ********** */
bytes32 public constant LOAN_TYPE = bytes32("DIRECT_LOAN_FIXED_OFFER");
/* *********** */
/* CONSTRUCTOR */
/* *********** */
/**
* @dev Sets `hub` and permitted erc20-s
*
* @param _admin - Initial admin of this contract.
* @param _nftfiHub - NFTfiHub address
* @param _permittedErc20s - list of permitted ERC20 token contract addresses
*/
constructor(
address _admin,
address _nftfiHub,
address[] memory _permittedErc20s
)
DirectLoanBaseMinimal(
_admin,
_nftfiHub,
ContractKeys.getIdFromStringKey("DIRECT_LOAN_COORDINATOR"),
_permittedErc20s
)
{
// solhint-disable-previous-line no-empty-blocks
}
/* ********* */
/* FUNCTIONS */
/* ********* */
/**
* @notice This function is called by the borrower when accepting a lender's offer to begin a loan.
*
* @param _offer - The offer made by the lender.
* @param _signature - The components of the lender's signature.
* @param _borrowerSettings - Some extra parameters that the borrower needs to set when accepting an offer.
*/
function acceptOffer(
Offer memory _offer,
Signature memory _signature,
BorrowerSettings memory _borrowerSettings
) external whenNotPaused nonReentrant {
address nftWrapper = _getWrapper(_offer.nftCollateralContract);
_loanSanityChecks(_offer, nftWrapper);
_loanSanityChecksOffer(_offer);
_acceptOffer(
LOAN_TYPE,
_setupLoanTerms(_offer, nftWrapper),
_setupLoanExtras(_borrowerSettings.revenueSharePartner, _borrowerSettings.referralFeeInBasisPoints),
_offer,
_signature
);
}
/* ******************* */
/* READ-ONLY FUNCTIONS */
/* ******************* */
/**
* @notice This function can be used to view the current quantity of the ERC20 currency used in the specified loan
* required by the borrower to repay their loan, measured in the smallest unit of the ERC20 currency.
*
* @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator.
*
* @return The amount of the specified ERC20 currency required to pay back this loan, measured in the smallest unit
* of the specified ERC20 currency.
*/
function getPayoffAmount(uint32 _loanId) external view override returns (uint256) {
LoanTerms storage loan = loanIdToLoan[_loanId];
return loan.maximumRepaymentAmount;
}
/* ****************** */
/* INTERNAL FUNCTIONS */
/* ****************** */
/**
* @notice This function is called by the borrower when accepting a lender's offer to begin a loan.
*
* @param _loanType - The loan type being created.
* @param _loanTerms - The main Loan Terms struct. This data is saved upon loan creation on loanIdToLoan.
* @param _loanExtras - The main Loan Terms struct. This data is saved upon loan creation on loanIdToLoanExtras.
* @param _offer - The offer made by the lender.
* @param _signature - The components of the lender's signature.
*/
function _acceptOffer(
bytes32 _loanType,
LoanTerms memory _loanTerms,
LoanExtras memory _loanExtras,
Offer memory _offer,
Signature memory _signature
) internal {
// Check loan nonces. These are different from Ethereum account nonces.
// Here, these are uint256 numbers that should uniquely identify
// each signature for each user (i.e. each user should only create one
// off-chain signature for each nonce, with a nonce being any arbitrary
// uint256 value that they have not used yet for an off-chain NFTfi
// signature).
require(!_nonceHasBeenUsedForUser[_signature.signer][_signature.nonce], "Lender nonce invalid");
_nonceHasBeenUsedForUser[_signature.signer][_signature.nonce] = true;
require(NFTfiSigningUtils.isValidLenderSignature(_offer, _signature), "Lender signature is invalid");
address bundle = hub.getContract(ContractKeys.NFTFI_BUNDLER);
require(_loanTerms.nftCollateralContract != bundle, "Collateral cannot be bundle");
uint32 loanId = _createLoan(_loanType, _loanTerms, _loanExtras, msg.sender, _signature.signer, _offer.referrer);
// Emit an event with all relevant details from this transaction.
emit LoanStarted(loanId, msg.sender, _signature.signer, _loanTerms, _loanExtras);
}
/**
* @dev Creates a `LoanTerms` struct using data sent as the lender's `_offer` on `acceptOffer`.
* This is needed in order to avoid stack too deep issues.
* Since this is a Fixed loan type loanInterestRateForDurationInBasisPoints is ignored.
*/
function _setupLoanTerms(Offer memory _offer, address _nftWrapper) internal view returns (LoanTerms memory) {
return
LoanTerms({
loanERC20Denomination: _offer.loanERC20Denomination,
loanPrincipalAmount: _offer.loanPrincipalAmount,
maximumRepaymentAmount: _offer.maximumRepaymentAmount,
nftCollateralContract: _offer.nftCollateralContract,
nftCollateralWrapper: _nftWrapper,
nftCollateralId: _offer.nftCollateralId,
loanStartTime: uint64(block.timestamp),
loanDuration: _offer.loanDuration,
loanInterestRateForDurationInBasisPoints: uint16(0),
loanAdminFeeInBasisPoints: _offer.loanAdminFeeInBasisPoints,
borrower: msg.sender
});
}
/**
* @dev Calculates the payoff amount and admin fee
*
* @param _loanTerms - Struct containing all the loan's parameters
*/
function _payoffAndFee(LoanTerms memory _loanTerms)
internal
pure
override
returns (uint256 adminFee, uint256 payoffAmount)
{
// Calculate amounts to send to lender and admins
uint256 interestDue = _loanTerms.maximumRepaymentAmount - _loanTerms.loanPrincipalAmount;
adminFee = LoanChecksAndCalculations.computeAdminFee(
interestDue,
uint256(_loanTerms.loanAdminFeeInBasisPoints)
);
payoffAmount = _loanTerms.maximumRepaymentAmount - adminFee;
}
/**
* @dev Function that performs some validation checks over loan parameters when accepting an offer
*
*/
function _loanSanityChecksOffer(LoanData.Offer memory _offer) internal pure {
require(
_offer.maximumRepaymentAmount >= _offer.loanPrincipalAmount,
"Negative interest rate loans are not allowed."
);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
import "./IDirectLoanBase.sol";
import "./LoanData.sol";
import "./LoanChecksAndCalculations.sol";
import "./LoanAirdropUtils.sol";
import "../../BaseLoan.sol";
import "../../../utils/NftReceiver.sol";
import "../../../utils/NFTfiSigningUtils.sol";
import "../../../interfaces/INftfiHub.sol";
import "../../../utils/ContractKeys.sol";
import "../../../interfaces/IDirectLoanCoordinator.sol";
import "../../../interfaces/INftWrapper.sol";
import "../../../interfaces/IPermittedPartners.sol";
import "../../../interfaces/IPermittedERC20s.sol";
import "../../../interfaces/IPermittedNFTs.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
* @title DirectLoanBase
* @author NFTfi
* @notice Main contract for NFTfi Direct Loans Type. This contract manages the ability to create NFT-backed
* peer-to-peer loans.
*
* There are two ways to commence an NFT-backed loan:
*
* a. The borrower accepts a lender's offer by calling `acceptOffer`.
* 1. the borrower calls nftContract.approveAll(NFTfi), approving the NFTfi contract to move their NFT's on their
* be1alf.
* 2. the lender calls erc20Contract.approve(NFTfi), allowing NFTfi to move the lender's ERC20 tokens on their
* behalf.
* 3. the lender signs an off-chain message, proposing its offer terms.
* 4. the borrower calls `acceptOffer` to accept these terms and enter into the loan. The NFT is stored in
* the contract, the borrower receives the loan principal in the specified ERC20 currency, the lender receives an
* NFTfi promissory note (in ERC721 form) that represents the rights to either the principal-plus-interest, or the
* underlying NFT collateral if the borrower does not pay back in time, and the borrower receives obligation receipt
* (in ERC721 form) that gives them the right to pay back the loan and get the collateral back.
*
* b. The lender accepts a borrowe's binding terms by calling `acceptListing`.
* 1. the borrower calls nftContract.approveAll(NFTfi), approving the NFTfi contract to move their NFT's on their
* be1alf.
* 2. the lender calls erc20Contract.approve(NFTfi), allowing NFTfi to move the lender's ERC20 tokens on their
* behalf.
* 3. the borrower signs an off-chain message, proposing its binding terms.
* 4. the lender calls `acceptListing` with an offer matching the binding terms and enter into the loan. The NFT is
* stored in the contract, the borrower receives the loan principal in the specified ERC20 currency, the lender
* receives an NFTfi promissory note (in ERC721 form) that represents the rights to either the principal-plus-interest,
* or the underlying NFT collateral if the borrower does not pay back in time, and the borrower receives obligation
* receipt (in ERC721 form) that gives them the right to pay back the loan and get the collateral back.
*
* The lender can freely transfer and trade this ERC721 promissory note as they wish, with the knowledge that
* transferring the ERC721 promissory note tranfsers the rights to principal-plus-interest and/or collateral, and that
* they will no longer have a claim on the loan. The ERC721 promissory note itself represents that claim.
*
* The borrower can freely transfer and trade this ERC721 obligaiton receipt as they wish, with the knowledge that
* transferring the ERC721 obligaiton receipt tranfsers the rights right to pay back the loan and get the collateral
* back.
*
* A loan may end in one of two ways:
* - First, a borrower may call NFTfi.payBackLoan() and pay back the loan plus interest at any time, in which case they
* receive their NFT back in the same transaction.
* - Second, if the loan's duration has passed and the loan has not been paid back yet, a lender can call
* NFTfi.liquidateOverdueLoan(), in which case they receive the underlying NFT collateral and forfeit the rights to the
* principal-plus-interest, which the borrower now keeps.
*
*
* If the loan was created as a ProRated type loan (pro-rata interest loan), then the user only pays the principal plus
* pro-rata interest if repaid early.
* However, if the loan was was created as a Fixed type loan (agreed to be a fixed-repayment loan), then the borrower
* pays the maximumRepaymentAmount regardless of whether they repay early or not.
*
*/
abstract contract DirectLoanBaseMinimal is IDirectLoanBase, IPermittedERC20s, BaseLoan, NftReceiver, LoanData {
using SafeERC20 for IERC20;
/* ******* */
/* STORAGE */
/* ******* */
uint16 public constant HUNDRED_PERCENT = 10000;
bytes32 public immutable override LOAN_COORDINATOR;
/**
* @notice The maximum duration of any loan started for this loan type, measured in seconds. This is both a
* sanity-check for borrowers and an upper limit on how long admins will have to support v1 of this contract if they
* eventually deprecate it, as well as a check to ensure that the loan duration never exceeds the space alotted for
* it in the loan struct.
*/
uint256 public override maximumLoanDuration = 53 weeks;
/**
* @notice The percentage of interest earned by lenders on this platform that is taken by the contract admin's as a
* fee, measured in basis points (hundreths of a percent). The max allowed value is 10000.
*/
uint16 public override adminFeeInBasisPoints = 25;
/**
* @notice A mapping from a loan's identifier to the loan's details, represted by the loan struct.
*/
mapping(uint32 => LoanTerms) public override loanIdToLoan;
mapping(uint32 => LoanExtras) public loanIdToLoanExtras;
/**
* @notice A mapping tracking whether a loan has either been repaid or liquidated. This prevents an attacker trying
* to repay or liquidate the same loan twice.
*/
mapping(uint32 => bool) public override loanRepaidOrLiquidated;
/**
* @dev keeps track of tokens being held as loan collateral, so we dont allow these
* to be transferred with the aridrop draining functions
*/
mapping(address => mapping(uint256 => uint256)) private _escrowTokens;
/**
* @notice A mapping that takes both a user's address and a loan nonce that was first used when signing an off-chain
* order and checks whether that nonce has previously either been used for a loan, or has been pre-emptively
* cancelled. The nonce referred to here is not the same as an Ethereum account's nonce. We are referring instead to
* nonces that are used by both the lender and the borrower when they are first signing off-chain NFTfi orders.
*
* These nonces can be any uint256 value that the user has not previously used to sign an off-chain order. Each
* nonce can be used at most once per user within NFTfi, regardless of whether they are the lender or the borrower
* in that situation. This serves two purposes. First, it prevents replay attacks where an attacker would submit a
* user's off-chain order more than once. Second, it allows a user to cancel an off-chain order by calling
* NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from
* using the user's off-chain order that contains that nonce.
*/
mapping(address => mapping(uint256 => bool)) internal _nonceHasBeenUsedForUser;
/**
* @notice A mapping from an ERC20 currency address to whether that currency
* is permitted to be used by this contract.
*/
mapping(address => bool) private erc20Permits;
INftfiHub public immutable hub;
/* ****** */
/* EVENTS */
/* ****** */
/**
* @notice This event is fired whenever the admins change the percent of interest rates earned that they charge as a
* fee. Note that newAdminFee can never exceed 10,000, since the fee is measured in basis points.
*
* @param newAdminFee - The new admin fee measured in basis points. This is a percent of the interest paid upon a
* loan's completion that go to the contract admins.
*/
event AdminFeeUpdated(uint16 newAdminFee);
/**
* @notice This event is fired whenever the admins change the maximum duration of any loan started for this loan
* type.
*
* @param newMaximumLoanDuration - The new maximum duration.
*/
event MaximumLoanDurationUpdated(uint256 newMaximumLoanDuration);
/**
* @notice This event is fired whenever a borrower begins a loan by calling NFTfi.beginLoan(), which can only occur
* after both the lender and borrower have approved their ERC721 and ERC20 contracts to use NFTfi, and when they
* both have signed off-chain messages that agree on the terms of the loan.
*
* @param loanId - A unique identifier for this particular loan, sourced from the Loan Coordinator.
* @param borrower - The address of the borrower.
* @param lender - The address of the lender. The lender can change their address by transferring the NFTfi ERC721
* token that they received when the loan began.
*/
event LoanStarted(
uint32 indexed loanId,
address indexed borrower,
address indexed lender,
LoanTerms loanTerms,
LoanExtras loanExtras
);
/**
* @notice This event is fired whenever a borrower successfully repays their loan, paying
* principal-plus-interest-minus-fee to the lender in loanERC20Denomination, paying fee to owner in
* loanERC20Denomination, and receiving their NFT collateral back.
*
* @param loanId - A unique identifier for this particular loan, sourced from the Loan Coordinator.
* @param borrower - The address of the borrower.
* @param lender - The address of the lender. The lender can change their address by transferring the NFTfi ERC721
* token that they received when the loan began.
* @param loanPrincipalAmount - The original sum of money transferred from lender to borrower at the beginning of
* the loan, measured in loanERC20Denomination's smallest units.
* @param nftCollateralId - The ID within the NFTCollateralContract for the NFT being used as collateral for this
* loan. The NFT is stored within this contract during the duration of the loan.
* @param amountPaidToLender The amount of ERC20 that the borrower paid to the lender, measured in the smalled
* units of loanERC20Denomination.
* @param adminFee The amount of interest paid to the contract admins, measured in the smalled units of
* loanERC20Denomination and determined by adminFeeInBasisPoints. This amount never exceeds the amount of interest
* earned.
* @param revenueShare The amount taken from admin fee amount shared with the partner.
* @param revenueSharePartner - The address of the partner that will receive the revenue share.
* @param nftCollateralContract - The ERC721 contract of the NFT collateral
* @param loanERC20Denomination - The ERC20 contract of the currency being used as principal/interest for this
* loan.
*/
event LoanRepaid(
uint32 indexed loanId,
address indexed borrower,
address indexed lender,
uint256 loanPrincipalAmount,
uint256 nftCollateralId,
uint256 amountPaidToLender,
uint256 adminFee,
uint256 revenueShare,
address revenueSharePartner,
address nftCollateralContract,
address loanERC20Denomination
);
/**
* @notice This event is fired whenever a lender liquidates an outstanding loan that is owned to them that has
* exceeded its duration. The lender receives the underlying NFT collateral, and the borrower no longer needs to
* repay the loan principal-plus-interest.
*
* @param loanId - A unique identifier for this particular loan, sourced from the Loan Coordinator.
* @param borrower - The address of the borrower.
* @param lender - The address of the lender. The lender can change their address by transferring the NFTfi ERC721
* token that they received when the loan began.
* @param loanPrincipalAmount - The original sum of money transferred from lender to borrower at the beginning of
* the loan, measured in loanERC20Denomination's smallest units.
* @param nftCollateralId - The ID within the NFTCollateralContract for the NFT being used as collateral for this
* loan. The NFT is stored within this contract during the duration of the loan.
* @param loanMaturityDate - The unix time (measured in seconds) that the loan became due and was eligible for
* liquidation.
* @param loanLiquidationDate - The unix time (measured in seconds) that liquidation occurred.
* @param nftCollateralContract - The ERC721 contract of the NFT collateral
*/
event LoanLiquidated(
uint32 indexed loanId,
address indexed borrower,
address indexed lender,
uint256 loanPrincipalAmount,
uint256 nftCollateralId,
uint256 loanMaturityDate,
uint256 loanLiquidationDate,
address nftCollateralContract
);
/**
* @notice This event is fired when some of the terms of a loan are being renegotiated.
*
* @param loanId - The unique identifier for the loan to be renegotiated
* @param newLoanDuration - The new amount of time (measured in seconds) that can elapse before the lender can
* liquidate the loan and seize the underlying collateral NFT.
* @param newMaximumRepaymentAmount - The new maximum amount of money that the borrower would be required to
* retrieve their collateral, measured in the smallest units of the ERC20 currency used for the loan. The
* borrower will always have to pay this amount to retrieve their collateral, regardless of whether they repay
* early.
* @param renegotiationFee Agreed upon fee in loan denomination that borrower pays for the lender for the
* renegotiation, has to be paid with an ERC20 transfer loanERC20Denomination token, uses transfer from,
* frontend will have to propmt an erc20 approve for this from the borrower to the lender
* @param renegotiationAdminFee renegotiationFee admin portion based on determined by adminFeeInBasisPoints
*/
event LoanRenegotiated(
uint32 indexed loanId,
address indexed borrower,
address indexed lender,
uint32 newLoanDuration,
uint256 newMaximumRepaymentAmount,
uint256 renegotiationFee,
uint256 renegotiationAdminFee
);
/**
* @notice This event is fired whenever the admin sets a ERC20 permit.
*
* @param erc20Contract - Address of the ERC20 contract.
* @param isPermitted - Signals ERC20 permit.
*/
event ERC20Permit(address indexed erc20Contract, bool isPermitted);
/* *********** */
/* CONSTRUCTOR */
/* *********** */
/**
* @dev Sets `hub`
*
* @param _admin - Initial admin of this contract.
* @param _nftfiHub - NFTfiHub address
* @param _loanCoordinatorKey -
* @param _permittedErc20s -
*/
constructor(
address _admin,
address _nftfiHub,
bytes32 _loanCoordinatorKey,
address[] memory _permittedErc20s
) BaseLoan(_admin) {
hub = INftfiHub(_nftfiHub);
LOAN_COORDINATOR = _loanCoordinatorKey;
for (uint256 i = 0; i < _permittedErc20s.length; i++) {
_setERC20Permit(_permittedErc20s[i], true);
}
}
/* *************** */
/* ADMIN FUNCTIONS */
/* *************** */
/**
* @notice This function can be called by admins to change the maximumLoanDuration. Note that they can never change
* maximumLoanDuration to be greater than UINT32_MAX, since that's the maximum space alotted for the duration in the
* loan struct.
*
* @param _newMaximumLoanDuration - The new maximum loan duration, measured in seconds.
*/
function updateMaximumLoanDuration(uint256 _newMaximumLoanDuration) external onlyOwner {
require(_newMaximumLoanDuration <= uint256(type(uint32).max), "Loan duration overflow");
maximumLoanDuration = _newMaximumLoanDuration;
emit MaximumLoanDurationUpdated(_newMaximumLoanDuration);
}
/**
* @notice This function can be called by admins to change the percent of interest rates earned that they charge as
* a fee. Note that newAdminFee can never exceed 10,000, since the fee is measured in basis points.
*
* @param _newAdminFeeInBasisPoints - The new admin fee measured in basis points. This is a percent of the interest
* paid upon a loan's completion that go to the contract admins.
*/
function updateAdminFee(uint16 _newAdminFeeInBasisPoints) external onlyOwner {
require(_newAdminFeeInBasisPoints <= HUNDRED_PERCENT, "basis points > 10000");
adminFeeInBasisPoints = _newAdminFeeInBasisPoints;
emit AdminFeeUpdated(_newAdminFeeInBasisPoints);
}
/**
* @notice used by the owner account to be able to drain ERC20 tokens received as airdrops
* for the locked collateral NFT-s
* @param _tokenAddress - address of the token contract for the token to be sent out
* @param _receiver - receiver of the token
*/
function drainERC20Airdrop(address _tokenAddress, address _receiver) external onlyOwner {
IERC20 tokenContract = IERC20(_tokenAddress);
uint256 amount = tokenContract.balanceOf(address(this));
require(amount > 0, "no tokens owned");
tokenContract.safeTransfer(_receiver, amount);
}
/**
* @notice This function can be called by admins to change the permitted status of an ERC20 currency. This includes
* both adding an ERC20 currency to the permitted list and removing it.
*
* @param _erc20 - The address of the ERC20 currency whose permit list status changed.
* @param _permit - The new status of whether the currency is permitted or not.
*/
function setERC20Permit(address _erc20, bool _permit) external onlyOwner {
_setERC20Permit(_erc20, _permit);
}
/**
* @notice This function can be called by admins to change the permitted status of a batch of ERC20 currency. This
* includes both adding an ERC20 currency to the permitted list and removing it.
*
* @param _erc20s - The addresses of the ERC20 currencies whose permit list status changed.
* @param _permits - The new statuses of whether the currency is permitted or not.
*/
function setERC20Permits(address[] memory _erc20s, bool[] memory _permits) external onlyOwner {
require(_erc20s.length == _permits.length, "setERC20Permits function information arity mismatch");
for (uint256 i = 0; i < _erc20s.length; i++) {
_setERC20Permit(_erc20s[i], _permits[i]);
}
}
/**
* @notice used by the owner account to be able to drain ERC721 tokens received as airdrops
* for the locked collateral NFT-s
* @param _tokenAddress - address of the token contract for the token to be sent out
* @param _tokenId - id token to be sent out
* @param _receiver - receiver of the token
*/
function drainERC721Airdrop(
address _tokenAddress,
uint256 _tokenId,
address _receiver
) external onlyOwner {
IERC721 tokenContract = IERC721(_tokenAddress);
require(_escrowTokens[_tokenAddress][_tokenId] == 0, "token is collateral");
require(tokenContract.ownerOf(_tokenId) == address(this), "nft not owned");
tokenContract.safeTransferFrom(address(this), _receiver, _tokenId);
}
/**
* @notice used by the owner account to be able to drain ERC1155 tokens received as airdrops
* for the locked collateral NFT-s
* @param _tokenAddress - address of the token contract for the token to be sent out
* @param _tokenId - id token to be sent out
* @param _receiver - receiver of the token
*/
function drainERC1155Airdrop(
address _tokenAddress,
uint256 _tokenId,
address _receiver
) external onlyOwner {
IERC1155 tokenContract = IERC1155(_tokenAddress);
uint256 amount = tokenContract.balanceOf(address(this), _tokenId);
require(_escrowTokens[_tokenAddress][_tokenId] == 0, "token is collateral");
require(amount > 0, "no nfts owned");
tokenContract.safeTransferFrom(address(this), _receiver, _tokenId, amount, "");
}
function mintObligationReceipt(uint32 _loanId) external nonReentrant {
address borrower = loanIdToLoan[_loanId].borrower;
require(msg.sender == borrower, "sender has to be borrower");
IDirectLoanCoordinator loanCoordinator = IDirectLoanCoordinator(hub.getContract(LOAN_COORDINATOR));
loanCoordinator.mintObligationReceipt(_loanId, borrower);
delete loanIdToLoan[_loanId].borrower;
}
/**
* @dev makes possible to change loan duration and max repayment amount, loan duration even can be extended if
* loan was expired but not liquidated.
*
* @param _loanId - The unique identifier for the loan to be renegotiated
* @param _newLoanDuration - The new amount of time (measured in seconds) that can elapse before the lender can
* liquidate the loan and seize the underlying collateral NFT.
* @param _newMaximumRepaymentAmount - The new maximum amount of money that the borrower would be required to
* retrieve their collateral, measured in the smallest units of the ERC20 currency used for the loan. The
* borrower will always have to pay this amount to retrieve their collateral, regardless of whether they repay
* early.
* @param _renegotiationFee Agreed upon fee in ether that borrower pays for the lender for the renegitiation
* @param _lenderNonce - The nonce referred to here is not the same as an Ethereum account's nonce. We are
* referring instead to nonces that are used by both the lender and the borrower when they are first signing
* off-chain NFTfi orders. These nonces can be any uint256 value that the user has not previously used to sign an
* off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the
* lender or the borrower in that situation. This serves two purposes:
* - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once.
* - Second, it allows a user to cancel an off-chain order by calling NFTfi.cancelLoanCommitmentBeforeLoanHasBegun()
* , which marks the nonce as used and prevents any future loan from using the user's off-chain order that contains
* that nonce.
* @param _expiry - The date when the renegotiation offer expires
* @param _lenderSignature - The ECDSA signature of the lender, obtained off-chain ahead of time, signing the
* following combination of parameters:
* - _loanId
* - _newLoanDuration
* - _newMaximumRepaymentAmount
* - _lender
* - _expiry
* - address of this contract
* - chainId
*/
function renegotiateLoan(
uint32 _loanId,
uint32 _newLoanDuration,
uint256 _newMaximumRepaymentAmount,
uint256 _renegotiationFee,
uint256 _lenderNonce,
uint256 _expiry,
bytes memory _lenderSignature
) external whenNotPaused nonReentrant {
_renegotiateLoan(
_loanId,
_newLoanDuration,
_newMaximumRepaymentAmount,
_renegotiationFee,
_lenderNonce,
_expiry,
_lenderSignature
);
}
/**
* @notice This function is called by a anyone to repay a loan. It can be called at any time after the loan has
* begun and before loan expiry.. The caller will pay a pro-rata portion of their interest if the loan is paid off
* early and the loan is pro-rated type, but the complete repayment amount if it is fixed type.
* The the borrower (current owner of the obligation note) will get the collaterl NFT back.
*
* This function is purposefully not pausable in order to prevent an attack where the contract admin's pause the
* contract and hold hostage the NFT's that are still within it.
*
* @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator.
*/
function payBackLoan(uint32 _loanId) external nonReentrant {
LoanChecksAndCalculations.payBackChecks(_loanId, hub);
(
address borrower,
address lender,
LoanTerms memory loan,
IDirectLoanCoordinator loanCoordinator
) = _getPartiesAndData(_loanId);
_payBackLoan(_loanId, borrower, lender, loan);
_resolveLoan(_loanId, borrower, loan, loanCoordinator);
// Delete the loan from storage in order to achieve a substantial gas savings and to lessen the burden of
// storage on Ethereum nodes, since we will never access this loan's details again, and the details are still
// available through event data.
delete loanIdToLoan[_loanId];
delete loanIdToLoanExtras[_loanId];
}
/**
* @notice This function is called by a lender once a loan has finished its duration and the borrower still has not
* repaid. The lender can call this function to seize the underlying NFT collateral, although the lender gives up
* all rights to the principal-plus-collateral by doing so.
*
* This function is purposefully not pausable in order to prevent an attack where the contract admin's pause
* the contract and hold hostage the NFT's that are still within it.
*
* We intentionally allow anybody to call this function, although only the lender will end up receiving the seized
* collateral. We are exploring the possbility of incentivizing users to call this function by using some of the
* admin funds.
*
* @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator.
*/
function liquidateOverdueLoan(uint32 _loanId) external nonReentrant {
LoanChecksAndCalculations.checkLoanIdValidity(_loanId, hub);
// Sanity check that payBackLoan() and liquidateOverdueLoan() have never been called on this loanId.
// Depending on how the rest of the code turns out, this check may be unnecessary.
require(!loanRepaidOrLiquidated[_loanId], "Loan already repaid/liquidated");
(
address borrower,
address lender,
LoanTerms memory loan,
IDirectLoanCoordinator loanCoordinator
) = _getPartiesAndData(_loanId);
// Ensure that the loan is indeed overdue, since we can only liquidate overdue loans.
uint256 loanMaturityDate = uint256(loan.loanStartTime) + uint256(loan.loanDuration);
require(block.timestamp > loanMaturityDate, "Loan is not overdue yet");
require(msg.sender == lender, "Only lender can liquidate");
_resolveLoan(_loanId, lender, loan, loanCoordinator);
// Emit an event with all relevant details from this transaction.
emit LoanLiquidated(
_loanId,
borrower,
lender,
loan.loanPrincipalAmount,
loan.nftCollateralId,
loanMaturityDate,
block.timestamp,
loan.nftCollateralContract
);
// Delete the loan from storage in order to achieve a substantial gas savings and to lessen the burden of
// storage on Ethereum nodes, since we will never access this loan's details again, and the details are still
// available through event data.
delete loanIdToLoan[_loanId];
delete loanIdToLoanExtras[_loanId];
}
/**
* @notice this function initiates a flashloan to pull an airdrop from a tartget contract
*
* @param _loanId -
* @param _target - address of the airdropping contract
* @param _data - function selector to be called on the airdropping contract
* @param _nftAirdrop - address of the used claiming nft in the drop
* @param _nftAirdropId - id of the used claiming nft in the drop
* @param _is1155 -
* @param _nftAirdropAmount - amount in case of 1155
*/
function pullAirdrop(
uint32 _loanId,
address _target,
bytes calldata _data,
address _nftAirdrop,
uint256 _nftAirdropId,
bool _is1155,
uint256 _nftAirdropAmount
) external nonReentrant {
LoanChecksAndCalculations.checkLoanIdValidity(_loanId, hub);
require(!loanRepaidOrLiquidated[_loanId], "Loan already repaid/liquidated");
LoanTerms memory loan = loanIdToLoan[_loanId];
LoanAirdropUtils.pullAirdrop(
_loanId,
loan,
_target,
_data,
_nftAirdrop,
_nftAirdropId,
_is1155,
_nftAirdropAmount,
hub
);
}
/**
* @notice this function creates a proxy contract wrapping the collateral to be able to catch an expected airdrop
*
* @param _loanId -
*/
function wrapCollateral(uint32 _loanId) external nonReentrant {
LoanChecksAndCalculations.checkLoanIdValidity(_loanId, hub);
require(!loanRepaidOrLiquidated[_loanId], "Loan already repaid/liquidated");
LoanTerms storage loan = loanIdToLoan[_loanId];
_escrowTokens[loan.nftCollateralContract][loan.nftCollateralId] -= 1;
(address instance, uint256 receiverId) = LoanAirdropUtils.wrapCollateral(_loanId, loan, hub);
_escrowTokens[instance][receiverId] += 1;
}
/**
* @notice This function can be called by either a lender or a borrower to cancel all off-chain orders that they
* have signed that contain this nonce. If the off-chain orders were created correctly, there should only be one
* off-chain order that contains this nonce at all.
*
* The nonce referred to here is not the same as an Ethereum account's nonce. We are referring
* instead to nonces that are used by both the lender and the borrower when they are first signing off-chain NFTfi
* orders. These nonces can be any uint256 value that the user has not previously used to sign an off-chain order.
* Each nonce can be used at most once per user within NFTfi, regardless of whether they are the lender or the
* borrower in that situation. This serves two purposes. First, it prevents replay attacks where an attacker would
* submit a user's off-chain order more than once. Second, it allows a user to cancel an off-chain order by calling
* NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from
* using the user's off-chain order that contains that nonce.
*
* @param _nonce - User nonce
*/
function cancelLoanCommitmentBeforeLoanHasBegun(uint256 _nonce) external {
require(!_nonceHasBeenUsedForUser[msg.sender][_nonce], "Invalid nonce");
_nonceHasBeenUsedForUser[msg.sender][_nonce] = true;
}
/* ******************* */
/* READ-ONLY FUNCTIONS */
/* ******************* */
/**
* @notice This function can be used to view the current quantity of the ERC20 currency used in the specified loan
* required by the borrower to repay their loan, measured in the smallest unit of the ERC20 currency.
*
* @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator.
*
* @return The amount of the specified ERC20 currency required to pay back this loan, measured in the smallest unit
* of the specified ERC20 currency.
*/
function getPayoffAmount(uint32 _loanId) external view virtual returns (uint256);
/**
* @notice This function can be used to view whether a particular nonce for a particular user has already been used,
* either from a successful loan or a cancelled off-chain order.
*
* @param _user - The address of the user. This function works for both lenders and borrowers alike.
* @param _nonce - The nonce referred to here is not the same as an Ethereum account's nonce. We are referring
* instead to nonces that are used by both the lender and the borrower when they are first signing off-chain
* NFTfi orders. These nonces can be any uint256 value that the user has not previously used to sign an off-chain
* order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the lender or
* the borrower in that situation. This serves two purposes:
* - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once.
* - Second, it allows a user to cancel an off-chain order by calling NFTfi.cancelLoanCommitmentBeforeLoanHasBegun()
* , which marks the nonce as used and prevents any future loan from using the user's off-chain order that contains
* that nonce.
*
* @return A bool representing whether or not this nonce has been used for this user.
*/
function getWhetherNonceHasBeenUsedForUser(address _user, uint256 _nonce) external view override returns (bool) {
return _nonceHasBeenUsedForUser[_user][_nonce];
}
/**
* @notice This function can be called by anyone to get the permit associated with the erc20 contract.
*
* @param _erc20 - The address of the erc20 contract.
*
* @return Returns whether the erc20 is permitted
*/
function getERC20Permit(address _erc20) public view override returns (bool) {
return erc20Permits[_erc20];
}
/* ****************** */
/* INTERNAL FUNCTIONS */
/* ****************** */
/**
* @dev makes possible to change loan duration and max repayment amount, loan duration even can be extended if
* loan was expired but not liquidated. IMPORTANT: Frontend will have to propt the caller to do an ERC20 approve for
* the fee amount from themselves (borrower/obligation reciept holder) to the lender (promissory note holder)
*
* @param _loanId - The unique identifier for the loan to be renegotiated
* @param _newLoanDuration - The new amount of time (measured in seconds) that can elapse before the lender can
* liquidate the loan and seize the underlying collateral NFT.
* @param _newMaximumRepaymentAmount - The new maximum amount of money that the borrower would be required to
* retrieve their collateral, measured in the smallest units of the ERC20 currency used for the loan. The
* borrower will always have to pay this amount to retrieve their collateral, regardless of whether they repay
* early.
* @param _renegotiationFee Agreed upon fee in loan denomination that borrower pays for the lender and
* the admin for the renegotiation, has to be paid with an ERC20 transfer loanERC20Denomination token,
* uses transfer from, frontend will have to propmt an erc20 approve for this from the borrower to the lender,
* admin fee is calculated by the loan's loanAdminFeeInBasisPoints value
* @param _lenderNonce - The nonce referred to here is not the same as an Ethereum account's nonce. We are
* referring instead to nonces that are used by both the lender and the borrower when they are first signing
* off-chain NFTfi orders. These nonces can be any uint256 value that the user has not previously used to sign an
* off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the
* lender or the borrower in that situation. This serves two purposes:
* - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once.
* - Second, it allows a user to cancel an off-chain order by calling NFTfi.cancelLoanCommitmentBeforeLoanHasBegun()
, which marks the nonce as used and prevents any future loan from using the user's off-chain order that contains
* that nonce.
* @param _expiry - The date when the renegotiation offer expires
* @param _lenderSignature - The ECDSA signature of the lender, obtained off-chain ahead of time, signing the
* following combination of parameters:
* - _loanId
* - _newLoanDuration
* - _newMaximumRepaymentAmount
* - _lender
* - _expiry
* - address of this contract
* - chainId
*/
function _renegotiateLoan(
uint32 _loanId,
uint32 _newLoanDuration,
uint256 _newMaximumRepaymentAmount,
uint256 _renegotiationFee,
uint256 _lenderNonce,
uint256 _expiry,
bytes memory _lenderSignature
) internal {
LoanTerms storage loan = loanIdToLoan[_loanId];
(address borrower, address lender) = LoanChecksAndCalculations.renegotiationChecks(
loan,
_loanId,
_newLoanDuration,
_newMaximumRepaymentAmount,
_lenderNonce,
hub
);
_nonceHasBeenUsedForUser[lender][_lenderNonce] = true;
require(
NFTfiSigningUtils.isValidLenderRenegotiationSignature(
_loanId,
_newLoanDuration,
_newMaximumRepaymentAmount,
_renegotiationFee,
Signature({signer: lender, nonce: _lenderNonce, expiry: _expiry, signature: _lenderSignature})
),
"Renegotiation signature is invalid"
);
uint256 renegotiationAdminFee;
/**
* @notice Transfers fee to the lender immediately
* @dev implements Checks-Effects-Interactions pattern by modifying state only after
* the transfer happened successfully, we also add the nonReentrant modifier to
* the pbulic versions
*/
if (_renegotiationFee > 0) {
renegotiationAdminFee = LoanChecksAndCalculations.computeAdminFee(
_renegotiationFee,
loan.loanAdminFeeInBasisPoints
);
// Transfer principal-plus-interest-minus-fees from the caller (always has to be borrower) to lender
IERC20(loan.loanERC20Denomination).safeTransferFrom(
borrower,
lender,
_renegotiationFee - renegotiationAdminFee
);
// Transfer fees from the caller (always has to be borrower) to admins
IERC20(loan.loanERC20Denomination).safeTransferFrom(borrower, owner(), renegotiationAdminFee);
}
loan.loanDuration = _newLoanDuration;
loan.maximumRepaymentAmount = _newMaximumRepaymentAmount;
emit LoanRenegotiated(
_loanId,
borrower,
lender,
_newLoanDuration,
_newMaximumRepaymentAmount,
_renegotiationFee,
renegotiationAdminFee
);
}
/**
* @dev Transfer collateral NFT from borrower to this contract and principal from lender to the borrower and
* registers the new loan through the loan coordinator.
*
* @param _loanType - The type of loan it is being created
* @param _loanTerms - Struct containing the loan's settings
* @param _loanExtras - Struct containing some loan's extra settings, needed to avoid stack too deep
* @param _lender - The address of the lender.
* @param _referrer - The address of the referrer who found the lender matching the listing, Zero address to signal
* that there is no referrer.
*/
function _createLoan(
bytes32 _loanType,
LoanTerms memory _loanTerms,
LoanExtras memory _loanExtras,
address _borrower,
address _lender,
address _referrer
) internal returns (uint32) {
// Transfer collateral from borrower to this contract to be held until
// loan completion.
_transferNFT(_loanTerms, _borrower, address(this));
return _createLoanNoNftTransfer(_loanType, _loanTerms, _loanExtras, _borrower, _lender, _referrer);
}
/**
* @dev Transfer principal from lender to the borrower and
* registers the new loan through the loan coordinator.
*
* @param _loanType - The type of loan it is being created
* @param _loanTerms - Struct containing the loan's settings
* @param _loanExtras - Struct containing some loan's extra settings, needed to avoid stack too deep
* @param _lender - The address of the lender.
* @param _referrer - The address of the referrer who found the lender matching the listing, Zero address to signal
* that there is no referrer.
*/
function _createLoanNoNftTransfer(
bytes32 _loanType,
LoanTerms memory _loanTerms,
LoanExtras memory _loanExtras,
address _borrower,
address _lender,
address _referrer
) internal returns (uint32 loanId) {
_escrowTokens[_loanTerms.nftCollateralContract][_loanTerms.nftCollateralId] += 1;
uint256 referralfee = LoanChecksAndCalculations.computeReferralFee(
_loanTerms.loanPrincipalAmount,
_loanExtras.referralFeeInBasisPoints,
_referrer
);
uint256 principalAmount = _loanTerms.loanPrincipalAmount - referralfee;
if (referralfee > 0) {
// Transfer the referral fee from lender to referrer.
IERC20(_loanTerms.loanERC20Denomination).safeTransferFrom(_lender, _referrer, referralfee);
}
// Transfer principal from lender to borrower.
IERC20(_loanTerms.loanERC20Denomination).safeTransferFrom(_lender, _borrower, principalAmount);
// Issue an ERC721 promissory note to the lender that gives them the
// right to either the principal-plus-interest or the collateral,
// and an obligation note to the borrower that gives them the
// right to pay back the loan and get the collateral back.
IDirectLoanCoordinator loanCoordinator = IDirectLoanCoordinator(hub.getContract(LOAN_COORDINATOR));
loanId = loanCoordinator.registerLoan(_lender, _loanType);
// Add the loan to storage before moving collateral/principal to follow
// the Checks-Effects-Interactions pattern.
loanIdToLoan[loanId] = _loanTerms;
loanIdToLoanExtras[loanId] = _loanExtras;
return loanId;
}
/**
* @dev Transfers several types of NFTs using a wrapper that knows how to handle each case.
*
* @param _loanTerms - Struct containing all the loan's parameters
* @param _sender - Current owner of the NFT
* @param _recipient - Recipient of the transfer
*/
function _transferNFT(
LoanTerms memory _loanTerms,
address _sender,
address _recipient
) internal {
Address.functionDelegateCall(
_loanTerms.nftCollateralWrapper,
abi.encodeWithSelector(
INftWrapper(_loanTerms.nftCollateralWrapper).transferNFT.selector,
_sender,
_recipient,
_loanTerms.nftCollateralContract,
_loanTerms.nftCollateralId
),
"NFT not successfully transferred"
);
}
/**
* @notice This function is called by a anyone to repay a loan. It can be called at any time after the loan has
* begun and before loan expiry.. The caller will pay a pro-rata portion of their interest if the loan is paid off
* early and the loan is pro-rated type, but the complete repayment amount if it is fixed type.
* The the borrower (current owner of the obligation note) will get the collaterl NFT back.
*
* This function is purposefully not pausable in order to prevent an attack where the contract admin's pause the
* contract and hold hostage the NFT's that are still within it.
*
* @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator.
*/
function _payBackLoan(
uint32 _loanId,
address _borrower,
address _lender,
LoanTerms memory _loan
) internal {
// Fetch loan details from storage, but store them in memory for the sake of saving gas.
LoanExtras memory loanExtras = loanIdToLoanExtras[_loanId];
(uint256 adminFee, uint256 payoffAmount) = _payoffAndFee(_loan);
// Transfer principal-plus-interest-minus-fees from the caller to lender
IERC20(_loan.loanERC20Denomination).safeTransferFrom(msg.sender, _lender, payoffAmount);
uint256 revenueShare = LoanChecksAndCalculations.computeRevenueShare(
adminFee,
loanExtras.revenueShareInBasisPoints
);
// PermittedPartners contract doesn't allow to set a revenueShareInBasisPoints for address zero so revenuShare
// > 0 implies that revenueSharePartner ~= address(0), BUT revenueShare can be zero for a partener when the
// adminFee is low
if (revenueShare > 0 && loanExtras.revenueSharePartner != address(0)) {
adminFee -= revenueShare;
// Transfer revenue share from the caller to permitted partner
IERC20(_loan.loanERC20Denomination).safeTransferFrom(
msg.sender,
loanExtras.revenueSharePartner,
revenueShare
);
}
// Transfer fees from the caller to admins
IERC20(_loan.loanERC20Denomination).safeTransferFrom(msg.sender, owner(), adminFee);
// Emit an event with all relevant details from this transaction.
emit LoanRepaid(
_loanId,
_borrower,
_lender,
_loan.loanPrincipalAmount,
_loan.nftCollateralId,
payoffAmount,
adminFee,
revenueShare,
loanExtras.revenueSharePartner, // this could be a non address zero even if revenueShare is 0
_loan.nftCollateralContract,
_loan.loanERC20Denomination
);
}
/**
* @notice A convenience function with shared functionality between `payBackLoan` and `liquidateOverdueLoan`.
*
* @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator.
* @param _nftReceiver - The receiver of the collateral nft. The borrower when `payBackLoan` or the lender when
* `liquidateOverdueLoan`.
* @param _loanTerms - The main Loan Terms struct. This data is saved upon loan creation on loanIdToLoan.
* @param _loanCoordinator - The loan coordinator used when creating the loan.
*/
function _resolveLoan(
uint32 _loanId,
address _nftReceiver,
LoanTerms memory _loanTerms,
IDirectLoanCoordinator _loanCoordinator
) internal {
_resolveLoanNoNftTransfer(_loanId, _loanTerms, _loanCoordinator);
// Transfer collateral from this contract to the lender, since the lender is seizing collateral for an overdue
// loan
_transferNFT(_loanTerms, address(this), _nftReceiver);
}
/**
* @notice Resolving the loan without trasferring the nft to provide a base for the bundle
* break up of the bundled loans
*
* @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator.
* @param _loanTerms - The main Loan Terms struct. This data is saved upon loan creation on loanIdToLoan.
* @param _loanCoordinator - The loan coordinator used when creating the loan.
*/
function _resolveLoanNoNftTransfer(
uint32 _loanId,
LoanTerms memory _loanTerms,
IDirectLoanCoordinator _loanCoordinator
) internal {
// Mark loan as liquidated before doing any external transfers to follow the Checks-Effects-Interactions design
// pattern
loanRepaidOrLiquidated[_loanId] = true;
_escrowTokens[_loanTerms.nftCollateralContract][_loanTerms.nftCollateralId] -= 1;
// Destroy the lender's promissory note for this loan and borrower obligation receipt
_loanCoordinator.resolveLoan(_loanId);
}
/**
* @notice This function can be called by admins to change the permitted status of an ERC20 currency. This includes
* both adding an ERC20 currency to the permitted list and removing it.
*
* @param _erc20 - The address of the ERC20 currency whose permit list status changed.
* @param _permit - The new status of whether the currency is permitted or not.
*/
function _setERC20Permit(address _erc20, bool _permit) internal {
require(_erc20 != address(0), "erc20 is zero address");
erc20Permits[_erc20] = _permit;
emit ERC20Permit(_erc20, _permit);
}
/**
* @dev Performs some validation checks over loan parameters
*
*/
function _loanSanityChecks(LoanData.Offer memory _offer, address _nftWrapper) internal view {
require(getERC20Permit(_offer.loanERC20Denomination), "Currency denomination is not permitted");
require(_nftWrapper != address(0), "NFT collateral contract is not permitted");
require(uint256(_offer.loanDuration) <= maximumLoanDuration, "Loan duration exceeds maximum loan duration");
require(uint256(_offer.loanDuration) != 0, "Loan duration cannot be zero");
require(
_offer.loanAdminFeeInBasisPoints == adminFeeInBasisPoints,
"The admin fee has changed since this order was signed."
);
}
/**
* @dev reads some variable values of a loan for payback functions, created to reduce code repetition
*/
function _getPartiesAndData(uint32 _loanId)
internal
view
returns (
address borrower,
address lender,
LoanTerms memory loan,
IDirectLoanCoordinator loanCoordinator
)
{
loanCoordinator = IDirectLoanCoordinator(hub.getContract(LOAN_COORDINATOR));
IDirectLoanCoordinator.Loan memory loanCoordinatorData = loanCoordinator.getLoanData(_loanId);
uint256 smartNftId = loanCoordinatorData.smartNftId;
// Fetch loan details from storage, but store them in memory for the sake of saving gas.
loan = loanIdToLoan[_loanId];
if (loan.borrower != address(0)) {
borrower = loan.borrower;
} else {
// Fetch current owner of loan obligation note.
borrower = IERC721(loanCoordinator.obligationReceiptToken()).ownerOf(smartNftId);
}
lender = IERC721(loanCoordinator.promissoryNoteToken()).ownerOf(smartNftId);
}
/**
* @dev Creates a `LoanExtras` struct using data sent as the borrower's extra settings.
* This is needed in order to avoid stack too deep issues.
*/
function _setupLoanExtras(address _revenueSharePartner, uint16 _referralFeeInBasisPoints)
internal
view
returns (LoanExtras memory)
{
// Save loan details to a struct in memory first, to save on gas if any
// of the below checks fail, and to avoid the "Stack Too Deep" error by
// clumping the parameters together into one struct held in memory.
return
LoanExtras({
revenueSharePartner: _revenueSharePartner,
revenueShareInBasisPoints: LoanChecksAndCalculations.getRevenueSharePercent(_revenueSharePartner, hub),
referralFeeInBasisPoints: _referralFeeInBasisPoints
});
}
/**
* @dev Calculates the payoff amount and admin fee
*/
function _payoffAndFee(LoanTerms memory _loanTerms) internal view virtual returns (uint256, uint256);
/**
* @dev Checks that the collateral is a supported contracts and returns what wrapper to use for the loan's NFT
* collateral contract.
*
* @param _nftCollateralContract - The address of the the NFT collateral contract.
*
* @return Address of the NftWrapper to use for the loan's NFT collateral.
*/
function _getWrapper(address _nftCollateralContract) internal view returns (address) {
return IPermittedNFTs(hub.getContract(ContractKeys.PERMITTED_NFTS)).getNFTWrapper(_nftCollateralContract);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
/**
* @title ContractKeys
* @author NFTfi
* @dev Common library for contract keys
*/
library ContractKeys {
bytes32 public constant PERMITTED_ERC20S = bytes32("PERMITTED_ERC20S");
bytes32 public constant PERMITTED_NFTS = bytes32("PERMITTED_NFTS");
bytes32 public constant PERMITTED_PARTNERS = bytes32("PERMITTED_PARTNERS");
bytes32 public constant NFT_TYPE_REGISTRY = bytes32("NFT_TYPE_REGISTRY");
bytes32 public constant LOAN_REGISTRY = bytes32("LOAN_REGISTRY");
bytes32 public constant PERMITTED_SNFT_RECEIVER = bytes32("PERMITTED_SNFT_RECEIVER");
bytes32 public constant PERMITTED_BUNDLE_ERC20S = bytes32("PERMITTED_BUNDLE_ERC20S");
bytes32 public constant PERMITTED_AIRDROPS = bytes32("PERMITTED_AIRDROPS");
bytes32 public constant AIRDROP_RECEIVER = bytes32("AIRDROP_RECEIVER");
bytes32 public constant AIRDROP_FACTORY = bytes32("AIRDROP_FACTORY");
bytes32 public constant AIRDROP_FLASH_LOAN = bytes32("AIRDROP_FLASH_LOAN");
bytes32 public constant NFTFI_BUNDLER = bytes32("NFTFI_BUNDLER");
string public constant AIRDROP_WRAPPER_STRING = "AirdropWrapper";
/**
* @notice Returns the bytes32 representation of a string
* @param _key the string key
* @return id bytes32 representation
*/
function getIdFromStringKey(string memory _key) external pure returns (bytes32 id) {
require(bytes(_key).length <= 32, "invalid key");
// solhint-disable-next-line no-inline-assembly
assembly {
id := mload(add(_key, 32))
}
}
}
// SPDX-License-Identifier: BUSL-1.1
import "./LoanData.sol";
pragma solidity 0.8.4;
interface IDirectLoanBase {
function maximumLoanDuration() external view returns (uint256);
function adminFeeInBasisPoints() external view returns (uint16);
// solhint-disable-next-line func-name-mixedcase
function LOAN_COORDINATOR() external view returns (bytes32);
function loanIdToLoan(uint32)
external
view
returns (
uint256,
uint256,
uint256,
address,
uint32,
uint16,
uint16,
address,
uint64,
address,
address
);
function loanRepaidOrLiquidated(uint32) external view returns (bool);
function getWhetherNonceHasBeenUsedForUser(address _user, uint256 _nonce) external view returns (bool);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
/**
* @title LoanData
* @author NFTfi
* @notice An interface containg the main Loan struct shared by Direct Loans types.
*/
interface LoanData {
/* ********** */
/* DATA TYPES */
/* ********** */
/**
* @notice The main Loan Terms struct. This data is saved upon loan creation.
*
* @param loanERC20Denomination - The address of the ERC20 contract of the currency being used as principal/interest
* for this loan.
* @param loanPrincipalAmount - The original sum of money transferred from lender to borrower at the beginning of
* the loan, measured in loanERC20Denomination's smallest units.
* @param maximumRepaymentAmount - The maximum amount of money that the borrower would be required to retrieve their
* collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have
* to pay this amount to retrieve their collateral, regardless of whether they repay early.
* @param nftCollateralContract - The address of the the NFT collateral contract.
* @param nftCollateralWrapper - The NFTfi wrapper of the NFT collateral contract.
* @param nftCollateralId - The ID within the NFTCollateralContract for the NFT being used as collateral for this
* loan. The NFT is stored within this contract during the duration of the loan.
* @param loanStartTime - The block.timestamp when the loan first began (measured in seconds).
* @param loanDuration - The amount of time (measured in seconds) that can elapse before the lender can liquidate
* the loan and seize the underlying collateral NFT.
* @param loanInterestRateForDurationInBasisPoints - This is the interest rate (measured in basis points, e.g.
* hundreths of a percent) for the loan, that must be repaid pro-rata by the borrower at the conclusion of the loan
* or risk seizure of their nft collateral. Note if the type of the loan is fixed then this value is not used and
* is irrelevant so it should be set to 0.
* @param loanAdminFeeInBasisPoints - The percent (measured in basis points) of the interest earned that will be
* taken as a fee by the contract admins when the loan is repaid. The fee is stored in the loan struct to prevent an
* attack where the contract admins could adjust the fee right before a loan is repaid, and take all of the interest
* earned.
* @param borrower
*/
struct LoanTerms {
uint256 loanPrincipalAmount;
uint256 maximumRepaymentAmount;
uint256 nftCollateralId;
address loanERC20Denomination;
uint32 loanDuration;
uint16 loanInterestRateForDurationInBasisPoints;
uint16 loanAdminFeeInBasisPoints;
address nftCollateralWrapper;
uint64 loanStartTime;
address nftCollateralContract;
address borrower;
}
/**
* @notice Some extra Loan's settings struct. This data is saved upon loan creation.
* We need this to avoid stack too deep errors.
*
* @param revenueSharePartner - The address of the partner that will receive the revenue share.
* @param revenueShareInBasisPoints - The percent (measured in basis points) of the admin fee amount that will be
* taken as a revenue share for a t
* @param referralFeeInBasisPoints - The percent (measured in basis points) of the loan principal amount that will
* be taken as a fee to pay to the referrer, 0 if the lender is not paying referral fee.he partner, at the moment
* the loan is begun.
*/
struct LoanExtras {
address revenueSharePartner;
uint16 revenueShareInBasisPoints;
uint16 referralFeeInBasisPoints;
}
/**
* @notice The offer made by the lender. Used as parameter on both acceptOffer (initiated by the borrower) and
* acceptListing (initiated by the lender).
*
* @param loanERC20Denomination - The address of the ERC20 contract of the currency being used as principal/interest
* for this loan.
* @param loanPrincipalAmount - The original sum of money transferred from lender to borrower at the beginning of
* the loan, measured in loanERC20Denomination's smallest units.
* @param maximumRepaymentAmount - The maximum amount of money that the borrower would be required to retrieve their
* collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always
* have to pay this amount to retrieve their collateral, regardless of whether they repay early.
* @param nftCollateralContract - The address of the ERC721 contract of the NFT collateral.
* @param nftCollateralId - The ID within the NFTCollateralContract for the NFT being used as collateral for this
* loan. The NFT is stored within this contract during the duration of the loan.
* @param referrer - The address of the referrer who found the lender matching the listing, Zero address to signal
* this there is no referrer.
* @param loanDuration - The amount of time (measured in seconds) that can elapse before the lender can liquidate
* the loan and seize the underlying collateral NFT.
* @param loanAdminFeeInBasisPoints - The percent (measured in basis points) of the interest earned that will be
* taken as a fee by the contract admins when the loan is repaid. The fee is stored in the loan struct to prevent an
* attack where the contract admins could adjust the fee right before a loan is repaid, and take all of the interest
* earned.
*/
struct Offer {
uint256 loanPrincipalAmount;
uint256 maximumRepaymentAmount;
uint256 nftCollateralId;
address nftCollateralContract;
uint32 loanDuration;
uint16 loanAdminFeeInBasisPoints;
address loanERC20Denomination;
address referrer;
}
/**
* @notice Signature related params. Used as parameter on both acceptOffer (containing borrower signature) and
* acceptListing (containing lender signature).
*
* @param signer - The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`.
* @param nonce - The nonce referred here is not the same as an Ethereum account's nonce.
* We are referring instead to a nonce that is used by the lender or the borrower when they are first signing
* off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an
* off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the
* lender or the borrower in that situation. This serves two purposes:
* - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once.
* - Second, it allows a user to cancel an off-chain order by calling NFTfi.cancelLoanCommitmentBeforeLoanHasBegun()
* , which marks the nonce as used and prevents any future loan from using the user's off-chain order that contains
* that nonce.
* @param expiry - Date when the signature expires
* @param signature - The ECDSA signature of the borrower or the lender, obtained off-chain ahead of time, signing
* the following combination of parameters:
* - Borrower
* - ListingTerms.loanERC20Denomination,
* - ListingTerms.minLoanPrincipalAmount,
* - ListingTerms.maxLoanPrincipalAmount,
* - ListingTerms.nftCollateralContract,
* - ListingTerms.nftCollateralId,
* - ListingTerms.revenueSharePartner,
* - ListingTerms.minLoanDuration,
* - ListingTerms.maxLoanDuration,
* - ListingTerms.maxInterestRateForDurationInBasisPoints,
* - ListingTerms.referralFeeInBasisPoints,
* - Signature.signer,
* - Signature.nonce,
* - Signature.expiry,
* - address of the loan type contract
* - chainId
* - Lender:
* - Offer.loanERC20Denomination
* - Offer.loanPrincipalAmount
* - Offer.maximumRepaymentAmount
* - Offer.nftCollateralContract
* - Offer.nftCollateralId
* - Offer.referrer
* - Offer.loanDuration
* - Offer.loanAdminFeeInBasisPoints
* - Signature.signer,
* - Signature.nonce,
* - Signature.expiry,
* - address of the loan type contract
* - chainId
*/
struct Signature {
uint256 nonce;
uint256 expiry;
address signer;
bytes signature;
}
/**
* @notice Some extra parameters that the borrower needs to set when accepting an offer.
*
* @param revenueSharePartner - The address of the partner that will receive the revenue share.
* @param referralFeeInBasisPoints - The percent (measured in basis points) of the loan principal amount that will
* be taken as a fee to pay to the referrer, 0 if the lender is not paying referral fee.
*/
struct BorrowerSettings {
address revenueSharePartner;
uint16 referralFeeInBasisPoints;
}
/**
* @notice Terms the borrower set off-chain and is willing to accept automatically when fulfiled by a lender's
* offer.
*
* @param loanERC20Denomination - The address of the ERC20 contract of the currency being used as principal/interest
* for this loan.
* @param minLoanPrincipalAmount - The minumum sum of money transferred from lender to borrower at the beginning of
* the loan, measured in loanERC20Denomination's smallest units.
* @param maxLoanPrincipalAmount - The sum of money transferred from lender to borrower at the beginning of
* the loan, measured in loanERC20Denomination's smallest units.
* @param maximumRepaymentAmount - The maximum amount of money that the borrower would be required to retrieve their
* collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have
* to pay this amount to retrieve their collateral, regardless of whether they repay early.
* @param nftCollateralContract - The address of the ERC721 contract of the NFT collateral.
* @param nftCollateralId - The ID within the NFTCollateralContract for the NFT being used as collateral for this
* loan. The NFT is stored within this contract during the duration of the loan.
* @param revenueSharePartner - The address of the partner that will receive the revenue share.
* @param minLoanDuration - The minumum amount of time (measured in seconds) that can elapse before the lender can
* liquidate the loan and seize the underlying collateral NFT.
* @param maxLoanDuration - The maximum amount of time (measured in seconds) that can elapse before the lender can
* liquidate the loan and seize the underlying collateral NFT.
* @param maxInterestRateForDurationInBasisPoints - This is maximum the interest rate (measured in basis points,
* e.g. hundreths of a percent) for the loan.
* @param referralFeeInBasisPoints - The percent (measured in basis points) of the loan principal amount that will
* be taken as a fee to pay to the referrer, 0 if the lender is not paying referral fee.
*/
struct ListingTerms {
uint256 minLoanPrincipalAmount;
uint256 maxLoanPrincipalAmount;
uint256 nftCollateralId;
address nftCollateralContract;
uint32 minLoanDuration;
uint32 maxLoanDuration;
uint16 maxInterestRateForDurationInBasisPoints;
uint16 referralFeeInBasisPoints;
address revenueSharePartner;
address loanERC20Denomination;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
import "./IDirectLoanBase.sol";
import "./LoanData.sol";
import "../../../interfaces/IDirectLoanCoordinator.sol";
import "../../../utils/ContractKeys.sol";
import "../../../interfaces/INftfiHub.sol";
import "../../../interfaces/IPermittedPartners.sol";
import "../../../interfaces/IPermittedERC20s.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
/**
* @title LoanChecksAndCalculations
* @author NFTfi
* @notice Helper library for LoanBase
*/
library LoanChecksAndCalculations {
uint16 private constant HUNDRED_PERCENT = 10000;
/**
* @dev Function that performs some validation checks before trying to repay a loan
*
* @param _loanId - The id of the loan being repaid
*/
function payBackChecks(uint32 _loanId, INftfiHub _hub) external view {
checkLoanIdValidity(_loanId, _hub);
// Sanity check that payBackLoan() and liquidateOverdueLoan() have never been called on this loanId.
// Depending on how the rest of the code turns out, this check may be unnecessary.
require(!IDirectLoanBase(address(this)).loanRepaidOrLiquidated(_loanId), "Loan already repaid/liquidated");
// Fetch loan details from storage, but store them in memory for the sake of saving gas.
(, , , , uint32 loanDuration, , , , uint64 loanStartTime, , ) = IDirectLoanBase(address(this)).loanIdToLoan(
_loanId
);
// When a loan exceeds the loan term, it is expired. At this stage the Lender can call Liquidate Loan to resolve
// the loan.
require(block.timestamp <= (uint256(loanStartTime) + uint256(loanDuration)), "Loan is expired");
}
function checkLoanIdValidity(uint32 _loanId, INftfiHub _hub) public view {
require(
IDirectLoanCoordinator(_hub.getContract(IDirectLoanBase(address(this)).LOAN_COORDINATOR())).isValidLoanId(
_loanId,
address(this)
),
"invalid loanId"
);
}
/**
* @dev Function that the partner is permitted and returns its shared percent.
*
* @param _revenueSharePartner - Partner's address
*
* @return The revenue share percent for the partner.
*/
function getRevenueSharePercent(address _revenueSharePartner, INftfiHub _hub) external view returns (uint16) {
// return soon if no partner is set to avoid a public call
if (_revenueSharePartner == address(0)) {
return 0;
}
uint16 revenueSharePercent = IPermittedPartners(_hub.getContract(ContractKeys.PERMITTED_PARTNERS))
.getPartnerPermit(_revenueSharePartner);
return revenueSharePercent;
}
/**
* @dev Performs some validation checks before trying to renegotiate a loan.
* Needed to avoid stack too deep.
*
* @param _loan - The main Loan Terms struct.
* @param _loanId - The unique identifier for the loan to be renegotiated
* @param _newLoanDuration - The new amount of time (measured in seconds) that can elapse before the lender can
* liquidate the loan and seize the underlying collateral NFT.
* @param _newMaximumRepaymentAmount - The new maximum amount of money that the borrower would be required to
* retrieve their collateral, measured in the smallest units of the ERC20 currency used for the loan. The
* borrower will always have to pay this amount to retrieve their collateral, regardless of whether they repay
* early.
* @param _lenderNonce - The nonce referred to here is not the same as an Ethereum account's nonce. We are
* referring instead to nonces that are used by both the lender and the borrower when they are first signing
* off-chain NFTfi orders. These nonces can be any uint256 value that the user has not previously used to sign an
* off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the
* lender or the borrower in that situation. This serves two purposes:
* - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once.
* - Second, it allows a user to cancel an off-chain order by calling NFTfi.cancelLoanCommitmentBeforeLoanHasBegun()
, which marks the nonce as used and prevents any future loan from using the user's off-chain order that contains
* that nonce.
* @return Borrower and Lender addresses
*/
function renegotiationChecks(
LoanData.LoanTerms memory _loan,
uint32 _loanId,
uint32 _newLoanDuration,
uint256 _newMaximumRepaymentAmount,
uint256 _lenderNonce,
INftfiHub _hub
) external view returns (address, address) {
checkLoanIdValidity(_loanId, _hub);
IDirectLoanCoordinator loanCoordinator = IDirectLoanCoordinator(
_hub.getContract(IDirectLoanBase(address(this)).LOAN_COORDINATOR())
);
uint256 smartNftId = loanCoordinator.getLoanData(_loanId).smartNftId;
address borrower;
if (_loan.borrower != address(0)) {
borrower = _loan.borrower;
} else {
borrower = IERC721(loanCoordinator.obligationReceiptToken()).ownerOf(smartNftId);
}
require(msg.sender == borrower, "Only borrower can initiate");
require(block.timestamp <= (uint256(_loan.loanStartTime) + _newLoanDuration), "New duration already expired");
require(
uint256(_newLoanDuration) <= IDirectLoanBase(address(this)).maximumLoanDuration(),
"New duration exceeds maximum loan duration"
);
require(!IDirectLoanBase(address(this)).loanRepaidOrLiquidated(_loanId), "Loan already repaid/liquidated");
require(
_newMaximumRepaymentAmount >= _loan.loanPrincipalAmount,
"Negative interest rate loans are not allowed."
);
// Fetch current owner of loan promissory note.
address lender = IERC721(loanCoordinator.promissoryNoteToken()).ownerOf(smartNftId);
require(
!IDirectLoanBase(address(this)).getWhetherNonceHasBeenUsedForUser(lender, _lenderNonce),
"Lender nonce invalid"
);
return (borrower, lender);
}
/**
* @dev Performs some validation checks over loan parameters when accepting a listing
*
*/
function bindingTermsSanityChecks(LoanData.ListingTerms memory _listingTerms, LoanData.Offer memory _offer)
external
pure
{
// offer vs listing validations
require(_offer.loanERC20Denomination == _listingTerms.loanERC20Denomination, "Invalid loanERC20Denomination");
require(
_offer.loanPrincipalAmount >= _listingTerms.minLoanPrincipalAmount &&
_offer.loanPrincipalAmount <= _listingTerms.maxLoanPrincipalAmount,
"Invalid loanPrincipalAmount"
);
uint256 maxRepaymentLimit = _offer.loanPrincipalAmount +
(_offer.loanPrincipalAmount * _listingTerms.maxInterestRateForDurationInBasisPoints) /
HUNDRED_PERCENT;
require(_offer.maximumRepaymentAmount <= maxRepaymentLimit, "maxInterestRateForDurationInBasisPoints violated");
require(
_offer.loanDuration >= _listingTerms.minLoanDuration &&
_offer.loanDuration <= _listingTerms.maxLoanDuration,
"Invalid loanDuration"
);
}
/**
* @notice A convenience function computing the revenue share taken from the admin fee to transferr to the permitted
* partner.
*
* @param _adminFee - The quantity of ERC20 currency (measured in smalled units of that ERC20 currency) that is due
* as an admin fee.
* @param _revenueShareInBasisPoints - The percent (measured in basis points) of the admin fee amount that will be
* taken as a revenue share for a the partner, at the moment the loan is begun.
*
* @return The quantity of ERC20 currency (measured in smalled units of that ERC20 currency) that should be sent to
* the `revenueSharePartner`.
*/
function computeRevenueShare(uint256 _adminFee, uint256 _revenueShareInBasisPoints)
external
pure
returns (uint256)
{
return (_adminFee * _revenueShareInBasisPoints) / HUNDRED_PERCENT;
}
/**
* @notice A convenience function computing the adminFee taken from a specified quantity of interest.
*
* @param _interestDue - The amount of interest due, measured in the smallest quantity of the ERC20 currency being
* used to pay the interest.
* @param _adminFeeInBasisPoints - The percent (measured in basis points) of the interest earned that will be taken
* as a fee by the contract admins when the loan is repaid. The fee is stored in the loan struct to prevent an
* attack where the contract admins could adjust the fee right before a loan is repaid, and take all of the interest
* earned.
*
* @return The quantity of ERC20 currency (measured in smalled units of that ERC20 currency) that is due as an admin
* fee.
*/
function computeAdminFee(uint256 _interestDue, uint256 _adminFeeInBasisPoints) external pure returns (uint256) {
return (_interestDue * _adminFeeInBasisPoints) / HUNDRED_PERCENT;
}
/**
* @notice A convenience function computing the referral fee taken from the loan principal amount to transferr to
* the referrer.
*
* @param _loanPrincipalAmount - The original sum of money transferred from lender to borrower at the beginning of
* the loan, measured in loanERC20Denomination's smallest units.
* @param _referralFeeInBasisPoints - The percent (measured in basis points) of the loan principal amount that will
* be taken as a fee to pay to the referrer, 0 if the lender is not paying referral fee.
* @param _referrer - The address of the referrer who found the lender matching the listing, Zero address to signal
* that there is no referrer.
*
* @return The quantity of ERC20 currency (measured in smalled units of that ERC20 currency) that should be sent to
* the referrer.
*/
function computeReferralFee(
uint256 _loanPrincipalAmount,
uint256 _referralFeeInBasisPoints,
address _referrer
) external pure returns (uint256) {
if (_referralFeeInBasisPoints == 0 || _referrer == address(0)) {
return 0;
}
return (_loanPrincipalAmount * _referralFeeInBasisPoints) / HUNDRED_PERCENT;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
import "./IDirectLoanBase.sol";
import "./LoanData.sol";
import "../../../interfaces/IDirectLoanCoordinator.sol";
import "../../../utils/ContractKeys.sol";
import "../../../interfaces/INftfiHub.sol";
import "../../../interfaces/IPermittedPartners.sol";
import "../../../interfaces/IPermittedERC20s.sol";
import "../../../interfaces/IAirdropFlashLoan.sol";
import "../../../interfaces/INftWrapper.sol";
import "../../../airdrop/IAirdropReceiverFactory.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/utils/Address.sol";
/**
* @title LoanAirdropUtils
* @author NFTfi
* @notice Helper library for LoanBase
*/
library LoanAirdropUtils {
/**
* @notice This event is fired whenever a flashloan is initiated to pull an airdrop
*
* @param loanId - A unique identifier for this particular loan, sourced from the Loan Coordinator.
* @param borrower - The address of the borrower.
* @param nftCollateralId - The ID within the AirdropReceiver for the NFT being used as collateral for this
* loan.
* @param nftCollateralContract - The ERC721 contract of the NFT collateral
* @param target - address of the airdropping contract
* @param data - function selector to be called
*/
event AirdropPulledFlashloan(
uint256 indexed loanId,
address indexed borrower,
uint256 nftCollateralId,
address nftCollateralContract,
address target,
bytes data
);
/**
* @notice This event is fired whenever the collateral gets wrapped in an airdrop receiver
*
* @param loanId - A unique identifier for this particular loan, sourced from the Loan Coordinator.
* @param borrower - The address of the borrower.
* @param nftCollateralId - The ID within the AirdropReceiver for the NFT being used as collateral for this
* loan.
* @param nftCollateralContract - The contract of the NFT collateral
* @param receiverId - id of the created AirdropReceiver, takes the place of nftCollateralId on the loan
* @param receiverInstance - address of the created AirdropReceiver
*/
event CollateralWrapped(
uint256 indexed loanId,
address indexed borrower,
uint256 nftCollateralId,
address nftCollateralContract,
uint256 receiverId,
address receiverInstance
);
function pullAirdrop(
uint32 _loanId,
LoanData.LoanTerms memory _loan,
address _target,
bytes calldata _data,
address _nftAirdrop,
uint256 _nftAirdropId,
bool _is1155,
uint256 _nftAirdropAmount,
INftfiHub _hub
) external {
IDirectLoanCoordinator loanCoordinator = IDirectLoanCoordinator(
_hub.getContract(IDirectLoanBase(address(this)).LOAN_COORDINATOR())
);
address borrower;
// scoped to aviod stack too deep
{
IDirectLoanCoordinator.Loan memory loanCoordinatorData = loanCoordinator.getLoanData(_loanId);
uint256 smartNftId = loanCoordinatorData.smartNftId;
if (_loan.borrower != address(0)) {
borrower = _loan.borrower;
} else {
borrower = IERC721(loanCoordinator.obligationReceiptToken()).ownerOf(smartNftId);
}
}
require(msg.sender == borrower, "Only borrower can airdrop");
{
IAirdropFlashLoan airdropFlashLoan = IAirdropFlashLoan(_hub.getContract(ContractKeys.AIRDROP_FLASH_LOAN));
_transferNFT(_loan, address(this), address(airdropFlashLoan));
airdropFlashLoan.pullAirdrop(
_loan.nftCollateralContract,
_loan.nftCollateralId,
_loan.nftCollateralWrapper,
_target,
_data,
_nftAirdrop,
_nftAirdropId,
_is1155,
_nftAirdropAmount,
borrower
);
}
// revert if the collateral hasn't been transferred back before it ends
require(
INftWrapper(_loan.nftCollateralWrapper).isOwner(
address(this),
_loan.nftCollateralContract,
_loan.nftCollateralId
),
"Collateral should be returned"
);
emit AirdropPulledFlashloan(
_loanId,
borrower,
_loan.nftCollateralId,
_loan.nftCollateralContract,
_target,
_data
);
}
function wrapCollateral(
uint32 _loanId,
LoanData.LoanTerms storage _loan,
INftfiHub _hub
) external returns (address instance, uint256 receiverId) {
IDirectLoanCoordinator loanCoordinator = IDirectLoanCoordinator(
_hub.getContract(IDirectLoanBase(address(this)).LOAN_COORDINATOR())
);
// Fetch the current lender of the promissory note corresponding to this overdue loan.
IDirectLoanCoordinator.Loan memory loanCoordinatorData = loanCoordinator.getLoanData(_loanId);
uint256 smartNftId = loanCoordinatorData.smartNftId;
address borrower;
if (_loan.borrower != address(0)) {
borrower = _loan.borrower;
} else {
borrower = IERC721(loanCoordinator.obligationReceiptToken()).ownerOf(smartNftId);
}
require(msg.sender == borrower, "Only borrower can wrapp");
IAirdropReceiverFactory factory = IAirdropReceiverFactory(_hub.getContract(ContractKeys.AIRDROP_FACTORY));
(instance, receiverId) = factory.createAirdropReceiver(address(this));
// transfer collateral to airdrop receiver wrapper
_transferNFTtoAirdropReceiver(_loan, instance, borrower);
emit CollateralWrapped(
_loanId,
borrower,
_loan.nftCollateralId,
_loan.nftCollateralContract,
receiverId,
instance
);
// set the receiver as the new collateral
_loan.nftCollateralContract = instance;
_loan.nftCollateralId = receiverId;
}
/**
* @dev Transfers several types of NFTs using a wrapper that knows how to handle each case.
*
* @param _loan -
* @param _sender - Current owner of the NFT
* @param _recipient - Recipient of the transfer
*/
function _transferNFT(
LoanData.LoanTerms memory _loan,
address _sender,
address _recipient
) internal {
Address.functionDelegateCall(
_loan.nftCollateralWrapper,
abi.encodeWithSelector(
INftWrapper(_loan.nftCollateralWrapper).transferNFT.selector,
_sender,
_recipient,
_loan.nftCollateralContract,
_loan.nftCollateralId
),
"NFT not successfully transferred"
);
}
/**
* @dev Transfers several types of NFTs to an airdrop receiver with an airdrop beneficiary
* address attached as supplementing data using a wrapper that knows how to handle each case.
*
* @param _loan -
* @param _airdropReceiverInstance - Recipient of the transfer
* @param _airdropBeneficiary - Beneficiary of the future airdops
*/
function _transferNFTtoAirdropReceiver(
LoanData.LoanTerms memory _loan,
address _airdropReceiverInstance,
address _airdropBeneficiary
) internal {
Address.functionDelegateCall(
_loan.nftCollateralWrapper,
abi.encodeWithSelector(
INftWrapper(_loan.nftCollateralWrapper).wrapAirdropReceiver.selector,
_airdropReceiverInstance,
_loan.nftCollateralContract,
_loan.nftCollateralId,
_airdropBeneficiary
),
"NFT was not successfully migrated"
);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
import "../utils/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
/**
* @title BaseLoan
* @author NFTfi
* @dev Implements base functionalities common to all Loan types.
* Mostly related to governance and security.
*/
abstract contract BaseLoan is Ownable, Pausable, ReentrancyGuard {
/* *********** */
/* CONSTRUCTOR */
/* *********** */
/**
* @notice Sets the admin of the contract.
*
* @param _admin - Initial admin of this contract.
*/
constructor(address _admin) Ownable(_admin) {
// solhint-disable-previous-line no-empty-blocks
}
/* ********* */
/* FUNCTIONS */
/* ********* */
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - Only the owner can call this method.
* - The contract must not be paused.
*/
function pause() external onlyOwner {
_pause();
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - Only the owner can call this method.
* - The contract must be paused.
*/
function unpause() external onlyOwner {
_unpause();
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
/**
* @title NftReceiver
* @author NFTfi
* @dev Base contract with capabilities for receiving ERC1155 and ERC721 tokens
*/
abstract contract NftReceiver is IERC1155Receiver, ERC721Holder {
/**
* @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a
* `safeTransferFrom` after the balance has been updated.
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if allowed
*/
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes calldata
) external virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
/**
* @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a
* `safeBatchTransferFrom` after the balances have been updated.
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if allowed
*/
function onERC1155BatchReceived(
address,
address,
uint256[] calldata,
uint256[] calldata,
bytes calldata
) external virtual override returns (bytes4) {
revert("ERC1155 batch not supported");
}
/**
* @dev Checks whether this contract implements the interface defined by `interfaceId`.
* @param _interfaceId Id of the interface
* @return true if this contract implements the interface
*/
function supportsInterface(bytes4 _interfaceId) public view virtual override returns (bool) {
return
_interfaceId == type(IERC1155Receiver).interfaceId ||
_interfaceId == type(IERC721Receiver).interfaceId ||
_interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
import "../interfaces/IBundleBuilder.sol";
import "../loans/direct/loanTypes/LoanData.sol";
import "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
/**
* @title NFTfiSigningUtils
* @author NFTfi
* @notice Helper contract for NFTfi. This contract manages verifying signatures from off-chain NFTfi orders.
* Based on the version of this same contract used on NFTfi V1
*/
library NFTfiSigningUtils {
/* ********* */
/* FUNCTIONS */
/* ********* */
/**
* @dev This function gets the current chain ID.
*/
function getChainID() public view returns (uint256) {
uint256 id;
// solhint-disable-next-line no-inline-assembly
assembly {
id := chainid()
}
return id;
}
/**
* @notice This function is when the lender accepts a borrower's binding listing terms, to validate the lender's
* signature that the borrower provided off-chain to verify that it did indeed made such listing.
*
* @param _listingTerms - The listing terms struct containing:
* - loanERC20Denomination: The address of the ERC20 contract of the currency being used as principal/interest
* for this loan.
* - minLoanPrincipalAmount: The minumum sum of money transferred from lender to borrower at the beginning of
* the loan, measured in loanERC20Denomination's smallest units.
* - maxLoanPrincipalAmount: The sum of money transferred from lender to borrower at the beginning of
* the loan, measured in loanERC20Denomination's smallest units.
* - maximumRepaymentAmount: The maximum amount of money that the borrower would be required to retrieve their
* collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have
* to pay this amount to retrieve their collateral, regardless of whether they repay early.
* - nftCollateralContract: The address of the ERC721 contract of the NFT collateral.
* - nftCollateralId: The ID within the NFTCollateralContract for the NFT being used as collateral for this
* loan. The NFT is stored within this contract during the duration of the loan.
* - revenueSharePartner: The address of the partner that will receive the revenue share.
* - minLoanDuration: The minumum amount of time (measured in seconds) that can elapse before the lender can
* liquidate the loan and seize the underlying collateral NFT.
* - maxLoanDuration: The maximum amount of time (measured in seconds) that can elapse before the lender can
* liquidate the loan and seize the underlying collateral NFT.
* - maxInterestRateForDurationInBasisPoints: This is maximum the interest rate (measured in basis points, e.g.
* hundreths of a percent) for the loan, that must be repaid pro-rata by the borrower at the conclusion of the loan
* or risk seizure of their nft collateral. Note if the type of the loan is fixed then this value is not used and
* is irrelevant so it should be set to 0.
* - referralFeeInBasisPoints: The percent (measured in basis points) of the loan principal amount that will be
* taken as a fee to pay to the referrer, 0 if the lender is not paying referral fee.
* @param _signature - The offer struct containing:
* - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`.
* - nonce: The nonce referred here is not the same as an Ethereum account's nonce.
* We are referring instead to a nonce that is used by the lender or the borrower when they are first signing
* off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an
* off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the
* lender or the borrower in that situation. This serves two purposes:
* - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once.
* - Second, it allows a user to cancel an off-chain order by calling
* NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from
* using the user's off-chain order that contains that nonce.
* - expiry: Date when the signature expires
* - signature: The ECDSA signature of the borrower, obtained off-chain ahead of time, signing the following
* combination of parameters:
* - listingTerms.loanERC20Denomination,
* - listingTerms.minLoanPrincipalAmount,
* - listingTerms.maxLoanPrincipalAmount,
* - listingTerms.nftCollateralContract,
* - listingTerms.nftCollateralId,
* - listingTerms.revenueSharePartner,
* - listingTerms.minLoanDuration,
* - listingTerms.maxLoanDuration,
* - listingTerms.maxInterestRateForDurationInBasisPoints,
* - listingTerms.referralFeeInBasisPoints,
* - signature.signer,
* - signature.nonce,
* - signature.expiry,
* - address of this contract
* - chainId
*/
function isValidBorrowerSignature(LoanData.ListingTerms memory _listingTerms, LoanData.Signature memory _signature)
external
view
returns (bool)
{
return isValidBorrowerSignature(_listingTerms, _signature, address(this));
}
/**
* @dev This function overload the previous function to allow the caller to specify the address of the contract
*
*/
function isValidBorrowerSignature(
LoanData.ListingTerms memory _listingTerms,
LoanData.Signature memory _signature,
address _loanContract
) public view returns (bool) {
require(block.timestamp <= _signature.expiry, "Borrower Signature has expired");
require(_loanContract != address(0), "Loan is zero address");
if (_signature.signer == address(0)) {
return false;
} else {
bytes32 message = keccak256(
abi.encodePacked(
getEncodedListing(_listingTerms),
getEncodedSignature(_signature),
_loanContract,
getChainID()
)
);
return
SignatureChecker.isValidSignatureNow(
_signature.signer,
ECDSA.toEthSignedMessageHash(message),
_signature.signature
);
}
}
/**
* @notice This function is when the lender accepts a borrower's binding listing terms, to validate the lender's
* signature that the borrower provided off-chain to verify that it did indeed made such listing.
*
* @param _listingTerms - The listing terms struct containing:
* - loanERC20Denomination: The address of the ERC20 contract of the currency being used as principal/interest
* for this loan.
* - minLoanPrincipalAmount: The minumum sum of money transferred from lender to borrower at the beginning of
* the loan, measured in loanERC20Denomination's smallest units.
* - maxLoanPrincipalAmount: The sum of money transferred from lender to borrower at the beginning of
* the loan, measured in loanERC20Denomination's smallest units.
* - maximumRepaymentAmount: The maximum amount of money that the borrower would be required to retrieve their
* collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have
* to pay this amount to retrieve their collateral, regardless of whether they repay early.
* - nftCollateralContract: The address of the ERC721 contract of the NFT collateral.
* - nftCollateralId: The ID within the NFTCollateralContract for the NFT being used as collateral for this
* loan. The NFT is stored within this contract during the duration of the loan.
* - revenueSharePartner: The address of the partner that will receive the revenue share.
* - minLoanDuration: The minumum amount of time (measured in seconds) that can elapse before the lender can
* liquidate the loan and seize the underlying collateral NFT.
* - maxLoanDuration: The maximum amount of time (measured in seconds) that can elapse before the lender can
* liquidate the loan and seize the underlying collateral NFT.
* - maxInterestRateForDurationInBasisPoints: This is maximum the interest rate (measured in basis points, e.g.
* hundreths of a percent) for the loan, that must be repaid pro-rata by the borrower at the conclusion of the loan
* or risk seizure of their nft collateral. Note if the type of the loan is fixed then this value is not used and
* is irrelevant so it should be set to 0.
* - referralFeeInBasisPoints: The percent (measured in basis points) of the loan principal amount that will be
* taken as a fee to pay to the referrer, 0 if the lender is not paying referral fee.
* @param _bundleElements - the lists of erc721-20-1155 tokens that are to be bundled
* @param _signature - The offer struct containing:
* - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`.
* - nonce: The nonce referred here is not the same as an Ethereum account's nonce.
* We are referring instead to a nonce that is used by the lender or the borrower when they are first signing
* off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an
* off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the
* lender or the borrower in that situation. This serves two purposes:
* - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once.
* - Second, it allows a user to cancel an off-chain order by calling
* NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from
* using the user's off-chain order that contains that nonce.
* - expiry: Date when the signature expires
* - signature: The ECDSA signature of the borrower, obtained off-chain ahead of time, signing the following
* combination of parameters:
* - listingTerms.loanERC20Denomination,
* - listingTerms.minLoanPrincipalAmount,
* - listingTerms.maxLoanPrincipalAmount,
* - listingTerms.nftCollateralContract,
* - listingTerms.nftCollateralId,
* - listingTerms.revenueSharePartner,
* - listingTerms.minLoanDuration,
* - listingTerms.maxLoanDuration,
* - listingTerms.maxInterestRateForDurationInBasisPoints,
* - listingTerms.referralFeeInBasisPoints,
* - bundleElements
* - signature.signer,
* - signature.nonce,
* - signature.expiry,
* - address of this contract
* - chainId
*/
function isValidBorrowerSignatureBundle(
LoanData.ListingTerms memory _listingTerms,
IBundleBuilder.BundleElements memory _bundleElements,
LoanData.Signature memory _signature
) external view returns (bool) {
return isValidBorrowerSignatureBundle(_listingTerms, _bundleElements, _signature, address(this));
}
/**
* @dev This function overload the previous function to allow the caller to specify the address of the contract
*
*/
function isValidBorrowerSignatureBundle(
LoanData.ListingTerms memory _listingTerms,
IBundleBuilder.BundleElements memory _bundleElements,
LoanData.Signature memory _signature,
address _loanContract
) public view returns (bool) {
require(block.timestamp <= _signature.expiry, "Borrower Signature has expired");
require(_loanContract != address(0), "Loan is zero address");
if (_signature.signer == address(0)) {
return false;
} else {
bytes32 message = keccak256(
abi.encodePacked(
getEncodedListing(_listingTerms),
abi.encode(_bundleElements),
getEncodedSignature(_signature),
_loanContract,
getChainID()
)
);
return
SignatureChecker.isValidSignatureNow(
_signature.signer,
ECDSA.toEthSignedMessageHash(message),
_signature.signature
);
}
}
/**
* @notice This function is when the borrower accepts a lender's offer, to validate the lender's signature that the
* lender provided off-chain to verify that it did indeed made such offer.
*
* @param _offer - The offer struct containing:
* - loanERC20Denomination: The address of the ERC20 contract of the currency being used as principal/interest
* for this loan.
* - loanPrincipalAmount: The original sum of money transferred from lender to borrower at the beginning of
* the loan, measured in loanERC20Denomination's smallest units.
* - maximumRepaymentAmount: The maximum amount of money that the borrower would be required to retrieve their
* collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have
* to pay this amount to retrieve their collateral, regardless of whether they repay early.
* - nftCollateralContract: The address of the ERC721 contract of the NFT collateral.
* - nftCollateralId: The ID within the NFTCollateralContract for the NFT being used as collateral for this
* loan. The NFT is stored within this contract during the duration of the loan.
* - referrer: The address of the referrer who found the lender matching the listing, Zero address to signal
* this there is no referrer.
* - loanDuration: The amount of time (measured in seconds) that can elapse before the lender can liquidate the
* loan and seize the underlying collateral NFT.
* - loanInterestRateForDurationInBasisPoints: This is the interest rate (measured in basis points, e.g.
* hundreths of a percent) for the loan, that must be repaid pro-rata by the borrower at the conclusion of the loan
* or risk seizure of their nft collateral. Note if the type of the loan is fixed then this value is not used and
* is irrelevant so it should be set to 0.
* - loanAdminFeeInBasisPoints: The percent (measured in basis points) of the interest earned that will be
* taken as a fee by the contract admins when the loan is repaid. The fee is stored in the loan struct to prevent an
* attack where the contract admins could adjust the fee right before a loan is repaid, and take all of the interest
* earned.
* @param _signature - The signature structure containing:
* - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`.
* - nonce: The nonce referred here is not the same as an Ethereum account's nonce.
* We are referring instead to a nonce that is used by the lender or the borrower when they are first signing
* off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an
* off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the
* lender or the borrower in that situation. This serves two purposes:
* - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once.
* - Second, it allows a user to cancel an off-chain order by calling
* NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from
* using the user's off-chain order that contains that nonce.
* - expiry: Date when the signature expires
* - signature: The ECDSA signature of the lender, obtained off-chain ahead of time, signing the following
* combination of parameters:
* - offer.loanERC20Denomination
* - offer.loanPrincipalAmount
* - offer.maximumRepaymentAmount
* - offer.nftCollateralContract
* - offer.nftCollateralId
* - offer.referrer
* - offer.loanDuration
* - offer.loanAdminFeeInBasisPoints
* - signature.signer,
* - signature.nonce,
* - signature.expiry,
* - address of this contract
* - chainId
*/
function isValidLenderSignature(LoanData.Offer memory _offer, LoanData.Signature memory _signature)
external
view
returns (bool)
{
return isValidLenderSignature(_offer, _signature, address(this));
}
/**
* @dev This function overload the previous function to allow the caller to specify the address of the contract
*
*/
function isValidLenderSignature(
LoanData.Offer memory _offer,
LoanData.Signature memory _signature,
address _loanContract
) public view returns (bool) {
require(block.timestamp <= _signature.expiry, "Lender Signature has expired");
require(_loanContract != address(0), "Loan is zero address");
if (_signature.signer == address(0)) {
return false;
} else {
bytes32 message = keccak256(
abi.encodePacked(getEncodedOffer(_offer), getEncodedSignature(_signature), _loanContract, getChainID())
);
return
SignatureChecker.isValidSignatureNow(
_signature.signer,
ECDSA.toEthSignedMessageHash(message),
_signature.signature
);
}
}
/**
* @notice This function is when the borrower accepts a lender's offer, to validate the lender's signature that the
* lender provided off-chain to verify that it did indeed made such offer.
*
* @param _offer - The offer struct containing:
* - loanERC20Denomination: The address of the ERC20 contract of the currency being used as principal/interest
* for this loan.
* - loanPrincipalAmount: The original sum of money transferred from lender to borrower at the beginning of
* the loan, measured in loanERC20Denomination's smallest units.
* - maximumRepaymentAmount: The maximum amount of money that the borrower would be required to retrieve their
* collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have
* to pay this amount to retrieve their collateral, regardless of whether they repay early.
* - nftCollateralContract: The address of the ERC721 contract of the NFT collateral.
* - nftCollateralId: The ID within the NFTCollateralContract for the NFT being used as collateral for this
* loan. The NFT is stored within this contract during the duration of the loan.
* - referrer: The address of the referrer who found the lender matching the listing, Zero address to signal
* this there is no referrer.
* - loanDuration: The amount of time (measured in seconds) that can elapse before the lender can liquidate the
* loan and seize the underlying collateral NFT.
* - loanInterestRateForDurationInBasisPoints: This is the interest rate (measured in basis points, e.g.
* hundreths of a percent) for the loan, that must be repaid pro-rata by the borrower at the conclusion of the loan
* or risk seizure of their nft collateral. Note if the type of the loan is fixed then this value is not used and
* is irrelevant so it should be set to 0.
* - loanAdminFeeInBasisPoints: The percent (measured in basis points) of the interest earned that will be
* taken as a fee by the contract admins when the loan is repaid. The fee is stored in the loan struct to prevent an
* attack where the contract admins could adjust the fee right before a loan is repaid, and take all of the interest
* earned.
* @param _bundleElements - the lists of erc721-20-1155 tokens that are to be bundled
* @param _signature - The signature structure containing:
* - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`.
* - nonce: The nonce referred here is not the same as an Ethereum account's nonce.
* We are referring instead to a nonce that is used by the lender or the borrower when they are first signing
* off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an
* off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the
* lender or the borrower in that situation. This serves two purposes:
* - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once.
* - Second, it allows a user to cancel an off-chain order by calling
* NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from
* using the user's off-chain order that contains that nonce.
* - expiry: Date when the signature expires
* - signature: The ECDSA signature of the lender, obtained off-chain ahead of time, signing the following
* combination of parameters:
* - offer.loanERC20Denomination
* - offer.loanPrincipalAmount
* - offer.maximumRepaymentAmount
* - offer.nftCollateralContract
* - offer.nftCollateralId
* - offer.referrer
* - offer.loanDuration
* - offer.loanAdminFeeInBasisPoints
* - bundleElements
* - signature.signer,
* - signature.nonce,
* - signature.expiry,
* - address of this contract
* - chainId
*/
function isValidLenderSignatureBundle(
LoanData.Offer memory _offer,
IBundleBuilder.BundleElements memory _bundleElements,
LoanData.Signature memory _signature
) external view returns (bool) {
return isValidLenderSignatureBundle(_offer, _bundleElements, _signature, address(this));
}
/**
* @dev This function overload the previous function to allow the caller to specify the address of the contract
*
*/
function isValidLenderSignatureBundle(
LoanData.Offer memory _offer,
IBundleBuilder.BundleElements memory _bundleElements,
LoanData.Signature memory _signature,
address _loanContract
) public view returns (bool) {
require(block.timestamp <= _signature.expiry, "Lender Signature has expired");
require(_loanContract != address(0), "Loan is zero address");
if (_signature.signer == address(0)) {
return false;
} else {
bytes32 message = keccak256(
abi.encodePacked(
getEncodedOffer(_offer),
abi.encode(_bundleElements),
getEncodedSignature(_signature),
_loanContract,
getChainID()
)
);
return
SignatureChecker.isValidSignatureNow(
_signature.signer,
ECDSA.toEthSignedMessageHash(message),
_signature.signature
);
}
}
/**
* @notice This function is called in renegotiateLoan() to validate the lender's signature that the lender provided
* off-chain to verify that they did indeed want to agree to this loan renegotiation according to these terms.
*
* @param _loanId - The unique identifier for the loan to be renegotiated
* @param _newLoanDuration - The new amount of time (measured in seconds) that can elapse before the lender can
* liquidate the loan and seize the underlying collateral NFT.
* @param _newMaximumRepaymentAmount - The new maximum amount of money that the borrower would be required to
* retrieve their collateral, measured in the smallest units of the ERC20 currency used for the loan. The
* borrower will always have to pay this amount to retrieve their collateral, regardless of whether they repay
* early.
* @param _renegotiationFee Agreed upon fee in ether that borrower pays for the lender for the renegitiation
* @param _signature - The signature structure containing:
* - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`.
* - nonce: The nonce referred here is not the same as an Ethereum account's nonce.
* We are referring instead to a nonce that is used by the lender or the borrower when they are first signing
* off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an
* off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the
* lender or the borrower in that situation. This serves two purposes:
* - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once.
* - Second, it allows a user to cancel an off-chain order by calling NFTfi.cancelLoanCommitmentBeforeLoanHasBegun()
* , which marks the nonce as used and prevents any future loan from using the user's off-chain order that contains
* that nonce.
* - expiry - The date when the renegotiation offer expires
* - lenderSignature - The ECDSA signature of the lender, obtained off-chain ahead of time, signing the
* following combination of parameters:
* - _loanId
* - _newLoanDuration
* - _newMaximumRepaymentAmount
* - _lender
* - _lenderNonce
* - _expiry
* - address of this contract
* - chainId
*/
function isValidLenderRenegotiationSignature(
uint256 _loanId,
uint32 _newLoanDuration,
uint256 _newMaximumRepaymentAmount,
uint256 _renegotiationFee,
LoanData.Signature memory _signature
) external view returns (bool) {
return
isValidLenderRenegotiationSignature(
_loanId,
_newLoanDuration,
_newMaximumRepaymentAmount,
_renegotiationFee,
_signature,
address(this)
);
}
/**
* @dev This function overload the previous function to allow the caller to specify the address of the contract
*
*/
function isValidLenderRenegotiationSignature(
uint256 _loanId,
uint32 _newLoanDuration,
uint256 _newMaximumRepaymentAmount,
uint256 _renegotiationFee,
LoanData.Signature memory _signature,
address _loanContract
) public view returns (bool) {
require(block.timestamp <= _signature.expiry, "Renegotiation Signature has expired");
require(_loanContract != address(0), "Loan is zero address");
if (_signature.signer == address(0)) {
return false;
} else {
bytes32 message = keccak256(
abi.encodePacked(
_loanId,
_newLoanDuration,
_newMaximumRepaymentAmount,
_renegotiationFee,
getEncodedSignature(_signature),
_loanContract,
getChainID()
)
);
return
SignatureChecker.isValidSignatureNow(
_signature.signer,
ECDSA.toEthSignedMessageHash(message),
_signature.signature
);
}
}
/**
* @dev We need this to avoid stack too deep errors.
*/
function getEncodedListing(LoanData.ListingTerms memory _listingTerms) internal pure returns (bytes memory) {
return
abi.encodePacked(
_listingTerms.loanERC20Denomination,
_listingTerms.minLoanPrincipalAmount,
_listingTerms.maxLoanPrincipalAmount,
_listingTerms.nftCollateralContract,
_listingTerms.nftCollateralId,
_listingTerms.revenueSharePartner,
_listingTerms.minLoanDuration,
_listingTerms.maxLoanDuration,
_listingTerms.maxInterestRateForDurationInBasisPoints,
_listingTerms.referralFeeInBasisPoints
);
}
/**
* @dev We need this to avoid stack too deep errors.
*/
function getEncodedOffer(LoanData.Offer memory _offer) internal pure returns (bytes memory) {
return
abi.encodePacked(
_offer.loanERC20Denomination,
_offer.loanPrincipalAmount,
_offer.maximumRepaymentAmount,
_offer.nftCollateralContract,
_offer.nftCollateralId,
_offer.referrer,
_offer.loanDuration,
_offer.loanAdminFeeInBasisPoints
);
}
/**
* @dev We need this to avoid stack too deep errors.
*/
function getEncodedSignature(LoanData.Signature memory _signature) internal pure returns (bytes memory) {
return abi.encodePacked(_signature.signer, _signature.nonce, _signature.expiry);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
/**
* @title INftfiHub
* @author NFTfi
* @dev NftfiHub interface
*/
interface INftfiHub {
function setContract(string calldata _contractKey, address _contractAddress) external;
function getContract(bytes32 _contractKey) external view returns (address);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
/**
* @title IDirectLoanCoordinator
* @author NFTfi
* @dev DirectLoanCoordinator interface.
*/
interface IDirectLoanCoordinator {
enum StatusType {
NOT_EXISTS,
NEW,
RESOLVED
}
/**
* @notice This struct contains data related to a loan
*
* @param smartNftId - The id of both the promissory note and obligation receipt.
* @param status - The status in which the loan currently is.
* @param loanContract - Address of the LoanType contract that created the loan.
*/
struct Loan {
address loanContract;
uint64 smartNftId;
StatusType status;
}
function registerLoan(address _lender, bytes32 _loanType) external returns (uint32);
function mintObligationReceipt(uint32 _loanId, address _borrower) external;
function resolveLoan(uint32 _loanId) external;
function promissoryNoteToken() external view returns (address);
function obligationReceiptToken() external view returns (address);
function getLoanData(uint32 _loanId) external view returns (Loan memory);
function isValidLoanId(uint32 _loanId, address _loanContract) external view returns (bool);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
/**
* @title INftTypeRegistry
* @author NFTfi
* @dev Interface for NFT Wrappers.
*/
interface INftWrapper {
function transferNFT(
address from,
address to,
address nftContract,
uint256 tokenId
) external returns (bool);
function isOwner(
address owner,
address nftContract,
uint256 tokenId
) external view returns (bool);
function wrapAirdropReceiver(
address _recipient,
address _nftContract,
uint256 _nftId,
address _beneficiary
) external returns (bool);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
interface IPermittedPartners {
function getPartnerPermit(address _partner) external view returns (uint16);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
interface IPermittedERC20s {
function getERC20Permit(address _erc20) external view returns (bool);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
interface IPermittedNFTs {
function setNFTPermit(address _nftContract, string memory _nftType) external;
function getNFTPermit(address _nftContract) external view returns (bytes32);
function getNFTWrapper(address _nftContract) external view returns (address);
}
// 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 (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
interface IAirdropFlashLoan {
function pullAirdrop(
address _nftCollateralContract,
uint256 _nftCollateralId,
address _nftWrapper,
address _target,
bytes calldata _data,
address _nftAirdrop,
uint256 _nftAirdropId,
bool _is1155,
uint256 _nftAirdropAmount,
address _beneficiary
) external;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
/**
* @title IAirdropReceiver
* @author NFTfi
* @dev
*/
interface IAirdropReceiverFactory {
function createAirdropReceiver(address _to) external returns (address, uint256);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
import "@openzeppelin/contracts/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.
*
* Modified version from openzeppelin/contracts/access/Ownable.sol that allows to
* initialize the owner using a parameter in the constructor
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor(address _initialOwner) {
_setOwner(_initialOwner);
}
/**
* @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);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Sets the owner.
*/
function _setOwner(address _newOwner) private {
address oldOwner = _owner;
_owner = _newOwner;
emit OwnershipTransferred(oldOwner, _newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
* @dev Handles the receipt of a single ERC1155 token type. This function is
* called at the end of a `safeTransferFrom` after the balance has been updated.
*
* NOTE: To accept the transfer, this must return
* `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* (i.e. 0xf23a6e61, or its own function selector).
*
* @param operator The address which initiated the transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param id The ID of the token being transferred
* @param value The amount of tokens being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
* @dev Handles the receipt of a multiple ERC1155 token types. This function
* is called at the end of a `safeBatchTransferFrom` after the balances have
* been updated.
*
* NOTE: To accept the transfer(s), this must return
* `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* (i.e. 0xbc197c81, or its own function selector).
*
* @param operator The address which initiated the batch transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param ids An array containing ids of each token being transferred (order and length must match values array)
* @param values An array containing amounts of each token being transferred (order and length must match ids array)
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/utils/ERC721Holder.sol)
pragma solidity ^0.8.0;
import "../IERC721Receiver.sol";
/**
* @dev Implementation of the {IERC721Receiver} interface.
*
* Accepts all token transfers.
* Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.
*/
contract ERC721Holder is IERC721Receiver {
/**
* @dev See {IERC721Receiver-onERC721Received}.
*
* Always returns `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address,
address,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
}
// SPDX-License-Identifier: MIT
// 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: BUSL-1.1
pragma solidity 0.8.4;
interface IBundleBuilder {
/**
* @notice data of a erc721 bundle element
*
* @param tokenContract - address of the token contract
* @param id - id of the token
* @param safeTransferable - wether the implementing token contract has a safeTransfer function or not
*/
struct BundleElementERC721 {
address tokenContract;
uint256 id;
bool safeTransferable;
}
/**
* @notice data of a erc20 bundle element
*
* @param tokenContract - address of the token contract
* @param amount - amount of the token
*/
struct BundleElementERC20 {
address tokenContract;
uint256 amount;
}
/**
* @notice data of a erc20 bundle element
*
* @param tokenContract - address of the token contract
* @param ids - list of ids of the tokens
* @param amounts - list amounts of the tokens
*/
struct BundleElementERC1155 {
address tokenContract;
uint256[] ids;
uint256[] amounts;
}
/**
* @notice the lists of erc721-20-1155 tokens that are to be bundled
*
* @param erc721s list of erc721 tokens
* @param erc20s list of erc20 tokens
* @param erc1155s list of erc1155 tokens
*/
struct BundleElements {
BundleElementERC721[] erc721s;
BundleElementERC20[] erc20s;
BundleElementERC1155[] erc1155s;
}
/**
* @notice used by the loan contract to build a bundle from the BundleElements struct at the beginning of a loan,
* returns the id of the created bundle
*
* @param _bundleElements - the lists of erc721-20-1155 tokens that are to be bundled
* @param _sender sender of the tokens in the bundle - the borrower
* @param _receiver receiver of the created bundle, normally the loan contract
*/
function buildBundle(
BundleElements memory _bundleElements,
address _sender,
address _receiver
) external returns (uint256);
/**
* @notice Remove all the children from the bundle
* @dev This method may run out of gas if the list of children is too big. In that case, children can be removed
* individually.
* @param _tokenId the id of the bundle
* @param _receiver address of the receiver of the children
*/
function decomposeBundle(uint256 _tokenId, address _receiver) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/SignatureChecker.sol)
pragma solidity ^0.8.0;
import "./ECDSA.sol";
import "../Address.sol";
import "../../interfaces/IERC1271.sol";
/**
* @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA
* signatures from externally owned accounts (EOAs) as well as ERC1271 signatures from smart contract wallets like
* Argent and Gnosis Safe.
*
* _Available since v4.1._
*/
library SignatureChecker {
/**
* @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the
* signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECDSA.recover`.
*
* NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
* change through time. It could return true at block N and false at block N+1 (or the opposite).
*/
function isValidSignatureNow(
address signer,
bytes32 hash,
bytes memory signature
) internal view returns (bool) {
(address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature);
if (error == ECDSA.RecoverError.NoError && recovered == signer) {
return true;
}
(bool success, bytes memory result) = signer.staticcall(
abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature)
);
return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.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 = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC1271 standard signature validation method for
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
*
* _Available since v4.1._
*/
interface IERC1271 {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param hash Hash of the data to be signed
* @param signature Signature byte array associated with _data
*/
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}
// 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);
}
}
|
A convenience function with shared functionality between `payBackLoan` and `liquidateOverdueLoan`. _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator. _nftReceiver - The receiver of the collateral nft. The borrower when `payBackLoan` or the lender when `liquidateOverdueLoan`. _loanTerms - The main Loan Terms struct. This data is saved upon loan creation on loanIdToLoan. _loanCoordinator - The loan coordinator used when creating the loan./ Transfer collateral from this contract to the lender, since the lender is seizing collateral for an overdue loan
|
function _resolveLoan(
uint32 _loanId,
address _nftReceiver,
LoanTerms memory _loanTerms,
IDirectLoanCoordinator _loanCoordinator
) internal {
_resolveLoanNoNftTransfer(_loanId, _loanTerms, _loanCoordinator);
_transferNFT(_loanTerms, address(this), _nftReceiver);
}
| 1,474,512
|
/*
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;
pragma experimental ABIEncoderV2;
/// @dev THIS IS A SELF-CONTAINED CONVENIENCE CONTRACT FOR TESTING THE DYDX BRIDGE ON MAINNET.
/// Currently deployed at 0xeb58c2caa96f39626dcceb74fdbb7a9a8b54ec18.
/// Steps:
/// 1. Deploy to mainnet (can copy-paste this into Remix and deploy).
/// 2. Send some DAI to the contract.
/// 3. Call `init()` to configure.
interface IERC20Token {
/// @dev `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 wei to be approved for transfer
/// @return Always true if the call has enough gas to complete execution
function approve(address spender, uint256 value)
external
returns (bool);
/// @dev Query the balance of owner
/// @param owner The address from which the balance will be retrieved
/// @return Balance of owner
function balanceOf(address owner)
external
view
returns (uint256);
}
/// @dev TestDydxUser uses this interface to interact with dydx.
interface IDydx {
/// @dev Respresents an operator's privileges.
struct OperatorArg {
address operator;
bool trusted;
}
/// @dev Represents the unique key that specifies an account
struct AccountInfo {
address owner; // The address that owns the account
uint256 number; // A nonce that allows a single address to control many accounts
}
enum ActionType {
Deposit, // supply tokens
Withdraw, // borrow tokens
Transfer, // transfer balance between accounts
Buy, // buy an amount of some token (externally)
Sell, // sell an amount of some token (externally)
Trade, // trade tokens against another account
Liquidate, // liquidate an undercollateralized or expiring account
Vaporize, // use excess tokens to zero-out a completely negative account
Call // send arbitrary data to an address
}
/// @dev Arguments that are passed to Solo in an ordered list as part of a single operation.
/// Each ActionArgs has an actionType which specifies which action struct that this data will be
/// parsed into before being processed.
struct ActionArgs {
ActionType actionType;
uint256 accountId;
AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
enum AssetDenomination {
Wei, // the amount is denominated in wei
Par // the amount is denominated in par
}
enum AssetReference {
Delta, // the amount is given as a delta from the current value
Target // the amount is given as an exact number to end up at
}
struct AssetAmount {
bool sign; // true if positive
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
/// @dev The main entry-point to Solo that allows users and contracts to manage accounts.
/// Take one or more actions on one or more accounts. The msg.sender must be the owner or
/// operator of all accounts except for those being liquidated, vaporized, or traded with.
/// One call to operate() is considered a singular "operation". Account collateralization is
/// ensured only after the completion of the entire operation.
/// @param accounts A list of all accounts that will be used in this operation. Cannot contain
/// duplicates. In each action, the relevant account will be referred-to by its
/// index in the list.
/// @param actions An ordered list of all actions that will be taken in this operation. The
/// actions will be processed in order.
function operate(
AccountInfo[] calldata accounts,
ActionArgs[] calldata actions
)
external;
/// @dev Sets operators of dydx account.
/// @param operators to give/remove access.
function setOperators(OperatorArg[] calldata operators)
external;
}
/// @dev Deploy this contract and call `init` to run the mainnet DydxBridge integration tests.
contract TestDydxUser {
address public constant DYDX_BRIDGE_ADDRESS = 0x55dC8f21D20D4c6ED3C82916A438A413ca68e335;
address public constant DYDX_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
uint256 public constant DYDX_DAI_MARKET_ID = 3;
bytes4 public constant MAGIC_BYTES = bytes4(keccak256("init()"));
function init()
public
returns (bytes4)
{
// 1. Assert that this account has DAI.
uint256 daiBalance = IERC20Token(DAI_ADDRESS).balanceOf(address(this));
require(
daiBalance > 0,
"TestDydxUser/DAI_BALANCE_MUST_BE_NONZERO"
);
// 2. Set allowance for Dydx to transfer DAI.
require(
IERC20Token(DAI_ADDRESS).approve(
DYDX_ADDRESS,
daiBalance
),
"TestDydxUser/FAILED_TO_SET_DAI_ALLOWANCE"
);
// 3. Add DydxBridge as operator on dydx.
// This will revert on failure.
IDydx.OperatorArg[] memory operatorArgs = new IDydx.OperatorArg[](1);
operatorArgs[0] = IDydx.OperatorArg({
operator: DYDX_BRIDGE_ADDRESS,
trusted: true
});
IDydx(DYDX_ADDRESS).setOperators(operatorArgs);
// 4. Deposit 1/2 DAI balance into dydx. This allows us to test withdrawals.
// 4.i Create dydx account struct.
IDydx.AccountInfo[] memory accounts = new IDydx.AccountInfo[](1);
accounts[0] = IDydx.AccountInfo({
owner: address(this),
number: 0
});
// 4.ii Create dydx amount.
IDydx.AssetAmount memory dydxAmount = IDydx.AssetAmount({
sign: true, // true if positive.
denomination: IDydx.AssetDenomination.Wei, // Wei => actual token amount held in account.
ref: IDydx.AssetReference.Delta, // Delta => a relative amount.
value: daiBalance / 2 // amount to deposit.
});
// 4.iii Create dydx deposit action.
IDydx.ActionArgs[] memory actions = new IDydx.ActionArgs[](1);
actions[0] = IDydx.ActionArgs({
actionType: IDydx.ActionType.Deposit, // deposit tokens.
amount: dydxAmount, // amount to deposit.
accountId: 0, // index in the `accounts` when calling `operate`.
primaryMarketId: DYDX_DAI_MARKET_ID, // indicates which token to deposit.
otherAddress: address(this), // deposit from the account owner.
// unused parameters
secondaryMarketId: 0,
otherAccountId: 0,
data: hex''
});
// 4.iv Deposit DAI into dydx. This will revert on failure.
IDydx(DYDX_ADDRESS).operate(
accounts,
actions
);
// Return magic bytes on success.
return MAGIC_BYTES;
}
}
|
THIS IS A SELF-CONTAINED CONVENIENCE CONTRACT FOR TESTING THE DYDX BRIDGE ON MAINNET. Currently deployed at 0xeb58c2caa96f39626dcceb74fdbb7a9a8b54ec18. Steps: 1. Deploy to mainnet (can copy-paste this into Remix and deploy). 2. Send some DAI to the contract. 3. Call `init()` to configure.
|
interface IERC20Token {
function approve(address spender, uint256 value)
external
returns (bool);
function balanceOf(address owner)
external
view
returns (uint256);
}
| 12,752,694
|
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@chainlink/contracts/src/v0.7/interfaces/AggregatorV2V3Interface.sol";
import "./interfaces/IBPool.sol";
import "./interfaces/IBRegistry.sol";
import "./interfaces/IEurPriceFeed.sol";
import "./interfaces/IXTokenWrapper.sol";
import "hardhat/console.sol";
interface IDecimals {
function decimals() external view returns (uint8);
}
/**
* @title SmtPriceFeed
* @author Protofire
* @dev Contract module to retrieve SMT price per asset.
*/
contract SmtPriceFeed is Ownable {
using SafeMath for uint256;
uint256 public constant decimals = 18;
uint256 public constant ONE = 10**18;
address public constant ETH_TOKEN_ADDRESS = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
/// @dev Address smt
address public smt;
/// @dev Address of BRegistry
IBRegistry public registry;
/// @dev Address of EurPriceFeed module
IEurPriceFeed public eurPriceFeed;
/// @dev Address of XTokenWrapper module
IXTokenWrapper public xTokenWrapper;
/**
* @dev Emitted when `registry` address is set.
*/
event RegistrySet(address registry);
/**
* @dev Emitted when `eurPriceFeed` address is set.
*/
event EurPriceFeedSet(address eurPriceFeed);
/**
* @dev Emitted when `smt` address is set.
*/
event SmtSet(address smt);
/**
* @dev Emitted when `xTokenWrapper` address is set.
*/
event XTokenWrapperSet(address xTokenWrapper);
/**
* @dev Sets the values for {registry}, {eurPriceFeed} {smt} and {xTokenWrapper}.
*
* Sets ownership to the account that deploys the contract.
*
*/
constructor(
address _registry,
address _eurPriceFeed,
address _smt,
address _xTokenWrapper
) {
_setRegistry(_registry);
_setEurPriceFeed(_eurPriceFeed);
_setSmt(_smt);
_setXTokenWrapper(_xTokenWrapper);
}
/**
* @dev Sets `_registry` as the new registry.
*
* Requirements:
*
* - the caller must be the owner.
* - `_registry` should not be the zero address.
*
* @param _registry The address of the registry.
*/
function setRegistry(address _registry) external onlyOwner {
_setRegistry(_registry);
}
/**
* @dev Sets `_eurPriceFeed` as the new EurPriceFeed.
*
* Requirements:
*
* - the caller must be the owner.
* - `_eurPriceFeed` should not be the zero address.
*
* @param _eurPriceFeed The address of the EurPriceFeed.
*/
function setEurPriceFeed(address _eurPriceFeed) external onlyOwner {
_setEurPriceFeed(_eurPriceFeed);
}
/**
* @dev Sets `_smt` as the new Smt.
*
* Requirements:
*
* - the caller must be the owner.
* - `_smt` should not be the zero address.
*
* @param _smt The address of the Smt.
*/
function setSmt(address _smt) external onlyOwner {
_setSmt(_smt);
}
/**
* @dev Sets `_xTokenWrapper` as the new xTokenWrapper.
*
* Requirements:
*
* - the caller must be the owner.
* - `_xTokenWrapper` should not be the zero address.
*
* @param _xTokenWrapper The address of the xTokenWrapper.
*/
function setXTokenWrapper(address _xTokenWrapper) external onlyOwner {
_setXTokenWrapper(_xTokenWrapper);
}
/**
* @dev Sets `_registry` as the new registry.
*
* Requirements:
*
* - `_registry` should not be the zero address.
*
* @param _registry The address of the registry.
*/
function _setRegistry(address _registry) internal {
require(_registry != address(0), "registry is the zero address");
emit RegistrySet(_registry);
registry = IBRegistry(_registry);
}
/**
* @dev Sets `_eurPriceFeed` as the new EurPriceFeed.
*
* Requirements:
*
* - `_eurPriceFeed` should not be the zero address.
*
* @param _eurPriceFeed The address of the EurPriceFeed.
*/
function _setEurPriceFeed(address _eurPriceFeed) internal {
require(_eurPriceFeed != address(0), "eurPriceFeed is the zero address");
emit EurPriceFeedSet(_eurPriceFeed);
eurPriceFeed = IEurPriceFeed(_eurPriceFeed);
}
/**
* @dev Sets `_smt` as the new Smt.
*
* Requirements:
*
* - `_smt` should not be the zero address.
*
* @param _smt The address of the Smt.
*/
function _setSmt(address _smt) internal {
require(_smt != address(0), "smt is the zero address");
emit SmtSet(_smt);
smt = _smt;
}
/**
* @dev Sets `_xTokenWrapper` as the new xTokenWrapper.
*
* Requirements:
*
* - `_xTokenWrapper` should not be the zero address.
*
* @param _xTokenWrapper The address of the xTokenWrapper.
*/
function _setXTokenWrapper(address _xTokenWrapper) internal {
require(_xTokenWrapper != address(0), "xTokenWrapper is the zero address");
emit XTokenWrapperSet(_xTokenWrapper);
xTokenWrapper = IXTokenWrapper(_xTokenWrapper);
}
/**
* @dev Gets the price of `_asset` in SMT.
*
* @param _asset address of asset to get the price.
*/
function getPrice(address _asset) external view returns (uint256) {
uint8 assetDecimals = IDecimals(_asset).decimals();
return calculateAmount(_asset, 10**assetDecimals);
}
/**
* @dev Gets how many SMT represents the `_amount` of `_asset`.
*
* @param _asset address of asset to get the amount.
* @param _assetAmountIn amount of `_asset`.
*/
function calculateAmount(address _asset, uint256 _assetAmountIn) public view returns (uint256) {
// pools will include the wrapepd SMT
address xSMT = xTokenWrapper.tokenToXToken(smt);
address xETH = xTokenWrapper.tokenToXToken(ETH_TOKEN_ADDRESS);
// get amount from some of the pools
uint256 amount = getAvgAmountFromPools(_asset, xSMT, _assetAmountIn);
// not pool with SMT/asset pair -> calculate base on SMT/ETH pool and Asset/ETH external price feed
if (amount == 0) {
// pools will include the wrapepd ETH
uint256 ethSmtAmount = getAvgAmountFromPools(xETH, xSMT, ONE);
address assetEthFeed = eurPriceFeed.assetEthFeed(_asset);
if (assetEthFeed != address(0)) {
// always 18 decimals
int256 assetEthPrice = AggregatorV2V3Interface(assetEthFeed).latestAnswer();
if (assetEthPrice > 0) {
uint8 assetDecimals = IDecimals(_asset).decimals();
uint256 assetToEthAmount = _assetAmountIn.mul(uint256(assetEthPrice)).div(10**assetDecimals);
amount = assetToEthAmount.mul(ethSmtAmount).div(ONE);
}
}
}
return amount;
}
/**
* @dev Gets SMT/ETH based on the avg price from pools containig the pair.
*
* To be consume by EurPriceFeed module as the `assetEthFeed` from xSMT.
*/
function latestAnswer() external view returns (int256) {
// pools will include the wrapepd SMT and wrapped ETH
uint256 price =
getAvgAmountFromPools(
xTokenWrapper.tokenToXToken(smt),
xTokenWrapper.tokenToXToken(ETH_TOKEN_ADDRESS),
ONE
);
return int256(price);
}
function getAvgAmountFromPools(
address _assetIn,
address _assetOut,
uint256 _assetAmountIn
) internal view returns (uint256) {
address[] memory poolAddresses = registry.getBestPoolsWithLimit(_assetIn, _assetOut, 10);
uint256 totalAmount;
for (uint256 i = 0; i < poolAddresses.length; i++) {
totalAmount += calcOutGivenIn(poolAddresses[i], _assetIn, _assetOut, _assetAmountIn);
}
return totalAmount > 0 ? totalAmount.div(poolAddresses.length) : 0;
}
function calcOutGivenIn(
address poolAddress,
address _assetIn,
address _assetOut,
uint256 _assetAmountIn
) internal view returns (uint256) {
IBPool pool = IBPool(poolAddress);
uint256 tokenBalanceIn = pool.getBalance(_assetIn);
uint256 tokenBalanceOut = pool.getBalance(_assetOut);
uint256 tokenWeightIn = pool.getDenormalizedWeight(_assetIn);
uint256 tokenWeightOut = pool.getDenormalizedWeight(_assetOut);
return pool.calcOutGivenIn(tokenBalanceIn, tokenWeightIn, tokenBalanceOut, tokenWeightOut, _assetAmountIn, 0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, 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.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: MIT
pragma solidity >=0.7.0;
import "./AggregatorInterface.sol";
import "./AggregatorV3Interface.sol";
interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface
{
}
//SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
/**
* @title IBPool
* @author Protofire
* @dev Balancer BPool contract interface.
*
*/
interface IBPool {
function getDenormalizedWeight(address token) external view returns (uint256);
function getBalance(address token) external view returns (uint256);
function calcOutGivenIn(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 tokenBalanceOut,
uint256 tokenWeightOut,
uint256 tokenAmountIn,
uint256 swapFee
) external pure returns (uint256 tokenAmountOut);
}
//SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
/**
* @title IBRegistry
* @author Protofire
* @dev Balancer BRegistry contract interface.
*
*/
interface IBRegistry {
function getBestPoolsWithLimit(
address fromToken,
address destToken,
uint256 limit
) external view returns (address[] memory);
}
//SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
/**
* @title IEurPriceFeed
* @author Protofire
* @dev Interface to be implemented by any EurPriceFeed logic contract used in the protocol.
*
*/
interface IEurPriceFeed {
/**
* @dev Gets the price `_asset` ETH price feed.
*
* @param _asset address of asset to get the price feed.
*/
function assetEthFeed(address _asset) external view returns (address);
}
//SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
/**
* @title IXTokenWrapper
* @author Protofire
* @dev XTokenWrapper Interface.
*
*/
interface IXTokenWrapper {
/**
* @dev Token to xToken registry.
*/
function tokenToXToken(address _token) external view returns (address);
}
// 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;
/*
* @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.0;
interface AggregatorInterface {
function latestAnswer() external view returns (int256);
function latestTimestamp() external view returns (uint256);
function latestRound() external view returns (uint256);
function getAnswer(uint256 roundId) external view returns (int256);
function getTimestamp(uint256 roundId) external view returns (uint256);
event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt);
event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.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
);
}
|
Gets how many SMT represents the `_amount` of `_asset`. _asset address of asset to get the amount. _assetAmountIn amount of `_asset`./ pools will include the wrapepd SMT get amount from some of the pools not pool with SMT/asset pair -> calculate base on SMT/ETH pool and Asset/ETH external price feed pools will include the wrapepd ETH always 18 decimals
|
function calculateAmount(address _asset, uint256 _assetAmountIn) public view returns (uint256) {
address xSMT = xTokenWrapper.tokenToXToken(smt);
address xETH = xTokenWrapper.tokenToXToken(ETH_TOKEN_ADDRESS);
uint256 amount = getAvgAmountFromPools(_asset, xSMT, _assetAmountIn);
if (amount == 0) {
uint256 ethSmtAmount = getAvgAmountFromPools(xETH, xSMT, ONE);
address assetEthFeed = eurPriceFeed.assetEthFeed(_asset);
if (assetEthFeed != address(0)) {
int256 assetEthPrice = AggregatorV2V3Interface(assetEthFeed).latestAnswer();
if (assetEthPrice > 0) {
uint8 assetDecimals = IDecimals(_asset).decimals();
uint256 assetToEthAmount = _assetAmountIn.mul(uint256(assetEthPrice)).div(10**assetDecimals);
amount = assetToEthAmount.mul(ethSmtAmount).div(ONE);
}
}
}
return amount;
}
| 13,799,068
|
./partial_match/42/0xfF28153F4a59f59a3cCb1c24B7331B42a4e89EAf/sources/FixedSwap.sol
|
Action Functions / Confirm Amount is positive / Confirm Amount is less than tokens available / Confirm the user has funds for the transfer, confirm the value is equal / Confirm Amount is bigger than minimum Amount / Confirm Amount is smaller than maximum Amount / Verify all user purchases, loop thru them /
|
function swap(uint256 _amount) payable external whenNotPaused isFunded isSaleOpen {
require(_amount > 0, "Amount has to be positive");
require(_amount <= tokensLeft(), "Amount is less than tokens available");
require(msg.value == cost(_amount), "User has to cover the cost of the swap in ETH, use the cost function to determine");
require(_amount >= individualMinimumAmount, "Amount is bigger than minimum amount");
require(_amount <= individualMaximumAmount, "Amount is smaller than maximum amount");
uint256[] memory _purchases = getMyPurchases(msg.sender);
uint256 purchaserTotalAmountPurchased = 0;
for (uint i = 0; i < _purchases.length; i++) {
Purchase memory _purchase = purchases[_purchases[i]];
purchaserTotalAmountPurchased = purchaserTotalAmountPurchased.add(_purchase.amount);
}
require(purchaserTotalAmountPurchased.add(_amount) <= individualMaximumAmount, "Address has already passed the max amount of swap");
if(isTokenSwapAtomic){
require(erc20.transfer(msg.sender, _amount), "ERC20 transfer didn´t work");
uint256 purchase_id = increment;
increment = increment.add(1);
purchases[purchase_id] = purchase;
purchaseIds.push(purchase_id);
myPurchases[msg.sender].push(purchase_id);
buyers.push(msg.sender);
tokensAllocated = tokensAllocated.add(_amount);
emit PurchaseEvent(_amount, msg.sender, block.timestamp);
}
| 3,342,572
|
pragma solidity 0.4.24;
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "openzeppelin-solidity/contracts/lifecycle/Pausable.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./IKODAV2Controls.sol";
/**
* @title Artists self minting for KnownOrigin (KODA)
*
* Allows for the edition artists to mint there own assets and control the price of an edition
*
* https://www.knownorigin.io/
*
* BE ORIGINAL. BUY ORIGINAL.
*/
contract ArtistEditionControls is Ownable, Pausable {
using SafeMath for uint256;
// Interface into the KODA world
IKODAV2Controls public kodaAddress;
event PriceChanged(
uint256 indexed _editionNumber,
address indexed _artist,
uint256 _priceInWei
);
constructor(IKODAV2Controls _kodaAddress) public {
kodaAddress = _kodaAddress;
}
/**
* @dev Ability to gift new NFTs to an address, from a KODA edition
* @dev Only callable from edition artists defined in KODA NFT contract
* @dev Only callable when contract is not paused
* @dev Reverts if edition is invalid
* @dev Reverts if edition is not active in KDOA NFT contract
*/
function gift(address _receivingAddress, uint256 _editionNumber)
external
whenNotPaused
returns (uint256)
{
require(_receivingAddress != address(0), "Unable to send to zero address");
address artistAccount;
uint256 artistCommission;
(artistAccount, artistCommission) = kodaAddress.artistCommission(_editionNumber);
require(msg.sender == artistAccount || msg.sender == owner, "Only from the edition artist account");
bool isActive = kodaAddress.editionActive(_editionNumber);
require(isActive, "Only when edition is active");
return kodaAddress.mint(_receivingAddress, _editionNumber);
}
/**
* @dev Sets the price of the provided edition in the WEI
* @dev Only callable from edition artists defined in KODA NFT contract
* @dev Only callable when contract is not paused
* @dev Reverts if edition is invalid
* @dev Reverts if edition is not active in KDOA NFT contract
*/
function updateEditionPrice(uint256 _editionNumber, uint256 _priceInWei)
external
whenNotPaused
returns (bool)
{
address artistAccount;
uint256 artistCommission;
(artistAccount, artistCommission) = kodaAddress.artistCommission(_editionNumber);
require(msg.sender == artistAccount || msg.sender == owner, "Only from the edition artist account");
bool isActive = kodaAddress.editionActive(_editionNumber);
require(isActive, "Only when edition is active");
kodaAddress.updatePriceInWei(_editionNumber, _priceInWei);
emit PriceChanged(_editionNumber, msg.sender, _priceInWei);
return true;
}
/**
* @dev Sets the KODA address
* @dev Only callable from owner
*/
function setKodavV2(IKODAV2Controls _kodaAddress) onlyOwner public {
kodaAddress = _kodaAddress;
}
}
|
Sets the KODA address Only callable from owner/
|
function setKodavV2(IKODAV2Controls _kodaAddress) onlyOwner public {
kodaAddress = _kodaAddress;
}
| 1,836,385
|
./full_match/80001/0x65d63958fc1Bf199e8a44762F77b329c864898fA/sources/contracts/Battle.sol
|
Player 1 attacks, player 2 does nothing
|
function _handleAttackDoNothing(
BattleData storage battle,
CharacterProxy storage proxyA,
CharacterProxy storage proxyB
)
private
returns (
uint256[2] memory damageDealt,
address[2] memory damagedPlayers
)
{
uint256 damageA = (proxyA.stats.attack * proxyA.attackMultiplier) /
1000;
proxyB.stats.health = proxyB.stats.health > damageA
? proxyB.stats.health - damageA
: 0;
damagedPlayers[0] = battle.players[1];
damageDealt[0] = damageA;
proxyA.stats.mana -= 3;
return (damageDealt, damagedPlayers);
}
| 5,549,113
|
./full_match/80001/0x6ee73E980d53C4c60b63E8a6A8B34E6b15dBE718/sources/contracts/CloudArtworkGenerator.sol
|
gets the inner code for the image. In this case, this includes filters to geenrate the cloud effect tokenId the tokenId for the image/
|
function getFragment(uint tokenId) public view returns (string memory fragment){
Theme memory theme = themesMap[randomInRange(0, maxTheme, Strings.toString(tokenId))];
string memory width = Strings.toString(randomInRange(200, 370, Strings.toString(tokenId)));
string memory fillString = getColor(theme.hue, theme.suffix);
return string.concat(
getFilter(tokenId),
'<g id="cld',Strings.toString(tokenId),'"><ellipse cx="320" cy="320" rx="',width,'" ry="80" fill="',fillString,'" filter="url(#base', Strings.toString(tokenId), ')"/><ellipse cx="320" cy="360" rx="200" ry="20" fill="rgba(20, 32, 45, 0.2)" filter="url(#cloud-front)" /></g>');
}
| 9,434,829
|
// Copyrights(c) 2020 Zhou Le, Tang Jingyao
// Course project of EE357 spring semester, 2020, Shanghai JiaoTong University
// The contract source file of game "Crypto Galaxy"
// ONLY used for research and study
// Version 1.0.0
pragma solidity >=0.4.22 <0.5.2;
pragma experimental ABIEncoderV2;
contract Random {
uint saltForRandom;
function _rand() internal returns (uint) {
uint lastBlockNumber = block.number; // block.number - 1
uint hashVal = uint(blockhash(lastBlockNumber));
uint factor = 1157920892373161954235709850086879078532699846656405640394575840079131296399;
saltForRandom += uint(msg.sender) % 100 + uint(uint(hashVal) / factor);
return saltForRandom;
}
function _randRange(uint min, uint max) internal returns (uint) {
return uint256(keccak256(abi.encode(_rand(), now))) % (max - min + 1) + min;
}
function _randChance(uint percent) internal returns (bool) {
return _randRange(0, 100) < percent;
}
}
contract GalaxyStorage is Random {
struct Planet {
string name;
address owner;
uint pid;
// data
// loc_y, loc_x, planet_type, last_update_time, res_type, res_gen_speed, current_res[3], max_res[3]
uint[12] data;
}
struct ShipTemplate {
string name;
// data
// attack, shield, hull, speed, cargo, build_time, build_res[3]
uint[9] data;
}
struct Ship {
string name;
address owner;
uint sid;
// data
// loc_y, loc_x, state, type_id, attack, shield, hull, speed, cargo, max_hull, rarity, num_of_treasure_install
// state 0-null 1-destroyed 2-moving 3-normal 4-onsale
uint[12] data;
}
struct Treasure {
string name;
address owner;
uint tid;
// data
// old_effect_num(can check whether installed), on_sale, effect_type, effect_percent, rarity
uint[5] data;
}
struct Sale {
address seller;
uint said;
// data
// sale_type, token_id, start_time, end_time, price
// sale_type: 0-null 1-ship 2-treasure
uint[5] data;
}
struct BattleLog {
address attacker;
address defencer;
// data
// loc_y, loc_x, result, stage_num, time
uint[5] data;
uint[3][2][5] detail; // store sum of attack, shield receive damage, hull receive damage
uint[][2][6] stage_sids; // store remain ship id of each player, 1+5
}
struct Order {
address player;
uint oid;
// data
// loc_y, loc_x, order_type, object_id, start_time, end_time, res[3]
uint[9] data;
}
uint MAX_X = 100;
uint MAX_Y = 100;
uint[10000] galaxyMap;
uint planetNum = 0;
uint salePt = 0;
uint orderPt = 0;
uint[] saleKeyList;
uint[] orderKeyList;
Planet[] planetList;
ShipTemplate[] shipTemplateList;
Ship[] shipList;
Treasure[] treasureList;
BattleLog[] battleLogList;
mapping (address => uint) ppcount;
mapping (address => uint) pscount;
mapping (address => uint) ptcount;
mapping (address => uint) pocount;
mapping (address => uint) pblcount;
mapping (uint => uint) tinstall;
mapping (uint => uint) plid;
// mapping (uint256 => uint256) orderIdToIndex;
mapping (uint => Sale) saleList;
mapping (uint => Order) orderList;
mapping (address => uint) ownerApprovals;
}
contract GalaxyGetter is GalaxyStorage {
function getPlanetInfo(uint _loc_y, uint _loc_x) external view returns (string memory name, address owner, uint[12] memory data) {
uint loc = _loc_y * MAX_X + _loc_x;
require(loc < 10000);
data[2] = galaxyMap[loc];
if (data[2] > 1) {
Planet storage p = planetList[plid[loc]];
name = p.name;
owner = p.owner;
data = p.data;
}
}
function getShipInfo(uint _sid) external view returns (string memory name, address owner, uint[12] memory data) {
require(_sid < shipList.length);
Ship storage s = shipList[_sid];
name = s.name;
owner = s.owner;
data = s.data;
}
function getShipTemplateInfo(uint _stid) external view returns (string memory name, uint[9] memory data) {
require(_stid < shipTemplateList.length);
ShipTemplate storage st = shipTemplateList[_stid];
name = st.name;
data = st.data;
}
function getTreasureInfo(uint _tid) external view returns (string memory name, address owner, uint[5] memory data) {
require(_tid < treasureList.length);
Treasure storage t = treasureList[_tid];
name = t.name;
owner = t.owner;
data = t.data;
}
function getSaleInfo(uint _said) external view returns (address seller, uint[5] memory data) {
require(saleList[_said].data[0] > 0);
Sale storage sa = saleList[_said];
seller = sa.seller;
data = sa.data;
}
function getBattleLogInfo(uint _blid) external view returns (
address at,
address de,
uint[5] memory data,
uint[3][2][5] memory detail,
uint[][2][6] memory stage_sids
){
require(_blid < battleLogList.length);
BattleLog storage bl = battleLogList[_blid];
at = bl.attacker;
de = bl.defencer;
data = bl.data;
detail = bl.detail;
stage_sids = bl.stage_sids;
}
function getOrderInfo(uint _oid) external view returns (address player, uint[9] memory data) {
require(_oid < orderPt);
Order storage od = orderList[_oid];
player = od.player;
data = od.data;
}
function getPlayerOrders() external view returns (
uint[] memory os_id,
uint[9][] memory os_data
) {
os_id = new uint[] (pocount[msg.sender]);
os_data = new uint[9][] (pocount[msg.sender]);
uint count = 0;
for (uint i = 0; i < orderKeyList.length; i++) {
if (orderList[orderKeyList[i]].player == msg.sender) {
os_id[count] = orderKeyList[i];
os_data[count] = orderList[orderKeyList[i]].data;
count++;
}
}
}
function getPlayerPlanets() external view returns (
string[] memory ps_name,
uint[] memory ps_id,
uint[12][] memory ps_data
) {
ps_name = new string[] (ppcount[msg.sender]);
ps_id = new uint[] (ppcount[msg.sender]);
ps_data = new uint[12][] (ppcount[msg.sender]);
uint count = 0;
for (uint i = 0; i < planetList.length; i++) {
if (planetList[i].owner == msg.sender) {
ps_name[count] = planetList[i].name;
ps_id[count] = planetList[i].pid;
ps_data[count] = planetList[i].data;
count++;
}
}
}
function getPlayerShips() external view returns (
string[] memory ss_name,
uint[] memory ss_id,
uint[12][] memory ss_data
) {
ss_name = new string[] (pscount[msg.sender]);
ss_id = new uint[] (pscount[msg.sender]);
ss_data = new uint[12][] (pscount[msg.sender]);
uint count = 0;
for (uint i = 0; i < shipList.length; i++) {
if (shipList[i].owner == msg.sender) {
ss_name[count] = shipList[i].name;
ss_id[count] = shipList[i].sid;
ss_data[count] = shipList[i].data;
count++;
}
}
}
function getPlayerTreasures() external view returns (
string[] memory ts_name,
uint[] memory ts_id,
uint[5][] memory ts_data
) {
ts_name = new string[] (ptcount[msg.sender]);
ts_id = new uint[] (ptcount[msg.sender]);
ts_data = new uint[5][] (ptcount[msg.sender]);
uint count = 0;
for (uint i = 0; i < treasureList.length; i++) {
if (treasureList[i].owner == msg.sender) {
ts_name[count] = treasureList[i].name;
ts_id[count] = treasureList[i].tid;
ts_data[count] = treasureList[i].data;
count++;
}
}
}
function getSales() external view returns (address[] memory sas_seller, uint[] memory sas_id) {
sas_id = saleKeyList;
sas_seller = new address[] (saleKeyList.length);
for (uint i = 0; i < saleKeyList.length; i++) {
sas_seller[i] = saleList[saleKeyList[i]].seller;
}
}
// function getShipTemplates() external view returns (string[] memory sts_name, uint[] memory sts_id) {
// sts_name = new string[] (shipTemplateList.length);
// sts_id = new uint[] (shipTemplateList.length);
// for (uint i = 0; i < shipTemplateList.length; i++) {
// sts_name[i] = shipTemplateList[i].name;
// sts_id[i] = i;
// }
// }
function getPlayerBattleLogs() external view returns (
uint[] memory bls_id,
uint[] memory bls_result,
address[] memory bls_at,
address[] memory bls_de
) {
bls_id = new uint[] (pblcount[msg.sender]);
bls_result = new uint[] (pblcount[msg.sender]);
bls_at = new address[] (pblcount[msg.sender]);
bls_de = new address[] (pblcount[msg.sender]);
uint count = 0;
for (uint i = 0; i < battleLogList.length; i++) {
if (battleLogList[i].attacker == msg.sender || battleLogList[i].defencer == msg.sender) {
bls_id[count] = i;
bls_result[count] = battleLogList[i].data[2];
bls_at[count] = battleLogList[i].attacker;
bls_de[count] = battleLogList[i].defencer;
count++;
}
}
}
function getMap(uint256 _sector) external view returns (uint[10][10] memory sector_map) {
require(_sector < 100);
uint x_bias = (_sector % 10) * 10;
uint y_bias = (_sector / 10) * 1000;
uint current_bias;
for (uint i = 0; i < 10; i++) {
for (uint j = 0; j < 10; j++) {
current_bias = y_bias + x_bias + j + i * 100;
sector_map[j][i] = galaxyMap[current_bias];
}
}
}
}
contract GalaxyPlanet is GalaxyGetter {
function createPlanets() public {
for (uint i = 0; i < 50; i++) {
createOnePlanet(false);
}
}
function setPName(uint _loc_y, uint _loc_x, string calldata _name) external {
uint loc = _loc_y * MAX_X + _loc_x;
require(loc < 10000 && galaxyMap[loc] > 1 && planetList[plid[loc]].owner == msg.sender);
planetList[plid[loc]].name = _name;
}
function refreshRes(uint _loc_y, uint _loc_x) public {
uint loc = _loc_y * MAX_X + _loc_x;
require (loc < 10000 && galaxyMap[loc] > 1);
uint[12] storage data = planetList[plid[loc]].data;
uint gain = (now - data[3]) * data[5] / 1 seconds; // 3600 seconds
data[6 + data[4]] = data[6 + data[4]] + gain < data[9 + data[4]]? data[6 + data[4]] + gain: data[9 + data[4]];
data[3] = now;
}
function createHomePlanet(address _player) internal returns (uint, uint) {
require (ppcount[_player] == 0);
uint loc_y;
uint loc_x;
(loc_y, loc_x) = createOnePlanet(true);
surveyPlanet(loc_y, loc_x, true);
transferPlanet(address(0), _player, planetList.length - 1);
return (loc_y, loc_x);
}
function surveyPlanet(uint _loc_y, uint _loc_x, bool _must_habitable) internal returns (bool) {
uint loc = _loc_y * MAX_X + _loc_x;
uint[3] memory data;
require(loc < 10000 && galaxyMap[loc] == 1);
data[0] = (_randChance(50) || _must_habitable)? 3: 2;
data[1] = _randRange(0, 2);
data[2] = _randRange(80, 120);
planetList.push(Planet("New Planet", address(0), planetList.length,
[_loc_y, _loc_x, data[0], now, data[1], data[2], 0, 0, 0, 1000000, 1000000, 1000000]));
plid[loc] = planetList.length - 1;
galaxyMap[loc] = data[0];
transferPlanet(address(0), address(0), planetList.length - 1);
return (data[0] == 3) ? true: false;
}
function transferRes(uint _loc, uint[3] memory _res, bool _reverse) internal {
uint[12] storage data = planetList[plid[_loc]].data;
if (!_reverse) {
data[6] -= _res[0];
data[7] -= _res[1];
data[8] -= _res[2];
} else {
data[6] = data[6] + _res[0] < data[9]? (data[6] + _res[0]): data[9];
data[7] = data[7] + _res[1] < data[10]? (data[7] + _res[1]): data[10];
data[8] = data[8] + _res[2] < data[11]? (data[8] + _res[2]): data[11];
}
}
function createOnePlanet(bool _must) internal returns (uint, uint) {
if (planetNum >= 800 && !_must) {
return (MAX_Y, MAX_X);
}
uint256 random = _randRange(0, 9999);
while (galaxyMap[random] != 0) {
random = (random + 1) % 9999;
}
galaxyMap[random] = 1;
planetNum++;
return (random / MAX_X, random % MAX_X);
}
function transferPlanet(address _from, address _to, uint256 _pid) internal {
ppcount[_to]++;
ppcount[_from]--;
planetList[_pid].owner = _to;
}
function checkEnoughRes(uint _loc, uint[3] memory _res) internal view returns (bool) {
uint[12] storage data = planetList[plid[_loc]].data;
if (data[6] < _res[0] || data[7] < _res[1] || data[8] < _res[2]) {
return false;
}
return true;
}
}
contract GalaxyShip is GalaxyPlanet {
function setSName(uint _sid, string calldata _name) external {
require(_sid < shipList.length && shipList[_sid].owner == msg.sender);
shipList[_sid].name = _name;
}
function buildShip(address _player, uint _loc_y, uint _loc_x, uint _type) internal {
require (_type < shipTemplateList.length);
uint[6] memory sdata;
uint[9] storage stdata = shipTemplateList[_type].data;
sdata[5] = _randRange(0, 4);
for (uint i = 0; i < 5; i++) {
sdata[i] = stdata[i] * (100 + 20 * sdata[5] * _randRange(0, 999) / 1000) / 100;
}
shipList.push(Ship("New ship", _player, shipList.length,
[_loc_y, _loc_x, 3, _type, sdata[0], sdata[1], sdata[2], sdata[3], sdata[4], sdata[2], sdata[5], 0]));
pscount[_player]++;
}
function endMoveShip(uint _sid, uint _loc_y, uint _loc_x) internal {
uint[12] storage data = shipList[_sid].data;
data[0] = _loc_y;
data[1] = _loc_x;
data[2] = 3;
}
function startMoveShip(uint _sid, uint _loc_y, uint _loc_x) internal returns (uint) {
uint[12] storage data = shipList[_sid].data;
require(data[2] == 3);
data[2] = 2;
uint dy = _loc_y > data[0]? _loc_y - data[0]: data[0] - _loc_y;
uint dx = _loc_x > data[1]? _loc_x - data[1]: data[1] - _loc_x;
return (dy + dx) * 1000 / data[7];
}
function checkEnoughResAndCargo(uint _loc, uint _sid, uint[3] memory _res) internal view returns (bool) {
if (!checkEnoughRes(_loc, _res) || shipList[_sid].data[8] < _res[0] + _res[1] + _res[2]) {
return false;
}
return true;
}
function transferShip(address _from, address _to, uint256 _id) internal {
pscount[_to]++;
pscount[_from]--;
shipList[_id].owner = _to;
}
function getShipAttackSum(uint[] memory _sids) internal view returns (uint) {
uint sum = 0;
for (uint i = 0; i < _sids.length; i++) {
if(shipList[_sids[i]].data[2] == 3) {
sum += shipList[_sids[i]].data[4];
}
}
return sum;
}
function damageShip(uint _sid, uint _damage) internal returns (bool, uint, uint) {
uint[12] storage data = shipList[_sid].data;
if (data[5] < _damage) {
_damage -= data[5];
if (data[6] < _damage) {
data[6] = 0;
data[2] = 1;
return (true, data[5], _damage);
} else {
data[6] -= _damage;
return (false, data[5], _damage);
}
}
return (false, _damage, 0);
}
function getValidSids(uint _loc_y, uint _loc_x, address _player, bool _is_player) internal view returns (uint[] memory) {
uint count = 0;
uint[] memory sids = new uint[] (shipList.length);
for (uint i = 0; i < shipList.length; i++) {
uint[12] storage data = shipList[i].data;
if (data[0] == _loc_y && data[1] == _loc_x && data[2] == 3 && (_player == shipList[i].owner) == _is_player) {
sids[count] = i;
count++;
}
}
uint[] memory sids2 = new uint[] (count);
for (uint i = 0; i < sids2.length; i++)
sids2[i] = sids[i];
return sids2;
}
}
contract GalaxyTreasure is GalaxyShip {
function createTreasure(address _player) internal {
uint[3] memory data;
data[0] = _randRange(0, 3);
data[2] = _randRange(0, 5);
data[1] = _randRange(5 + 20 * data[2], 20 + 20 * data[2]);
string memory name = data[0] == 0? "Weapon Charger":
(data[0] == 1? "Shield Charger": (data[0] == 2? "Structure stengthener": "Booster"));
treasureList.push(Treasure(name, _player, treasureList.length, [0, 0, data[0], data[1], data[2]]));
ptcount[_player]++;
}
function transferTreasure(address _from, address _to, uint _id) internal {
ptcount[_to]++;
ptcount[_from]--;
treasureList[_id].owner = _to;
}
function installTreasure(uint _sid, uint _tid) external {
require(_sid < shipList.length && _tid < treasureList.length);
uint[12] storage sdata = shipList[_sid].data;
uint[5] storage tdata = treasureList[_tid].data;
require(tdata[0] == 0 && tdata[1] == 0 && sdata[11] < 3);
if (tdata[2] == 2) {
tdata[0] = sdata[9];
sdata[9] = sdata[9] * tdata[3] / 100;
sdata[6] = sdata[6] * tdata[3] / 100;
} else {
tdata[0] = sdata[4 + tdata[2]] / 100;
sdata[4 + tdata[2]] = sdata[4 + tdata[2]] * tdata[3] / 100;
}
sdata[11] ++;
tinstall[_tid] = _sid;
}
function uninstallTreasure(uint _tid) external {
require(_tid < treasureList.length);
uint[5] storage tdata = treasureList[_tid].data;
require(tdata[0] > 0);
uint[12] storage sdata = shipList[tinstall[_tid]].data;
if (tdata[2] == 2) {
sdata[6] = sdata[6] * tdata[0] / sdata[9];
sdata[9] = tdata[0];
} else {
sdata[4 + tdata[2]] = tdata[0];
}
sdata[11]--;
tdata[0] = 0;
}
function survey(uint _loc_y, uint _loc_x) external {
uint256[] memory player_ships_id;
player_ships_id = getValidSids(_loc_y, _loc_x, msg.sender, true);
require(player_ships_id.length > 0);
createTreasure(msg.sender);
surveyPlanet(_loc_y, _loc_x, false);
}
}
contract GalaxySale is GalaxyTreasure {
function createSale(uint _sale_type, uint _id, uint _price) external {
require(0 < _sale_type && _sale_type < 3);
if (_sale_type == 1) {
setShipSale(msg.sender, _id);
} else if (_sale_type == 2) {
setTreasureSale(msg.sender, _id);
}
saleList[salePt] = Sale(msg.sender, salePt, [_sale_type, _id, now, now + 24 hours, _price]);
saleKeyList.push(salePt);
salePt++;
// emit saleCreated(_sale_type, _id, _price, now + 24 hours);
}
function acceptSale(uint _said) external payable {
refreshSales();
require(saleList[_said].data[0] > 0);
Sale storage sa = saleList[_said];
require(msg.value >= sa.data[4] && msg.sender != sa.seller);
// emit saleSuccessful(_sale_type, current_sale.token_id, current_sale.price, msg.sender);
executeSale(msg.sender, sa.data[0], _said);
if (!msg.sender.send(msg.value - sa.data[4]))
ownerApprovals[msg.sender] = msg.value - sa.data[4];
}
function checkApproval() external {
refreshSales();
if (ownerApprovals[msg.sender] > 0 && msg.sender.send(ownerApprovals[msg.sender])) {
ownerApprovals[msg.sender] = 0;
}
}
function refreshSales() public {
for(uint256 i = 0; i < saleKeyList.length; i++) {
uint[5] storage data = saleList[saleKeyList[i]].data;
if (now > data[3]) {
if (data[0] == 1) {
shipList[data[1]].data[2] = 3;
} else if (data[0] == 2) {
treasureList[data[1]].data[1] = 0;
}
// delete saleList[saleKeylist[i]];
saleKeyList[i] = saleKeyList[saleKeyList.length - 1];
saleKeyList.length--;
i--;
}
}
}
function setTreasureSale(address _player, uint _tid) internal {
require(_tid < treasureList.length && treasureList[_tid].owner == _player);
uint[5] storage data = treasureList[_tid].data;
require(data[0] == 0 && data[1] == 0);
data[1] = 1;
}
function setShipSale(address _player, uint _sid) internal {
require(_sid < shipList.length && shipList[_sid].owner == _player);
uint[12] storage data = shipList[_sid].data;
require(data[2] == 3);
data[2] = 4;
}
function executeSale(address _to, uint _sale_type, uint _said) internal {
if (_sale_type == 1) {
transferShip(saleList[_said].seller, _to, saleList[_said].data[1]);
shipList[saleList[_said].data[1]].data[2] = 3;
} else if (_sale_type == 2) {
transferTreasure(saleList[_said].seller, _to, saleList[_said].data[1]);
treasureList[saleList[_said].data[1]].data[1] = 0;
}
ownerApprovals[saleList[_said].seller] = saleList[_said].data[4];
// delete saleList[_id];
for (uint i = 0; i < saleKeyList.length; i++) {
if (saleKeyList[i] == _said) {
saleKeyList[i] = saleKeyList[saleKeyList.length - 1];
saleKeyList.length--;
break;
}
}
}
}
contract GalaxyBattle is GalaxySale {
function capture(uint _loc_y, uint _loc_x) external {
uint loc = _loc_y * MAX_X + _loc_x;
require (loc < 10000 && galaxyMap[loc] > 1 && planetList[plid[loc]].owner != msg.sender);
uint[] memory sids;
uint[] memory desids;
sids = getValidSids(_loc_y, _loc_x, msg.sender, true);
desids = getValidSids(_loc_y, _loc_x, msg.sender, false);
require(sids.length > 0 && desids.length == 0);
transferPlanet(planetList[plid[loc]].owner, msg.sender, plid[loc]);
}
function battle(uint _loc_y, uint _loc_x, address _attacker) external {
require (_loc_y * MAX_X + _loc_x < 10000);
//get ships of attacker's and defencer's ships first
//if can not find such defencer, return false
//in each stage, calculate the sum of damage of each side, divide them into equl part and resort in enemy's ship
//ship whose hull is equl to 0 will be ignored in next stage of battle and marked as destroyed
address defencer;
uint[] memory atsids = getValidSids(_loc_y, _loc_x, _attacker, true);
uint[] memory desids = getValidSids(_loc_y, _loc_x, _attacker, false);
require(atsids.length != 0);
if (desids.length == 0) {
return;
} else {
defencer = shipList[desids[0]].owner;
}
// uint attacker_attack_sum;
// uint attacker_attack_each;
// uint defencer_attack_sum;
// uint defencer_attack_each;
// uint attacker_shield_recieve;
// uint attacker_hull_recieve;
// uint defencer_shield_recieve;
// uint defencer_hull_recieve;
// uint shield_recieve;
// uint hull_recieve;
uint[10] memory detail;
uint stage;
uint result;
uint atcount = atsids.length;
uint decount = desids.length;
bool destroyed;
BattleLog memory blank;
battleLogList.push(blank);
BattleLog storage bl = battleLogList[battleLogList.length - 1];
bl.attacker = _attacker;
bl.defencer = defencer;
bl.stage_sids[0][0] = atsids;
bl.stage_sids[0][1] = desids;
for (stage = 1; stage < 6; stage++) {
(detail[4], detail[5], detail[6], detail[7]) = (0, 0, 0, 0);
detail[0] = getShipAttackSum(atsids);
detail[1] = detail[0] / decount;
for (uint i = 0; i < desids.length; ++i) {
if (shipList[desids[i]].data[2] == 3) {
(destroyed, detail[8], detail[9]) = damageShip(desids[i], detail[1]);
if (destroyed) {
decount--;
} else {
bl.stage_sids[stage][1].push(desids[i]);
}
detail[6] += detail[8];
detail[7] += detail[9];
}
}
detail[2] = getShipAttackSum(desids);
detail[3] = detail[2] / atcount;
for (uint i = 0; i < atsids.length; ++i) {
if (shipList[atsids[i]].data[2] == 3) {
(destroyed, detail[8], detail[9]) = damageShip(atsids[i], detail[3]);
if (destroyed) {
atcount--;
} else {
bl.stage_sids[stage][0].push(atsids[i]);
}
detail[4] += detail[8];
detail[5] += detail[9];
}
}
bl.detail[stage][0] = [detail[0], detail[4], detail[5]];
bl.detail[stage][1] = [detail[2], detail[6], detail[7]];
if (atcount == 0) {
result = 2;
break;
}
if (decount == 0) {
result = 1;
break;
}
}
if (atcount != 0 && decount != 0) {
result = 3;
}
bl.data = [_loc_y, _loc_x, result, stage, now];
pblcount[_attacker]++;
pblcount[defencer]++;
}
}
contract GalaxyOrder is GalaxyBattle {
function createBuildOrder(uint _loc_y, uint _loc_x, uint _stid) external {
refreshOrder();
uint loc = _loc_y * MAX_Y + _loc_x;
require(_stid < shipTemplateList.length && loc < 10000 && galaxyMap[loc] == 3 && planetList[plid[loc]].owner == msg.sender);
ShipTemplate storage st = shipTemplateList[_stid];
uint[3] memory res = [st.data[6], st.data[7], st.data[8]];
refreshRes(_loc_y, _loc_x);
require(checkEnoughRes(loc, res));
transferRes(loc, res, false);
uint[9] memory data = [_loc_y, _loc_x, 1, _stid, now, now + st.data[5], res[0], res[1], res[2]];
createOrder(msg.sender, data);
}
function createTransOrder(uint _loc_y, uint _loc_x, uint _sid, uint[3] calldata _res) external {
refreshOrder();
uint loc = _loc_y * MAX_Y + _loc_x;
require(_sid < shipList.length && loc < 10000 && galaxyMap[loc] > 1 && shipList[_sid].owner == msg.sender);
refreshRes(_loc_y, _loc_x);
require(checkEnoughResAndCargo(loc, _sid, _res));
transferRes(loc, _res, false);
uint[9] memory data = [_loc_y, _loc_x, 2, _sid, now, now + startMoveShip(_sid, _loc_y, _loc_x), _res[0], _res[1], _res[2]];
createOrder(msg.sender, data);
}
function createMoveOrder(uint _loc_y, uint _loc_x, uint _sid) external {
refreshOrder();
uint loc = _loc_y * MAX_Y + _loc_x;
require(_sid < shipList.length && loc < 10000 && shipList[_sid].owner == msg.sender);
uint[9] memory data = [_loc_y, _loc_x, 3, _sid, now, now + startMoveShip(_sid, _loc_y, _loc_x), 0, 0, 0];
createOrder(msg.sender, data);
}
function createOrder(address _player, uint[9] memory data) internal {
orderList[orderPt] = Order(_player, orderPt, data);
orderKeyList.push(orderPt);
orderPt++;
pocount[_player]++;
}
function deleteOrder(uint _oid) internal {
orderList[_oid].data[2] = 0;
pocount[orderList[_oid].player]--;
for (uint i = 0; i < orderKeyList.length; i++) {
if (orderKeyList[i] == _oid) {
orderKeyList[i] = orderKeyList[orderKeyList.length - 1];
orderKeyList.length--;
break;
}
}
}
function withdrawOrder(uint _oid) external {
refreshOrder();
require(orderList[_oid].data[2] > 0 && orderList[_oid].player == msg.sender && orderList[_oid].data[5] < now);
Order storage od = orderList[_oid];
if (od.data[2] == 1) {
transferRes(od.data[0] * MAX_Y + od.data[1], [od.data[6], od.data[7], od.data[8]], true);
} else if (od.data[2] == 2 || od.data[2] == 3) {
uint[12] memory sdata = shipList[od.data[3]].data;
require(!(od.data[0] == sdata[0] && od.data[1] == sdata[1]));
od.data[0] = sdata[0];
od.data[1] = sdata[1];
od.data[5] = now + od.data[5] - od.data[4];
od.data[4] = now;
return;
}
deleteOrder(_oid);
}
function executeOrder(uint _oid) internal {
Order storage od = orderList[_oid];
if (od.data[2] == 1) {
buildShip(od.player, od.data[0], od.data[1], od.data[3]);
} else if (od.data[2] == 2) {
transferRes(od.data[0] * MAX_X + od.data[1], [od.data[6], od.data[7], od.data[8]], true);
endMoveShip(od.data[3], od.data[0], od.data[1]);
} else if (od.data[2] == 3) {
endMoveShip(od.data[3], od.data[0], od.data[1]);
}
deleteOrder(_oid);
}
function refreshOrder() public {
for (uint i = 0; i < orderKeyList.length; i++) {
if (orderList[orderKeyList[i]].data[5] < now) {
executeOrder(orderKeyList[i]);
i--;
}
}
}
}
contract CryptoGalaxy is GalaxyOrder {
address[] playerList;
address host;
mapping (address => uint) freetime;
constructor() public {
host = msg.sender;
}
function checkPlExt() public view returns (bool) {
for (uint i = 0; i < playerList.length; i++) {
if (playerList[i] == msg.sender)
return true;
}
return false;
}
function joinGame() external {
require(!checkPlExt());
playerList.push(msg.sender);
uint loc_y;
uint loc_x;
(loc_y, loc_x) = createHomePlanet(msg.sender);
buildShip(msg.sender, loc_y, loc_x, 2);
freetime[msg.sender] = now;
}
function getFreeShip() external {
require(checkPlExt());
require(freetime[msg.sender] + 12 hours < now);
freetime[msg.sender] = now;
uint loc = _randRange(0, 9999);
buildShip(msg.sender, loc / MAX_X, loc % MAX_X, 2);
}
function checkFT() external view returns (uint) {
require(checkPlExt());
return freetime[msg.sender];
}
function donate() external payable {
return;
}
function gameOver() external {
require(msg.sender == host);
selfdestruct(address(uint160(host)));
}
function init() external {
shipTemplateList.push(ShipTemplate("corvette", [uint256(100), 50, 400, 800, 500, 30 seconds, 0, 0, 0]));
shipTemplateList.push(ShipTemplate("destroyer", [uint256(200), 100, 800, 600, 800, 60 seconds, 12000, 4000, 2000]));
shipTemplateList.push(ShipTemplate("cruiser", [uint256(600), 300, 1500, 400, 1000, 60 seconds, 5000, 10000, 20000]));
shipTemplateList.push(ShipTemplate("battleship", [uint256(1600), 800, 6000, 200, 2000, 60 seconds, 100000, 80000, 60000]));
shipTemplateList.push(ShipTemplate("small transporter", [uint256(0), 50, 800, 600, 3000, 60 seconds, 10000, 20000, 10000]));
shipTemplateList.push(ShipTemplate("large transporter", [uint256(0), 100, 1500, 400, 8000, 60 seconds, 40000, 40000, 40000]));
}
}
|
delete saleList[_id];
|
function executeSale(address _to, uint _sale_type, uint _said) internal {
if (_sale_type == 1) {
transferShip(saleList[_said].seller, _to, saleList[_said].data[1]);
shipList[saleList[_said].data[1]].data[2] = 3;
transferTreasure(saleList[_said].seller, _to, saleList[_said].data[1]);
treasureList[saleList[_said].data[1]].data[1] = 0;
}
ownerApprovals[saleList[_said].seller] = saleList[_said].data[4];
for (uint i = 0; i < saleKeyList.length; i++) {
if (saleKeyList[i] == _said) {
saleKeyList[i] = saleKeyList[saleKeyList.length - 1];
saleKeyList.length--;
break;
}
}
}
| 14,034,925
|
./partial_match/1/0x5F1127EcbEeC10cb614A62869AD7DA2f9358343d/sources/NiftyBuilderInstance.sol
|
Prevent the minting of additional NFTs of this 'niftyType'./
|
function setFinalized(uint256 niftyType) public onlyValidSender {
uint256 quotient = niftyType / 256;
bytes32 chunk = _finalized[quotient];
_finalized[quotient] = chunk | bytes32(1 << (niftyType % 256));
}
| 4,355,425
|
./full_match/1/0x2b7b2aF75f588C81EdBccBc832c20dDdc58D7484/sources/contract-5512c8d244.sol
|
Transfer amount minus tax Transfer tax to tax address
|
function transfer(address recipient, uint256 amount) public override returns (bool) {
super.transfer(recipient, amount.sub(taxAmount));
super.transfer(taxAddress, taxAmount);
return true;
}
| 3,068,400
|
./full_match/1/0x7132c10A5fDeb8236Be65F451c1973E26E8515EF/sources/contracts/sugartown/SugartownOrasNFT.sol
|
Overriden safeTransferFrom function for operator filtering./
|
function safeTransferFrom(address from, address to, uint256 tokenId) public override onlyAllowedOperator(from) {
super.safeTransferFrom(from, to, tokenId);
}
| 3,072,400
|
./partial_match/42/0x5bFa399a5a2c6d20192b4Fa4704D38bAF5e241B4/sources/H2OChef.sol
|
Deposit LP tokens to MasterChef for PICKLE allocation.
|
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user
.amount
.mul(pool.accWaterPerShare)
.div(1e12)
.sub(user.rewardDebt);
safeWaterTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accWaterPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
| 3,354,119
|
./full_match/80001/0xf416854209769796f3367c785A3F155a9fe2D6B7/sources/@uniswap/v3-periphery/contracts/libraries/PoolAddress.sol
|
Deterministically computes the pool address given the factory and PoolKey factory The Uniswap V3 factory contract address key The PoolKey return pool The contract address of the V3 pool Convert to bytes20 and then to address
|
function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
require(key.token0 < key.token1);
bytes32 salt = keccak256(abi.encode(key.token0, key.token1, key.fee));
bytes32 rawAddress = keccak256(
abi.encodePacked(
bytes1(0xff),
factory,
salt,
POOL_INIT_CODE_HASH
)
);
pool = address(bytes20(rawAddress << 96));
}
| 5,572,225
|
pragma solidity 0.4.26;
import '../utility/ContractRegistryClient.sol';
import './interfaces/IBancorConverterRegistry.sol';
import './interfaces/IBancorConverterRegistryData.sol';
import '../token/interfaces/ISmartToken.sol';
import '../token/interfaces/ISmartTokenController.sol';
/**
* @dev The BancorConverterRegistry maintains a list of all active converters in the Bancor Network.
*
* Since converters can be upgraded and thus their address can change, the registry actually keeps smart tokens internally and not the converters themselves.
* The active converter for each smart token can be easily accessed by querying the smart token owner.
*
* The registry exposes 3 differnet lists that can be accessed and iterated, based on the use-case of the caller:
* - Smart tokens - can be used to get all the latest / historical data in the network
* - Liquidity pools - can be used to get all liquidity pools for funding, liquidation etc.
* - Convertible tokens - can be used to get all tokens that can be converted in the network (excluding pool
* tokens), and for each one - all smart tokens that hold it in their reserves
*
*
* The contract fires events whenever one of the primitives is added to or removed from the registry
*
* The contract is upgradable.
*/
contract BancorConverterRegistry is IBancorConverterRegistry, ContractRegistryClient {
/**
* @dev triggered when a smart token is added to the registry
*
* @param _smartToken smart token
*/
event SmartTokenAdded(address indexed _smartToken);
/**
* @dev triggered when a smart token is removed from the registry
*
* @param _smartToken smart token
*/
event SmartTokenRemoved(address indexed _smartToken);
/**
* @dev triggered when a liquidity pool is added to the registry
*
* @param _liquidityPool liquidity pool
*/
event LiquidityPoolAdded(address indexed _liquidityPool);
/**
* @dev triggered when a liquidity pool is removed from the registry
*
* @param _liquidityPool liquidity pool
*/
event LiquidityPoolRemoved(address indexed _liquidityPool);
/**
* @dev triggered when a convertible token is added to the registry
*
* @param _convertibleToken convertible token
* @param _smartToken associated smart token
*/
event ConvertibleTokenAdded(address indexed _convertibleToken, address indexed _smartToken);
/**
* @dev triggered when a convertible token is removed from the registry
*
* @param _convertibleToken convertible token
* @param _smartToken associated smart token
*/
event ConvertibleTokenRemoved(address indexed _convertibleToken, address indexed _smartToken);
/**
* @dev initializes a new BancorConverterRegistry instance
*
* @param _registry address of a contract registry contract
*/
constructor(IContractRegistry _registry) ContractRegistryClient(_registry) public {
}
/**
* @dev adds a converter to the registry
* anyone can add a converter to the registry, as long as the converter is active and valid
* note that a liquidity pool converter can be added only if no converter with the same reserve-configuration is already registered
*
* @param _converter converter
*/
function addConverter(IBancorConverter _converter) external {
// validate input
require(isConverterValid(_converter) && !isSimilarLiquidityPoolRegistered(_converter));
IBancorConverterRegistryData converterRegistryData = IBancorConverterRegistryData(addressOf(BANCOR_CONVERTER_REGISTRY_DATA));
ISmartToken token = ISmartTokenController(_converter).token();
uint reserveTokenCount = _converter.connectorTokenCount();
// add the smart token
addSmartToken(converterRegistryData, token);
if (reserveTokenCount > 1)
addLiquidityPool(converterRegistryData, token);
else
addConvertibleToken(converterRegistryData, token, token);
// add all reserve tokens
for (uint i = 0; i < reserveTokenCount; i++)
addConvertibleToken(converterRegistryData, _converter.connectorTokens(i), token);
}
/**
* @dev removes a converter from the registry
* anyone can remove invalid or inactive converters from the registry
* note that the owner can also remove valid converters
*
* @param _converter converter
*/
function removeConverter(IBancorConverter _converter) external {
// validate input
require(msg.sender == owner || !isConverterValid(_converter));
IBancorConverterRegistryData converterRegistryData = IBancorConverterRegistryData(addressOf(BANCOR_CONVERTER_REGISTRY_DATA));
ISmartToken token = ISmartTokenController(_converter).token();
uint reserveTokenCount = _converter.connectorTokenCount();
// remove the smart token
removeSmartToken(converterRegistryData, token);
if (reserveTokenCount > 1)
removeLiquidityPool(converterRegistryData, token);
else
removeConvertibleToken(converterRegistryData, token, token);
// remove all reserve tokens
for (uint i = 0; i < reserveTokenCount; i++)
removeConvertibleToken(converterRegistryData, _converter.connectorTokens(i), token);
}
/**
* @dev returns the number of smart tokens in the registry
*
* @return number of smart tokens
*/
function getSmartTokenCount() external view returns (uint) {
return IBancorConverterRegistryData(addressOf(BANCOR_CONVERTER_REGISTRY_DATA)).getSmartTokenCount();
}
/**
* @dev returns the list of smart tokens in the registry
*
* @return list of smart tokens
*/
function getSmartTokens() external view returns (address[]) {
return IBancorConverterRegistryData(addressOf(BANCOR_CONVERTER_REGISTRY_DATA)).getSmartTokens();
}
/**
* @dev returns the smart token at a given index
*
* @param _index index
* @return smart token at the given index
*/
function getSmartToken(uint _index) external view returns (address) {
return IBancorConverterRegistryData(addressOf(BANCOR_CONVERTER_REGISTRY_DATA)).getSmartToken(_index);
}
/**
* @dev checks whether or not a given value is a smart token
*
* @param _value value
* @return true if the given value is a smart token, false if not
*/
function isSmartToken(address _value) external view returns (bool) {
return IBancorConverterRegistryData(addressOf(BANCOR_CONVERTER_REGISTRY_DATA)).isSmartToken(_value);
}
/**
* @dev returns the number of liquidity pools in the registry
*
* @return number of liquidity pools
*/
function getLiquidityPoolCount() external view returns (uint) {
return IBancorConverterRegistryData(addressOf(BANCOR_CONVERTER_REGISTRY_DATA)).getLiquidityPoolCount();
}
/**
* @dev returns the list of liquidity pools in the registry
*
* @return list of liquidity pools
*/
function getLiquidityPools() external view returns (address[]) {
return IBancorConverterRegistryData(addressOf(BANCOR_CONVERTER_REGISTRY_DATA)).getLiquidityPools();
}
/**
* @dev returns the liquidity pool at a given index
*
* @param _index index
* @return liquidity pool at the given index
*/
function getLiquidityPool(uint _index) external view returns (address) {
return IBancorConverterRegistryData(addressOf(BANCOR_CONVERTER_REGISTRY_DATA)).getLiquidityPool(_index);
}
/**
* @dev checks whether or not a given value is a liquidity pool
*
* @param _value value
* @return true if the given value is a liquidity pool, false if not
*/
function isLiquidityPool(address _value) external view returns (bool) {
return IBancorConverterRegistryData(addressOf(BANCOR_CONVERTER_REGISTRY_DATA)).isLiquidityPool(_value);
}
/**
* @dev returns the number of convertible tokens in the registry
*
* @return number of convertible tokens
*/
function getConvertibleTokenCount() external view returns (uint) {
return IBancorConverterRegistryData(addressOf(BANCOR_CONVERTER_REGISTRY_DATA)).getConvertibleTokenCount();
}
/**
* @dev returns the list of convertible tokens in the registry
*
* @return list of convertible tokens
*/
function getConvertibleTokens() external view returns (address[]) {
return IBancorConverterRegistryData(addressOf(BANCOR_CONVERTER_REGISTRY_DATA)).getConvertibleTokens();
}
/**
* @dev returns the convertible token at a given index
*
* @param _index index
* @return convertible token at the given index
*/
function getConvertibleToken(uint _index) external view returns (address) {
return IBancorConverterRegistryData(addressOf(BANCOR_CONVERTER_REGISTRY_DATA)).getConvertibleToken(_index);
}
/**
* @dev checks whether or not a given value is a convertible token
*
* @param _value value
* @return true if the given value is a convertible token, false if not
*/
function isConvertibleToken(address _value) external view returns (bool) {
return IBancorConverterRegistryData(addressOf(BANCOR_CONVERTER_REGISTRY_DATA)).isConvertibleToken(_value);
}
/**
* @dev returns the number of smart tokens associated with a given convertible token
*
* @param _convertibleToken convertible token
* @return number of smart tokens associated with the given convertible token
*/
function getConvertibleTokenSmartTokenCount(address _convertibleToken) external view returns (uint) {
return IBancorConverterRegistryData(addressOf(BANCOR_CONVERTER_REGISTRY_DATA)).getConvertibleTokenSmartTokenCount(_convertibleToken);
}
/**
* @dev returns the list of smart tokens associated with a given convertible token
*
* @param _convertibleToken convertible token
* @return list of smart tokens associated with the given convertible token
*/
function getConvertibleTokenSmartTokens(address _convertibleToken) external view returns (address[]) {
return IBancorConverterRegistryData(addressOf(BANCOR_CONVERTER_REGISTRY_DATA)).getConvertibleTokenSmartTokens(_convertibleToken);
}
/**
* @dev returns the smart token associated with a given convertible token at a given index
*
* @param _index index
* @return smart token associated with the given convertible token at the given index
*/
function getConvertibleTokenSmartToken(address _convertibleToken, uint _index) external view returns (address) {
return IBancorConverterRegistryData(addressOf(BANCOR_CONVERTER_REGISTRY_DATA)).getConvertibleTokenSmartToken(_convertibleToken, _index);
}
/**
* @dev checks whether or not a given value is a smart token of a given convertible token
*
* @param _convertibleToken convertible token
* @param _value value
* @return true if the given value is a smart token of the given convertible token, false if not
*/
function isConvertibleTokenSmartToken(address _convertibleToken, address _value) external view returns (bool) {
return IBancorConverterRegistryData(addressOf(BANCOR_CONVERTER_REGISTRY_DATA)).isConvertibleTokenSmartToken(_convertibleToken, _value);
}
/**
* @dev returns a list of converters for a given list of smart tokens
* this is a utility function that can be used to reduce the number of calls to the contract
*
* @param _smartTokens list of smart tokens
* @return list of converters
*/
function getConvertersBySmartTokens(address[] _smartTokens) external view returns (address[]) {
address[] memory converters = new address[](_smartTokens.length);
for (uint i = 0; i < _smartTokens.length; i++)
converters[i] = ISmartToken(_smartTokens[i]).owner();
return converters;
}
/**
* @dev checks whether or not a given converter is valid
*
* @param _converter converter
* @return true if the given converter is valid, false if not
*/
function isConverterValid(IBancorConverter _converter) public view returns (bool) {
// verify the the smart token has a supply and that the converter is active
ISmartToken token = ISmartTokenController(_converter).token();
if (token.totalSupply() == 0 || token.owner() != address(_converter))
return false;
// verify that the converter holds balance in each of its reserves
uint reserveTokenCount = _converter.connectorTokenCount();
for (uint i = 0; i < reserveTokenCount; i++) {
if (_converter.connectorTokens(i).balanceOf(_converter) == 0)
return false;
}
return true;
}
/**
* @dev searches for a liquidity pool with specific reserve tokens/ratios
*
* @param _reserveTokens reserve tokens
* @param _reserveRatios reserve ratios
* @return the liquidity pool, or zero if no such liquidity pool exists
*/
function getLiquidityPoolByReserveConfig(address[] memory _reserveTokens, uint[] memory _reserveRatios) public view returns (ISmartToken) {
// verify that the input parameters represent a valid liquidity pool
if (_reserveTokens.length == _reserveRatios.length && _reserveTokens.length > 1) {
// get the smart tokens of the least frequent token (optimization)
address[] memory convertibleTokenSmartTokens = getLeastFrequentTokenSmartTokens(_reserveTokens);
// search for a converter with an identical reserve-configuration
for (uint i = 0; i < convertibleTokenSmartTokens.length; i++) {
ISmartToken smartToken = ISmartToken(convertibleTokenSmartTokens[i]);
IBancorConverter converter = IBancorConverter(smartToken.owner());
if (isConverterReserveConfigEqual(converter, _reserveTokens, _reserveRatios))
return smartToken;
}
}
return ISmartToken(0);
}
/**
* @dev checks if a liquidity pool with given reserve tokens/ratios is already registered
*
* @param _converter converter with specific reserve tokens/ratios
* @return if a liquidity pool with the same reserve tokens/ratios is already registered
*/
function isSimilarLiquidityPoolRegistered(IBancorConverter _converter) internal view returns (bool) {
uint reserveTokenCount = _converter.connectorTokenCount();
address[] memory reserveTokens = new address[](reserveTokenCount);
uint[] memory reserveRatios = new uint[](reserveTokenCount);
// get the reserve-configuration of the converter
for (uint i = 0; i < reserveTokenCount; i++) {
IERC20Token reserveToken = _converter.connectorTokens(i);
reserveTokens[i] = reserveToken;
reserveRatios[i] = getReserveRatio(_converter, reserveToken);
}
// return if a liquidity pool with the same reserve tokens/ratios is already registered
return getLiquidityPoolByReserveConfig(reserveTokens, reserveRatios) != ISmartToken(0);
}
/**
* @dev adds a smart token to the registry
*
* @param _smartToken smart token
*/
function addSmartToken(IBancorConverterRegistryData _converterRegistryData, address _smartToken) internal {
_converterRegistryData.addSmartToken(_smartToken);
emit SmartTokenAdded(_smartToken);
}
/**
* @dev removes a smart token from the registry
*
* @param _smartToken smart token
*/
function removeSmartToken(IBancorConverterRegistryData _converterRegistryData, address _smartToken) internal {
_converterRegistryData.removeSmartToken(_smartToken);
emit SmartTokenRemoved(_smartToken);
}
/**
* @dev adds a liquidity pool to the registry
*
* @param _liquidityPool liquidity pool
*/
function addLiquidityPool(IBancorConverterRegistryData _converterRegistryData, address _liquidityPool) internal {
_converterRegistryData.addLiquidityPool(_liquidityPool);
emit LiquidityPoolAdded(_liquidityPool);
}
/**
* @dev removes a liquidity pool from the registry
*
* @param _liquidityPool liquidity pool
*/
function removeLiquidityPool(IBancorConverterRegistryData _converterRegistryData, address _liquidityPool) internal {
_converterRegistryData.removeLiquidityPool(_liquidityPool);
emit LiquidityPoolRemoved(_liquidityPool);
}
/**
* @dev adds a convertible token to the registry
*
* @param _convertibleToken convertible token
* @param _smartToken associated smart token
*/
function addConvertibleToken(IBancorConverterRegistryData _converterRegistryData, address _convertibleToken, address _smartToken) internal {
_converterRegistryData.addConvertibleToken(_convertibleToken, _smartToken);
emit ConvertibleTokenAdded(_convertibleToken, _smartToken);
}
/**
* @dev removes a convertible token from the registry
*
* @param _convertibleToken convertible token
* @param _smartToken associated smart token
*/
function removeConvertibleToken(IBancorConverterRegistryData _converterRegistryData, address _convertibleToken, address _smartToken) internal {
_converterRegistryData.removeConvertibleToken(_convertibleToken, _smartToken);
emit ConvertibleTokenRemoved(_convertibleToken, _smartToken);
}
function getLeastFrequentTokenSmartTokens(address[] memory _tokens) private view returns (address[] memory) {
IBancorConverterRegistryData bancorConverterRegistryData = IBancorConverterRegistryData(addressOf(BANCOR_CONVERTER_REGISTRY_DATA));
// find the token that has the smallest number of smart tokens
uint minSmartTokenCount = bancorConverterRegistryData.getConvertibleTokenSmartTokenCount(_tokens[0]);
address[] memory smartTokens = bancorConverterRegistryData.getConvertibleTokenSmartTokens(_tokens[0]);
for (uint i = 1; i < _tokens.length; i++) {
uint convertibleTokenSmartTokenCount = bancorConverterRegistryData.getConvertibleTokenSmartTokenCount(_tokens[i]);
if (minSmartTokenCount > convertibleTokenSmartTokenCount) {
minSmartTokenCount = convertibleTokenSmartTokenCount;
smartTokens = bancorConverterRegistryData.getConvertibleTokenSmartTokens(_tokens[i]);
}
}
return smartTokens;
}
function isConverterReserveConfigEqual(IBancorConverter _converter, address[] memory _reserveTokens, uint[] memory _reserveRatios) private view returns (bool) {
if (_reserveTokens.length != _converter.connectorTokenCount())
return false;
for (uint i = 0; i < _reserveTokens.length; i++) {
if (_reserveRatios[i] != getReserveRatio(_converter, _reserveTokens[i]))
return false;
}
return true;
}
bytes4 private constant CONNECTORS_FUNC_SELECTOR = bytes4(uint256(keccak256("connectors(address)") >> (256 - 4 * 8)));
function getReserveRatio(address _converter, address _reserveToken) private view returns (uint256) {
uint256[2] memory ret;
bytes memory data = abi.encodeWithSelector(CONNECTORS_FUNC_SELECTOR, _reserveToken);
assembly {
let success := staticcall(
gas, // gas remaining
_converter, // destination address
add(data, 32), // input buffer (starts after the first 32 bytes in the `data` array)
mload(data), // input length (loaded from the first 32 bytes in the `data` array)
ret, // output buffer
64 // output length
)
if iszero(success) {
revert(0, 0)
}
}
return ret[1];
}
}
|
checks if a liquidity pool with given reserve tokens/ratios is already registered _converter converter with specific reserve tokens/ratios return if a liquidity pool with the same reserve tokens/ratios is already registered/ get the reserve-configuration of the converter
|
function isSimilarLiquidityPoolRegistered(IBancorConverter _converter) internal view returns (bool) {
uint reserveTokenCount = _converter.connectorTokenCount();
address[] memory reserveTokens = new address[](reserveTokenCount);
uint[] memory reserveRatios = new uint[](reserveTokenCount);
for (uint i = 0; i < reserveTokenCount; i++) {
IERC20Token reserveToken = _converter.connectorTokens(i);
reserveTokens[i] = reserveToken;
reserveRatios[i] = getReserveRatio(_converter, reserveToken);
}
}
| 14,018,074
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @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 {
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* 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_;
}
/**
* @dev Returns the name of the token.
*/
function name() external view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external 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 this function is
* overloaded;
*
* 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 virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() external view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) external 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) external virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) external 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) external 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) external virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) external virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) external virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `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 += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
///////////////////////////////////////////////
// QANX STARTS HERE, OPENZEPPELIN CODE ABOVE //
///////////////////////////////////////////////
contract QANX is ERC20 {
// EVENTS TO BE EMITTED UPON LOCKS ARE APPLIED & REMOVED
event LockApplied(address indexed account, uint256 amount, uint32 hardLockUntil, uint32 softLockUntil, uint8 allowedHops);
event LockRemoved(address indexed account);
// INITIALIZE AN ERC20 TOKEN BASED ON THE OPENZEPPELIN VERSION
constructor() ERC20("QANX Token", "QANX") {
// INITIALLY MINT TOTAL SUPPLY TO CREATOR
_mint(_msgSender(), 3333333000 * (10 ** 18));
}
// MAPPING FOR QUANTUM PUBLIC KEY HASHES
mapping (address => bytes32) private _qPubKeyHashes;
// REGISTER QUANTUM PUBLIC KEY HASH OF THE CURRENT ACCOUNT
function setQuantumPubkeyHash(bytes32 qPubKeyHash) external {
_qPubKeyHashes[_msgSender()] = qPubKeyHash;
}
// QUERY A QUANTUM PUBLIC KEY HASH OF A GIVEN ACCOUNT
function getQuantumPubkeyHash(address account) external view virtual returns (bytes32) {
return _qPubKeyHashes[account];
}
// REPRESENTS A LOCK WHICH MIGHT BE APPLIED ON AN ADDRESS
struct Lock {
uint256 tokenAmount; // HOW MANY TOKENS ARE LOCKED
uint32 hardLockUntil; // UNTIL WHEN NO LOCKED TOKENS CAN BE ACCESSED
uint32 softLockUntil; // UNTIL WHEN LOCKED TOKENS CAN BE GRADUALLY RELEASED
uint8 allowedHops; // HOW MANY TRANSFERS LEFT WITH SAME LOCK PARAMS
uint32 lastUnlock; // LAST GRADUAL UNLOCK TIME (SOFTLOCK PERIOD)
uint256 unlockPerSec; // HOW MANY TOKENS ARE UNLOCKABLE EACH SEC FROM HL -> SL
}
// THIS MAPS LOCK PARAMS TO CERTAIN ADDRESSES WHICH RECEIVED LOCKED TOKENS
mapping (address => Lock) private _locks;
// RETURNS LOCK INFORMATION OF A GIVEN ADDRESS
function lockOf(address account) external view virtual returns (Lock memory) {
return _locks[account];
}
// RETURN THE BALANCE OF UNLOCKED AND LOCKED TOKENS COMBINED
function balanceOf(address account) external view virtual override returns (uint256) {
return _balances[account] + _locks[account].tokenAmount;
}
// TRANSFER FUNCTION WITH LOCK PARAMETERS
function transferLocked(address recipient, uint256 amount, uint32 hardLockUntil, uint32 softLockUntil, uint8 allowedHops) external returns (bool) {
// ONLY ONE LOCKED TRANSACTION ALLOWED PER RECIPIENT
require(_locks[recipient].tokenAmount == 0, "Only one lock per address allowed!");
// SENDER MUST HAVE ENOUGH TOKENS (UNLOCKED + LOCKED BALANCE COMBINED)
require(_balances[_msgSender()] + _locks[_msgSender()].tokenAmount >= amount, "Transfer amount exceeds balance");
// IF SENDER HAS ENOUGH UNLOCKED BALANCE, THEN LOCK PARAMS CAN BE CHOSEN
if(_balances[_msgSender()] >= amount){
// DEDUCT SENDER BALANCE
_balances[_msgSender()] = _balances[_msgSender()] - amount;
// APPLY LOCK
return _applyLock(recipient, amount, hardLockUntil, softLockUntil, allowedHops);
}
// OTHERWISE REQUIRE THAT THE CHOSEN LOCK PARAMS ARE SAME / STRICTER (allowedHops) THAN THE SENDER'S
require(
hardLockUntil >= _locks[_msgSender()].hardLockUntil &&
softLockUntil >= _locks[_msgSender()].softLockUntil &&
allowedHops < _locks[_msgSender()].allowedHops
);
// IF SENDER HAS ENOUGH LOCKED BALANCE
if(_locks[_msgSender()].tokenAmount >= amount){
// DECREASE LOCKED BALANCE OF SENDER
_locks[_msgSender()].tokenAmount = _locks[_msgSender()].tokenAmount - amount;
// APPLY LOCK
return _applyLock(recipient, amount, hardLockUntil, softLockUntil, allowedHops);
}
// IF NO CONDITIONS WERE MET SO FAR, DEDUCT FROM THE UNLOCKED BALANCE
_balances[_msgSender()] = _balances[_msgSender()] - (amount - _locks[_msgSender()].tokenAmount);
// THEN SPEND LOCKED BALANCE OF SENDER FIRST
_locks[_msgSender()].tokenAmount = 0;
// APPLY LOCK
return _applyLock(recipient, amount, hardLockUntil, softLockUntil, allowedHops);
}
// APPLIES LOCK TO RECIPIENT WITH SPECIFIED PARAMS AND EMITS A TRANSFER EVENT
function _applyLock(address recipient, uint256 amount, uint32 hardLockUntil, uint32 softLockUntil, uint8 allowedHops) private returns (bool) {
// MAKE SURE THAT SOFTLOCK IS AFTER HARDLOCK
require(softLockUntil > hardLockUntil, "SoftLock must be greater than HardLock!");
// APPLY LOCK, EMIT TRANSFER EVENT
_locks[recipient] = Lock(amount, hardLockUntil, softLockUntil, allowedHops, hardLockUntil, amount / (softLockUntil - hardLockUntil));
emit LockApplied(recipient, amount, hardLockUntil, softLockUntil, allowedHops);
emit Transfer(_msgSender(), recipient, amount);
return true;
}
function lockedBalanceOf(address account) external view virtual returns (uint256) {
return _locks[account].tokenAmount;
}
function unlockedBalanceOf(address account) external view virtual returns (uint256) {
return _balances[account];
}
function unlockableBalanceOf(address account) public view virtual returns (uint256) {
// IF THE HARDLOCK HAS NOT PASSED YET, THERE ARE NO UNLOCKABLE TOKENS
if(block.timestamp < _locks[account].hardLockUntil) {
return 0;
}
// IF THE SOFTLOCK PERIOD PASSED, ALL CURRENTLY TOKENS ARE UNLOCKABLE
if(block.timestamp > _locks[account].softLockUntil) {
return _locks[account].tokenAmount;
}
// OTHERWISE THE PROPORTIONAL AMOUNT IS UNLOCKABLE
return (block.timestamp - _locks[account].lastUnlock) * _locks[account].unlockPerSec;
}
function unlock(address account) external returns (bool) {
// CALCULATE UNLOCKABLE BALANCE
uint256 unlockable = unlockableBalanceOf(account);
// ONLY ADDRESSES OWNING LOCKED TOKENS AND BYPASSED HARDLOCK TIME ARE UNLOCKABLE
require(unlockable > 0 && _locks[account].tokenAmount > 0 && block.timestamp > _locks[account].hardLockUntil, "No unlockable tokens!");
// SET LAST UNLOCK TIME, DEDUCT FROM LOCKED BALANCE & CREDIT TO REGULAR BALANCE
_locks[account].lastUnlock = uint32(block.timestamp);
_locks[account].tokenAmount = _locks[account].tokenAmount - unlockable;
_balances[account] = _balances[account] + unlockable;
// IF NO MORE LOCKED TOKENS LEFT, REMOVE LOCK OBJECT FROM ADDRESS
if(_locks[account].tokenAmount == 0){
delete _locks[account];
emit LockRemoved(account);
}
// UNLOCK SUCCESSFUL
emit Transfer(account, account, unlockable);
return true;
}
}
|
Returns the symbol of the token, usually a shorter version of the name./
|
function symbol() external view virtual returns (string memory) {
return _symbol;
}
| 63,216
|
pragma solidity 0.5.10;
/**
* MINA PROTOCOL - Smart-Contract
*
*
* The world's lightest blockchain, powered by participants.
*
* By design, the entire Mina blockchain is and will always be about 22kb - the size of a couple of tweets.
* So anyone with a smartphone will be able to sync and verify the network in seconds.
*
* About the Tech: https://minaprotocol.com/tech
* Knowledge Base: https://minaprotocol.com/get-started#knowledge-base
*
* Technical Whitepaper: https://minaprotocol.com/static/pdf/technicalWhitepaper.pdf
* Economics Whitepaper: https://minaprotocol.com/static/pdf/economicsWhitepaper.pdf
*
* Mina Protocol-media
* Official Website: https://minaprotocol.com
* Github: https://github.com/MinaProtocol/mina
* Twitter: https://twitter.com/minaprotocol
* Telegram: https://t.me/minaprotocol
* Forums: https://forums.minaprotocol.com/t/mina-protocol-chinese-resources/200
* Discord: https://discord.com/invite/RDQc43H
* Facebook: https://www.facebook.com/Mina-Protocol-108885454193665
* Reddit: https://www.reddit.com/r/MinaProtocol
* Wiki: https://minawiki.com/Main_Page
*/
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error.
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
/**
* @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 internal _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor(address initialOwner) internal {
require(initialOwner != address(0));
_owner = initialOwner;
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner(), "Caller is not the owner");
_;
}
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0), "New owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function balanceOf(address who) external view returns (uint256);
}
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*/
contract ReentrancyGuard {
uint256 private _guardCounter;
constructor () internal {
_guardCounter = 1;
}
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
}
/**
* @title BonusMina interface
*/
interface BonusMina {
function sendBonus(address account, uint256 amount) external;
function RS_changeInterval(uint256 newInterval) external;
function RS_newTicket() external;
function RS_addReferrer(address referrer) external;
function RS_ticketsOf(address player) external view returns(uint256);
function RS_referrerOf(address player) external view returns(address);
function RS_interval() external view returns(uint256);
}
/**
* @title Invest contract.
*/
contract MinaProtocol is ReentrancyGuard, Ownable {
using SafeMath for uint256;
// The token being sold
IERC20 private _token;
// BonusMina contract
BonusMina private _MPBS;
// Address where funds are collected
address payable private _wallet;
// Amount of wei raised
uint256 private _weiRaised;
// Amount of reserved tokens
uint256 private _reserve;
// How many token units a buyer gets per 1 ether
uint256 private _rate = 2e15;
// Minimum amount of wei to invest
uint256 private _minimum = 0.5 ether;
// Token amount set as share
uint256 private _share = 1000000000000000;
// Ref Bonus per share
uint256 private _bonusPerShare = 50000000000000;
// Delay period (UNIX time)
uint256 private _delay;
// User data
mapping (address => User) users;
struct User {
Deposit[] deposits;
uint256 checkpoint;
uint256 reserved;
}
struct Deposit {
uint256 amount;
uint256 endtime;
uint256 delay;
}
// Pause of recieving new deposits
bool public paused;
modifier notPaused() {
require(!paused);
_;
}
// Requiring of being referrer (more than 100 tickets)
bool public refRequired;
// Enable of referral programm
enum ReferrerSystem {OFF, ON}
ReferrerSystem public RS = ReferrerSystem.OFF;
// Sending bonus to referral
bool public referralMode;
// Events
event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount, uint256 delay);
event Withdrawn(address indexed account, uint256 amount);
/**
* @param rate Number of token units a buyer gets per wei
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor(uint256 rate, address payable wallet, IERC20 token, address initialOwner, address MPBSAddr) public Ownable(initialOwner) {
require(rate != 0, "Rate is 0");
require(wallet != address(0), "Wallet is the zero address");
require(address(token) != address(0), "Token is the zero address");
require(MPBSAddr != address(0), "MPBSAddr is the zero address");
_rate = rate;
_wallet = wallet;
_token = token;
_MPBS = BonusMina(MPBSAddr);
}
/**
* @dev fallback function
*/
function() external payable {
if (msg.value > 0) {
buyTokens(msg.sender);
} else {
withdraw();
}
}
/**
* @dev token purchase
* This function has a non-reentrancy guard
* @param beneficiary Recipient of the token purchase
*/
function buyTokens(address beneficiary) public notPaused nonReentrant payable {
require(beneficiary != address(0), "Beneficiary is the zero address");
require(msg.value >= _minimum, "Wei amount is less than minimum");
if (refRequired) {
require(_MPBS.RS_ticketsOf(msg.sender) >= _MPBS.RS_interval());
}
uint256 weiAmount = msg.value;
uint256 tokens = getTokenAmount(weiAmount);
require(tokens <= availableTokens(), "Not enough available tokens");
_weiRaised = _weiRaised.add(weiAmount);
_wallet.transfer(weiAmount);
if (_delay == 0) {
_token.transfer(beneficiary, tokens);
} else {
createDeposit(beneficiary, tokens);
}
if (_MPBS.RS_referrerOf(beneficiary) != address(0)) {
if (RS == ReferrerSystem.ON) {
_MPBS.sendBonus(_MPBS.RS_referrerOf(beneficiary), tokens.div(_share).mul(_bonusPerShare));
if (referralMode) {
_MPBS.sendBonus(beneficiary, tokens.div(_share).mul(_bonusPerShare));
}
}
} else if (msg.data.length == 20) {
addReferrer();
}
emit TokensPurchased(msg.sender, beneficiary, weiAmount, tokens, _delay);
}
/**
* @dev internal invest function
* @param account address of users
* @param amount amount of tokens to deposit
*/
function createDeposit(address account, uint256 amount) internal {
if (getDividends(account) > 0) {
users[account].reserved += getDividends(account);
}
users[account].checkpoint = block.timestamp;
users[account].deposits.push(Deposit(amount, block.timestamp.add(_delay), _delay));
_reserve = _reserve.add(amount);
}
/**
* @dev withdraw available dividens
*/
function withdraw() public {
uint256 payout = getDividends(msg.sender);
if (users[msg.sender].reserved > 0) {
users[msg.sender].reserved = 0;
}
require(payout > 0);
users[msg.sender].checkpoint = block.timestamp;
_token.transfer(msg.sender, payout);
_reserve = _reserve.sub(payout);
emit Withdrawn(msg.sender, payout);
}
/**
* @dev internal addReferrer function
*/
function addReferrer() internal {
address referrer = bytesToAddress(bytes(msg.data));
if (referrer != msg.sender) {
uint256 interval = _MPBS.RS_interval();
_MPBS.RS_changeInterval(0);
_MPBS.RS_addReferrer(referrer);
_MPBS.RS_changeInterval(interval);
}
}
/**
* @dev internal function to convert bytes type to address
*/
function bytesToAddress(bytes memory source) internal pure returns(address parsedReferrer) {
assembly {
parsedReferrer := mload(add(source,0x14))
}
}
/**
* @dev Calculate amount of tokens to recieve for a given amount of wei
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function getTokenAmount(uint256 weiAmount) public view returns(uint256) {
return weiAmount.mul(_rate).div(1e18);
}
/**
* @dev Calculate amount of tokens to recieve for a given account at current time
* @param account Address of user
* @return Number of tokens that can be withdrawn
*/
function getDividends(address account) public view returns(uint256) {
uint256 payout = users[account].reserved;
for (uint256 i = 0; i < users[account].deposits.length; i++) {
if (block.timestamp < users[account].deposits[i].endtime) {
payout += (users[account].deposits[i].amount).mul(block.timestamp.sub(users[account].checkpoint)).div(users[account].deposits[i].delay);
} else if (users[account].checkpoint < users[account].deposits[i].endtime) {
payout += (users[account].deposits[i].amount).mul(users[account].deposits[i].endtime.sub(users[account].checkpoint)).div(users[account].deposits[i].delay);
}
}
return payout;
}
/**
* @dev Function to change the rate.
* Available only to the owner.
* @param newRate new value.
*/
function setRate(uint256 newRate) external onlyOwner {
require(newRate != 0, "New rate is 0");
_rate = newRate;
}
/**
* @dev Function to change the share value
* Available only to the owner.
* @param newShare new value.
*/
function setShare(uint256 newShare) external onlyOwner {
require(newShare != 0, "New share value is 0");
_share = newShare;
}
/**
* @dev Function to change the bonusPerShare value
* Available only to the owner.
* @param newBonus new value.
*/
function setBonus(uint256 newBonus) external onlyOwner {
require(newBonus != 0, "New bonus value is 0");
_bonusPerShare = newBonus;
}
/**
* @dev Function to change the address to receive ether.
* Available only to the owner.
* @param newWallet new address.
*/
function setWallet(address payable newWallet) external onlyOwner {
require(newWallet != address(0), "New wallet is the zero address");
_wallet = newWallet;
}
/**
* @dev Function to change the delay period of recieving tokens.
* Available only to the owner.
* @param newDelay new value (UNIX time).
*/
function setDelayPeriod(uint256 newDelay) external onlyOwner {
_delay = newDelay;
}
/**
* @dev Function to change the minimum amount (wei).
* Available only to the owner.
* @param newMinimum new minimum value (wei).
*/
function setMinimum(uint256 newMinimum) external onlyOwner {
require(newMinimum != 0, "New parameter value is 0");
_minimum = newMinimum;
}
/**
* @dev Function to pause recieving of deposits.
* Available only to the owner.
*/
function pause() external onlyOwner {
require(!paused);
paused = true;
}
/**
* @dev Function to unpause recieving of deposits.
* Available only to the owner.
*/
function unpause() external onlyOwner {
require(paused);
paused = false;
}
/**
* @dev Function to switch if referrer is required.
* Available only to the owner.
*/
function switchRefSys() external onlyOwner {
if (RS == ReferrerSystem.ON) {
RS = ReferrerSystem.OFF;
} else {
RS = ReferrerSystem.ON;
}
}
/**
* @dev Function to switch the requiring of being referrer
* Available only to the owner.
*/
function switchRequiringOfRef() external onlyOwner {
if (refRequired == true) {
refRequired = false;
} else {
refRequired = true;
}
}
/**
* @dev Function to switch if referral gets bonus
* Available only to the owner.
*/
function switchReferralMode() external onlyOwner {
if (referralMode == true) {
referralMode = false;
} else {
referralMode = true;
}
}
/**
* @dev Allows to withdraw needed ERC20 token from this contract (promo or bounties for example).
* Available only to the owner.
* @param ERC20Token Address of ERC20 token.
* @param recipient Account to receive tokens.
*/
function withdrawERC20(address ERC20Token, address recipient) external onlyOwner {
uint256 amount = IERC20(ERC20Token).balanceOf(address(this));
IERC20(ERC20Token).transfer(recipient, amount);
}
/**
* @return the token being sold.
*/
function token() public view returns (IERC20) {
return _token;
}
/**
* @return address of BonusMina.
*/
function MPBS() public view returns (BonusMina) {
return _MPBS;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns (address payable) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns (uint256) {
return _rate;
}
/**
* @return the number of token set as share.
*/
function share() public view returns (uint256) {
return _share;
}
/**
* @return the number of token units a referrer gets per share.
*/
function bonusPerShare() public view returns (uint256) {
return _bonusPerShare;
}
/**
* @return minimum amount of wei to invest.
*/
function minimum() public view returns (uint256) {
return _minimum;
}
/**
* @return the amount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @return the amount of reserved tokens.
*/
function availableTokens() public view returns (uint256) {
if (_token.balanceOf(address(this)) > _reserve) {
return _token.balanceOf(address(this)).sub(_reserve);
} else {
return 0;
}
}
/**
* @return the amount of reserved tokens.
*/
function reserved() public view returns (uint256) {
return _reserve;
}
/**
* @return delay time (UNIX time).
*/
function delay() public view returns (uint256) {
return _delay;
}
}
|
Calculate amount of tokens to recieve for a given amount of wei weiAmount Value in wei to be converted into tokens return Number of tokens that can be purchased with the specified _weiAmount/
|
function getTokenAmount(uint256 weiAmount) public view returns(uint256) {
return weiAmount.mul(_rate).div(1e18);
}
| 310,707
|
./full_match/5/0x999512dC124371E6B9ff43CE8D1AF83252F0C851/sources/src/BaseVault.sol
|
Returns the amounts that can be redeemed for an user on the round. round The round. user The user. return amountX The amount of token X that can be redeemed. return amountY The amount of token Y that can be redeemed./ Get the queued withdrawal of the round. Get the total amount of tokens that were queued for the round. Get the shares that were queued for the user and the total of shares. Calculate the amounts to be redeemed.
|
function getRedeemableAmounts(uint256 round, address user)
public
view
virtual
override
returns (uint256 amountX, uint256 amountY)
{
QueuedWithdrawal storage queuedWithdrawal = _queuedWithdrawalsByRound[round];
uint256 totalAmountX = queuedWithdrawal.totalAmountX;
uint256 totalAmountY = queuedWithdrawal.totalAmountY;
uint256 shares = queuedWithdrawal.userWithdrawals[user];
uint256 totalShares = queuedWithdrawal.totalQueuedShares;
if (totalShares > 0) {
amountX = totalAmountX.mulDivRoundDown(shares, totalShares);
amountY = totalAmountY.mulDivRoundDown(shares, totalShares);
}
}
| 1,894,033
|
pragma solidity ^0.5.1;
interface ERC20 {
function BALANCEOF565(address _owner) external view returns (uint256); //inject NONSTANDARD NAMING
function ALLOWANCE851(address _owner, address _spender) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER334(address _to, uint256 _value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM87(address _from, address _to, uint256 _value) external returns (bool); //inject NONSTANDARD NAMING
function APPROVE782(address _spender, uint256 _value) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER933(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL210(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeMath {
function MUL1000(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function DIV822(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a / b;
return c;
}
function SUB660(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
assert(b <= a);
return a - b;
}
function ADD287(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract RIX is ERC20 {
using SafeMath for uint256;
address private deployer;
string public name = "rix.finance";
string public symbol = "RIXF";
uint8 public constant decimals308 = 2; //inject NONSTANDARD NAMING
uint256 public constant decimalfactor692 = 10 ** uint256(decimals308); //inject NONSTANDARD NAMING
uint256 public constant totalsupply945 = 1500 * decimalfactor692; //inject NONSTANDARD NAMING
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
event TRANSFER933(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL210(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
constructor() public {
balances[msg.sender] = totalsupply945;
deployer = msg.sender;
emit TRANSFER933(address(0), msg.sender, totalsupply945);
}
function BALANCEOF565(address _owner) public view returns (uint256 balance) { //inject NONSTANDARD NAMING
return balances[_owner];
}
function ALLOWANCE851(address _owner, address _spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return allowed[_owner][_spender];
}
function TRANSFER334(address _to, uint256 _value) public returns (bool) { //inject NONSTANDARD NAMING
require(_to != address(0));
require(_value <= balances[msg.sender]);
require(block.timestamp >= 1545102693);
balances[msg.sender] = balances[msg.sender].SUB660(_value);
balances[_to] = balances[_to].ADD287(_value);
emit TRANSFER933(msg.sender, _to, _value);
return true;
}
function TRANSFERFROM87(address _from, address _to, uint256 _value) public returns (bool) { //inject NONSTANDARD NAMING
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(block.timestamp >= 1545102693);
balances[_from] = balances[_from].SUB660(_value);
balances[_to] = balances[_to].ADD287(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].SUB660(_value);
emit TRANSFER933(_from, _to, _value);
return true;
}
function APPROVE782(address _spender, uint256 _value) public returns (bool) { //inject NONSTANDARD NAMING
allowed[msg.sender][_spender] = _value;
emit APPROVAL210(msg.sender, _spender, _value);
return true;
}
function INCREASEAPPROVAL326(address _spender, uint _addedValue) public returns (bool) { //inject NONSTANDARD NAMING
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].ADD287(_addedValue);
emit APPROVAL210(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function DECREASEAPPROVAL424(address _spender, uint _subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.SUB660(_subtractedValue);
}
emit APPROVAL210(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
|
inject NONSTANDARD NAMING
|
function MUL1000(uint256 a, uint256 b) internal pure returns (uint256) {
| 13,119,262
|
// 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/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/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: contracts/library/NameFilter.sol
pragma solidity 0.6.12;
library NameFilter {
/**
* @dev filters name strings
* -converts uppercase to lower case.
* -makes sure it does not start/end with a space
* -makes sure it does not contain multiple spaces in a row
* -cannot be only numbers
* -cannot start with 0x
* -restricts characters to A-Z, a-z, 0-9, and space.
* @return reprocessed string in bytes32 format
*/
function nameFilter(string memory _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//sorry limited to 32 characters
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
// make sure first two characters are not 0x
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
// create a bool to track if we have a non number character
bool _hasNonNumber;
// convert & check
for (uint256 i = 0; i < _length; i++)
{
// if its uppercase A-Z
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
// convert to lower case a-z
_temp[i] = byte(uint8(_temp[i]) + 32);
// we have a non number
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
// OR lowercase a-z
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
// or 0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
// see if we have a character other than a number
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
// File: contracts/library/Governance.sol
pragma solidity 0.6.12;
contract Governance {
address public _governance;
constructor() public {
_governance = tx.origin;
}
event GovernanceTransferred(address indexed previousOwner, address indexed newOwner);
modifier onlyGovernance {
require(msg.sender == _governance, "not governance");
_;
}
function setGovernance(address governance) public onlyGovernance
{
require(governance != address(0), "new governance the zero address");
emit GovernanceTransferred(_governance, governance);
_governance = governance;
}
}
// File: contracts/interface/IPlayerBook.sol
pragma solidity 0.6.12;
interface IPlayerBook {
function settleReward( address from,uint256 amount ) external returns (uint256);
function bindRefer( address from,string calldata affCode ) external returns (bool);
function hasRefer(address from) external returns(bool);
function getPlayerLaffAddress(address from) external returns(address);
}
// File: contracts/PlayerBook.sol
pragma solidity 0.6.12;
// import '@openzeppelin/contracts/ownership/Ownable.sol';
// import "../library/SafeERC20.sol";
contract PlayerBook is Governance {
using NameFilter for string;
using SafeMath for uint256;
using SafeERC20 for IERC20;
// register pools
mapping (address => bool) public _pools;
// (addr => pID) returns player id by address
mapping (address => uint256) public _pIDxAddr;
// (name => pID) returns player id by name
mapping (bytes32 => uint256) public _pIDxName;
// (pID => data) player data
mapping (uint256 => Player) public _plyr;
// (pID => name => bool) list of names a player owns. (used so you can change your display name amoungst any name you own)
mapping (uint256 => mapping (bytes32 => bool)) public _plyrNames;
// total number of players
uint256 public _pID;
// total register name count
uint256 public _totalRegisterCount = 0;
// the direct refer's reward rate 直接推荐人的奖励率
uint256 public _referRewardRate = 1000; //10%
// base rate
uint256 public _baseRate = 10000;
// base price to register a name
uint256 public _registrationBaseFee = 10 finney;
// register fee count step
uint256 public _registrationStep = 100;
// add base price for one step
uint256 public _stepFee = 10 finney;
bytes32 public _defaulRefer = "hbt";
address payable public _teamWallet;
struct Player {
address addr;
bytes32 name;
uint8 nameCount;
uint256 laff;
uint256 lvCount;
}
event eveBindRefer(uint256 pID, address addr, bytes32 name, uint256 affID, address affAddr, bytes32 affName);
event eveDefaultPlayer(uint256 pID, address addr, bytes32 name);
event eveNewName(uint256 pID, address addr, bytes32 name, uint256 affID, address affAddr, bytes32 affName, uint256 balance );
event eveAddPool(address addr);
event eveRemovePool(address addr);
constructor(address payable teamWallet)
public
{
_pID = 0;
_teamWallet = teamWallet;
addDefaultPlayer(_teamWallet,_defaulRefer);
}
/**
* check address
*/
modifier validAddress( address addr ) {
require(addr != address(0x0));
_;
}
/**
* check pool
*/
modifier isRegisteredPool(){
require(_pools[msg.sender],"invalid pool address!");
_;
}
// only function for creating additional rewards from dust
function seize(IERC20 asset) external returns (uint256 balance) {
balance = asset.balanceOf(address(this));
asset.safeTransfer(_teamWallet, balance);
}
// get register fee
function seizeEth() external {
uint256 _currentBalance = address(this).balance;
_teamWallet.transfer(_currentBalance);
}
/**
* revert invalid transfer action
*/
fallback() external payable {
revert();
}
receive() external payable {
revert();
}
/**
* registe a pool
*/
function addPool(address poolAddr)
onlyGovernance
public
{
require( !_pools[poolAddr], "derp, that pool already been registered");
_pools[poolAddr] = true;
emit eveAddPool(poolAddr);
}
/**
* remove a pool
*/
function removePool(address poolAddr)
onlyGovernance
public
{
require( _pools[poolAddr], "derp, that pool must be registered");
_pools[poolAddr] = false;
emit eveRemovePool(poolAddr);
}
/**
* check name string
* 查询某个名字是否可以注册
*/
function checkIfNameValid(string memory nameStr)
public
view
returns(bool)
{
bytes32 name = nameStr.nameFilter();
if (_pIDxName[name] == 0)
return (true);
else
return (false);
}
/**
* @dev add a default player
*/
function addDefaultPlayer(address addr, bytes32 name)
private
{
_pID++;
_plyr[_pID].addr = addr;
_plyr[_pID].name = name;
_plyr[_pID].nameCount = 1;
_pIDxAddr[addr] = _pID;
_pIDxName[name] = _pID;
_plyrNames[_pID][name] = true;
//fire event
emit eveDefaultPlayer(_pID,addr,name);
}
/**
* @dev set refer reward rate
*/
function setReferRewardRate(uint256 referRate) public
onlyGovernance
{
_referRewardRate = referRate;
}
/**
* @dev set registration step count
*/
function setRegistrationStep(uint256 registrationStep) public
onlyGovernance
{
_registrationStep = registrationStep;
}
/**
* @dev registers a name. UI will always display the last name you registered.
* but you will still own all previously registered names to use as affiliate
* links.
* - must pay a registration fee.
* - name must be unique
* - names will be converted to lowercase
* - cannot be only numbers
* - cannot start with 0x
* - name must be at least 1 char
* - max length of 32 characters long
* - allowed characters: a-z, 0-9
* -functionhash- 0x921dec21 (using ID for affiliate)
* -functionhash- 0x3ddd4698 (using address for affiliate)
* -functionhash- 0x685ffd83 (using name for affiliate)
* @param nameString players desired name
* @param affCode affiliate name of who refered you
* (this might cost a lot of gas)
*/
/**
参数类型:(string memory nameString, string memory affCode) //自己的名字,邀请人的名字
说明:如果邀请人的名字为“”意味着没有邀请者
每一次注册是需要支付手续费的,【0,99)号用户收取100 finney,【100,199)200 ~
*/
function registerNameXName(string memory nameString, string memory affCode)
public
payable
{
// make sure name fees paid
require (msg.value >= this.getRegistrationFee(), "umm..... you have to pay the name fee");
// filter name + condition checks
bytes32 name = NameFilter.nameFilter(nameString);
// if names already has been used
require(_pIDxName[name] == 0, "sorry that names already taken");
// set up address
address addr = msg.sender;
// set up our tx event data and determine if player is new or not
_determinePID(addr);
// fetch player id
uint256 pID = _pIDxAddr[addr];
// if names already has been used
require(_plyrNames[pID][name] == false, "sorry that names already taken");
// add name to player profile, registry, and name book
_plyrNames[pID][name] = true;
_pIDxName[name] = pID;
_plyr[pID].name = name;
_plyr[pID].nameCount++;
_totalRegisterCount++;
//try bind a refer
if(_plyr[pID].laff == 0){
bytes memory tempCode = bytes(affCode);
bytes32 affName = 0x0;
if (tempCode.length >= 0) {
assembly {
affName := mload(add(tempCode, 32))
}
}
_bindRefer(addr,affName);
}
uint256 affID = _plyr[pID].laff;
// fire event
emit eveNewName(pID, addr, name, affID, _plyr[affID].addr, _plyr[affID].name, _registrationBaseFee );
}
/**
* @dev bind a refer,if affcode invalid, use default refer
*/
function bindRefer( address from, string calldata affCode )
isRegisteredPool()
external
// override
returns (bool)
{
bytes memory tempCode = bytes(affCode);
bytes32 affName = 0x0;
if (tempCode.length >= 0) {
assembly {
affName := mload(add(tempCode, 32))
}
}
return _bindRefer(from, affName);
}
/**
* @dev bind a refer,if affcode invalid, use default refer
*/
function _bindRefer( address from, bytes32 name )
validAddress(msg.sender)
validAddress(from)
private
returns (bool)
{
// set up our tx event data and determine if player is new or not
_determinePID(from);
// fetch player id
uint256 pID = _pIDxAddr[from];
if( _plyr[pID].laff != 0){
return false;
}
if (_pIDxName[name] == 0){
//unregister name
name = _defaulRefer;
}
uint256 affID = _pIDxName[name];
if( affID == pID){
affID = _pIDxName[_defaulRefer];
}
_plyr[pID].laff = affID;
//lvcount
_plyr[affID].lvCount++;
// fire event
emit eveBindRefer(pID, from, name, affID, _plyr[affID].addr, _plyr[affID].name);
return true;
}
//
function _determinePID(address addr)
private
returns (bool)
{
if (_pIDxAddr[addr] == 0)
{
_pID++;
_pIDxAddr[addr] = _pID;
_plyr[_pID].addr = addr;
// set the new player bool to true
return (true);
} else {
return (false);
}
}
function hasRefer(address from)
isRegisteredPool()
external
// override
returns(bool)
{
_determinePID(from);
uint256 pID = _pIDxAddr[from];
return (_plyr[pID].laff > 0);
}
//查询某个用户的名字
function getPlayerName(address from)
external
view
returns (bytes32)
{
uint256 pID = _pIDxAddr[from];
if(_pID==0){
return "";
}
return (_plyr[pID].name);
}
//查询某个用户的邀请者地址
function getPlayerLaffAddress(address from) external view returns(address laffAddress) {
uint256 pID = _pIDxAddr[from];
if(_pID==0){
return _teamWallet;
}
uint256 laffID = _plyr[pID].laff;
if(laffID == 0) {
return _teamWallet;
}
return _plyr[laffID].addr;
}
//查询某个用户的邀请者的地址
function getPlayerLaffName(address from)
external
view
returns (bytes32)
{
uint256 pID = _pIDxAddr[from];
if(_pID==0){
return "";
}
uint256 aID=_plyr[pID].laff;
if( aID== 0){
return "";
}
return (_plyr[aID].name);
}
//查询某个用户的id,邀请者id,邀请数量
function getPlayerInfo(address from)
external
view
returns (uint256,uint256,uint256)
{
uint256 pID = _pIDxAddr[from];
if(_pID==0){
return (0,0,0);
}
return (pID,_plyr[pID].laff,_plyr[pID].lvCount);
}
//获取当前注册费用
function getRegistrationFee()
external
view
returns (uint256)
{
if( _totalRegisterCount <_registrationStep || _registrationStep == 0){
return _registrationBaseFee;
}
else{
uint256 step = _totalRegisterCount.div(_registrationStep);
return _registrationBaseFee.add(step.mul(_stepFee));
}
}
}
|
/ make sure name fees paid filter name + condition checks if names already has been used set up address set up our tx event data and determine if player is new or not fetch player id if names already has been used add name to player profile, registry, and name booktry bind a refer
|
function registerNameXName(string memory nameString, string memory affCode)
public
payable
{
require (msg.value >= this.getRegistrationFee(), "umm..... you have to pay the name fee");
bytes32 name = NameFilter.nameFilter(nameString);
require(_pIDxName[name] == 0, "sorry that names already taken");
address addr = msg.sender;
_determinePID(addr);
uint256 pID = _pIDxAddr[addr];
require(_plyrNames[pID][name] == false, "sorry that names already taken");
_plyrNames[pID][name] = true;
_pIDxName[name] = pID;
_plyr[pID].name = name;
_plyr[pID].nameCount++;
_totalRegisterCount++;
if(_plyr[pID].laff == 0){
bytes memory tempCode = bytes(affCode);
bytes32 affName = 0x0;
if (tempCode.length >= 0) {
assembly {
affName := mload(add(tempCode, 32))
}
}
_bindRefer(addr,affName);
}
uint256 affID = _plyr[pID].laff;
}
| 948,495
|
./partial_match/42/0xc3Fa8D75Ec3cb35f6cb7D640FcF1F0318f2cF9d7/sources/StakingRewards.sol
|
called by join when user unlocks his collaterals allowed to call only from join contract (GemJoinWithReward)/
|
function withdraw(
uint256 amount,
address gem,
address usr
) public nonReentrant updateReward(usr) checkFinish checkStart {
require(amount > 0, "Cannot withdraw 0");
require(pairDescs[gem].staker == msg.sender, "Stake from join only allowed");
withdrawLp(amount, gem, usr);
emit Withdrawn(usr, gem, amount);
}
| 8,846,350
|
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.2 <0.9.0;
import "hardhat/console.sol";
contract Auction {
type UserType is uint256;
enum Status {
Pending,
Shipped,
Accepted,
Rejected,
Canceled
}
struct TodoStruct {
string text;
bool completed;
Status status;
}
string internal stateString = "Hello";
bool private stateBool = true;
uint public stateInt = 123;
address payable public stateAddr;
UserType public stateUserType;
Status internal stateEnum = Status.Rejected;
TodoStruct stateStruct;
uint256[] public stateIntArray;
Status[] public stateEnumArray;
UserType[] public stateUserTypeArray;
TodoStruct[] public stateStructArray;
mapping(address => uint) stateSimpleMapping;
mapping(UserType => UserType) stateUserTypeMapping;
mapping(address => string[]) stateNestedArrayMapping;
mapping(address => mapping(address => uint)) stateNestedMapMapping;
event SimpleEvent();
event ArgEvent(address first, uint second);
error SimpleError();
error ArgError(uint first, TodoStruct second, Auction third, Status fourth);
function getText() external view virtual returns (string memory output) {
return "output";
}
function locals() external view virtual returns (uint256) {
string memory localString = this.getText();
bool localBool = true;
uint256 localInt = 456;
address localAddr = msg.sender;
UserType localUserType = UserType.wrap(uint256(456));
Status localEnum = Status.Pending;
TodoStruct memory localStruct;
uint[] memory localIntArray = new uint[](5);
Status[] memory localEnumArray = new Status[](5);
UserType[] memory localUserTypeArray = new UserType[](5);
TodoStruct[] memory localStructArray = new TodoStruct[](5);
// mapping(address => uint) memory localMapping;
// Local Accesses
console.log(localString);
console.log(localBool);
console.log(localInt);
console.log(localAddr);
console.log(UserType.unwrap(localUserType));
console.log(localEnum == Status.Pending);
console.log(localStruct.text);
console.log(localIntArray.length);
console.log(localEnumArray.length);
console.log(localUserTypeArray.length);
console.log(localStructArray.length);
// console.log(localMapping);
return 0;
}
function parameters(
string calldata paramString,
bool paramBool,
uint112 paramInt,
address paramAddr,
UserType paramUserType,
Status paramEnum,
TodoStruct memory paramStruct,
uint144[] storage paramIntArray,
Status[] memory paramEnumArray,
UserType[] calldata paramUserTypeArray,
TodoStruct[] storage paramStructArray,
mapping(address => uint) storage paramSimpleMapping,
mapping(UserType => UserType) storage paramUserTypeMapping,
mapping(address => string[]) storage paramNestedArrayMapping,
mapping(address => mapping(address => uint))
storage paramNestedMapMapping
) internal view virtual returns (uint256) {
// Param Accesses
console.log(paramString);
console.log(paramBool);
console.log(paramInt);
console.log(paramAddr);
console.log(UserType.unwrap(paramUserType));
console.log(paramEnum == Status.Pending);
console.log(paramStruct.text);
console.log(paramIntArray.length);
console.log(paramEnumArray.length);
console.log(paramUserTypeArray.length);
console.log(paramStructArray.length);
console.log(paramSimpleMapping[msg.sender]);
console.log(UserType.unwrap(paramUserTypeMapping[UserType.wrap(123)]));
console.log(paramNestedArrayMapping[msg.sender].length);
console.log(paramNestedMapMapping[msg.sender][msg.sender]);
return 0;
}
function stateVariables() external view virtual returns (uint256) {
// State variable accesses
console.log(stateString);
console.log(stateBool);
console.log(stateInt);
console.log(stateAddr);
console.log(UserType.unwrap(stateUserType));
console.log(stateEnum == Status.Pending);
console.log(stateStruct.text);
console.log(stateIntArray.length);
console.log(stateEnumArray.length);
console.log(stateUserTypeArray.length);
console.log(stateStructArray.length);
console.log(stateSimpleMapping[msg.sender]);
console.log(UserType.unwrap(stateUserTypeMapping[UserType.wrap(123)]));
console.log(stateNestedArrayMapping[msg.sender].length);
console.log(stateNestedMapMapping[msg.sender][msg.sender]);
return 0;
}
}
|
mapping(address => uint) memory localMapping; Local Accesses console.log(localMapping);
|
function locals() external view virtual returns (uint256) {
string memory localString = this.getText();
bool localBool = true;
uint256 localInt = 456;
address localAddr = msg.sender;
UserType localUserType = UserType.wrap(uint256(456));
Status localEnum = Status.Pending;
TodoStruct memory localStruct;
uint[] memory localIntArray = new uint[](5);
Status[] memory localEnumArray = new Status[](5);
UserType[] memory localUserTypeArray = new UserType[](5);
TodoStruct[] memory localStructArray = new TodoStruct[](5);
console.log(localString);
console.log(localBool);
console.log(localInt);
console.log(localAddr);
console.log(UserType.unwrap(localUserType));
console.log(localEnum == Status.Pending);
console.log(localStruct.text);
console.log(localIntArray.length);
console.log(localEnumArray.length);
console.log(localUserTypeArray.length);
console.log(localStructArray.length);
return 0;
}
| 12,967,322
|
pragma solidity ^0.4.24;
// File: libs/EC.sol
contract EC {
uint256 constant public gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798;
uint256 constant public gy = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8;
uint256 constant public n = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;
uint256 constant public a = 0;
uint256 constant public b = 7;
function _jAdd(
uint256 x1, uint256 z1,
uint256 x2, uint256 z2)
public
pure
returns(uint256 x3, uint256 z3)
{
(x3, z3) = (
addmod(
mulmod(z2, x1, n),
mulmod(x2, z1, n),
n
),
mulmod(z1, z2, n)
);
}
function _jSub(
uint256 x1, uint256 z1,
uint256 x2, uint256 z2)
public
pure
returns(uint256 x3, uint256 z3)
{
(x3, z3) = (
addmod(
mulmod(z2, x1, n),
mulmod(n - x2, z1, n),
n
),
mulmod(z1, z2, n)
);
}
function _jMul(
uint256 x1, uint256 z1,
uint256 x2, uint256 z2)
public
pure
returns(uint256 x3, uint256 z3)
{
(x3, z3) = (
mulmod(x1, x2, n),
mulmod(z1, z2, n)
);
}
function _jDiv(
uint256 x1, uint256 z1,
uint256 x2, uint256 z2)
public
pure
returns(uint256 x3, uint256 z3)
{
(x3, z3) = (
mulmod(x1, z2, n),
mulmod(z1, x2, n)
);
}
function _inverse(uint256 val) public pure
returns(uint256 invVal)
{
uint256 t = 0;
uint256 newT = 1;
uint256 r = n;
uint256 newR = val;
uint256 q;
while (newR != 0) {
q = r / newR;
(t, newT) = (newT, addmod(t, (n - mulmod(q, newT, n)), n));
(r, newR) = (newR, r - q * newR );
}
return t;
}
function _ecAdd(
uint256 x1, uint256 y1, uint256 z1,
uint256 x2, uint256 y2, uint256 z2)
public
pure
returns(uint256 x3, uint256 y3, uint256 z3)
{
uint256 lx;
uint256 lz;
uint256 da;
uint256 db;
if (x1 == 0 && y1 == 0) {
return (x2, y2, z2);
}
if (x2 == 0 && y2 == 0) {
return (x1, y1, z1);
}
if (x1 == x2 && y1 == y2) {
(lx, lz) = _jMul(x1, z1, x1, z1);
(lx, lz) = _jMul(lx, lz, 3, 1);
(lx, lz) = _jAdd(lx, lz, a, 1);
(da,db) = _jMul(y1, z1, 2, 1);
} else {
(lx, lz) = _jSub(y2, z2, y1, z1);
(da, db) = _jSub(x2, z2, x1, z1);
}
(lx, lz) = _jDiv(lx, lz, da, db);
(x3, da) = _jMul(lx, lz, lx, lz);
(x3, da) = _jSub(x3, da, x1, z1);
(x3, da) = _jSub(x3, da, x2, z2);
(y3, db) = _jSub(x1, z1, x3, da);
(y3, db) = _jMul(y3, db, lx, lz);
(y3, db) = _jSub(y3, db, y1, z1);
if (da != db) {
x3 = mulmod(x3, db, n);
y3 = mulmod(y3, da, n);
z3 = mulmod(da, db, n);
} else {
z3 = da;
}
}
function _ecDouble(uint256 x1, uint256 y1, uint256 z1) public pure
returns(uint256 x3, uint256 y3, uint256 z3)
{
(x3, y3, z3) = _ecAdd(x1, y1, z1, x1, y1, z1);
}
function _ecMul(uint256 d, uint256 x1, uint256 y1, uint256 z1) public pure
returns(uint256 x3, uint256 y3, uint256 z3)
{
uint256 remaining = d;
uint256 px = x1;
uint256 py = y1;
uint256 pz = z1;
uint256 acx = 0;
uint256 acy = 0;
uint256 acz = 1;
if (d == 0) {
return (0, 0, 1);
}
while (remaining != 0) {
if ((remaining & 1) != 0) {
(acx,acy,acz) = _ecAdd(acx, acy, acz, px, py, pz);
}
remaining = remaining / 2;
(px, py, pz) = _ecDouble(px, py, pz);
}
(x3, y3, z3) = (acx, acy, acz);
}
function ecadd(
uint256 x1, uint256 y1,
uint256 x2, uint256 y2)
public
pure
returns(uint256 x3, uint256 y3)
{
uint256 z;
(x3, y3, z) = _ecAdd(x1, y1, 1, x2, y2, 1);
z = _inverse(z);
x3 = mulmod(x3, z, n);
y3 = mulmod(y3, z, n);
}
function ecmul(uint256 x1, uint256 y1, uint256 scalar) public pure
returns(uint256 x2, uint256 y2)
{
uint256 z;
(x2, y2, z) = _ecMul(scalar, x1, y1, 1);
z = _inverse(z);
x2 = mulmod(x2, z, n);
y2 = mulmod(y2, z, n);
}
function ecmulVerify(uint256 x1, uint256 y1, uint256 scalar, uint256 qx, uint256 qy) public pure
returns(bool)
{
uint256 m = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141;
address signer = ecrecover(0, y1 % 2 != 0 ? 28 : 27, bytes32(x1), bytes32(mulmod(scalar, x1, m)));
address xyAddress = address(uint256(keccak256(abi.encodePacked(qx, qy))) & 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return xyAddress == signer;
}
function publicKey(uint256 privKey) public pure
returns(uint256 qx, uint256 qy)
{
return ecmul(gx, gy, privKey);
}
function publicKeyVerify(uint256 privKey, uint256 x, uint256 y) public pure
returns(bool)
{
return ecmulVerify(gx, gy, privKey, x, y);
}
function deriveKey(uint256 privKey, uint256 pubX, uint256 pubY) public pure
returns(uint256 qx, uint256 qy)
{
uint256 z;
(qx, qy, z) = _ecMul(privKey, pubX, pubY, 1);
z = _inverse(z);
qx = mulmod(qx, z, n);
qy = mulmod(qy, z, n);
}
}
// 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 OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: contracts/Upgradable.sol
contract IUpgradable {
function startUpgrade() public;
function endUpgrade() public;
}
contract Upgradable is Ownable {
struct UpgradableState {
bool isUpgrading;
address prevVersion;
address nextVersion;
}
UpgradableState public upgradableState;
event Initialized(address indexed prevVersion);
event Upgrading(address indexed nextVersion);
event Upgraded(address indexed nextVersion);
modifier isLastestVersion {
require(!upgradableState.isUpgrading);
require(upgradableState.nextVersion == address(0));
_;
}
modifier onlyOwnerOrigin {
require(tx.origin == owner);
_;
}
constructor(address _prevVersion) public {
if (_prevVersion != address(0)) {
require(msg.sender == Ownable(_prevVersion).owner());
upgradableState.isUpgrading = true;
upgradableState.prevVersion = _prevVersion;
IUpgradable(_prevVersion).startUpgrade();
} else {
emit Initialized(_prevVersion);
}
}
function startUpgrade() public onlyOwnerOrigin {
require(msg.sender != owner);
require(!upgradableState.isUpgrading);
require(upgradableState.nextVersion == 0);
upgradableState.isUpgrading = true;
upgradableState.nextVersion = msg.sender;
emit Upgrading(msg.sender);
}
//function upgrade(uint index, uint size) public onlyOwner {}
function endUpgrade() public onlyOwnerOrigin {
require(upgradableState.isUpgrading);
upgradableState.isUpgrading = false;
if (msg.sender != owner) {
require(upgradableState.nextVersion == msg.sender);
emit Upgraded(upgradableState.nextVersion);
}
else {
if (upgradableState.prevVersion != address(0)) {
Upgradable(upgradableState.prevVersion).endUpgrade();
}
emit Initialized(upgradableState.prevVersion);
}
}
}
// File: contracts/VanityLib.sol
contract VanityLib {
uint constant m = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f;
function lengthOfCommonPrefix(bytes32 a, bytes32 b) public pure returns(uint) {
for (uint i = 0; i < 32; i++) {
if (a[i] != b[i] || a[i] == 0) {
return i;
}
}
return 0;
}
function bytesToBytes32(bytes source) public pure returns(bytes32 result) {
assembly {
result := mload(add(source, 32))
}
}
/* Converts given number to base58, limited by 32 symbols */
function toBase58Checked(uint256 _value, byte appCode) public pure returns(bytes32) {
string memory letters = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
bytes memory alphabet = bytes(letters);
uint8 base = 58;
uint8 len = 0;
uint256 remainder = 0;
bool needBreak = false;
bytes memory bytesReversed = bytes(new string(32));
for (uint8 i = 0; true; i++) {
if (_value < base) {
needBreak = true;
}
remainder = _value % base;
_value = uint256(_value / base);
if (len == 32) {
for (uint j = 0; j < len - 1; j++) {
bytesReversed[j] = bytesReversed[j + 1];
}
len--;
}
bytesReversed[len] = alphabet[remainder];
len++;
if (needBreak) {
break;
}
}
// Reverse
bytes memory result = bytes(new string(32));
result[0] = appCode;
for (i = 0; i < 31; i++) {
result[i + 1] = bytesReversed[len - 1 - i];
}
return bytesToBytes32(result);
}
// Create BTC Address: https://en.bitcoin.it/wiki/Technical_background_of_version_1_Bitcoin_addresses#How_to_create_Bitcoin_Address
function createBtcAddressHex(uint256 publicXPoint, uint256 publicYPoint) public pure returns(uint256) {
bytes20 publicKeyPart = ripemd160(abi.encodePacked(sha256(abi.encodePacked(byte(0x04), publicXPoint, publicYPoint))));
bytes32 publicKeyCheckCode = sha256(abi.encodePacked(sha256(abi.encodePacked(byte(0x00), publicKeyPart))));
bytes memory publicKey = new bytes(32);
for (uint i = 0; i < 7; i++) {
publicKey[i] = 0x00;
}
publicKey[7] = 0x00; // Main Network
for (uint j = 0; j < 20; j++) {
publicKey[j + 8] = publicKeyPart[j];
}
publicKey[28] = publicKeyCheckCode[0];
publicKey[29] = publicKeyCheckCode[1];
publicKey[30] = publicKeyCheckCode[2];
publicKey[31] = publicKeyCheckCode[3];
return uint256(bytesToBytes32(publicKey));
}
function createBtcAddress(uint256 publicXPoint, uint256 publicYPoint) public pure returns(bytes32) {
return toBase58Checked(createBtcAddressHex(publicXPoint, publicYPoint), "1");
}
function complexityForBtcAddressPrefix(bytes prefix) public pure returns(uint) {
return complexityForBtcAddressPrefixWithLength(prefix, prefix.length);
}
// https://bitcoin.stackexchange.com/questions/48586
function complexityForBtcAddressPrefixWithLength(bytes prefix, uint length) public pure returns(uint) {
require(prefix.length >= length);
uint8[128] memory unbase58 = [
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 255, 255, 255, 255, 255, 255,
255, 9, 10, 11, 12, 13, 14, 15, 16, 255, 17, 18, 19, 20, 21, 255,
22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 255, 255, 255, 255, 255,
255, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 255, 44, 45, 46,
47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 255, 255, 255, 255, 255
];
uint leadingOnes = countBtcAddressLeadingOnes(prefix, length);
uint256 prefixValue = 0;
uint256 prefix1 = 1;
for (uint i = 0; i < length; i++) {
uint index = uint(prefix[i]);
require(index != 255);
prefixValue = prefixValue * 58 + unbase58[index];
prefix1 *= 58;
}
uint256 top = (uint256(1) << (200 - 8*leadingOnes));
uint256 total = 0;
uint256 prefixMin = prefixValue;
uint256 diff = 0;
for (uint digits = 1; prefix1/58 < (1 << 192); digits++) {
prefix1 *= 58;
prefixMin *= 58;
prefixValue = prefixValue * 58 + 57;
diff = 0;
if (prefixValue >= top) {
diff += prefixValue - top;
}
if (prefixMin < (top >> 8)) {
diff += (top >> 8) - prefixMin;
}
if ((58 ** digits) >= diff) {
total += (58 ** digits) - diff;
}
}
if (prefixMin == 0) { // if prefix is contains only ones: 111111
total = (58 ** (digits - 1)) - diff;
}
return (1 << 192) / total;
}
function countBtcAddressLeadingOnes(bytes prefix, uint length) public pure returns(uint) {
uint leadingOnes = 1;
for (uint j = 0; j < length && prefix[j] == 49; j++) {
leadingOnes = j + 1;
}
return leadingOnes;
}
function isValidBicoinAddressPrefix(bytes prefixArg) public pure returns(bool) {
if (prefixArg.length < 5) {
return false;
}
if (prefixArg[0] != "1" && prefixArg[0] != "3") {
return false;
}
for (uint i = 0; i < prefixArg.length; i++) {
byte ch = prefixArg[i];
if (ch == "0" || ch == "O" || ch == "I" || ch == "l") {
return false;
}
if (!((ch >= "1" && ch <= "9") || (ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z"))) {
return false;
}
}
return true;
}
function isValidPublicKey(uint256 x, uint256 y) public pure returns(bool) {
return (mulmod(y, y, m) == addmod(mulmod(x, mulmod(x, x, m), m), 7, m));
}
}
// 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 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: 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: contracts/TaskRegister.sol
contract TaskRegister is Upgradable, VanityLib {
using SafeMath for uint256;
enum TaskType {
BITCOIN_ADDRESS_PREFIX
}
struct Task {
TaskType taskType;
uint256 taskId;
address creator;
address referrer;
uint256 reward;
bytes32 data;
uint256 dataLength;
uint256 requestPublicXPoint;
uint256 requestPublicYPoint;
uint256 answerPrivateKey;
}
EC public ec;
uint256 public nextTaskId = 1;
uint256 public totalReward;
uint256 constant public MAX_PERCENT = 1000000;
uint256 public serviceFee; // 1% == 10000, 100% == 1000000
uint256 public referrerFee; // Calculated from service fee, 50% == 500000
Task[] public tasks;
Task[] public completedTasks;
mapping(uint256 => uint) public indexOfTaskId; // Starting from 1
event TaskCreated(uint256 indexed taskId);
event TaskSolved(uint256 indexed taskId, uint256 reward);
event TaskPayed(uint256 indexed taskId, uint256 value);
constructor(address _ec, address _prevVersion) public Upgradable(_prevVersion) {
ec = EC(_ec);
}
function setServiceFee(uint256 _serviceFee) public onlyOwner {
require(_serviceFee < 20000); // 2% of reward
serviceFee = _serviceFee;
}
function setReferrerFee(uint256 _referrerFee) public onlyOwner {
require(_referrerFee < 50000); // 50% of serviceFee
referrerFee = _referrerFee;
}
function upgrade(uint _size) public onlyOwner {
require(upgradableState.isUpgrading);
require(upgradableState.prevVersion != 0);
// Migrate some vars
nextTaskId = TaskRegister(upgradableState.prevVersion).nextTaskId();
totalReward = TaskRegister(upgradableState.prevVersion).totalReward();
//TODO: uncomment for the next version
//serviceFee = TaskRegister(upgradableState.prevVersion).serviceFee();
//referrerFee = TaskRegister(upgradableState.prevVersion).referrerFee();
uint index = tasks.length;
uint tasksCount = TaskRegister(upgradableState.prevVersion).tasksCount();
// Migrate tasks
for (uint i = index; i < index + _size && i < tasksCount; i++) {
tasks.push(Task(TaskType.BITCOIN_ADDRESS_PREFIX,0,0,0,0,bytes32(0),0,0,0,0));
}
for (uint j = index; j < index + _size && j < tasksCount; j++) {
(
tasks[j].taskType,
tasks[j].taskId,
tasks[j].creator,
tasks[j].referrer,
,//tasks[j].reward,
,//tasks[j].data,
,//tasks[j].dataLength,
,//tasks[j].requestPublicXPoint,
,//tasks[j].requestPublicYPoint,
//tasks[j].answerPrivateKey
) = TaskRegister(upgradableState.prevVersion).tasks(j);
indexOfTaskId[tasks[j].taskId] = j + 1;
}
for (j = index; j < index + _size && j < tasksCount; j++) {
(
,//tasks[j].taskType,
,//tasks[j].taskId,
,//tasks[j].creator,
,//tasks[j].referrer,
tasks[j].reward,
tasks[j].data,
tasks[j].dataLength,
tasks[j].requestPublicXPoint,
,//tasks[j].requestPublicYPoint,
//tasks[j].answerPrivateKey
) = TaskRegister(upgradableState.prevVersion).tasks(j);
}
for (j = index; j < index + _size && j < tasksCount; j++) {
(
,//tasks[j].taskType,
,//tasks[j].taskId,
,//tasks[j].creator,
,//tasks[j].referrer,
,//tasks[j].reward,
,//tasks[j].data,
,//tasks[j].dataLength,
,//tasks[j].requestPublicXPoint,
tasks[j].requestPublicYPoint,
tasks[j].answerPrivateKey
) = TaskRegister(upgradableState.prevVersion).tasks(j);
}
}
function endUpgrade() public {
super.endUpgrade();
}
function tasksCount() public view returns(uint) {
return tasks.length;
}
function completedTasksCount() public view returns(uint) {
return completedTasks.length;
}
function payForTask(uint256 _taskId) payable public isLastestVersion {
if (msg.value > 0) {
Task storage task = tasks[safeIndexOfTaskId(_taskId)];
task.reward = task.reward.add(msg.value);
totalReward = totalReward.add(msg.value);
emit TaskPayed(_taskId, msg.value);
}
}
function safeIndexOfTaskId(uint _taskId) public view returns(uint) {
return indexOfTaskId[_taskId].sub(1);
}
function createBitcoinAddressPrefixTask(
bytes prefix,
uint256 requestPublicXPoint,
uint256 requestPublicYPoint,
address referrer
)
payable
public
isLastestVersion
{
require(prefix.length > 5);
require(prefix[0] == "1");
require(prefix[1] != "1"); // Do not support multiple 1s yet
require(isValidBicoinAddressPrefix(prefix));
require(isValidPublicKey(requestPublicXPoint, requestPublicYPoint));
bytes32 data;
assembly {
data := mload(add(prefix, 32))
}
Task memory task = Task({
taskType: TaskType.BITCOIN_ADDRESS_PREFIX,
taskId: nextTaskId++,
creator: msg.sender,
referrer: referrer,
reward: 0,
data: data,
dataLength: prefix.length,
requestPublicXPoint: requestPublicXPoint,
requestPublicYPoint: requestPublicYPoint,
answerPrivateKey: 0
});
indexOfTaskId[task.taskId] = tasks.push(task); // incremented to avoid 0 index
emit TaskCreated(task.taskId);
payForTask(task.taskId);
}
function solveTask(uint _taskId, uint256 _answerPrivateKey, uint256 publicXPoint, uint256 publicYPoint) public isLastestVersion {
uint taskIndex = safeIndexOfTaskId(_taskId);
Task storage task = tasks[taskIndex];
require(task.answerPrivateKey == 0, "solveTask: task is already solved");
// Require private key to be part of address to prevent front-running attack
require(_answerPrivateKey >> 128 == uint256(msg.sender) >> 32, "solveTask: this solution does not match miner address");
if (task.taskType == TaskType.BITCOIN_ADDRESS_PREFIX) {
///(publicXPoint, publicYPoint) = ec.publicKey(_answerPrivateKey);
require(ec.publicKeyVerify(_answerPrivateKey, publicXPoint, publicYPoint));
(publicXPoint, publicYPoint) = ec.ecadd(
task.requestPublicXPoint,
task.requestPublicYPoint,
publicXPoint,
publicYPoint
);
require(isValidPublicKey(publicXPoint, publicYPoint));
bytes32 btcAddress = createBtcAddress(publicXPoint, publicYPoint);
uint prefixLength = lengthOfCommonPrefix(btcAddress, task.data);
require(prefixLength == task.dataLength);
task.answerPrivateKey = _answerPrivateKey;
} else {
revert();
}
uint256 minerReward = task.reward.mul(MAX_PERCENT - serviceFee).div(MAX_PERCENT); // 1% fee
uint256 referrerReward = task.reward.mul(serviceFee).mul(referrerFee).div(MAX_PERCENT).div(MAX_PERCENT); // 50% of service fee
msg.sender.transfer(minerReward);
task.referrer.transfer(referrerReward);
totalReward = totalReward.sub(task.reward.sub(minerReward.add(referrerReward)));
_completeTask(_taskId, taskIndex);
emit TaskSolved(_taskId, minerReward);
}
function _completeTask(uint _taskId, uint _index) internal {
completedTasks.push(tasks[_index]);
if (_index < tasks.length - 1) { // if not latest
tasks[_index] = tasks[tasks.length - 1];
indexOfTaskId[tasks[_index].taskId] = _index + 1;
}
tasks.length -= 1;
delete indexOfTaskId[_taskId];
}
function claim(ERC20Basic _token, address _to) public onlyOwner {
if (_token == address(0)) {
_to.transfer(address(this).balance - totalReward);
} else {
_token.transfer(_to, _token.balanceOf(this));
}
}
}
|
https:bitcoin.stackexchange.com/questions/48586
|
function complexityForBtcAddressPrefixWithLength(bytes prefix, uint length) public pure returns(uint) {
require(prefix.length >= length);
uint8[128] memory unbase58 = [
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 255, 255, 255, 255, 255, 255,
255, 9, 10, 11, 12, 13, 14, 15, 16, 255, 17, 18, 19, 20, 21, 255,
22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 255, 255, 255, 255, 255,
255, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 255, 44, 45, 46,
47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 255, 255, 255, 255, 255
];
uint leadingOnes = countBtcAddressLeadingOnes(prefix, length);
uint256 prefixValue = 0;
uint256 prefix1 = 1;
for (uint i = 0; i < length; i++) {
uint index = uint(prefix[i]);
require(index != 255);
prefixValue = prefixValue * 58 + unbase58[index];
prefix1 *= 58;
}
uint256 top = (uint256(1) << (200 - 8*leadingOnes));
uint256 total = 0;
uint256 prefixMin = prefixValue;
uint256 diff = 0;
for (uint digits = 1; prefix1/58 < (1 << 192); digits++) {
prefix1 *= 58;
prefixMin *= 58;
prefixValue = prefixValue * 58 + 57;
diff = 0;
if (prefixValue >= top) {
diff += prefixValue - top;
}
if (prefixMin < (top >> 8)) {
diff += (top >> 8) - prefixMin;
}
if ((58 ** digits) >= diff) {
total += (58 ** digits) - diff;
}
}
total = (58 ** (digits - 1)) - diff;
}
return (1 << 192) / total;
| 2,367,793
|
pragma solidity ^0.5.10;
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see `ERC20Detailed`.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through `transferFrom`. This is
* zero by default.
*
* This value changes when `approve` or `transferFrom` are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* > Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an `Approval` event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to `approve`. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: openzeppelin-solidity/contracts/utils/Address.sol
/**
* @dev Collection of functions related to the address type,
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* > It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the `nonReentrant` modifier
* available, which can be aplied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*/
contract ReentrancyGuard {
/// @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, "ReentrancyGuard: reentrant call");
}
}
// File: openzeppelin-solidity/contracts/introspection/ERC165Checker.sol
/**
* @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 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 the `supportsERC165` method in this library.
* 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 success, bool result)
{
bytes memory encodedParams = abi.encodeWithSelector(_INTERFACE_ID_ERC165, interfaceId);
// solhint-disable-next-line no-inline-assembly
assembly {
let encodedParams_data := add(0x20, encodedParams)
let encodedParams_size := mload(encodedParams)
let output := mload(0x40) // Find empty storage location using "free memory pointer"
mstore(output, 0x0)
success := staticcall(
30000, // 30k gas
account, // To addr
encodedParams_data,
encodedParams_size,
output,
0x20 // Outputs are 32 bytes long
)
result := mload(output) // Load the result
}
}
}
// File: openzeppelin-solidity/contracts/introspection/IERC165.sol
/**
* @dev Interface of the ERC165 standard, as defined in the
* [EIP](https://eips.ethereum.org/EIPS/eip-165).
*
* 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
* [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: openzeppelin-solidity/contracts/introspection/ERC165.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;
}
}
// File: erc-payable-token/contracts/token/ERC1363/IERC1363.sol
/**
* @title IERC1363 Interface
* @author Vittorio Minacori (https://github.com/vittominacori)
* @dev Interface for a Payable Token contract as defined in
* https://github.com/ethereum/EIPs/issues/1363
*/
contract IERC1363 is IERC20, ERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0x4bbee2df.
* 0x4bbee2df ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)'))
*/
/*
* Note: the ERC-165 identifier for this interface is 0xfb9ec8ce.
* 0xfb9ec8ce ===
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @notice Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver
* @param to address The address which you want to transfer to
* @param value uint256 The amount of tokens to be transferred
* @return true unless throwing
*/
function transferAndCall(address to, uint256 value) public returns (bool);
/**
* @notice Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver
* @param to address The address which you want to transfer to
* @param value uint256 The amount of tokens to be transferred
* @param data bytes Additional data with no specified format, sent in call to `to`
* @return true unless throwing
*/
function transferAndCall(address to, uint256 value, bytes memory data) public returns (bool);
/**
* @notice Transfer tokens from one address to another and then call `onTransferReceived` on receiver
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 The amount of tokens to be transferred
* @return true unless throwing
*/
function transferFromAndCall(address from, address to, uint256 value) public returns (bool);
/**
* @notice Transfer tokens from one address to another and then call `onTransferReceived` on receiver
* @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
* @param data bytes Additional data with no specified format, sent in call to `to`
* @return true unless throwing
*/
function transferFromAndCall(address from, address to, uint256 value, bytes memory data) public returns (bool);
/**
* @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender
* and then call `onApprovalReceived` on spender.
* 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 address The address which will spend the funds
* @param value uint256 The amount of tokens to be spent
*/
function approveAndCall(address spender, uint256 value) public returns (bool);
/**
* @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender
* and then call `onApprovalReceived` on spender.
* 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 address The address which will spend the funds
* @param value uint256 The amount of tokens to be spent
* @param data bytes Additional data with no specified format, sent in call to `spender`
*/
function approveAndCall(address spender, uint256 value, bytes memory data) public returns (bool);
}
// File: erc-payable-token/contracts/token/ERC1363/IERC1363Receiver.sol
/**
* @title IERC1363Receiver Interface
* @author Vittorio Minacori (https://github.com/vittominacori)
* @dev Interface for any contract that wants to support transferAndCall or transferFromAndCall
* from ERC1363 token contracts as defined in
* https://github.com/ethereum/EIPs/issues/1363
*/
contract IERC1363Receiver {
/*
* Note: the ERC-165 identifier for this interface is 0x88a7ca5c.
* 0x88a7ca5c === bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))
*/
/**
* @notice Handle the receipt of ERC1363 tokens
* @dev Any ERC1363 smart contract calls this function on the recipient
* after a `transfer` or a `transferFrom`. This function MAY throw to revert and reject the
* transfer. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the token contract address is always the message sender.
* @param operator address The address which called `transferAndCall` or `transferFromAndCall` function
* @param from address The address which are token transferred from
* @param value uint256 The amount of tokens transferred
* @param data bytes Additional data with no specified format
* @return `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))`
* unless throwing
*/
function onTransferReceived(address operator, address from, uint256 value, bytes memory data) public returns (bytes4); // solhint-disable-line max-line-length
}
// File: erc-payable-token/contracts/token/ERC1363/IERC1363Spender.sol
/**
* @title IERC1363Spender Interface
* @author Vittorio Minacori (https://github.com/vittominacori)
* @dev Interface for any contract that wants to support approveAndCall
* from ERC1363 token contracts as defined in
* https://github.com/ethereum/EIPs/issues/1363
*/
contract IERC1363Spender {
/*
* Note: the ERC-165 identifier for this interface is 0x7b04a2d0.
* 0x7b04a2d0 === bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))
*/
/**
* @notice Handle the approval of ERC1363 tokens
* @dev Any ERC1363 smart contract calls this function on the recipient
* after an `approve`. This function MAY throw to revert and reject the
* approval. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the token contract address is always the message sender.
* @param owner address The address which called `approveAndCall` function
* @param value uint256 The amount of tokens to be spent
* @param data bytes Additional data with no specified format
* @return `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))`
* unless throwing
*/
function onApprovalReceived(address owner, uint256 value, bytes memory data) public returns (bytes4);
}
// File: erc-payable-token/contracts/payment/ERC1363Payable.sol
/**
* @title ERC1363Payable
* @author Vittorio Minacori (https://github.com/vittominacori)
* @dev Implementation proposal of a contract that wants to accept ERC1363 payments
*/
contract ERC1363Payable is IERC1363Receiver, IERC1363Spender, ERC165 {
using ERC165Checker for address;
/**
* @dev Magic value to be returned upon successful reception of ERC1363 tokens
* Equals to `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))`,
* which can be also obtained as `IERC1363Receiver(0).onTransferReceived.selector`
*/
bytes4 internal constant _INTERFACE_ID_ERC1363_RECEIVER = 0x88a7ca5c;
/**
* @dev Magic value to be returned upon successful approval of ERC1363 tokens.
* Equals to `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))`,
* which can be also obtained as `IERC1363Spender(0).onApprovalReceived.selector`
*/
bytes4 internal constant _INTERFACE_ID_ERC1363_SPENDER = 0x7b04a2d0;
/*
* Note: the ERC-165 identifier for the ERC1363 token transfer
* 0x4bbee2df ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)'))
*/
bytes4 private constant _INTERFACE_ID_ERC1363_TRANSFER = 0x4bbee2df;
/*
* Note: the ERC-165 identifier for the ERC1363 token approval
* 0xfb9ec8ce ===
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
bytes4 private constant _INTERFACE_ID_ERC1363_APPROVE = 0xfb9ec8ce;
event TokensReceived(
address indexed operator,
address indexed from,
uint256 value,
bytes data
);
event TokensApproved(
address indexed owner,
uint256 value,
bytes data
);
// The ERC1363 token accepted
IERC1363 private _acceptedToken;
/**
* @param acceptedToken Address of the token being accepted
*/
constructor(IERC1363 acceptedToken) public {
require(address(acceptedToken) != address(0));
require(
acceptedToken.supportsInterface(_INTERFACE_ID_ERC1363_TRANSFER) &&
acceptedToken.supportsInterface(_INTERFACE_ID_ERC1363_APPROVE)
);
_acceptedToken = acceptedToken;
// register the supported interface to conform to IERC1363Receiver and IERC1363Spender via ERC165
_registerInterface(_INTERFACE_ID_ERC1363_RECEIVER);
_registerInterface(_INTERFACE_ID_ERC1363_SPENDER);
}
/*
* @dev Note: remember that the token contract address is always the message sender.
* @param operator address The address which called `transferAndCall` or `transferFromAndCall` function
* @param from address The address which are token transferred from
* @param value uint256 The amount of tokens transferred
* @param data bytes Additional data with no specified format
*/
function onTransferReceived(address operator, address from, uint256 value, bytes memory data) public returns (bytes4) { // solhint-disable-line max-line-length
require(msg.sender == address(_acceptedToken));
emit TokensReceived(operator, from, value, data);
_transferReceived(operator, from, value, data);
return _INTERFACE_ID_ERC1363_RECEIVER;
}
/*
* @dev Note: remember that the token contract address is always the message sender.
* @param owner address The address which called `approveAndCall` function
* @param value uint256 The amount of tokens to be spent
* @param data bytes Additional data with no specified format
*/
function onApprovalReceived(address owner, uint256 value, bytes memory data) public returns (bytes4) {
require(msg.sender == address(_acceptedToken));
emit TokensApproved(owner, value, data);
_approvalReceived(owner, value, data);
return _INTERFACE_ID_ERC1363_SPENDER;
}
/**
* @dev The ERC1363 token accepted
*/
function acceptedToken() public view returns (IERC1363) {
return _acceptedToken;
}
/**
* @dev Called after validating a `onTransferReceived`. Override this method to
* make your stuffs within your contract.
* @param operator address The address which called `transferAndCall` or `transferFromAndCall` function
* @param from address The address which are token transferred from
* @param value uint256 The amount of tokens transferred
* @param data bytes Additional data with no specified format
*/
function _transferReceived(address operator, address from, uint256 value, bytes memory data) internal {
// solhint-disable-previous-line no-empty-blocks
// optional override
}
/**
* @dev Called after validating a `onApprovalReceived`. Override this method to
* make your stuffs within your contract.
* @param owner address The address which called `approveAndCall` function
* @param value uint256 The amount of tokens to be spent
* @param data bytes Additional data with no specified format
*/
function _approvalReceived(address owner, uint256 value, bytes memory data) internal {
// solhint-disable-previous-line no-empty-blocks
// optional override
}
}
// File: openzeppelin-solidity/contracts/ownership/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.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* > Note: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: openzeppelin-solidity/contracts/access/Roles.sol
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
// File: dao-smartcontracts/contracts/access/roles/DAORoles.sol
/**
* @title DAORoles
* @author Vittorio Minacori (https://github.com/vittominacori)
* @dev It identifies the DAO roles
*/
contract DAORoles is Ownable {
using Roles for Roles.Role;
event OperatorAdded(address indexed account);
event OperatorRemoved(address indexed account);
event DappAdded(address indexed account);
event DappRemoved(address indexed account);
Roles.Role private _operators;
Roles.Role private _dapps;
constructor () internal {} // solhint-disable-line no-empty-blocks
modifier onlyOperator() {
require(isOperator(msg.sender));
_;
}
modifier onlyDapp() {
require(isDapp(msg.sender));
_;
}
/**
* @dev Check if an address has the `operator` role
* @param account Address you want to check
*/
function isOperator(address account) public view returns (bool) {
return _operators.has(account);
}
/**
* @dev Check if an address has the `dapp` role
* @param account Address you want to check
*/
function isDapp(address account) public view returns (bool) {
return _dapps.has(account);
}
/**
* @dev Add the `operator` role from address
* @param account Address you want to add role
*/
function addOperator(address account) public onlyOwner {
_addOperator(account);
}
/**
* @dev Add the `dapp` role from address
* @param account Address you want to add role
*/
function addDapp(address account) public onlyOperator {
_addDapp(account);
}
/**
* @dev Remove the `operator` role from address
* @param account Address you want to remove role
*/
function removeOperator(address account) public onlyOwner {
_removeOperator(account);
}
/**
* @dev Remove the `operator` role from address
* @param account Address you want to remove role
*/
function removeDapp(address account) public onlyOperator {
_removeDapp(account);
}
function _addOperator(address account) internal {
_operators.add(account);
emit OperatorAdded(account);
}
function _addDapp(address account) internal {
_dapps.add(account);
emit DappAdded(account);
}
function _removeOperator(address account) internal {
_operators.remove(account);
emit OperatorRemoved(account);
}
function _removeDapp(address account) internal {
_dapps.remove(account);
emit DappRemoved(account);
}
}
// File: dao-smartcontracts/contracts/dao/Organization.sol
/**
* @title Organization
* @author Vittorio Minacori (https://github.com/vittominacori)
* @dev Library for managing organization
*/
library Organization {
using SafeMath for uint256;
// structure defining a member
struct Member {
uint256 id;
address account;
bytes9 fingerprint;
uint256 creationDate;
uint256 stakedTokens;
uint256 usedTokens;
bytes32 data;
bool approved;
}
// structure defining members status
struct Members {
uint256 count;
uint256 totalStakedTokens;
uint256 totalUsedTokens;
mapping(address => uint256) addressMap;
mapping(uint256 => Member) list;
}
/**
* @dev Returns if an address is member or not
* @param members Current members struct
* @param account Address of the member you are looking for
* @return bool
*/
function isMember(Members storage members, address account) internal view returns (bool) {
return members.addressMap[account] != 0;
}
/**
* @dev Get creation date of a member
* @param members Current members struct
* @param account Address you want to check
* @return uint256 Member creation date, zero otherwise
*/
function creationDateOf(Members storage members, address account) internal view returns (uint256) {
Member storage member = members.list[members.addressMap[account]];
return member.creationDate;
}
/**
* @dev Check how many tokens staked for given address
* @param members Current members struct
* @param account Address you want to check
* @return uint256 Member staked tokens
*/
function stakedTokensOf(Members storage members, address account) internal view returns (uint256) {
Member storage member = members.list[members.addressMap[account]];
return member.stakedTokens;
}
/**
* @dev Check how many tokens used for given address
* @param members Current members struct
* @param account Address you want to check
* @return uint256 Member used tokens
*/
function usedTokensOf(Members storage members, address account) internal view returns (uint256) {
Member storage member = members.list[members.addressMap[account]];
return member.usedTokens;
}
/**
* @dev Check if an address has been approved
* @param members Current members struct
* @param account Address you want to check
* @return bool
*/
function isApproved(Members storage members, address account) internal view returns (bool) {
Member storage member = members.list[members.addressMap[account]];
return member.approved;
}
/**
* @dev Returns the member structure
* @param members Current members struct
* @param memberId Id of the member you are looking for
* @return Member
*/
function getMember(Members storage members, uint256 memberId) internal view returns (Member storage) {
Member storage structure = members.list[memberId];
require(structure.account != address(0));
return structure;
}
/**
* @dev Generate a new member and the member structure
* @param members Current members struct
* @param account Address you want to make member
* @return uint256 The new member id
*/
function addMember(Members storage members, address account) internal returns (uint256) {
require(account != address(0));
require(!isMember(members, account));
uint256 memberId = members.count.add(1);
bytes9 fingerprint = getFingerprint(account, memberId);
members.addressMap[account] = memberId;
members.list[memberId] = Member(
memberId,
account,
fingerprint,
block.timestamp, // solhint-disable-line not-rely-on-time
0,
0,
"",
false
);
members.count = memberId;
return memberId;
}
/**
* @dev Add tokens to member stack
* @param members Current members struct
* @param account Address you want to stake tokens
* @param amount Number of tokens to stake
*/
function stake(Members storage members, address account, uint256 amount) internal {
require(isMember(members, account));
Member storage member = members.list[members.addressMap[account]];
member.stakedTokens = member.stakedTokens.add(amount);
members.totalStakedTokens = members.totalStakedTokens.add(amount);
}
/**
* @dev Remove tokens from member stack
* @param members Current members struct
* @param account Address you want to unstake tokens
* @param amount Number of tokens to unstake
*/
function unstake(Members storage members, address account, uint256 amount) internal {
require(isMember(members, account));
Member storage member = members.list[members.addressMap[account]];
require(member.stakedTokens >= amount);
member.stakedTokens = member.stakedTokens.sub(amount);
members.totalStakedTokens = members.totalStakedTokens.sub(amount);
}
/**
* @dev Use tokens from member stack
* @param members Current members struct
* @param account Address you want to use tokens
* @param amount Number of tokens to use
*/
function use(Members storage members, address account, uint256 amount) internal {
require(isMember(members, account));
Member storage member = members.list[members.addressMap[account]];
require(member.stakedTokens >= amount);
member.stakedTokens = member.stakedTokens.sub(amount);
members.totalStakedTokens = members.totalStakedTokens.sub(amount);
member.usedTokens = member.usedTokens.add(amount);
members.totalUsedTokens = members.totalUsedTokens.add(amount);
}
/**
* @dev Set the approved status for a member
* @param members Current members struct
* @param account Address you want to update
* @param status Bool the new status for approved
*/
function setApproved(Members storage members, address account, bool status) internal {
require(isMember(members, account));
Member storage member = members.list[members.addressMap[account]];
member.approved = status;
}
/**
* @dev Set data for a member
* @param members Current members struct
* @param account Address you want to update
* @param data bytes32 updated data
*/
function setData(Members storage members, address account, bytes32 data) internal {
require(isMember(members, account));
Member storage member = members.list[members.addressMap[account]];
member.data = data;
}
/**
* @dev Generate a member fingerprint
* @param account Address you want to make member
* @param memberId The member id
* @return bytes9 It represents member fingerprint
*/
function getFingerprint(address account, uint256 memberId) private pure returns (bytes9) {
return bytes9(keccak256(abi.encodePacked(account, memberId)));
}
}
// File: dao-smartcontracts/contracts/dao/DAO.sol
/**
* @title DAO
* @author Vittorio Minacori (https://github.com/vittominacori)
* @dev It identifies the DAO and Organization logic
*/
contract DAO is ERC1363Payable, DAORoles {
using SafeMath for uint256;
using Organization for Organization.Members;
using Organization for Organization.Member;
event MemberAdded(
address indexed account,
uint256 id
);
event MemberStatusChanged(
address indexed account,
bool approved
);
event TokensStaked(
address indexed account,
uint256 value
);
event TokensUnstaked(
address indexed account,
uint256 value
);
event TokensUsed(
address indexed account,
address indexed dapp,
uint256 value
);
Organization.Members private _members;
constructor (IERC1363 acceptedToken) public ERC1363Payable(acceptedToken) {} // solhint-disable-line no-empty-blocks
/**
* @dev fallback. This function will create a new member
*/
function () external payable { // solhint-disable-line no-complex-fallback
require(msg.value == 0);
_newMember(msg.sender);
}
/**
* @dev Generate a new member and the member structure
*/
function join() external {
_newMember(msg.sender);
}
/**
* @dev Generate a new member and the member structure
* @param account Address you want to make member
*/
function newMember(address account) external onlyOperator {
_newMember(account);
}
/**
* @dev Set the approved status for a member
* @param account Address you want to update
* @param status Bool the new status for approved
*/
function setApproved(address account, bool status) external onlyOperator {
_members.setApproved(account, status);
emit MemberStatusChanged(account, status);
}
/**
* @dev Set data for a member
* @param account Address you want to update
* @param data bytes32 updated data
*/
function setData(address account, bytes32 data) external onlyOperator {
_members.setData(account, data);
}
/**
* @dev Use tokens from a specific account
* @param account Address to use the tokens from
* @param amount Number of tokens to use
*/
function use(address account, uint256 amount) external onlyDapp {
_members.use(account, amount);
IERC20(acceptedToken()).transfer(msg.sender, amount);
emit TokensUsed(account, msg.sender, amount);
}
/**
* @dev Remove tokens from member stack
* @param amount Number of tokens to unstake
*/
function unstake(uint256 amount) public {
_members.unstake(msg.sender, amount);
IERC20(acceptedToken()).transfer(msg.sender, amount);
emit TokensUnstaked(msg.sender, amount);
}
/**
* @dev Returns the members number
* @return uint256
*/
function membersNumber() public view returns (uint256) {
return _members.count;
}
/**
* @dev Returns the total staked tokens number
* @return uint256
*/
function totalStakedTokens() public view returns (uint256) {
return _members.totalStakedTokens;
}
/**
* @dev Returns the total used tokens number
* @return uint256
*/
function totalUsedTokens() public view returns (uint256) {
return _members.totalUsedTokens;
}
/**
* @dev Returns if an address is member or not
* @param account Address of the member you are looking for
* @return bool
*/
function isMember(address account) public view returns (bool) {
return _members.isMember(account);
}
/**
* @dev Get creation date of a member
* @param account Address you want to check
* @return uint256 Member creation date, zero otherwise
*/
function creationDateOf(address account) public view returns (uint256) {
return _members.creationDateOf(account);
}
/**
* @dev Check how many tokens staked for given address
* @param account Address you want to check
* @return uint256 Member staked tokens
*/
function stakedTokensOf(address account) public view returns (uint256) {
return _members.stakedTokensOf(account);
}
/**
* @dev Check how many tokens used for given address
* @param account Address you want to check
* @return uint256 Member used tokens
*/
function usedTokensOf(address account) public view returns (uint256) {
return _members.usedTokensOf(account);
}
/**
* @dev Check if an address has been approved
* @param account Address you want to check
* @return bool
*/
function isApproved(address account) public view returns (bool) {
return _members.isApproved(account);
}
/**
* @dev Returns the member structure
* @param memberAddress Address of the member you are looking for
* @return array
*/
function getMemberByAddress(address memberAddress)
public
view
returns (
uint256 id,
address account,
bytes9 fingerprint,
uint256 creationDate,
uint256 stakedTokens,
uint256 usedTokens,
bytes32 data,
bool approved
)
{
return getMemberById(_members.addressMap[memberAddress]);
}
/**
* @dev Returns the member structure
* @param memberId Id of the member you are looking for
* @return array
*/
function getMemberById(uint256 memberId)
public
view
returns (
uint256 id,
address account,
bytes9 fingerprint,
uint256 creationDate,
uint256 stakedTokens,
uint256 usedTokens,
bytes32 data,
bool approved
)
{
Organization.Member storage structure = _members.getMember(memberId);
id = structure.id;
account = structure.account;
fingerprint = structure.fingerprint;
creationDate = structure.creationDate;
stakedTokens = structure.stakedTokens;
usedTokens = structure.usedTokens;
data = structure.data;
approved = structure.approved;
}
/**
* @dev Allow to recover tokens from contract
* @param tokenAddress address The token contract address
* @param tokenAmount uint256 Number of tokens to be sent
*/
function recoverERC20(address tokenAddress, uint256 tokenAmount) public onlyOwner {
if (tokenAddress == address(acceptedToken())) {
uint256 currentBalance = IERC20(acceptedToken()).balanceOf(address(this));
require(currentBalance.sub(_members.totalStakedTokens) >= tokenAmount);
}
IERC20(tokenAddress).transfer(owner(), tokenAmount);
}
/**
* @dev Called after validating a `onTransferReceived`
* @param operator address The address which called `transferAndCall` or `transferFromAndCall` function
* @param from address The address which are token transferred from
* @param value uint256 The amount of tokens transferred
* @param data bytes Additional data with no specified format
*/
function _transferReceived(
address operator, // solhint-disable-line no-unused-vars
address from,
uint256 value,
bytes memory data // solhint-disable-line no-unused-vars
)
internal
{
_stake(from, value);
}
/**
* @dev Called after validating a `onApprovalReceived`
* @param owner address The address which called `approveAndCall` function
* @param value uint256 The amount of tokens to be spent
* @param data bytes Additional data with no specified format
*/
function _approvalReceived(
address owner,
uint256 value,
bytes memory data // solhint-disable-line no-unused-vars
)
internal
{
IERC20(acceptedToken()).transferFrom(owner, address(this), value);
_stake(owner, value);
}
/**
* @dev Generate a new member and the member structure
* @param account Address you want to make member
* @return uint256 The new member id
*/
function _newMember(address account) internal {
uint256 memberId = _members.addMember(account);
emit MemberAdded(account, memberId);
}
/**
* @dev Add tokens to member stack
* @param account Address you want to stake tokens
* @param amount Number of tokens to stake
*/
function _stake(address account, uint256 amount) internal {
if (!isMember(account)) {
_newMember(account);
}
_members.stake(account, amount);
emit TokensStaked(account, amount);
}
}
// File: eth-token-recover/contracts/TokenRecover.sol
/**
* @title TokenRecover
* @author Vittorio Minacori (https://github.com/vittominacori)
* @dev Allow to recover any ERC20 sent into the contract for error
*/
contract TokenRecover is Ownable {
/**
* @dev Remember that only owner can call so be careful when use on contracts generated from other contracts.
* @param tokenAddress The token contract address
* @param tokenAmount Number of tokens to be sent
*/
function recoverERC20(address tokenAddress, uint256 tokenAmount) public onlyOwner {
IERC20(tokenAddress).transfer(owner(), tokenAmount);
}
}
// File: contracts/access/roles/OperatorRole.sol
contract OperatorRole {
using Roles for Roles.Role;
event OperatorAdded(address indexed account);
event OperatorRemoved(address indexed account);
Roles.Role private _operators;
constructor() internal {
_addOperator(msg.sender);
}
modifier onlyOperator() {
require(isOperator(msg.sender));
_;
}
function isOperator(address account) public view returns (bool) {
return _operators.has(account);
}
function addOperator(address account) public onlyOperator {
_addOperator(account);
}
function renounceOperator() public {
_removeOperator(msg.sender);
}
function _addOperator(address account) internal {
_operators.add(account);
emit OperatorAdded(account);
}
function _removeOperator(address account) internal {
_operators.remove(account);
emit OperatorRemoved(account);
}
}
// File: contracts/utils/Contributions.sol
/**
* @title Contributions
* @author Vittorio Minacori (https://github.com/vittominacori)
* @dev Utility contract where to save any information about Crowdsale contributions
*/
contract Contributions is OperatorRole, TokenRecover {
using SafeMath for uint256;
struct Contributor {
uint256 weiAmount;
uint256 tokenAmount;
bool exists;
}
// the number of sold tokens
uint256 private _totalSoldTokens;
// the number of wei raised
uint256 private _totalWeiRaised;
// list of addresses who contributed in crowdsales
address[] private _addresses;
// map of contributors
mapping(address => Contributor) private _contributors;
constructor() public {} // solhint-disable-line no-empty-blocks
/**
* @return the number of sold tokens
*/
function totalSoldTokens() public view returns (uint256) {
return _totalSoldTokens;
}
/**
* @return the number of wei raised
*/
function totalWeiRaised() public view returns (uint256) {
return _totalWeiRaised;
}
/**
* @return address of a contributor by list index
*/
function getContributorAddress(uint256 index) public view returns (address) {
return _addresses[index];
}
/**
* @dev return the contributions length
* @return uint representing contributors number
*/
function getContributorsLength() public view returns (uint) {
return _addresses.length;
}
/**
* @dev get wei contribution for the given address
* @param account Address has contributed
* @return uint256
*/
function weiContribution(address account) public view returns (uint256) {
return _contributors[account].weiAmount;
}
/**
* @dev get token balance for the given address
* @param account Address has contributed
* @return uint256
*/
function tokenBalance(address account) public view returns (uint256) {
return _contributors[account].tokenAmount;
}
/**
* @dev check if a contributor exists
* @param account The address to check
* @return bool
*/
function contributorExists(address account) public view returns (bool) {
return _contributors[account].exists;
}
/**
* @dev add contribution into the contributions array
* @param account Address being contributing
* @param weiAmount Amount of wei contributed
* @param tokenAmount Amount of token received
*/
function addBalance(address account, uint256 weiAmount, uint256 tokenAmount) public onlyOperator {
if (!_contributors[account].exists) {
_addresses.push(account);
_contributors[account].exists = true;
}
_contributors[account].weiAmount = _contributors[account].weiAmount.add(weiAmount);
_contributors[account].tokenAmount = _contributors[account].tokenAmount.add(tokenAmount);
_totalWeiRaised = _totalWeiRaised.add(weiAmount);
_totalSoldTokens = _totalSoldTokens.add(tokenAmount);
}
/**
* @dev remove the `operator` role from address
* @param account Address you want to remove role
*/
function removeOperator(address account) public onlyOwner {
_removeOperator(account);
}
}
// File: contracts/dealer/TokenDealer.sol
/**
* @title TokenDealer
* @author Vittorio Minacori (https://github.com/vittominacori)
* @dev TokenDealer is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether.
*/
contract TokenDealer is ReentrancyGuard, TokenRecover {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
uint256 private _rate;
// Address where funds are collected
address payable private _wallet;
// The token being sold
IERC20 private _token;
// the DAO smart contract
DAO private _dao;
// reference to Contributions contract
Contributions private _contributions;
/**
* Event for token purchase logging
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(address indexed beneficiary, uint256 value, uint256 amount);
/**
* @param rate Number of token units a buyer gets per wei
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
* @param contributions Address of the contributions contract
* @param dao DAO the decentralized organization address
*/
constructor(
uint256 rate,
address payable wallet,
address token,
address contributions,
address payable dao
)
public
{
require(rate > 0, "TokenDealer: rate is 0");
require(wallet != address(0), "TokenDealer: wallet is the zero address");
require(token != address(0), "TokenDealer: token is the zero address");
require(contributions != address(0), "TokenDealer: contributions is the zero address");
require(dao != address(0), "TokenDealer: dao is the zero address");
_rate = rate;
_wallet = wallet;
_token = IERC20(token);
_contributions = Contributions(contributions);
_dao = DAO(dao);
}
/**
* @dev fallback function
* Note that other contracts will transfer funds with a base gas stipend
* of 2300, which is not enough to call buyTokens. Consider calling
* buyTokens directly when purchasing tokens from a contract.
*/
function () external payable {
buyTokens();
}
/**
* @dev low level token purchase
* This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
*/
function buyTokens() public nonReentrant payable {
address beneficiary = msg.sender;
uint256 weiAmount = msg.value;
require(weiAmount != 0, "TokenDealer: weiAmount is 0");
// calculate token amount to be sent
uint256 tokenAmount = _getTokenAmount(beneficiary, weiAmount);
_token.safeTransfer(beneficiary, tokenAmount);
emit TokensPurchased(beneficiary, weiAmount, tokenAmount);
_contributions.addBalance(beneficiary, weiAmount, tokenAmount);
_wallet.transfer(weiAmount);
}
/**
* @dev Function to update rate
* @param newRate The rate is the conversion between wei and the smallest and indivisible token unit
*/
function setRate(uint256 newRate) public onlyOwner {
require(newRate > 0, "TokenDealer: rate is 0");
_rate = newRate;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns (uint256) {
return _rate;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns (address payable) {
return _wallet;
}
/**
* @return the token being sold.
*/
function token() public view returns (IERC20) {
return _token;
}
/**
* @return the crowdsale contributions contract address
*/
function contributions() public view returns (Contributions) {
return _contributions;
}
/**
* @return the crowdsale dao contract address
*/
function dao() public view returns (DAO) {
return _dao;
}
/**
* @dev Get expected token number for beneficiary.
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function expectedTokenAmount(address beneficiary, uint256 weiAmount) public view returns (uint256) {
return _getTokenAmount(beneficiary, weiAmount);
}
/**
* @dev The way in which ether is converted to tokens.
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(address beneficiary, uint256 weiAmount) internal view returns (uint256) {
uint256 tokenAmount = weiAmount.mul(_rate);
if (_dao.isMember(beneficiary)) {
tokenAmount = tokenAmount.mul(2);
if (_dao.stakedTokensOf(beneficiary) > 0) {
tokenAmount = tokenAmount.mul(2);
}
if (_dao.usedTokensOf(beneficiary) > 0) {
tokenAmount = tokenAmount.mul(2);
}
}
return tokenAmount;
}
}
|
Check if an address has the `dapp` role account Address you want to check/
|
function isDapp(address account) public view returns (bool) {
return _dapps.has(account);
}
| 943,827
|
pragma solidity ^0.6.0;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return _sub(a, b, "SafeMath: subtraction overflow");
}
function _sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return _div(a, b, "SafeMath: division by zero");
}
function _div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return _mod(a, b, "SafeMath: modulo by zero");
}
function _mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
interface IERC20 {
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool ok);
function transferFrom(address from, address to, uint256 value) external returns (bool ok);
function approve(address spender, uint256 value)external returns (bool ok);
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens);
}
contract BitmindCrowdsale {
using SafeMath for uint256;
struct Participant {
uint256 amount; // How many tokens the user has provided.
}
struct CrowdsaleHistory {
uint256 id;
uint256 start_time;
uint256 end_time;
uint256 initial_price;
uint256 final_price;
uint256 final_cap;
uint256 total_received;
uint256 token_available;
uint256 token_sold;
}
modifier onlyOwner {
require(msg.sender == owner, 'BitmindMsg: Only Owner');
_;
}
modifier onlyWhileOpen{
//Validation Crowdsale
require(start_time > 0 && end_time > 0 , 'BitmindMsg: Crowdsale is not started yet');
require(block.timestamp > start_time && block.timestamp < end_time, 'BitmindMsg: Crowdsale is not started yet');
_;
}
modifier onlyFreezer{
require(msg.sender == freezerAddress, 'BitmindMsg: Only Freezer Address');
_;
}
/**
* Configurator Crowdsale Contract
*/
address payable private owner;
address private freezerAddress;
/**
* Token Address for Crowdsale Contract
*/
IERC20 private tokenAddress;
IERC20 private pairAddress;
/**
* Time Configuration
*/
uint256 private start_time;
uint256 private end_time;
bool private pause;
/**
* Crowdsale Information
*/
uint256 private min_contribution;
uint256 private max_contribution;
uint256 public cap;
uint256 private rate;
uint256 private price;
uint256 public token_available;
uint256 public total_received;
uint256 public token_sold;
/**
* Participant Information
*/
mapping (address => Participant) public userInfo;
address[] private addressList;
mapping (uint256 => CrowdsaleHistory) public crowdsaleInfo;
uint256[] private crowdsaleid;
/**
* Event for token purchase logging
* @param purchaser : who paid for the tokens and get the tokens
* @param amount : total amount of tokens purchased
*/
event TokensPurchased(address indexed purchaser, uint256 amount);
/**
* Event shown after change Opening Time
* @param owner : who owner this contract
* @param openingtime : time when the Crowdsale started
*/
event setOpeningtime(address indexed owner, uint256 openingtime);
/**
* Event shown after change Closing Time
* @param owner : who owner this contract
* @param closingtime : time when the Crowdsale Ended
*/
event setClosingtime(address indexed owner, uint256 closingtime);
/**
* Event for withdraw usdt token from contract to owner
* @param owner : who owner this contract
* @param amount : time when the Crowdsale Ended
*/
event WithdrawUSDT(address indexed owner, uint256 amount);
/**
* Event for withdraw bmd token from contract to owner
* @param owner : who owner this contract
* @param amount : time when the Crowdsale Ended
*/
event WithdrawBMD(address indexed owner, uint256 amount);
/**
* Event for Transfer Ownership
* @param previousOwner : owner Crowdsale contract
* @param newOwner : New Owner of Crowdsale contract
* @param time : time when changeOwner function executed
*/
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner, uint256 time);
/**
* Event for Transfer Freezer Admin
* @param previousFreezer : Freezer of Crowdsale contract
* @param newFreezer : new Freezer of Crowdsale contract
* @param time : time when transferFreezer function executed
*/
event FreezerTransferred(address indexed previousFreezer, address indexed newFreezer, uint256 time);
/**
* Event for Freeze the Crowdsale
* @param FreezerAddress : Address who can freeze Crowdsale contract
* @param time : time when changeOwner function executed
*/
event FreezeCrowdsale(address indexed FreezerAddress, uint256 time);
/**
* Event for Unfreeze the Crowdsale
* @param FreezerAddress : Address who can freeze Crowdsale contract
* @param time : time when changeOwner function executed
*/
event UnfreezeCrowdsale(address indexed FreezerAddress, uint256 time);
/**
* Event for Initializing Crowdsale Contract
* @param Token : Main Token which will be distributed in Crowdsale
* @param Pair : Pair Token which will be used for transaction in Crowdsale
* @param owner : Address who can initialize Crowdsale contract
* @param min_contribution : min contribution for transaction in Crowdsale
* @param max_contribution : max contribution for transaction in Crowdsale
* @param start_time : time when the Crowdsale starts
* @param end_time : time when the Crowdsale ends
* @param rate : increasing price every period
* @param initial_price : initial price of Crowdsale
*/
event Initializing(
address indexed Token,
address indexed Pair,
address indexed owner,
uint256 min_contribution,
uint256 max_contribution,
uint256 start_time,
uint256 end_time,
uint256 rate,
uint256 initial_price
);
/**
* Constructor of Bitmind Crowdsale Contract
*/
constructor() public {
owner = msg.sender;
freezerAddress = msg.sender;
pause = false;
}
/**
* Function for Initialize default configuration of Crowdsale
*/
function initialize(
address Token,
address Pair,
uint256 MinContribution,
uint256 MaxContribution,
uint256 initial_cap,
uint256 StartTime,
uint256 EndTime,
uint256 initial_price,
uint256 initial_rate
) public onlyOwner returns(bool){
tokenAddress = IERC20(Token);
pairAddress = IERC20(Pair);
require(initial_price > 0 , "BitmindMsg: initial price must higher than 0");
price = initial_price;
require(StartTime > 0, "BitmindMsg: start_time must higher than 0");
start_time = StartTime;
require(EndTime > 0, "BitmindMsg: end_time must higher than 0");
end_time = EndTime;
require(MinContribution > 0, "BitmindMsg: min_contribution must higher than 0");
min_contribution = MinContribution;
require(MaxContribution > 0, "BitmindMsg: max_contribution must higher than 0");
max_contribution = MaxContribution;
require(initial_rate > 0, "BitmindMsg: initial_rate must higher than 0");
rate = initial_rate;
cap = initial_cap;
token_available = initial_cap;
token_sold = 0;
total_received = 0;
uint256 id = crowdsaleid.length.add(1);
crowdsaleid.push(id);
crowdsaleInfo[id].id = id;
crowdsaleInfo[id].start_time = StartTime;
crowdsaleInfo[id].end_time = EndTime;
crowdsaleInfo[id].initial_price = initial_price;
crowdsaleInfo[id].final_price = initial_price;
crowdsaleInfo[id].final_cap = initial_cap;
crowdsaleInfo[id].token_available = token_available;
emit Initializing(Token, Pair, msg.sender, MinContribution, MaxContribution, StartTime, EndTime, initial_rate, initial_price);
return true;
}
/**
* Function for Purchase Token on Crowdsale
* @param amount : amount which user purchase
*
* return deliveryTokens
*/
function Purchase(uint256 amount) external onlyWhileOpen returns(bool){
require(pause == false, 'BitmindMsg: Crowdsale is freezing');
require(price > 0, 'BitmindMsg: Initial Prize is not set yet');
if (min_contribution > 0 && max_contribution > 0 ){
require(amount >= min_contribution && amount <= max_contribution, "BitmindMsg: Amount invalid");
}
uint256 tokenReached = getEstimateToken(amount);
require(tokenReached > 0, "BitmindMsg: Calculating Error!");
require(token_available > 0 && token_available >= tokenReached, "BitmindMsg: INSUFFICIENT BMD");
pairAddress.transferFrom(msg.sender, address(this), amount.div(1e12));
total_received = total_received.add(amount);
crowdsaleInfo[crowdsaleid.length].total_received = total_received;
crowdsaleInfo[crowdsaleid.length].final_price = getPrice();
if (userInfo[msg.sender].amount == 0) {
addressList.push(address(msg.sender));
}
userInfo[msg.sender].amount = userInfo[msg.sender].amount.add(amount);
token_available = token_available.sub(tokenReached);
token_sold = token_sold.add(tokenReached);
crowdsaleInfo[crowdsaleid.length].token_available = token_available;
crowdsaleInfo[crowdsaleid.length].token_sold = token_sold;
tokenAddress.transfer(msg.sender, tokenReached);
emit TokensPurchased(msg.sender, tokenReached);
return true;
}
/**
* Function for Estimate token which user get on Crowdsale
* @param _amount : amount which user purchase
*
* return token_amount type uint256
*/
function getEstimateToken(uint256 _amount) private view returns(uint256) {
uint256 token_amount;
uint256 a;
uint256 b;
uint256 phase_1 = cap.mul(50).div(100);
uint256 phase_2 = cap.mul(80).div(100);
uint256 phase_3 = cap.mul(100).div(100);
uint256 get = _amount.div(getPrice().div(1e18));
if(token_available > cap.sub(phase_1)){
if(token_available.sub(get) < cap.sub(phase_1)){
a = token_available.sub(cap.sub(phase_1));
b = _amount.sub(a.mul(getPrice().div(1e18))).div(price.add(rate.mul(1)).div(1e18));
token_amount = a.add(b);
}else{
token_amount = get;
}
}else if(token_available > cap.sub(phase_2)){
if(token_available.sub(get) < cap.sub(phase_2)){
a = token_available.sub(cap.sub(phase_2));
b = _amount.sub(a.mul(getPrice().div(1e18))).div(price.add(rate.mul(2)).div(1e18));
token_amount = a.add(b);
}else{
token_amount = get;
}
}else if(token_available > cap.sub(phase_3)){
if(token_available.sub(get) < cap.sub(phase_3)){
token_amount = token_available.sub(phase_3);
}else{
token_amount = get;
}
}
return token_amount;
}
/**
* Function for getting current price
*
* return price (uint256)
*/
function getPrice() public view returns(uint256){
require(price > 0 && token_available > 0 && cap > 0, "BitmindMsg: Initializing contract first");
if(token_available > cap.sub(cap.mul(50).div(100))){
return price;
}else if(token_available > cap.sub(cap.mul(80).div(100))){
return price.add(rate.mul(1));
}else if(token_available > cap.sub(cap.mul(100).div(100))){
return price.add(rate.mul(2));
}else{
return price.add(rate.mul(2));
}
}
/**
* Function for withdraw usdt token on Crowdsale
*
* return event WithdrawUSDT
*/
function withdrawUSDT() public onlyOwner returns(bool){
require(total_received>0, 'BitmindMsg: Pair Token INSUFFICIENT');
uint256 balance = pairAddress.balanceOf(address(this));
pairAddress.transfer(msg.sender, balance);
emit WithdrawUSDT(msg.sender,balance);
return true;
}
/**
* Function for withdraw bmd token on Crowdsale
*
* return event WithdrawUSDT
*/
function withdrawBMD() public onlyOwner returns(bool){
require(token_available > 0, 'BitmindMsg: Distributed Token INSUFFICIENT');
uint256 balance = tokenAddress.balanceOf(address(this));
tokenAddress.transfer(owner, balance);
emit WithdrawBMD(msg.sender, balance);
return true;
}
/**
* Function to get opening time of Crowdsale
*/
function openingTime() public view returns(uint256){
return start_time;
}
/**
* Function to get closing time of Crowdsale
*/
function closingTime() public view returns(uint256){
return end_time;
}
/**
* Function to get minimum contribution of Crowdsale
*/
function MIN_CONTRIBUTION() public view returns(uint256){
return min_contribution;
}
/**
* Function to get maximum contribution of Crowdsale
*/
function MAX_CONTRIBUTION() public view returns(uint256){
return max_contribution;
}
/**
* Function to get rate which user get during transaction per 1 pair on Crowdsale
*/
function Rate() public view returns(uint256){
return rate;
}
/**
* Function to get status of Crowdsale which user get during transaction per 1 pair on Crowdsale
*/
function Pause() public view returns(bool){
return pause;
}
/**
* Function to get total participant of Crowdsale
*
* return total participant
*/
function totalParticipant() public view returns(uint){
return addressList.length;
}
/**
* Function to set opening time of Crowdsale
* @param _time : time for opening time
*
* return event OpeningTime
*/
function changeOpeningTime(uint256 _time) public onlyOwner returns(bool) {
require(_time >= block.timestamp, "BitmindMsg: Opening Time must before current time");
start_time = _time;
emit setOpeningtime(owner, _time);
return true;
}
/**
* Function to set closing time of Crowdsale
* @param _time : time for opening time
*
* return event ClosingTime
*/
function changeClosingTime(uint256 _time) public onlyOwner returns(bool) {
require(_time >= start_time, "BitmindMsg: Closing Time already set");
end_time = _time;
emit setClosingtime(owner, _time);
return true;
}
/**
* Function to change Crowdsale contract Owner
* Only Owner who could access this function
*
* return event OwnershipTransferred
*/
function transferOwnership(address payable _owner) onlyOwner public returns(bool) {
owner = _owner;
emit OwnershipTransferred(msg.sender, _owner, block.timestamp);
return true;
}
/**
* Function to change Freezer Address
* Only Freezer who could access this function
*
* return event FreezerTransferred
*/
function transferFreezer(address freezer) onlyFreezer public returns(bool){
freezerAddress = freezer;
emit FreezerTransferred(msg.sender, freezer, block.timestamp);
return true;
}
/**
* Function to freeze or pause crowdsale
* Only Freezer who could access this function
*
* return true
*/
function freeze() public onlyFreezer returns(bool) {
pause = true;
emit FreezeCrowdsale(freezerAddress, block.timestamp);
return true;
}
/**
* Function to unfreeze or pause crowdsale
* Only Freezer who could access this function
*
* return true
*/
function unfreeze() public onlyFreezer returns(bool) {
pause = false;
emit UnfreezeCrowdsale(freezerAddress, block.timestamp);
return true;
}
}
|
Function to get rate which user get during transaction per 1 pair on Crowdsale/
|
function Rate() public view returns(uint256){
return rate;
}
| 5,921,630
|
./full_match/1/0x63863008D18B5Bc4bcDe71C092A1591CD1AB731D/sources/contracts/WalletSimple.sol
|
Sets the autoflush 721 parameter on the forwarder. forwarderAddress the address of the forwarder to toggle. autoFlush whether to autoflush erc1155 tokens/
|
function setAutoFlush1155(address forwarderAddress, bool autoFlush)
external
onlySigner
{
IForwarder forwarder = IForwarder(forwarderAddress);
forwarder.setAutoFlush1155(autoFlush);
}
| 16,471,864
|
// SPDX-License-Identifier: AGPL-3.0-only
/**
* DepositBoxEth.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2019-Present SKALE Labs
* @author Artem Payvin
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@skalenetwork/ima-interfaces/mainnet/DepositBoxes/IDepositBoxEth.sol";
import "../DepositBox.sol";
import "../../Messages.sol";
/**
* @title DepositBoxEth
* @dev Runs on mainnet,
* accepts messages from schain,
* stores deposits of ETH.
*/
contract DepositBoxEth is DepositBox, IDepositBoxEth {
using AddressUpgradeable for address payable;
mapping(address => uint256) public approveTransfers;
mapping(bytes32 => uint256) public transferredAmount;
mapping(bytes32 => bool) public activeEthTransfers;
event ActiveEthTransfers(bytes32 indexed schainHash, bool active);
receive() external payable override {
revert("Use deposit function");
}
/**
* @dev Allows `msg.sender` to send ETH from mainnet to schain.
*
* Requirements:
*
* - Schain name must not be `Mainnet`.
* - Receiver contract should be added as twin contract on schain.
* - Schain that receives tokens should not be killed.
*/
function deposit(string memory schainName)
external
payable
override
rightTransaction(schainName, msg.sender)
whenNotKilled(keccak256(abi.encodePacked(schainName)))
{
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
address contractReceiver = schainLinks[schainHash];
require(contractReceiver != address(0), "Unconnected chain");
_saveTransferredAmount(schainHash, msg.value);
messageProxy.postOutgoingMessage(
schainHash,
contractReceiver,
Messages.encodeTransferEthMessage(msg.sender, msg.value)
);
}
/**
* @dev Allows MessageProxyForMainnet contract to execute transferring ERC20 token from schain to mainnet.
*
* Requirements:
*
* - Schain from which the eth came should not be killed.
* - Sender contract should be defined and schain name cannot be `Mainnet`.
* - Amount of eth on DepositBoxEth should be equal or more than transferred amount.
*/
function postMessage(
bytes32 schainHash,
address sender,
bytes calldata data
)
external
override
onlyMessageProxy
whenNotKilled(schainHash)
checkReceiverChain(schainHash, sender)
{
Messages.TransferEthMessage memory message = Messages.decodeTransferEthMessage(data);
require(
message.amount <= address(this).balance,
"Not enough money to finish this transaction"
);
_removeTransferredAmount(schainHash, message.amount);
if (!activeEthTransfers[schainHash]) {
approveTransfers[message.receiver] += message.amount;
} else {
payable(message.receiver).sendValue(message.amount);
}
}
/**
* @dev Transfers a user's ETH.
*
* Requirements:
*
* - DepositBoxETh must have sufficient ETH.
* - User must be approved for ETH transfer.
*/
function getMyEth() external override {
require(approveTransfers[msg.sender] > 0, "User has insufficient ETH");
uint256 amount = approveTransfers[msg.sender];
approveTransfers[msg.sender] = 0;
payable(msg.sender).sendValue(amount);
}
/**
* @dev Allows Schain owner to return each user their ETH.
*
* Requirements:
*
* - Amount of ETH on schain should be equal or more than transferred amount.
* - Receiver address must not be null.
* - msg.sender should be an owner of schain
* - IMA transfers Mainnet <-> schain should be killed
*/
function getFunds(string calldata schainName, address payable receiver, uint amount)
external
override
onlySchainOwner(schainName)
whenKilled(keccak256(abi.encodePacked(schainName)))
{
require(receiver != address(0), "Receiver address has to be set");
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(transferredAmount[schainHash] >= amount, "Incorrect amount");
_removeTransferredAmount(schainHash, amount);
receiver.sendValue(amount);
}
/**
* @dev Allows Schain owner to switch on or switch off active eth transfers.
*
* Requirements:
*
* - msg.sender should be an owner of schain
* - IMA transfers Mainnet <-> schain should be killed
*/
function enableActiveEthTransfers(string calldata schainName)
external
override
onlySchainOwner(schainName)
whenNotKilled(keccak256(abi.encodePacked(schainName)))
{
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(!activeEthTransfers[schainHash], "Active eth transfers enabled");
emit ActiveEthTransfers(schainHash, true);
activeEthTransfers[schainHash] = true;
}
/**
* @dev Allows Schain owner to switch on or switch off active eth transfers.
*
* Requirements:
*
* - msg.sender should be an owner of schain
* - IMA transfers Mainnet <-> schain should be killed
*/
function disableActiveEthTransfers(string calldata schainName)
external
override
onlySchainOwner(schainName)
whenNotKilled(keccak256(abi.encodePacked(schainName)))
{
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(activeEthTransfers[schainHash], "Active eth transfers disabled");
emit ActiveEthTransfers(schainHash, false);
activeEthTransfers[schainHash] = false;
}
/**
* @dev Returns receiver of message.
*
* Requirements:
*
* - Sender contract should be defined and schain name cannot be `Mainnet`.
*/
function gasPayer(
bytes32 schainHash,
address sender,
bytes calldata data
)
external
view
override
checkReceiverChain(schainHash, sender)
returns (address)
{
Messages.TransferEthMessage memory message = Messages.decodeTransferEthMessage(data);
return message.receiver;
}
/**
* @dev Creates a new DepositBoxEth contract.
*/
function initialize(
IContractManager contractManagerOfSkaleManagerValue,
ILinker linkerValue,
IMessageProxyForMainnet messageProxyValue
)
public
override(DepositBox, IDepositBox)
initializer
{
DepositBox.initialize(contractManagerOfSkaleManagerValue, linkerValue, messageProxyValue);
}
/**
* @dev Saves amount of ETH that was transferred to schain.
*/
function _saveTransferredAmount(bytes32 schainHash, uint256 amount) private {
transferredAmount[schainHash] += amount;
}
/**
* @dev Removes amount of ETH that was transferred from schain.
*/
function _removeTransferredAmount(bytes32 schainHash, uint256 amount) private {
transferredAmount[schainHash] -= amount;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
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 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: AGPL-3.0-only
/**
* IDepositBoxEth.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
import "../IDepositBox.sol";
interface IDepositBoxEth is IDepositBox {
receive() external payable;
function deposit(string memory schainName) external payable;
function getMyEth() external;
function getFunds(string calldata schainName, address payable receiver, uint amount) external;
function enableActiveEthTransfers(string calldata schainName) external;
function disableActiveEthTransfers(string calldata schainName) external;
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* DepositBox.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Artem Payvin
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
import "@skalenetwork/ima-interfaces/mainnet/IDepositBox.sol";
import "./Twin.sol";
/**
* @title DepositBox
* @dev Abstract contracts for DepositBoxes on mainnet.
*/
abstract contract DepositBox is IDepositBox, Twin {
ILinker public linker;
// schainHash => true if automatic deployment tokens on schain was enabled
mapping(bytes32 => bool) private _automaticDeploy;
bytes32 public constant DEPOSIT_BOX_MANAGER_ROLE = keccak256("DEPOSIT_BOX_MANAGER_ROLE");
/**
* @dev Modifier for checking whether schain was not killed.
*/
modifier whenNotKilled(bytes32 schainHash) {
require(linker.isNotKilled(schainHash), "Schain is killed");
_;
}
/**
* @dev Modifier for checking whether schain was killed.
*/
modifier whenKilled(bytes32 schainHash) {
require(!linker.isNotKilled(schainHash), "Schain is not killed");
_;
}
/**
* @dev Modifier for checking whether schainName is not equal to `Mainnet`
* and address of receiver is not equal to null before transferring funds from mainnet to schain.
*/
modifier rightTransaction(string memory schainName, address to) {
require(
keccak256(abi.encodePacked(schainName)) != keccak256(abi.encodePacked("Mainnet")),
"SKALE chain name cannot be Mainnet"
);
require(to != address(0), "Receiver address cannot be null");
_;
}
/**
* @dev Modifier for checking whether schainHash is not equal to `Mainnet`
* and sender contract was added as contract processor on schain.
*/
modifier checkReceiverChain(bytes32 schainHash, address sender) {
require(
schainHash != keccak256(abi.encodePacked("Mainnet")) &&
sender == schainLinks[schainHash],
"Receiver chain is incorrect"
);
_;
}
/**
* @dev Allows Schain owner turn on whitelist of tokens.
*/
function enableWhitelist(string memory schainName) external override onlySchainOwner(schainName) {
_automaticDeploy[keccak256(abi.encodePacked(schainName))] = false;
}
/**
* @dev Allows Schain owner turn off whitelist of tokens.
*/
function disableWhitelist(string memory schainName) external override onlySchainOwner(schainName) {
_automaticDeploy[keccak256(abi.encodePacked(schainName))] = true;
}
function initialize(
IContractManager contractManagerOfSkaleManagerValue,
ILinker newLinker,
IMessageProxyForMainnet messageProxyValue
)
public
override
virtual
initializer
{
Twin.initialize(contractManagerOfSkaleManagerValue, messageProxyValue);
_setupRole(LINKER_ROLE, address(newLinker));
linker = newLinker;
}
/**
* @dev Returns is whitelist enabled on schain.
*/
function isWhitelisted(string memory schainName) public view override returns (bool) {
return !_automaticDeploy[keccak256(abi.encodePacked(schainName))];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* Messages.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
/**
* @title Messages
* @dev Library for encoding and decoding messages
* for transferring from Mainnet to Schain and vice versa.
*/
library Messages {
/**
* @dev Enumerator that describes all supported message types.
*/
enum MessageType {
EMPTY,
TRANSFER_ETH,
TRANSFER_ERC20,
TRANSFER_ERC20_AND_TOTAL_SUPPLY,
TRANSFER_ERC20_AND_TOKEN_INFO,
TRANSFER_ERC721,
TRANSFER_ERC721_AND_TOKEN_INFO,
USER_STATUS,
INTERCHAIN_CONNECTION,
TRANSFER_ERC1155,
TRANSFER_ERC1155_AND_TOKEN_INFO,
TRANSFER_ERC1155_BATCH,
TRANSFER_ERC1155_BATCH_AND_TOKEN_INFO,
TRANSFER_ERC721_WITH_METADATA,
TRANSFER_ERC721_WITH_METADATA_AND_TOKEN_INFO
}
/**
* @dev Structure for base message.
*/
struct BaseMessage {
MessageType messageType;
}
/**
* @dev Structure for describing ETH.
*/
struct TransferEthMessage {
BaseMessage message;
address receiver;
uint256 amount;
}
/**
* @dev Structure for user status.
*/
struct UserStatusMessage {
BaseMessage message;
address receiver;
bool isActive;
}
/**
* @dev Structure for describing ERC20 token.
*/
struct TransferErc20Message {
BaseMessage message;
address token;
address receiver;
uint256 amount;
}
/**
* @dev Structure for describing additional data for ERC20 token.
*/
struct Erc20TokenInfo {
string name;
uint8 decimals;
string symbol;
}
/**
* @dev Structure for describing ERC20 with token supply.
*/
struct TransferErc20AndTotalSupplyMessage {
TransferErc20Message baseErc20transfer;
uint256 totalSupply;
}
/**
* @dev Structure for describing ERC20 with token info.
*/
struct TransferErc20AndTokenInfoMessage {
TransferErc20Message baseErc20transfer;
uint256 totalSupply;
Erc20TokenInfo tokenInfo;
}
/**
* @dev Structure for describing base ERC721.
*/
struct TransferErc721Message {
BaseMessage message;
address token;
address receiver;
uint256 tokenId;
}
/**
* @dev Structure for describing base ERC721 with metadata.
*/
struct TransferErc721MessageWithMetadata {
TransferErc721Message erc721message;
string tokenURI;
}
/**
* @dev Structure for describing ERC20 with token info.
*/
struct Erc721TokenInfo {
string name;
string symbol;
}
/**
* @dev Structure for describing additional data for ERC721 token.
*/
struct TransferErc721AndTokenInfoMessage {
TransferErc721Message baseErc721transfer;
Erc721TokenInfo tokenInfo;
}
/**
* @dev Structure for describing additional data for ERC721 token with metadata.
*/
struct TransferErc721WithMetadataAndTokenInfoMessage {
TransferErc721MessageWithMetadata baseErc721transferWithMetadata;
Erc721TokenInfo tokenInfo;
}
/**
* @dev Structure for describing whether interchain connection is allowed.
*/
struct InterchainConnectionMessage {
BaseMessage message;
bool isAllowed;
}
/**
* @dev Structure for describing whether interchain connection is allowed.
*/
struct TransferErc1155Message {
BaseMessage message;
address token;
address receiver;
uint256 id;
uint256 amount;
}
/**
* @dev Structure for describing ERC1155 token in batches.
*/
struct TransferErc1155BatchMessage {
BaseMessage message;
address token;
address receiver;
uint256[] ids;
uint256[] amounts;
}
/**
* @dev Structure for describing ERC1155 token info.
*/
struct Erc1155TokenInfo {
string uri;
}
/**
* @dev Structure for describing message for transferring ERC1155 token with info.
*/
struct TransferErc1155AndTokenInfoMessage {
TransferErc1155Message baseErc1155transfer;
Erc1155TokenInfo tokenInfo;
}
/**
* @dev Structure for describing message for transferring ERC1155 token in batches with info.
*/
struct TransferErc1155BatchAndTokenInfoMessage {
TransferErc1155BatchMessage baseErc1155Batchtransfer;
Erc1155TokenInfo tokenInfo;
}
/**
* @dev Returns type of message for encoded data.
*/
function getMessageType(bytes calldata data) internal pure returns (MessageType) {
uint256 firstWord = abi.decode(data, (uint256));
if (firstWord % 32 == 0) {
return getMessageType(data[firstWord:]);
} else {
return abi.decode(data, (Messages.MessageType));
}
}
/**
* @dev Encodes message for transferring ETH. Returns encoded message.
*/
function encodeTransferEthMessage(address receiver, uint256 amount) internal pure returns (bytes memory) {
TransferEthMessage memory message = TransferEthMessage(
BaseMessage(MessageType.TRANSFER_ETH),
receiver,
amount
);
return abi.encode(message);
}
/**
* @dev Decodes message for transferring ETH. Returns structure `TransferEthMessage`.
*/
function decodeTransferEthMessage(
bytes calldata data
) internal pure returns (TransferEthMessage memory) {
require(getMessageType(data) == MessageType.TRANSFER_ETH, "Message type is not ETH transfer");
return abi.decode(data, (TransferEthMessage));
}
/**
* @dev Encodes message for transferring ETH. Returns encoded message.
*/
function encodeTransferErc20Message(
address token,
address receiver,
uint256 amount
) internal pure returns (bytes memory) {
TransferErc20Message memory message = TransferErc20Message(
BaseMessage(MessageType.TRANSFER_ERC20),
token,
receiver,
amount
);
return abi.encode(message);
}
/**
* @dev Encodes message for transferring ERC20 with total supply. Returns encoded message.
*/
function encodeTransferErc20AndTotalSupplyMessage(
address token,
address receiver,
uint256 amount,
uint256 totalSupply
) internal pure returns (bytes memory) {
TransferErc20AndTotalSupplyMessage memory message = TransferErc20AndTotalSupplyMessage(
TransferErc20Message(
BaseMessage(MessageType.TRANSFER_ERC20_AND_TOTAL_SUPPLY),
token,
receiver,
amount
),
totalSupply
);
return abi.encode(message);
}
/**
* @dev Decodes message for transferring ERC20. Returns structure `TransferErc20Message`.
*/
function decodeTransferErc20Message(
bytes calldata data
) internal pure returns (TransferErc20Message memory) {
require(getMessageType(data) == MessageType.TRANSFER_ERC20, "Message type is not ERC20 transfer");
return abi.decode(data, (TransferErc20Message));
}
/**
* @dev Decodes message for transferring ERC20 with total supply.
* Returns structure `TransferErc20AndTotalSupplyMessage`.
*/
function decodeTransferErc20AndTotalSupplyMessage(
bytes calldata data
) internal pure returns (TransferErc20AndTotalSupplyMessage memory) {
require(
getMessageType(data) == MessageType.TRANSFER_ERC20_AND_TOTAL_SUPPLY,
"Message type is not ERC20 transfer and total supply"
);
return abi.decode(data, (TransferErc20AndTotalSupplyMessage));
}
/**
* @dev Encodes message for transferring ERC20 with token info.
* Returns encoded message.
*/
function encodeTransferErc20AndTokenInfoMessage(
address token,
address receiver,
uint256 amount,
uint256 totalSupply,
Erc20TokenInfo memory tokenInfo
) internal pure returns (bytes memory) {
TransferErc20AndTokenInfoMessage memory message = TransferErc20AndTokenInfoMessage(
TransferErc20Message(
BaseMessage(MessageType.TRANSFER_ERC20_AND_TOKEN_INFO),
token,
receiver,
amount
),
totalSupply,
tokenInfo
);
return abi.encode(message);
}
/**
* @dev Decodes message for transferring ERC20 with token info.
* Returns structure `TransferErc20AndTokenInfoMessage`.
*/
function decodeTransferErc20AndTokenInfoMessage(
bytes calldata data
) internal pure returns (TransferErc20AndTokenInfoMessage memory) {
require(
getMessageType(data) == MessageType.TRANSFER_ERC20_AND_TOKEN_INFO,
"Message type is not ERC20 transfer with token info"
);
return abi.decode(data, (TransferErc20AndTokenInfoMessage));
}
/**
* @dev Encodes message for transferring ERC721.
* Returns encoded message.
*/
function encodeTransferErc721Message(
address token,
address receiver,
uint256 tokenId
) internal pure returns (bytes memory) {
TransferErc721Message memory message = TransferErc721Message(
BaseMessage(MessageType.TRANSFER_ERC721),
token,
receiver,
tokenId
);
return abi.encode(message);
}
/**
* @dev Decodes message for transferring ERC721.
* Returns structure `TransferErc721Message`.
*/
function decodeTransferErc721Message(
bytes calldata data
) internal pure returns (TransferErc721Message memory) {
require(getMessageType(data) == MessageType.TRANSFER_ERC721, "Message type is not ERC721 transfer");
return abi.decode(data, (TransferErc721Message));
}
/**
* @dev Encodes message for transferring ERC721 with token info.
* Returns encoded message.
*/
function encodeTransferErc721AndTokenInfoMessage(
address token,
address receiver,
uint256 tokenId,
Erc721TokenInfo memory tokenInfo
) internal pure returns (bytes memory) {
TransferErc721AndTokenInfoMessage memory message = TransferErc721AndTokenInfoMessage(
TransferErc721Message(
BaseMessage(MessageType.TRANSFER_ERC721_AND_TOKEN_INFO),
token,
receiver,
tokenId
),
tokenInfo
);
return abi.encode(message);
}
/**
* @dev Decodes message for transferring ERC721 with token info.
* Returns structure `TransferErc721AndTokenInfoMessage`.
*/
function decodeTransferErc721AndTokenInfoMessage(
bytes calldata data
) internal pure returns (TransferErc721AndTokenInfoMessage memory) {
require(
getMessageType(data) == MessageType.TRANSFER_ERC721_AND_TOKEN_INFO,
"Message type is not ERC721 transfer with token info"
);
return abi.decode(data, (TransferErc721AndTokenInfoMessage));
}
/**
* @dev Encodes message for transferring ERC721.
* Returns encoded message.
*/
function encodeTransferErc721MessageWithMetadata(
address token,
address receiver,
uint256 tokenId,
string memory tokenURI
) internal pure returns (bytes memory) {
TransferErc721MessageWithMetadata memory message = TransferErc721MessageWithMetadata(
TransferErc721Message(
BaseMessage(MessageType.TRANSFER_ERC721_WITH_METADATA),
token,
receiver,
tokenId
),
tokenURI
);
return abi.encode(message);
}
/**
* @dev Decodes message for transferring ERC721.
* Returns structure `TransferErc721MessageWithMetadata`.
*/
function decodeTransferErc721MessageWithMetadata(
bytes calldata data
) internal pure returns (TransferErc721MessageWithMetadata memory) {
require(
getMessageType(data) == MessageType.TRANSFER_ERC721_WITH_METADATA,
"Message type is not ERC721 transfer"
);
return abi.decode(data, (TransferErc721MessageWithMetadata));
}
/**
* @dev Encodes message for transferring ERC721 with token info.
* Returns encoded message.
*/
function encodeTransferErc721WithMetadataAndTokenInfoMessage(
address token,
address receiver,
uint256 tokenId,
string memory tokenURI,
Erc721TokenInfo memory tokenInfo
) internal pure returns (bytes memory) {
TransferErc721WithMetadataAndTokenInfoMessage memory message = TransferErc721WithMetadataAndTokenInfoMessage(
TransferErc721MessageWithMetadata(
TransferErc721Message(
BaseMessage(MessageType.TRANSFER_ERC721_WITH_METADATA_AND_TOKEN_INFO),
token,
receiver,
tokenId
),
tokenURI
),
tokenInfo
);
return abi.encode(message);
}
/**
* @dev Decodes message for transferring ERC721 with token info.
* Returns structure `TransferErc721WithMetadataAndTokenInfoMessage`.
*/
function decodeTransferErc721WithMetadataAndTokenInfoMessage(
bytes calldata data
) internal pure returns (TransferErc721WithMetadataAndTokenInfoMessage memory) {
require(
getMessageType(data) == MessageType.TRANSFER_ERC721_WITH_METADATA_AND_TOKEN_INFO,
"Message type is not ERC721 transfer with token info"
);
return abi.decode(data, (TransferErc721WithMetadataAndTokenInfoMessage));
}
/**
* @dev Encodes message for activating user on schain.
* Returns encoded message.
*/
function encodeActivateUserMessage(address receiver) internal pure returns (bytes memory){
return _encodeUserStatusMessage(receiver, true);
}
/**
* @dev Encodes message for locking user on schain.
* Returns encoded message.
*/
function encodeLockUserMessage(address receiver) internal pure returns (bytes memory){
return _encodeUserStatusMessage(receiver, false);
}
/**
* @dev Decodes message for user status.
* Returns structure UserStatusMessage.
*/
function decodeUserStatusMessage(bytes calldata data) internal pure returns (UserStatusMessage memory) {
require(getMessageType(data) == MessageType.USER_STATUS, "Message type is not User Status");
return abi.decode(data, (UserStatusMessage));
}
/**
* @dev Encodes message for allowing interchain connection.
* Returns encoded message.
*/
function encodeInterchainConnectionMessage(bool isAllowed) internal pure returns (bytes memory) {
InterchainConnectionMessage memory message = InterchainConnectionMessage(
BaseMessage(MessageType.INTERCHAIN_CONNECTION),
isAllowed
);
return abi.encode(message);
}
/**
* @dev Decodes message for allowing interchain connection.
* Returns structure `InterchainConnectionMessage`.
*/
function decodeInterchainConnectionMessage(bytes calldata data)
internal
pure
returns (InterchainConnectionMessage memory)
{
require(getMessageType(data) == MessageType.INTERCHAIN_CONNECTION, "Message type is not Interchain connection");
return abi.decode(data, (InterchainConnectionMessage));
}
/**
* @dev Encodes message for transferring ERC1155 token.
* Returns encoded message.
*/
function encodeTransferErc1155Message(
address token,
address receiver,
uint256 id,
uint256 amount
) internal pure returns (bytes memory) {
TransferErc1155Message memory message = TransferErc1155Message(
BaseMessage(MessageType.TRANSFER_ERC1155),
token,
receiver,
id,
amount
);
return abi.encode(message);
}
/**
* @dev Decodes message for transferring ERC1155 token.
* Returns structure `TransferErc1155Message`.
*/
function decodeTransferErc1155Message(
bytes calldata data
) internal pure returns (TransferErc1155Message memory) {
require(getMessageType(data) == MessageType.TRANSFER_ERC1155, "Message type is not ERC1155 transfer");
return abi.decode(data, (TransferErc1155Message));
}
/**
* @dev Encodes message for transferring ERC1155 with token info.
* Returns encoded message.
*/
function encodeTransferErc1155AndTokenInfoMessage(
address token,
address receiver,
uint256 id,
uint256 amount,
Erc1155TokenInfo memory tokenInfo
) internal pure returns (bytes memory) {
TransferErc1155AndTokenInfoMessage memory message = TransferErc1155AndTokenInfoMessage(
TransferErc1155Message(
BaseMessage(MessageType.TRANSFER_ERC1155_AND_TOKEN_INFO),
token,
receiver,
id,
amount
),
tokenInfo
);
return abi.encode(message);
}
/**
* @dev Decodes message for transferring ERC1155 with token info.
* Returns structure `TransferErc1155AndTokenInfoMessage`.
*/
function decodeTransferErc1155AndTokenInfoMessage(
bytes calldata data
) internal pure returns (TransferErc1155AndTokenInfoMessage memory) {
require(
getMessageType(data) == MessageType.TRANSFER_ERC1155_AND_TOKEN_INFO,
"Message type is not ERC1155AndTokenInfo transfer"
);
return abi.decode(data, (TransferErc1155AndTokenInfoMessage));
}
/**
* @dev Encodes message for transferring ERC1155 token in batches.
* Returns encoded message.
*/
function encodeTransferErc1155BatchMessage(
address token,
address receiver,
uint256[] memory ids,
uint256[] memory amounts
) internal pure returns (bytes memory) {
TransferErc1155BatchMessage memory message = TransferErc1155BatchMessage(
BaseMessage(MessageType.TRANSFER_ERC1155_BATCH),
token,
receiver,
ids,
amounts
);
return abi.encode(message);
}
/**
* @dev Decodes message for transferring ERC1155 token in batches.
* Returns structure `TransferErc1155BatchMessage`.
*/
function decodeTransferErc1155BatchMessage(
bytes calldata data
) internal pure returns (TransferErc1155BatchMessage memory) {
require(
getMessageType(data) == MessageType.TRANSFER_ERC1155_BATCH,
"Message type is not ERC1155Batch transfer"
);
return abi.decode(data, (TransferErc1155BatchMessage));
}
/**
* @dev Encodes message for transferring ERC1155 token in batches with token info.
* Returns encoded message.
*/
function encodeTransferErc1155BatchAndTokenInfoMessage(
address token,
address receiver,
uint256[] memory ids,
uint256[] memory amounts,
Erc1155TokenInfo memory tokenInfo
) internal pure returns (bytes memory) {
TransferErc1155BatchAndTokenInfoMessage memory message = TransferErc1155BatchAndTokenInfoMessage(
TransferErc1155BatchMessage(
BaseMessage(MessageType.TRANSFER_ERC1155_BATCH_AND_TOKEN_INFO),
token,
receiver,
ids,
amounts
),
tokenInfo
);
return abi.encode(message);
}
/**
* @dev Decodes message for transferring ERC1155 token in batches with token info.
* Returns structure `TransferErc1155BatchAndTokenInfoMessage`.
*/
function decodeTransferErc1155BatchAndTokenInfoMessage(
bytes calldata data
) internal pure returns (TransferErc1155BatchAndTokenInfoMessage memory) {
require(
getMessageType(data) == MessageType.TRANSFER_ERC1155_BATCH_AND_TOKEN_INFO,
"Message type is not ERC1155BatchAndTokenInfo transfer"
);
return abi.decode(data, (TransferErc1155BatchAndTokenInfoMessage));
}
/**
* @dev Encodes message for transferring user status on schain.
* Returns encoded message.
*/
function _encodeUserStatusMessage(address receiver, bool isActive) private pure returns (bytes memory) {
UserStatusMessage memory message = UserStatusMessage(
BaseMessage(MessageType.USER_STATUS),
receiver,
isActive
);
return abi.encode(message);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* IDepositBox.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
import "@skalenetwork/skale-manager-interfaces/IContractManager.sol";
import "../IGasReimbursable.sol";
import "../IMessageReceiver.sol";
import "./ILinker.sol";
import "./IMessageProxyForMainnet.sol";
import "./ITwin.sol";
interface IDepositBox is ITwin, IMessageReceiver, IGasReimbursable {
function initialize(
IContractManager contractManagerOfSkaleManagerValue,
ILinker newLinker,
IMessageProxyForMainnet messageProxyValue
) external;
function enableWhitelist(string memory schainName) external;
function disableWhitelist(string memory schainName) external;
function isWhitelisted(string memory schainName) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IContractManager.sol - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaeiv
SKALE Manager Interfaces is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager Interfaces is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IContractManager {
/**
* @dev Emitted when contract is upgraded.
*/
event ContractUpgraded(string contractsName, address contractsAddress);
function initialize() external;
function setContractsAddress(string calldata contractsName, address newContractsAddress) external;
function contracts(bytes32 nameHash) external view returns (address);
function getDelegationPeriodManager() external view returns (address);
function getBounty() external view returns (address);
function getValidatorService() external view returns (address);
function getTimeHelpers() external view returns (address);
function getConstantsHolder() external view returns (address);
function getSkaleToken() external view returns (address);
function getTokenState() external view returns (address);
function getPunisher() external view returns (address);
function getContract(string calldata name) external view returns (address);
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* IGasReimbursable.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Artem Payvin
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
import "./IMessageReceiver.sol";
interface IGasReimbursable is IMessageReceiver {
function gasPayer(
bytes32 schainHash,
address sender,
bytes calldata data
)
external
returns (address);
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* IMessageReceiver.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IMessageReceiver {
function postMessage(
bytes32 schainHash,
address sender,
bytes calldata data
)
external;
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* ILinker.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
import "./ITwin.sol";
interface ILinker is ITwin {
function registerMainnetContract(address newMainnetContract) external;
function removeMainnetContract(address mainnetContract) external;
function connectSchain(string calldata schainName, address[] calldata schainContracts) external;
function kill(string calldata schainName) external;
function disconnectSchain(string calldata schainName) external;
function isNotKilled(bytes32 schainHash) external view returns (bool);
function hasMainnetContract(address mainnetContract) external view returns (bool);
function hasSchain(string calldata schainName) external view returns (bool connected);
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* IMessageProxyForMainnet.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
import "../IMessageProxy.sol";
import "./ICommunityPool.sol";
interface IMessageProxyForMainnet is IMessageProxy {
function setCommunityPool(ICommunityPool newCommunityPoolAddress) external;
function setNewHeaderMessageGasCost(uint256 newHeaderMessageGasCost) external;
function setNewMessageGasCost(uint256 newMessageGasCost) external;
function messageInProgress() external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* ITwin.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
import "./ISkaleManagerClient.sol";
interface ITwin is ISkaleManagerClient {
function addSchainContract(string calldata schainName, address contractReceiver) external;
function removeSchainContract(string calldata schainName) external;
function hasSchainContract(string calldata schainName) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* ISkaleManagerClient.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
import "@skalenetwork/skale-manager-interfaces/IContractManager.sol";
interface ISkaleManagerClient {
function initialize(IContractManager newContractManagerOfSkaleManager) external;
function isSchainOwner(address sender, bytes32 schainHash) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* IMessageProxy.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IMessageProxy {
/**
* @dev Structure that describes message. Should contain sender of message,
* destination contract on schain that will receiver message,
* data that contains all needed info about token or ETH.
*/
struct Message {
address sender;
address destinationContract;
bytes data;
}
/**
* @dev Structure that contains fields for bls signature.
*/
struct Signature {
uint256[2] blsSignature;
uint256 hashA;
uint256 hashB;
uint256 counter;
}
function addConnectedChain(string calldata schainName) external;
function postIncomingMessages(
string calldata fromSchainName,
uint256 startingCounter,
Message[] calldata messages,
Signature calldata sign
) external;
function setNewGasLimit(uint256 newGasLimit) external;
function registerExtraContractForAll(address extraContract) external;
function removeExtraContractForAll(address extraContract) external;
function removeConnectedChain(string memory schainName) external;
function postOutgoingMessage(
bytes32 targetChainHash,
address targetContract,
bytes memory data
) external;
function registerExtraContract(string memory chainName, address extraContract) external;
function removeExtraContract(string memory schainName, address extraContract) external;
function setVersion(string calldata newVersion) external;
function isContractRegistered(
bytes32 schainHash,
address contractAddress
) external view returns (bool);
function getContractRegisteredLength(bytes32 schainHash) external view returns (uint256);
function getContractRegisteredRange(
bytes32 schainHash,
uint256 from,
uint256 to
)
external
view
returns (address[] memory);
function getOutgoingMessagesCounter(string calldata targetSchainName) external view returns (uint256);
function getIncomingMessagesCounter(string calldata fromSchainName) external view returns (uint256);
function isConnectedChain(string memory schainName) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* ICommunityPool.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
import "@skalenetwork/skale-manager-interfaces/IContractManager.sol";
import "./ILinker.sol";
import "./IMessageProxyForMainnet.sol";
import "./ITwin.sol";
interface ICommunityPool is ITwin {
function initialize(
IContractManager contractManagerOfSkaleManagerValue,
ILinker linker,
IMessageProxyForMainnet messageProxyValue
) external;
function refundGasByUser(bytes32 schainHash, address payable node, address user, uint gas) external returns (uint);
function rechargeUserWallet(string calldata schainName, address user) external payable;
function withdrawFunds(string calldata schainName, uint amount) external;
function setMinTransactionGas(uint newMinTransactionGas) external;
function refundGasBySchainWallet(
bytes32 schainHash,
address payable node,
uint gas
) external returns (bool);
function getBalance(address user, string calldata schainName) external view returns (uint);
function checkUserBalance(bytes32 schainHash, address receiver) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* Twin.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Artem Payvin
* @author Dmytro Stebaiev
* @author Vadim Yavorsky
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
import "@skalenetwork/ima-interfaces/mainnet/ITwin.sol";
import "./MessageProxyForMainnet.sol";
import "./SkaleManagerClient.sol";
/**
* @title Twin
* @dev Runs on Mainnet,
* contains logic for connecting paired contracts on Mainnet and on Schain.
*/
abstract contract Twin is SkaleManagerClient, ITwin {
IMessageProxyForMainnet public messageProxy;
mapping(bytes32 => address) public schainLinks;
bytes32 public constant LINKER_ROLE = keccak256("LINKER_ROLE");
/**
* @dev Modifier for checking whether caller is MessageProxy contract.
*/
modifier onlyMessageProxy() {
require(msg.sender == address(messageProxy), "Sender is not a MessageProxy");
_;
}
/**
* @dev Binds a contract on mainnet with their twin on schain.
*
* Requirements:
*
* - `msg.sender` must be schain owner or has required role.
* - SKALE chain must not already be added.
* - Address of contract on schain must be non-zero.
*/
function addSchainContract(string calldata schainName, address contractReceiver) external override {
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(
hasRole(LINKER_ROLE, msg.sender) ||
isSchainOwner(msg.sender, schainHash), "Not authorized caller"
);
require(schainLinks[schainHash] == address(0), "SKALE chain is already set");
require(contractReceiver != address(0), "Incorrect address of contract receiver on Schain");
schainLinks[schainHash] = contractReceiver;
}
/**
* @dev Removes connection with contract on schain.
*
* Requirements:
*
* - `msg.sender` must be schain owner or has required role.
* - SKALE chain must already be set.
*/
function removeSchainContract(string calldata schainName) external override {
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(
hasRole(LINKER_ROLE, msg.sender) ||
isSchainOwner(msg.sender, schainHash), "Not authorized caller"
);
require(schainLinks[schainHash] != address(0), "SKALE chain is not set");
delete schainLinks[schainHash];
}
/**
* @dev Returns true if mainnet contract and schain contract are connected together for transferring messages.
*/
function hasSchainContract(string calldata schainName) external view override returns (bool) {
return schainLinks[keccak256(abi.encodePacked(schainName))] != address(0);
}
function initialize(
IContractManager contractManagerOfSkaleManagerValue,
IMessageProxyForMainnet newMessageProxy
)
public
virtual
initializer
{
SkaleManagerClient.initialize(contractManagerOfSkaleManagerValue);
messageProxy = newMessageProxy;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* MessageProxyForMainnet.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2019-Present SKALE Labs
* @author Artem Payvin
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@skalenetwork/skale-manager-interfaces/IWallets.sol";
import "@skalenetwork/skale-manager-interfaces/ISchains.sol";
import "@skalenetwork/ima-interfaces/mainnet/IMessageProxyForMainnet.sol";
import "@skalenetwork/ima-interfaces/mainnet/ICommunityPool.sol";
import "@skalenetwork/skale-manager-interfaces/ISchainsInternal.sol";
import "../MessageProxy.sol";
import "./SkaleManagerClient.sol";
import "./CommunityPool.sol";
interface IMessageProxyForMainnetInitializeFunction is IMessageProxyForMainnet {
function initializeAllRegisteredContracts(
bytes32 schainHash,
address[] calldata contracts
) external;
}
/**
* @title Message Proxy for Mainnet
* @dev Runs on Mainnet, contains functions to manage the incoming messages from
* `targetSchainName` and outgoing messages to `fromSchainName`. Every SKALE chain with
* IMA is therefore connected to MessageProxyForMainnet.
*
* Messages from SKALE chains are signed using BLS threshold signatures from the
* nodes in the chain. Since Ethereum Mainnet has no BLS public key, mainnet
* messages do not need to be signed.
*/
contract MessageProxyForMainnet is SkaleManagerClient, MessageProxy, IMessageProxyForMainnetInitializeFunction {
using AddressUpgradeable for address;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
/**
* 16 Agents
* Synchronize time with time.nist.gov
* Every agent checks if it is their time slot
* Time slots are in increments of 10 seconds
* At the start of their slot each agent:
* For each connected schain:
* Read incoming counter on the dst chain
* Read outgoing counter on the src chain
* Calculate the difference outgoing - incoming
* Call postIncomingMessages function passing (un)signed message array
* ID of this schain, Chain 0 represents ETH mainnet,
*/
ICommunityPool public communityPool;
uint256 public headerMessageGasCost;
uint256 public messageGasCost;
mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _registryContracts;
string public version;
bool public override messageInProgress;
/**
* @dev Emitted when gas cost for message header was changed.
*/
event GasCostMessageHeaderWasChanged(
uint256 oldValue,
uint256 newValue
);
/**
* @dev Emitted when gas cost for message was changed.
*/
event GasCostMessageWasChanged(
uint256 oldValue,
uint256 newValue
);
/**
* @dev Reentrancy guard for postIncomingMessages.
*/
modifier messageInProgressLocker() {
require(!messageInProgress, "Message is in progress");
messageInProgress = true;
_;
messageInProgress = false;
}
/**
* @dev Allows DEFAULT_ADMIN_ROLE to initialize registered contracts
* Notice - this function will be executed only once during upgrade
*
* Requirements:
*
* `msg.sender` should have DEFAULT_ADMIN_ROLE
*/
function initializeAllRegisteredContracts(
bytes32 schainHash,
address[] calldata contracts
) external override {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Sender is not authorized");
for (uint256 i = 0; i < contracts.length; i++) {
if (
deprecatedRegistryContracts[schainHash][contracts[i]] &&
!_registryContracts[schainHash].contains(contracts[i])
) {
_registryContracts[schainHash].add(contracts[i]);
delete deprecatedRegistryContracts[schainHash][contracts[i]];
}
}
}
/**
* @dev Allows `msg.sender` to connect schain with MessageProxyOnMainnet for transferring messages.
*
* Requirements:
*
* - Schain name must not be `Mainnet`.
*/
function addConnectedChain(string calldata schainName) external override {
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(ISchainsInternal(
contractManagerOfSkaleManager.getContract("SchainsInternal")
).isSchainExist(schainHash), "SKALE chain must exist");
_addConnectedChain(schainHash);
}
/**
* @dev Allows owner of the contract to set CommunityPool address for gas reimbursement.
*
* Requirements:
*
* - `msg.sender` must be granted as DEFAULT_ADMIN_ROLE.
* - Address of CommunityPool contract must not be null.
*/
function setCommunityPool(ICommunityPool newCommunityPoolAddress) external override {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Not authorized caller");
require(address(newCommunityPoolAddress) != address(0), "CommunityPool address has to be set");
communityPool = newCommunityPoolAddress;
}
/**
* @dev Allows `msg.sender` to register extra contract for being able to transfer messages from custom contracts.
*
* Requirements:
*
* - `msg.sender` must be granted as EXTRA_CONTRACT_REGISTRAR_ROLE.
* - Schain name must not be `Mainnet`.
*/
function registerExtraContract(string memory schainName, address extraContract) external override {
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(
hasRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender) ||
isSchainOwner(msg.sender, schainHash),
"Not enough permissions to register extra contract"
);
require(schainHash != MAINNET_HASH, "Schain hash can not be equal Mainnet");
_registerExtraContract(schainHash, extraContract);
}
/**
* @dev Allows `msg.sender` to remove extra contract,
* thus `extraContract` will no longer be available to transfer messages from mainnet to schain.
*
* Requirements:
*
* - `msg.sender` must be granted as EXTRA_CONTRACT_REGISTRAR_ROLE.
* - Schain name must not be `Mainnet`.
*/
function removeExtraContract(string memory schainName, address extraContract) external override {
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(
hasRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender) ||
isSchainOwner(msg.sender, schainHash),
"Not enough permissions to register extra contract"
);
require(schainHash != MAINNET_HASH, "Schain hash can not be equal Mainnet");
_removeExtraContract(schainHash, extraContract);
}
/**
* @dev Posts incoming message from `fromSchainName`.
*
* Requirements:
*
* - `msg.sender` must be authorized caller.
* - `fromSchainName` must be initialized.
* - `startingCounter` must be equal to the chain's incoming message counter.
* - If destination chain is Mainnet, message signature must be valid.
*/
function postIncomingMessages(
string calldata fromSchainName,
uint256 startingCounter,
Message[] calldata messages,
Signature calldata sign
)
external
override(IMessageProxy, MessageProxy)
messageInProgressLocker
{
uint256 gasTotal = gasleft();
bytes32 fromSchainHash = keccak256(abi.encodePacked(fromSchainName));
require(_checkSchainBalance(fromSchainHash), "Schain wallet has not enough funds");
require(connectedChains[fromSchainHash].inited, "Chain is not initialized");
require(messages.length <= MESSAGES_LENGTH, "Too many messages");
require(
startingCounter == connectedChains[fromSchainHash].incomingMessageCounter,
"Starting counter is not equal to incoming message counter");
require(_verifyMessages(
fromSchainName,
_hashedArray(messages, startingCounter, fromSchainName), sign),
"Signature is not verified");
uint additionalGasPerMessage =
(gasTotal - gasleft() + headerMessageGasCost + messages.length * messageGasCost) / messages.length;
uint notReimbursedGas = 0;
connectedChains[fromSchainHash].incomingMessageCounter += messages.length;
for (uint256 i = 0; i < messages.length; i++) {
gasTotal = gasleft();
if (isContractRegistered(bytes32(0), messages[i].destinationContract)) {
address receiver = _getGasPayer(fromSchainHash, messages[i], startingCounter + i);
_callReceiverContract(fromSchainHash, messages[i], startingCounter + i);
notReimbursedGas += communityPool.refundGasByUser(
fromSchainHash,
payable(msg.sender),
receiver,
gasTotal - gasleft() + additionalGasPerMessage
);
} else {
_callReceiverContract(fromSchainHash, messages[i], startingCounter + i);
notReimbursedGas += gasTotal - gasleft() + additionalGasPerMessage;
}
}
communityPool.refundGasBySchainWallet(fromSchainHash, payable(msg.sender), notReimbursedGas);
}
/**
* @dev Sets headerMessageGasCost to a new value.
*
* Requirements:
*
* - `msg.sender` must be granted as CONSTANT_SETTER_ROLE.
*/
function setNewHeaderMessageGasCost(uint256 newHeaderMessageGasCost) external override onlyConstantSetter {
emit GasCostMessageHeaderWasChanged(headerMessageGasCost, newHeaderMessageGasCost);
headerMessageGasCost = newHeaderMessageGasCost;
}
/**
* @dev Sets messageGasCost to a new value.
*
* Requirements:
*
* - `msg.sender` must be granted as CONSTANT_SETTER_ROLE.
*/
function setNewMessageGasCost(uint256 newMessageGasCost) external override onlyConstantSetter {
emit GasCostMessageWasChanged(messageGasCost, newMessageGasCost);
messageGasCost = newMessageGasCost;
}
/**
* @dev Sets new version of contracts on mainnet
*
* Requirements:
*
* - `msg.sender` must be granted DEFAULT_ADMIN_ROLE.
*/
function setVersion(string calldata newVersion) external override {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "DEFAULT_ADMIN_ROLE is required");
emit VersionUpdated(version, newVersion);
version = newVersion;
}
/**
* @dev Creates a new MessageProxyForMainnet contract.
*/
function initialize(IContractManager contractManagerOfSkaleManagerValue) public virtual override initializer {
SkaleManagerClient.initialize(contractManagerOfSkaleManagerValue);
MessageProxy.initializeMessageProxy(1e6);
headerMessageGasCost = 73800;
messageGasCost = 9000;
}
/**
* @dev Checks whether chain is currently connected.
*
* Note: Mainnet chain does not have a public key, and is implicitly
* connected to MessageProxy.
*
* Requirements:
*
* - `schainName` must not be Mainnet.
*/
function isConnectedChain(
string memory schainName
)
public
view
override(IMessageProxy, MessageProxy)
returns (bool)
{
require(keccak256(abi.encodePacked(schainName)) != MAINNET_HASH, "Schain id can not be equal Mainnet");
return super.isConnectedChain(schainName);
}
// private
function _authorizeOutgoingMessageSender(bytes32 targetChainHash) internal view override {
require(
isContractRegistered(bytes32(0), msg.sender)
|| isContractRegistered(targetChainHash, msg.sender)
|| isSchainOwner(msg.sender, targetChainHash),
"Sender contract is not registered"
);
}
/**
* @dev Converts calldata structure to memory structure and checks
* whether message BLS signature is valid.
*/
function _verifyMessages(
string calldata fromSchainName,
bytes32 hashedMessages,
MessageProxyForMainnet.Signature calldata sign
)
internal
view
returns (bool)
{
return ISchains(
contractManagerOfSkaleManager.getContract("Schains")
).verifySchainSignature(
sign.blsSignature[0],
sign.blsSignature[1],
hashedMessages,
sign.counter,
sign.hashA,
sign.hashB,
fromSchainName
);
}
/**
* @dev Checks whether balance of schain wallet is sufficient for
* for reimbursement custom message.
*/
function _checkSchainBalance(bytes32 schainHash) internal view returns (bool) {
return IWallets(
payable(contractManagerOfSkaleManager.getContract("Wallets"))
).getSchainBalance(schainHash) >= (MESSAGES_LENGTH + 1) * gasLimit * tx.gasprice;
}
/**
* @dev Returns list of registered custom extra contracts.
*/
function _getRegistryContracts()
internal
view
override
returns (mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) storage)
{
return _registryContracts;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* SkaleManagerClient.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Artem Payvin
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import "@skalenetwork/skale-manager-interfaces/IContractManager.sol";
import "@skalenetwork/skale-manager-interfaces/ISchainsInternal.sol";
import "@skalenetwork/ima-interfaces/mainnet/ISkaleManagerClient.sol";
/**
* @title SkaleManagerClient - contract that knows ContractManager
* and makes calls to SkaleManager contracts.
*/
contract SkaleManagerClient is Initializable, AccessControlEnumerableUpgradeable, ISkaleManagerClient {
IContractManager public contractManagerOfSkaleManager;
/**
* @dev Modifier for checking whether caller is owner of SKALE chain.
*/
modifier onlySchainOwner(string memory schainName) {
require(
isSchainOwner(msg.sender, keccak256(abi.encodePacked(schainName))),
"Sender is not an Schain owner"
);
_;
}
/**
* @dev initialize - sets current address of ContractManager of SkaleManager.
* @param newContractManagerOfSkaleManager - current address of ContractManager of SkaleManager.
*/
function initialize(
IContractManager newContractManagerOfSkaleManager
)
public
override
virtual
initializer
{
AccessControlEnumerableUpgradeable.__AccessControlEnumerable_init();
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
contractManagerOfSkaleManager = newContractManagerOfSkaleManager;
}
/**
* @dev Checks whether sender is owner of SKALE chain
*/
function isSchainOwner(address sender, bytes32 schainHash) public view override returns (bool) {
address skaleChainsInternal = contractManagerOfSkaleManager.getContract("SchainsInternal");
return ISchainsInternal(skaleChainsInternal).isOwnerAddress(sender, schainHash);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IWallets - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaeiv
SKALE Manager Interfaces is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager Interfaces is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IWallets {
/**
* @dev Emitted when the validator wallet was funded
*/
event ValidatorWalletRecharged(address sponsor, uint amount, uint validatorId);
/**
* @dev Emitted when the schain wallet was funded
*/
event SchainWalletRecharged(address sponsor, uint amount, bytes32 schainHash);
/**
* @dev Emitted when the node received a refund from validator to its wallet
*/
event NodeRefundedByValidator(address node, uint validatorId, uint amount);
/**
* @dev Emitted when the node received a refund from schain to its wallet
*/
event NodeRefundedBySchain(address node, bytes32 schainHash, uint amount);
/**
* @dev Emitted when the validator withdrawn funds from validator wallet
*/
event WithdrawFromValidatorWallet(uint indexed validatorId, uint amount);
/**
* @dev Emitted when the schain owner withdrawn funds from schain wallet
*/
event WithdrawFromSchainWallet(bytes32 indexed schainHash, uint amount);
receive() external payable;
function refundGasByValidator(uint validatorId, address payable spender, uint spentGas) external;
function refundGasByValidatorToSchain(uint validatorId, bytes32 schainHash) external;
function refundGasBySchain(bytes32 schainId, address payable spender, uint spentGas, bool isDebt) external;
function withdrawFundsFromSchainWallet(address payable schainOwner, bytes32 schainHash) external;
function withdrawFundsFromValidatorWallet(uint amount) external;
function rechargeValidatorWallet(uint validatorId) external payable;
function rechargeSchainWallet(bytes32 schainId) external payable;
function getSchainBalance(bytes32 schainHash) external view returns (uint);
function getValidatorBalance(uint validatorId) external view returns (uint);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ISchains.sol - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaeiv
SKALE Manager Interfaces is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager Interfaces is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface ISchains {
struct SchainOption {
string name;
bytes value;
}
/**
* @dev Emitted when an schain is created.
*/
event SchainCreated(
string name,
address owner,
uint partOfNode,
uint lifetime,
uint numberOfNodes,
uint deposit,
uint16 nonce,
bytes32 schainHash
);
/**
* @dev Emitted when an schain is deleted.
*/
event SchainDeleted(
address owner,
string name,
bytes32 indexed schainHash
);
/**
* @dev Emitted when a node in an schain is rotated.
*/
event NodeRotated(
bytes32 schainHash,
uint oldNode,
uint newNode
);
/**
* @dev Emitted when a node is added to an schain.
*/
event NodeAdded(
bytes32 schainHash,
uint newNode
);
/**
* @dev Emitted when a group of nodes is created for an schain.
*/
event SchainNodes(
string name,
bytes32 schainHash,
uint[] nodesInGroup
);
function addSchain(address from, uint deposit, bytes calldata data) external;
function addSchainByFoundation(
uint lifetime,
uint8 typeOfSchain,
uint16 nonce,
string calldata name,
address schainOwner,
address schainOriginator,
SchainOption[] calldata options
)
external
payable;
function deleteSchain(address from, string calldata name) external;
function deleteSchainByRoot(string calldata name) external;
function restartSchainCreation(string calldata name) external;
function verifySchainSignature(
uint256 signA,
uint256 signB,
bytes32 hash,
uint256 counter,
uint256 hashA,
uint256 hashB,
string calldata schainName
)
external
view
returns (bool);
function getSchainPrice(uint typeOfSchain, uint lifetime) external view returns (uint);
function getOption(bytes32 schainHash, string calldata optionName) external view returns (bytes memory);
function getOptions(bytes32 schainHash) external view returns (SchainOption[] memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ISchainsInternal - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaeiv
SKALE Manager Interfaces is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager Interfaces is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface ISchainsInternal {
struct Schain {
string name;
address owner;
uint indexInOwnerList;
uint8 partOfNode;
uint lifetime;
uint startDate;
uint startBlock;
uint deposit;
uint64 index;
uint generation;
address originator;
}
struct SchainType {
uint8 partOfNode;
uint numberOfNodes;
}
/**
* @dev Emitted when schain type added.
*/
event SchainTypeAdded(uint indexed schainType, uint partOfNode, uint numberOfNodes);
/**
* @dev Emitted when schain type removed.
*/
event SchainTypeRemoved(uint indexed schainType);
function initializeSchain(
string calldata name,
address from,
address originator,
uint lifetime,
uint deposit) external;
function createGroupForSchain(
bytes32 schainHash,
uint numberOfNodes,
uint8 partOfNode
)
external
returns (uint[] memory);
function changeLifetime(bytes32 schainHash, uint lifetime, uint deposit) external;
function removeSchain(bytes32 schainHash, address from) external;
function removeNodeFromSchain(uint nodeIndex, bytes32 schainHash) external;
function deleteGroup(bytes32 schainHash) external;
function setException(bytes32 schainHash, uint nodeIndex) external;
function setNodeInGroup(bytes32 schainHash, uint nodeIndex) external;
function removeHolesForSchain(bytes32 schainHash) external;
function addSchainType(uint8 partOfNode, uint numberOfNodes) external;
function removeSchainType(uint typeOfSchain) external;
function setNumberOfSchainTypes(uint newNumberOfSchainTypes) external;
function removeNodeFromAllExceptionSchains(uint nodeIndex) external;
function removeAllNodesFromSchainExceptions(bytes32 schainHash) external;
function makeSchainNodesInvisible(bytes32 schainHash) external;
function makeSchainNodesVisible(bytes32 schainHash) external;
function newGeneration() external;
function addSchainForNode(uint nodeIndex, bytes32 schainHash) external;
function removeSchainForNode(uint nodeIndex, uint schainIndex) external;
function removeNodeFromExceptions(bytes32 schainHash, uint nodeIndex) external;
function isSchainActive(bytes32 schainHash) external view returns (bool);
function schainsAtSystem(uint index) external view returns (bytes32);
function numberOfSchains() external view returns (uint64);
function getSchains() external view returns (bytes32[] memory);
function getSchainsPartOfNode(bytes32 schainHash) external view returns (uint8);
function getSchainListSize(address from) external view returns (uint);
function getSchainHashesByAddress(address from) external view returns (bytes32[] memory);
function getSchainIdsByAddress(address from) external view returns (bytes32[] memory);
function getSchainHashesForNode(uint nodeIndex) external view returns (bytes32[] memory);
function getSchainIdsForNode(uint nodeIndex) external view returns (bytes32[] memory);
function getSchainOwner(bytes32 schainHash) external view returns (address);
function getSchainOriginator(bytes32 schainHash) external view returns (address);
function isSchainNameAvailable(string calldata name) external view returns (bool);
function isTimeExpired(bytes32 schainHash) external view returns (bool);
function isOwnerAddress(address from, bytes32 schainId) external view returns (bool);
function getSchainName(bytes32 schainHash) external view returns (string memory);
function getActiveSchain(uint nodeIndex) external view returns (bytes32);
function getActiveSchains(uint nodeIndex) external view returns (bytes32[] memory activeSchains);
function getNumberOfNodesInGroup(bytes32 schainHash) external view returns (uint);
function getNodesInGroup(bytes32 schainHash) external view returns (uint[] memory);
function isNodeAddressesInGroup(bytes32 schainId, address sender) external view returns (bool);
function getNodeIndexInGroup(bytes32 schainHash, uint nodeId) external view returns (uint);
function isAnyFreeNode(bytes32 schainHash) external view returns (bool);
function checkException(bytes32 schainHash, uint nodeIndex) external view returns (bool);
function checkHoleForSchain(bytes32 schainHash, uint indexOfNode) external view returns (bool);
function checkSchainOnNode(uint nodeIndex, bytes32 schainHash) external view returns (bool);
function getSchainType(uint typeOfSchain) external view returns(uint8, uint);
function getGeneration(bytes32 schainHash) external view returns (uint);
function isSchainExist(bytes32 schainHash) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* MessageProxy.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";
import "@skalenetwork/ima-interfaces/IGasReimbursable.sol";
import "@skalenetwork/ima-interfaces/IMessageProxy.sol";
import "@skalenetwork/ima-interfaces/IMessageReceiver.sol";
/**
* @title MessageProxy
* @dev Abstract contract for MessageProxyForMainnet and MessageProxyForSchain.
*/
abstract contract MessageProxy is AccessControlEnumerableUpgradeable, IMessageProxy {
using AddressUpgradeable for address;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
/**
* @dev Structure that stores counters for outgoing and incoming messages.
*/
struct ConnectedChainInfo {
// message counters start with 0
uint256 incomingMessageCounter;
uint256 outgoingMessageCounter;
bool inited;
}
bytes32 public constant MAINNET_HASH = keccak256(abi.encodePacked("Mainnet"));
bytes32 public constant CHAIN_CONNECTOR_ROLE = keccak256("CHAIN_CONNECTOR_ROLE");
bytes32 public constant EXTRA_CONTRACT_REGISTRAR_ROLE = keccak256("EXTRA_CONTRACT_REGISTRAR_ROLE");
bytes32 public constant CONSTANT_SETTER_ROLE = keccak256("CONSTANT_SETTER_ROLE");
uint256 public constant MESSAGES_LENGTH = 10;
uint256 public constant REVERT_REASON_LENGTH = 64;
// schainHash => ConnectedChainInfo
mapping(bytes32 => ConnectedChainInfo) public connectedChains;
// schainHash => contract address => allowed
// solhint-disable-next-line private-vars-leading-underscore
mapping(bytes32 => mapping(address => bool)) internal deprecatedRegistryContracts;
uint256 public gasLimit;
/**
* @dev Emitted for every outgoing message to schain.
*/
event OutgoingMessage(
bytes32 indexed dstChainHash,
uint256 indexed msgCounter,
address indexed srcContract,
address dstContract,
bytes data
);
/**
* @dev Emitted when function `postMessage` returns revert.
* Used to prevent stuck loop inside function `postIncomingMessages`.
*/
event PostMessageError(
uint256 indexed msgCounter,
bytes message
);
/**
* @dev Emitted when gas limit per one call of `postMessage` was changed.
*/
event GasLimitWasChanged(
uint256 oldValue,
uint256 newValue
);
/**
* @dev Emitted when the version was updated
*/
event VersionUpdated(string oldVersion, string newVersion);
/**
* @dev Emitted when extra contract was added.
*/
event ExtraContractRegistered(
bytes32 indexed chainHash,
address contractAddress
);
/**
* @dev Emitted when extra contract was removed.
*/
event ExtraContractRemoved(
bytes32 indexed chainHash,
address contractAddress
);
/**
* @dev Modifier to make a function callable only if caller is granted with {CHAIN_CONNECTOR_ROLE}.
*/
modifier onlyChainConnector() {
require(hasRole(CHAIN_CONNECTOR_ROLE, msg.sender), "CHAIN_CONNECTOR_ROLE is required");
_;
}
/**
* @dev Modifier to make a function callable only if caller is granted with {EXTRA_CONTRACT_REGISTRAR_ROLE}.
*/
modifier onlyExtraContractRegistrar() {
require(hasRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender), "EXTRA_CONTRACT_REGISTRAR_ROLE is required");
_;
}
/**
* @dev Modifier to make a function callable only if caller is granted with {CONSTANT_SETTER_ROLE}.
*/
modifier onlyConstantSetter() {
require(hasRole(CONSTANT_SETTER_ROLE, msg.sender), "Not enough permissions to set constant");
_;
}
/**
* @dev Sets gasLimit to a new value.
*
* Requirements:
*
* - `msg.sender` must be granted CONSTANT_SETTER_ROLE.
*/
function setNewGasLimit(uint256 newGasLimit) external override onlyConstantSetter {
emit GasLimitWasChanged(gasLimit, newGasLimit);
gasLimit = newGasLimit;
}
/**
* @dev Virtual function for `postIncomingMessages`.
*/
function postIncomingMessages(
string calldata fromSchainName,
uint256 startingCounter,
Message[] calldata messages,
Signature calldata sign
)
external
virtual
override;
/**
* @dev Allows `msg.sender` to register extra contract for all schains
* for being able to transfer messages from custom contracts.
*
* Requirements:
*
* - `msg.sender` must be granted as EXTRA_CONTRACT_REGISTRAR_ROLE.
* - Passed address should be contract.
* - Extra contract must not be registered.
*/
function registerExtraContractForAll(address extraContract) external override onlyExtraContractRegistrar {
require(extraContract.isContract(), "Given address is not a contract");
require(!_getRegistryContracts()[bytes32(0)].contains(extraContract), "Extra contract is already registered");
_getRegistryContracts()[bytes32(0)].add(extraContract);
emit ExtraContractRegistered(bytes32(0), extraContract);
}
/**
* @dev Allows `msg.sender` to remove extra contract for all schains.
* Extra contract will no longer be able to send messages through MessageProxy.
*
* Requirements:
*
* - `msg.sender` must be granted as EXTRA_CONTRACT_REGISTRAR_ROLE.
*/
function removeExtraContractForAll(address extraContract) external override onlyExtraContractRegistrar {
require(_getRegistryContracts()[bytes32(0)].contains(extraContract), "Extra contract is not registered");
_getRegistryContracts()[bytes32(0)].remove(extraContract);
emit ExtraContractRemoved(bytes32(0), extraContract);
}
/**
* @dev Should return length of contract registered by schainHash.
*/
function getContractRegisteredLength(bytes32 schainHash) external view override returns (uint256) {
return _getRegistryContracts()[schainHash].length();
}
/**
* @dev Should return a range of contracts registered by schainHash.
*
* Requirements:
* range should be less or equal 10 contracts
*/
function getContractRegisteredRange(
bytes32 schainHash,
uint256 from,
uint256 to
)
external
view
override
returns (address[] memory contractsInRange)
{
require(
from < to && to - from <= 10 && to <= _getRegistryContracts()[schainHash].length(),
"Range is incorrect"
);
contractsInRange = new address[](to - from);
for (uint256 i = from; i < to; i++) {
contractsInRange[i - from] = _getRegistryContracts()[schainHash].at(i);
}
}
/**
* @dev Returns number of outgoing messages.
*
* Requirements:
*
* - Target schain must be initialized.
*/
function getOutgoingMessagesCounter(string calldata targetSchainName)
external
view
override
returns (uint256)
{
bytes32 dstChainHash = keccak256(abi.encodePacked(targetSchainName));
require(connectedChains[dstChainHash].inited, "Destination chain is not initialized");
return connectedChains[dstChainHash].outgoingMessageCounter;
}
/**
* @dev Returns number of incoming messages.
*
* Requirements:
*
* - Source schain must be initialized.
*/
function getIncomingMessagesCounter(string calldata fromSchainName)
external
view
override
returns (uint256)
{
bytes32 srcChainHash = keccak256(abi.encodePacked(fromSchainName));
require(connectedChains[srcChainHash].inited, "Source chain is not initialized");
return connectedChains[srcChainHash].incomingMessageCounter;
}
function initializeMessageProxy(uint newGasLimit) public initializer {
AccessControlEnumerableUpgradeable.__AccessControlEnumerable_init();
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(CHAIN_CONNECTOR_ROLE, msg.sender);
_setupRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender);
_setupRole(CONSTANT_SETTER_ROLE, msg.sender);
gasLimit = newGasLimit;
}
/**
* @dev Posts message from this contract to `targetChainHash` MessageProxy contract.
* This is called by a smart contract to make a cross-chain call.
*
* Emits an {OutgoingMessage} event.
*
* Requirements:
*
* - Target chain must be initialized.
* - Target chain must be registered as external contract.
*/
function postOutgoingMessage(
bytes32 targetChainHash,
address targetContract,
bytes memory data
)
public
override
virtual
{
require(connectedChains[targetChainHash].inited, "Destination chain is not initialized");
_authorizeOutgoingMessageSender(targetChainHash);
emit OutgoingMessage(
targetChainHash,
connectedChains[targetChainHash].outgoingMessageCounter,
msg.sender,
targetContract,
data
);
connectedChains[targetChainHash].outgoingMessageCounter += 1;
}
/**
* @dev Allows CHAIN_CONNECTOR_ROLE to remove connected chain from this contract.
*
* Requirements:
*
* - `msg.sender` must be granted CHAIN_CONNECTOR_ROLE.
* - `schainName` must be initialized.
*/
function removeConnectedChain(string memory schainName) public virtual override onlyChainConnector {
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(connectedChains[schainHash].inited, "Chain is not initialized");
delete connectedChains[schainHash];
}
/**
* @dev Checks whether chain is currently connected.
*/
function isConnectedChain(
string memory schainName
)
public
view
virtual
override
returns (bool)
{
return connectedChains[keccak256(abi.encodePacked(schainName))].inited;
}
/**
* @dev Checks whether contract is currently registered as extra contract.
*/
function isContractRegistered(
bytes32 schainHash,
address contractAddress
)
public
view
override
returns (bool)
{
return _getRegistryContracts()[schainHash].contains(contractAddress);
}
/**
* @dev Allows MessageProxy to register extra contract for being able to transfer messages from custom contracts.
*
* Requirements:
*
* - Extra contract address must be contract.
* - Extra contract must not be registered.
* - Extra contract must not be registered for all chains.
*/
function _registerExtraContract(
bytes32 chainHash,
address extraContract
)
internal
{
require(extraContract.isContract(), "Given address is not a contract");
require(!_getRegistryContracts()[chainHash].contains(extraContract), "Extra contract is already registered");
require(
!_getRegistryContracts()[bytes32(0)].contains(extraContract),
"Extra contract is already registered for all chains"
);
_getRegistryContracts()[chainHash].add(extraContract);
emit ExtraContractRegistered(chainHash, extraContract);
}
/**
* @dev Allows MessageProxy to remove extra contract,
* thus `extraContract` will no longer be available to transfer messages from mainnet to schain.
*
* Requirements:
*
* - Extra contract must be registered.
*/
function _removeExtraContract(
bytes32 chainHash,
address extraContract
)
internal
{
require(_getRegistryContracts()[chainHash].contains(extraContract), "Extra contract is not registered");
_getRegistryContracts()[chainHash].remove(extraContract);
emit ExtraContractRemoved(chainHash, extraContract);
}
/**
* @dev Allows MessageProxy to connect schain with MessageProxyOnMainnet for transferring messages.
*
* Requirements:
*
* - `msg.sender` must be granted CHAIN_CONNECTOR_ROLE.
* - SKALE chain must not be connected.
*/
function _addConnectedChain(bytes32 schainHash) internal onlyChainConnector {
require(!connectedChains[schainHash].inited,"Chain is already connected");
connectedChains[schainHash] = ConnectedChainInfo({
incomingMessageCounter: 0,
outgoingMessageCounter: 0,
inited: true
});
}
/**
* @dev Allows MessageProxy to send messages from schain to mainnet.
* Destination contract must implement `postMessage` method.
*/
function _callReceiverContract(
bytes32 schainHash,
Message calldata message,
uint counter
)
internal
{
if (!message.destinationContract.isContract()) {
emit PostMessageError(
counter,
"Destination contract is not a contract"
);
return;
}
try IMessageReceiver(message.destinationContract).postMessage{gas: gasLimit}(
schainHash,
message.sender,
message.data
) {
return;
} catch Error(string memory reason) {
emit PostMessageError(
counter,
_getSlice(bytes(reason), REVERT_REASON_LENGTH)
);
} catch Panic(uint errorCode) {
emit PostMessageError(
counter,
abi.encodePacked(errorCode)
);
} catch (bytes memory revertData) {
emit PostMessageError(
counter,
_getSlice(revertData, REVERT_REASON_LENGTH)
);
}
}
/**
* @dev Returns receiver of message.
*/
function _getGasPayer(
bytes32 schainHash,
Message calldata message,
uint counter
)
internal
returns (address)
{
try IGasReimbursable(message.destinationContract).gasPayer{gas: gasLimit}(
schainHash,
message.sender,
message.data
) returns (address receiver) {
return receiver;
} catch Error(string memory reason) {
emit PostMessageError(
counter,
_getSlice(bytes(reason), REVERT_REASON_LENGTH)
);
return address(0);
} catch Panic(uint errorCode) {
emit PostMessageError(
counter,
abi.encodePacked(errorCode)
);
return address(0);
} catch (bytes memory revertData) {
emit PostMessageError(
counter,
_getSlice(revertData, REVERT_REASON_LENGTH)
);
return address(0);
}
}
/**
* @dev Checks whether msg.sender is registered as custom extra contract.
*/
function _authorizeOutgoingMessageSender(bytes32 targetChainHash) internal view virtual {
require(
isContractRegistered(bytes32(0), msg.sender) || isContractRegistered(targetChainHash, msg.sender),
"Sender contract is not registered"
);
}
/**
* @dev Returns list of registered custom extra contracts.
*/
function _getRegistryContracts()
internal
view
virtual
returns (mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) storage);
/**
* @dev Returns hash of message array.
*/
function _hashedArray(
Message[] calldata messages,
uint256 startingCounter,
string calldata fromChainName
)
internal
pure
returns (bytes32)
{
bytes32 sourceHash = keccak256(abi.encodePacked(fromChainName));
bytes32 hash = keccak256(abi.encodePacked(sourceHash, bytes32(startingCounter)));
for (uint256 i = 0; i < messages.length; i++) {
hash = keccak256(
abi.encodePacked(
abi.encode(
hash,
messages[i].sender,
messages[i].destinationContract
),
messages[i].data
)
);
}
return hash;
}
function _getSlice(bytes memory text, uint end) private pure returns (bytes memory) {
uint slicedEnd = end < text.length ? end : text.length;
bytes memory sliced = new bytes(slicedEnd);
for(uint i = 0; i < slicedEnd; i++){
sliced[i] = text[i];
}
return sliced;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
CommunityPool.sol - SKALE Manager
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaiev
@author Artem Payvin
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
import "@skalenetwork/ima-interfaces/mainnet/ICommunityPool.sol";
import "@skalenetwork/skale-manager-interfaces/IWallets.sol";
import "../Messages.sol";
import "./Twin.sol";
/**
* @title CommunityPool
* @dev Contract contains logic to perform automatic self-recharging ETH for nodes.
*/
contract CommunityPool is Twin, ICommunityPool {
using AddressUpgradeable for address payable;
bytes32 public constant CONSTANT_SETTER_ROLE = keccak256("CONSTANT_SETTER_ROLE");
// address of user => schainHash => balance of gas wallet in ETH
mapping(address => mapping(bytes32 => uint)) private _userWallets;
// address of user => schainHash => true if unlocked for transferring
mapping(address => mapping(bytes32 => bool)) public activeUsers;
uint public minTransactionGas;
/**
* @dev Emitted when minimal value in gas for transactions from schain to mainnet was changed
*/
event MinTransactionGasWasChanged(
uint oldValue,
uint newValue
);
function initialize(
IContractManager contractManagerOfSkaleManagerValue,
ILinker linker,
IMessageProxyForMainnet messageProxyValue
)
external
override
initializer
{
Twin.initialize(contractManagerOfSkaleManagerValue, messageProxyValue);
_setupRole(LINKER_ROLE, address(linker));
minTransactionGas = 1e6;
}
/**
* @dev Allows MessageProxyForMainnet to reimburse gas for transactions
* that transfer funds from schain to mainnet.
*
* Requirements:
*
* - User that receives funds should have enough funds in their gas wallet.
* - Address that should be reimbursed for executing transaction must not be null.
*/
function refundGasByUser(
bytes32 schainHash,
address payable node,
address user,
uint gas
)
external
override
onlyMessageProxy
returns (uint)
{
require(node != address(0), "Node address must be set");
if (!activeUsers[user][schainHash]) {
return gas;
}
uint amount = tx.gasprice * gas;
if (amount > _userWallets[user][schainHash]) {
amount = _userWallets[user][schainHash];
}
_userWallets[user][schainHash] = _userWallets[user][schainHash] - amount;
if (!_balanceIsSufficient(schainHash, user, 0)) {
activeUsers[user][schainHash] = false;
messageProxy.postOutgoingMessage(
schainHash,
schainLinks[schainHash],
Messages.encodeLockUserMessage(user)
);
}
node.sendValue(amount);
return (tx.gasprice * gas - amount) / tx.gasprice;
}
function refundGasBySchainWallet(
bytes32 schainHash,
address payable node,
uint gas
)
external
override
onlyMessageProxy
returns (bool)
{
if (gas > 0) {
IWallets(payable(contractManagerOfSkaleManager.getContract("Wallets"))).refundGasBySchain(
schainHash,
node,
gas,
false
);
}
return true;
}
/**
* @dev Allows `msg.sender` to recharge their wallet for further gas reimbursement.
*
* Requirements:
*
* - 'msg.sender` should recharge their gas wallet for amount that enough to reimburse any
* transaction from schain to mainnet.
*/
function rechargeUserWallet(string calldata schainName, address user) external payable override {
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(
_balanceIsSufficient(schainHash, user, msg.value),
"Not enough ETH for transaction"
);
_userWallets[user][schainHash] = _userWallets[user][schainHash] + msg.value;
if (!activeUsers[user][schainHash]) {
activeUsers[user][schainHash] = true;
messageProxy.postOutgoingMessage(
schainHash,
schainLinks[schainHash],
Messages.encodeActivateUserMessage(user)
);
}
}
/**
* @dev Allows `msg.sender` to withdraw funds from their gas wallet.
* If `msg.sender` withdraws too much funds,
* then he will no longer be able to transfer their tokens on ETH from schain to mainnet.
*
* Requirements:
*
* - 'msg.sender` must have sufficient amount of ETH on their gas wallet.
*/
function withdrawFunds(string calldata schainName, uint amount) external override {
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(amount <= _userWallets[msg.sender][schainHash], "Balance is too low");
require(!messageProxy.messageInProgress(), "Message is in progress");
_userWallets[msg.sender][schainHash] = _userWallets[msg.sender][schainHash] - amount;
if (
!_balanceIsSufficient(schainHash, msg.sender, 0) &&
activeUsers[msg.sender][schainHash]
) {
activeUsers[msg.sender][schainHash] = false;
messageProxy.postOutgoingMessage(
schainHash,
schainLinks[schainHash],
Messages.encodeLockUserMessage(msg.sender)
);
}
payable(msg.sender).sendValue(amount);
}
/**
* @dev Allows `msg.sender` set the amount of gas that should be
* enough for reimbursing any transaction from schain to mainnet.
*
* Requirements:
*
* - 'msg.sender` must have sufficient amount of ETH on their gas wallet.
*/
function setMinTransactionGas(uint newMinTransactionGas) external override {
require(hasRole(CONSTANT_SETTER_ROLE, msg.sender), "CONSTANT_SETTER_ROLE is required");
emit MinTransactionGasWasChanged(minTransactionGas, newMinTransactionGas);
minTransactionGas = newMinTransactionGas;
}
/**
* @dev Returns the amount of ETH on gas wallet for particular user.
*/
function getBalance(address user, string calldata schainName) external view override returns (uint) {
return _userWallets[user][keccak256(abi.encodePacked(schainName))];
}
/**
* @dev Checks whether user is active and wallet was recharged for sufficient amount.
*/
function checkUserBalance(bytes32 schainHash, address receiver) external view override returns (bool) {
return activeUsers[receiver][schainHash] && _balanceIsSufficient(schainHash, receiver, 0);
}
/**
* @dev Checks whether user wallet was recharged for sufficient amount.
*/
function _balanceIsSufficient(bytes32 schainHash, address receiver, uint256 delta) private view returns (bool) {
return delta + _userWallets[receiver][schainHash] >= minTransactionGas * tx.gasprice;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControlEnumerableUpgradeable.sol";
import "./AccessControlUpgradeable.sol";
import "../utils/structs/EnumerableSetUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
function __AccessControlEnumerable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__AccessControlEnumerable_init_unchained();
}
function __AccessControlEnumerable_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {grantRole} to track enumerable memberships
*/
function grantRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library 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;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.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 AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.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 ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
|
Returns number of outgoing messages. Requirements: - Target schain must be initialized./
|
function getOutgoingMessagesCounter(string calldata targetSchainName)
external
view
override
returns (uint256)
{
bytes32 dstChainHash = keccak256(abi.encodePacked(targetSchainName));
require(connectedChains[dstChainHash].inited, "Destination chain is not initialized");
return connectedChains[dstChainHash].outgoingMessageCounter;
}
| 1,152,678
|
./full_match/1/0x845F5eC7331f07399703fD68C98954f980a31fCC/sources/browser/Treasury.sol
|
Interface of the ERC20 standard as defined in the EIP./
|
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function burn(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);
}
| 3,060,312
|
./full_match/5/0x61b3E0fcEF001A8bcBd216c72bd78902ef8EA325/sources/project_/contracts/lib/dataHandlers/SaleDataHandler.sol
|
Calculates the discounted price./
|
function _applyDiscount(
uint256 price,
uint256 purchaseAmount,
DiscountRule memory discountData
) private pure returns (uint256) {
uint256 discountRate = purchaseAmount.fitRange(
discountData.rangeMin - 1,
discountData.rangeMax,
0,
discountData.max
);
return (price * (10000 - discountRate)) / 10000;
}
| 1,920,271
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/ContextUpgradeable.sol";
import "./ERC20Upgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable {
function __ERC20Burnable_init() internal initializer {
__Context_init_unchained();
__ERC20Burnable_init_unchained();
}
function __ERC20Burnable_init_unchained() internal initializer {
}
using SafeMathUpgradeable for uint256;
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/ContextUpgradeable.sol";
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable {
using SafeMathUpgradeable for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./ContextUpgradeable.sol";
import "../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.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @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 `master`.
*
* This function uses the create opcode, which should never revert.
*/
function clone(address master) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
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 `master`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `master` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
function cloneDeterministic(address master, bytes32 salt) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
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 master, bytes32 salt, address deployer) internal pure returns (address predicted) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
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 master, bytes32 salt) internal view returns (address predicted) {
return predictDeterministicAddress(master, salt, address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./SwapUtils.sol";
/**
* @title AmplificationUtils library
* @notice A library to calculate and ramp the A parameter of a given `SwapUtils.Swap` struct.
* This library assumes the struct is fully validated.
*/
library AmplificationUtils {
using SafeMath for uint256;
event RampA(
uint256 oldA,
uint256 newA,
uint256 initialTime,
uint256 futureTime
);
event StopRampA(uint256 currentA, uint256 time);
// Constant values used in ramping A calculations
uint256 public constant A_PRECISION = 100;
uint256 public constant MAX_A = 10**6;
uint256 private constant MAX_A_CHANGE = 2;
uint256 private constant MIN_RAMP_TIME = 14 days;
/**
* @notice Return A, the amplification coefficient * n * (n - 1)
* @dev See the StableSwap paper for details
* @param self Swap struct to read from
* @return A parameter
*/
function getA(SwapUtils.Swap storage self) external view returns (uint256) {
return _getAPrecise(self).div(A_PRECISION);
}
/**
* @notice Return A in its raw precision
* @dev See the StableSwap paper for details
* @param self Swap struct to read from
* @return A parameter in its raw precision form
*/
function getAPrecise(SwapUtils.Swap storage self)
external
view
returns (uint256)
{
return _getAPrecise(self);
}
/**
* @notice Return A in its raw precision
* @dev See the StableSwap paper for details
* @param self Swap struct to read from
* @return A parameter in its raw precision form
*/
function _getAPrecise(SwapUtils.Swap storage self)
internal
view
returns (uint256)
{
uint256 t1 = self.futureATime; // time when ramp is finished
uint256 a1 = self.futureA; // final A value when ramp is finished
if (block.timestamp < t1) {
uint256 t0 = self.initialATime; // time when ramp is started
uint256 a0 = self.initialA; // initial A value when ramp is started
if (a1 > a0) {
// a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0)
return
a0.add(
a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0))
);
} else {
// a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0)
return
a0.sub(
a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0))
);
}
} else {
return a1;
}
}
/**
* @notice Start ramping up or down A parameter towards given futureA_ and futureTime_
* Checks if the change is too rapid, and commits the new A value only when it falls under
* the limit range.
* @param self Swap struct to update
* @param futureA_ the new A to ramp towards
* @param futureTime_ timestamp when the new A should be reached
*/
function rampA(
SwapUtils.Swap storage self,
uint256 futureA_,
uint256 futureTime_
) external {
require(
block.timestamp >= self.initialATime.add(1 days),
"Wait 1 day before starting ramp"
);
require(
futureTime_ >= block.timestamp.add(MIN_RAMP_TIME),
"Insufficient ramp time"
);
require(
futureA_ > 0 && futureA_ < MAX_A,
"futureA_ must be > 0 and < MAX_A"
);
uint256 initialAPrecise = _getAPrecise(self);
uint256 futureAPrecise = futureA_.mul(A_PRECISION);
if (futureAPrecise < initialAPrecise) {
require(
futureAPrecise.mul(MAX_A_CHANGE) >= initialAPrecise,
"futureA_ is too small"
);
} else {
require(
futureAPrecise <= initialAPrecise.mul(MAX_A_CHANGE),
"futureA_ is too large"
);
}
self.initialA = initialAPrecise;
self.futureA = futureAPrecise;
self.initialATime = block.timestamp;
self.futureATime = futureTime_;
emit RampA(
initialAPrecise,
futureAPrecise,
block.timestamp,
futureTime_
);
}
/**
* @notice Stops ramping A immediately. Once this function is called, rampA()
* cannot be called for another 24 hours
* @param self Swap struct to update
*/
function stopRampA(SwapUtils.Swap storage self) external {
require(self.futureATime > block.timestamp, "Ramp is already stopped");
uint256 currentA = _getAPrecise(self);
self.initialA = currentA;
self.futureA = currentA;
self.initialATime = block.timestamp;
self.futureATime = block.timestamp;
emit StopRampA(currentA, block.timestamp);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20BurnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "./interfaces/ISwap.sol";
/**
* @title Liquidity Provider Token
* @notice This token is an ERC20 detailed token with added capability to be minted by the owner.
* It is used to represent user's shares when providing liquidity to swap contracts.
* @dev Only Swap contracts should initialize and own LPToken contracts.
*/
contract LPToken is ERC20BurnableUpgradeable, OwnableUpgradeable {
using SafeMathUpgradeable for uint256;
/**
* @notice Initializes this LPToken contract with the given name and symbol
* @dev The caller of this function will become the owner. A Swap contract should call this
* in its initializer function.
* @param name name of this token
* @param symbol symbol of this token
*/
function initialize(string memory name, string memory symbol)
external
initializer
returns (bool)
{
__Context_init_unchained();
__ERC20_init_unchained(name, symbol);
__Ownable_init_unchained();
return true;
}
/**
* @notice Mints the given amount of LPToken to the recipient.
* @dev only owner can call this mint function
* @param recipient address of account to receive the tokens
* @param amount amount of tokens to mint
*/
function mint(address recipient, uint256 amount) external onlyOwner {
require(amount != 0, "LPToken: cannot mint 0");
_mint(recipient, amount);
}
/**
* @dev Overrides ERC20._beforeTokenTransfer() which get called on every transfers including
* minting and burning. This ensures that Swap.updateUserWithdrawFees are called everytime.
* This assumes the owner is set to a Swap contract's address.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override(ERC20Upgradeable) {
super._beforeTokenTransfer(from, to, amount);
require(to != address(this), "LPToken: cannot send to itself");
ISwap(owner()).updateUserWithdrawFee(to, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title MathUtils library
* @notice A library to be used in conjunction with SafeMath. Contains functions for calculating
* differences between two uint256.
*/
library MathUtils {
/**
* @notice Compares a and b and returns true if the difference between a and b
* is less than 1 or equal to each other.
* @param a uint256 to compare with
* @param b uint256 to compare with
* @return True if the difference between a and b is less than 1 or equal,
* otherwise return false
*/
function within1(uint256 a, uint256 b) internal pure returns (bool) {
return (difference(a, b) <= 1);
}
/**
* @notice Calculates absolute difference between a and b
* @param a uint256 to compare with
* @param b uint256 to compare with
* @return Difference between a and b
*/
function difference(uint256 a, uint256 b) internal pure returns (uint256) {
if (a > b) {
return a - b;
}
return b - a;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
/**
* @title OwnerPausable
* @notice An ownable contract allows the owner to pause and unpause the
* contract without a delay.
* @dev Only methods using the provided modifiers will be paused.
*/
abstract contract OwnerPausableUpgradeable is
OwnableUpgradeable,
PausableUpgradeable
{
function __OwnerPausable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
__Pausable_init_unchained();
}
/**
* @notice Pause the contract. Revert if already paused.
*/
function pause() external onlyOwner {
PausableUpgradeable._pause();
}
/**
* @notice Unpause the contract. Revert if already unpaused.
*/
function unpause() external onlyOwner {
PausableUpgradeable._unpause();
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/proxy/Clones.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "./OwnerPausableUpgradeable.sol";
import "./SwapUtils.sol";
import "./AmplificationUtils.sol";
/**
* @title Swap - A StableSwap implementation in solidity.
* @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins)
* and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens
* in desired ratios for an exchange of the pool token that represents their share of the pool.
* Users can burn pool tokens and withdraw their share of token(s).
*
* Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets
* distributed to the LPs.
*
* In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which
* stops the ratio of the tokens in the pool from changing.
* Users can always withdraw their tokens via multi-asset withdraws.
*
* @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's
* deployment size.
*/
contract Swap is OwnerPausableUpgradeable, ReentrancyGuardUpgradeable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using SwapUtils for SwapUtils.Swap;
using AmplificationUtils for SwapUtils.Swap;
// Struct storing data responsible for automatic market maker functionalities. In order to
// access this data, this contract uses SwapUtils library. For more details, see SwapUtils.sol
SwapUtils.Swap public swapStorage;
// Maps token address to an index in the pool. Used to prevent duplicate tokens in the pool.
// getTokenIndex function also relies on this mapping to retrieve token index.
mapping(address => uint8) private tokenIndexes;
/*** EVENTS ***/
// events replicated from SwapUtils to make the ABI easier for dumb
// clients
event TokenSwap(
address indexed buyer,
uint256 tokensSold,
uint256 tokensBought,
uint128 soldId,
uint128 boughtId
);
event AddLiquidity(
address indexed provider,
uint256[] tokenAmounts,
uint256[] fees,
uint256 invariant,
uint256 lpTokenSupply
);
event RemoveLiquidity(
address indexed provider,
uint256[] tokenAmounts,
uint256 lpTokenSupply
);
event RemoveLiquidityOne(
address indexed provider,
uint256 lpTokenAmount,
uint256 lpTokenSupply,
uint256 boughtId,
uint256 tokensBought
);
event RemoveLiquidityImbalance(
address indexed provider,
uint256[] tokenAmounts,
uint256[] fees,
uint256 invariant,
uint256 lpTokenSupply
);
event NewAdminFee(uint256 newAdminFee);
event NewSwapFee(uint256 newSwapFee);
event NewWithdrawFee(uint256 newWithdrawFee);
event RampA(
uint256 oldA,
uint256 newA,
uint256 initialTime,
uint256 futureTime
);
event StopRampA(uint256 currentA, uint256 time);
/**
* @notice Initializes this Swap contract with the given parameters.
* This will also clone a LPToken contract that represents users'
* LP positions. The owner of LPToken will be this contract - which means
* only this contract is allowed to mint/burn tokens.
*
* @param _pooledTokens an array of ERC20s this pool will accept
* @param decimals the decimals to use for each pooled token,
* eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS
* @param lpTokenName the long-form name of the token to be deployed
* @param lpTokenSymbol the short symbol for the token to be deployed
* @param _a the amplification coefficient * n * (n - 1). See the
* StableSwap paper for details
* @param _fee default swap fee to be initialized with
* @param _adminFee default adminFee to be initialized with
* @param _withdrawFee default withdrawFee to be initialized with
* @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target
*/
function initialize(
IERC20[] memory _pooledTokens,
uint8[] memory decimals,
string memory lpTokenName,
string memory lpTokenSymbol,
uint256 _a,
uint256 _fee,
uint256 _adminFee,
uint256 _withdrawFee,
address lpTokenTargetAddress
) public virtual initializer {
__OwnerPausable_init();
__ReentrancyGuard_init();
// Check _pooledTokens and precisions parameter
require(_pooledTokens.length > 1, "_pooledTokens.length <= 1");
require(_pooledTokens.length <= 32, "_pooledTokens.length > 32");
require(
_pooledTokens.length == decimals.length,
"_pooledTokens decimals mismatch"
);
uint256[] memory precisionMultipliers = new uint256[](decimals.length);
for (uint8 i = 0; i < _pooledTokens.length; i++) {
if (i > 0) {
// Check if index is already used. Check if 0th element is a duplicate.
require(
tokenIndexes[address(_pooledTokens[i])] == 0 &&
_pooledTokens[0] != _pooledTokens[i],
"Duplicate tokens"
);
}
require(
address(_pooledTokens[i]) != address(0),
"The 0 address isn't an ERC-20"
);
require(
decimals[i] <= SwapUtils.POOL_PRECISION_DECIMALS,
"Token decimals exceeds max"
);
precisionMultipliers[i] =
10 **
uint256(SwapUtils.POOL_PRECISION_DECIMALS).sub(
uint256(decimals[i])
);
tokenIndexes[address(_pooledTokens[i])] = i;
}
// Check _a, _fee, _adminFee, _withdrawFee parameters
require(_a < AmplificationUtils.MAX_A, "_a exceeds maximum");
require(_fee < SwapUtils.MAX_SWAP_FEE, "_fee exceeds maximum");
require(
_adminFee < SwapUtils.MAX_ADMIN_FEE,
"_adminFee exceeds maximum"
);
require(
_withdrawFee < SwapUtils.MAX_WITHDRAW_FEE,
"_withdrawFee exceeds maximum"
);
// Clone and initialize a LPToken contract
LPToken lpToken = LPToken(Clones.clone(lpTokenTargetAddress));
require(
lpToken.initialize(lpTokenName, lpTokenSymbol),
"could not init lpToken clone"
);
// Initialize swapStorage struct
swapStorage.lpToken = lpToken;
swapStorage.pooledTokens = _pooledTokens;
swapStorage.tokenPrecisionMultipliers = precisionMultipliers;
swapStorage.balances = new uint256[](_pooledTokens.length);
swapStorage.initialA = _a.mul(AmplificationUtils.A_PRECISION);
swapStorage.futureA = _a.mul(AmplificationUtils.A_PRECISION);
// swapStorage.initialATime = 0;
// swapStorage.futureATime = 0;
swapStorage.swapFee = _fee;
swapStorage.adminFee = _adminFee;
swapStorage.defaultWithdrawFee = _withdrawFee;
}
/*** MODIFIERS ***/
/**
* @notice Modifier to check deadline against current timestamp
* @param deadline latest timestamp to accept this transaction
*/
modifier deadlineCheck(uint256 deadline) {
require(block.timestamp <= deadline, "Deadline not met");
_;
}
/*** VIEW FUNCTIONS ***/
/**
* @notice Return A, the amplification coefficient * n * (n - 1)
* @dev See the StableSwap paper for details
* @return A parameter
*/
function getA() external view virtual returns (uint256) {
return swapStorage.getA();
}
/**
* @notice Return A in its raw precision form
* @dev See the StableSwap paper for details
* @return A parameter in its raw precision form
*/
function getAPrecise() external view virtual returns (uint256) {
return swapStorage.getAPrecise();
}
/**
* @notice Return address of the pooled token at given index. Reverts if tokenIndex is out of range.
* @param index the index of the token
* @return address of the token at given index
*/
function getToken(uint8 index) public view virtual returns (IERC20) {
require(index < swapStorage.pooledTokens.length, "Out of range");
return swapStorage.pooledTokens[index];
}
/**
* @notice Return the index of the given token address. Reverts if no matching
* token is found.
* @param tokenAddress address of the token
* @return the index of the given token address
*/
function getTokenIndex(address tokenAddress)
public
view
virtual
returns (uint8)
{
uint8 index = tokenIndexes[tokenAddress];
require(
address(getToken(index)) == tokenAddress,
"Token does not exist"
);
return index;
}
/**
* @notice Return timestamp of last deposit of given address
* @return timestamp of the last deposit made by the given address
*/
function getDepositTimestamp(address user)
external
view
virtual
returns (uint256)
{
return swapStorage.getDepositTimestamp(user);
}
/**
* @notice Return current balance of the pooled token at given index
* @param index the index of the token
* @return current balance of the pooled token at given index with token's native precision
*/
function getTokenBalance(uint8 index)
external
view
virtual
returns (uint256)
{
require(index < swapStorage.pooledTokens.length, "Index out of range");
return swapStorage.balances[index];
}
/**
* @notice Get the virtual price, to help calculate profit
* @return the virtual price, scaled to the POOL_PRECISION_DECIMALS
*/
function getVirtualPrice() external view virtual returns (uint256) {
return swapStorage.getVirtualPrice();
}
/**
* @notice Calculate amount of tokens you receive on swap
* @param tokenIndexFrom the token the user wants to sell
* @param tokenIndexTo the token the user wants to buy
* @param dx the amount of tokens the user wants to sell. If the token charges
* a fee on transfers, use the amount that gets transferred after the fee.
* @return amount of tokens the user will receive
*/
function calculateSwap(
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx
) external view virtual returns (uint256) {
return swapStorage.calculateSwap(tokenIndexFrom, tokenIndexTo, dx);
}
/**
* @notice A simple method to calculate prices from deposits or
* withdrawals, excluding fees but including slippage. This is
* helpful as an input into the various "min" parameters on calls
* to fight front-running
*
* @dev This shouldn't be used outside frontends for user estimates.
*
* @param account address that is depositing or withdrawing tokens
* @param amounts an array of token amounts to deposit or withdrawal,
* corresponding to pooledTokens. The amount should be in each
* pooled token's native precision. If a token charges a fee on transfers,
* use the amount that gets transferred after the fee.
* @param deposit whether this is a deposit or a withdrawal
* @return token amount the user will receive
*/
function calculateTokenAmount(
address account,
uint256[] calldata amounts,
bool deposit
) external view virtual returns (uint256) {
return swapStorage.calculateTokenAmount(account, amounts, deposit);
}
/**
* @notice A simple method to calculate amount of each underlying
* tokens that is returned upon burning given amount of LP tokens
* @param account the address that is withdrawing tokens
* @param amount the amount of LP tokens that would be burned on withdrawal
* @return array of token balances that the user will receive
*/
function calculateRemoveLiquidity(address account, uint256 amount)
external
view
virtual
returns (uint256[] memory)
{
return swapStorage.calculateRemoveLiquidity(account, amount);
}
/**
* @notice Calculate the amount of underlying token available to withdraw
* when withdrawing via only single token
* @param account the address that is withdrawing tokens
* @param tokenAmount the amount of LP token to burn
* @param tokenIndex index of which token will be withdrawn
* @return availableTokenAmount calculated amount of underlying token
* available to withdraw
*/
function calculateRemoveLiquidityOneToken(
address account,
uint256 tokenAmount,
uint8 tokenIndex
) external view virtual returns (uint256 availableTokenAmount) {
return
swapStorage.calculateWithdrawOneToken(
account,
tokenAmount,
tokenIndex
);
}
/**
* @notice Calculate the fee that is applied when the given user withdraws. The withdraw fee
* decays linearly over period of 4 weeks. For example, depositing and withdrawing right away
* will charge you the full amount of withdraw fee. But withdrawing after 4 weeks will charge you
* no additional fees.
* @dev returned value should be divided by FEE_DENOMINATOR to convert to correct decimals
* @param user address you want to calculate withdraw fee of
* @return current withdraw fee of the user
*/
function calculateCurrentWithdrawFee(address user)
external
view
virtual
returns (uint256)
{
return swapStorage.calculateCurrentWithdrawFee(user);
}
/**
* @notice This function reads the accumulated amount of admin fees of the token with given index
* @param index Index of the pooled token
* @return admin's token balance in the token's precision
*/
function getAdminBalance(uint256 index)
external
view
virtual
returns (uint256)
{
return swapStorage.getAdminBalance(index);
}
/*** STATE MODIFYING FUNCTIONS ***/
/**
* @notice Swap two tokens using this pool
* @param tokenIndexFrom the token the user wants to swap from
* @param tokenIndexTo the token the user wants to swap to
* @param dx the amount of tokens the user wants to swap from
* @param minDy the min amount the user would like to receive, or revert.
* @param deadline latest timestamp to accept this transaction
*/
function swap(
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx,
uint256 minDy,
uint256 deadline
)
external
virtual
nonReentrant
whenNotPaused
deadlineCheck(deadline)
returns (uint256)
{
return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy);
}
/**
* @notice Add liquidity to the pool with the given amounts of tokens
* @param amounts the amounts of each token to add, in their native precision
* @param minToMint the minimum LP tokens adding this amount of liquidity
* should mint, otherwise revert. Handy for front-running mitigation
* @param deadline latest timestamp to accept this transaction
* @return amount of LP token user minted and received
*/
function addLiquidity(
uint256[] calldata amounts,
uint256 minToMint,
uint256 deadline
)
external
virtual
nonReentrant
whenNotPaused
deadlineCheck(deadline)
returns (uint256)
{
return swapStorage.addLiquidity(amounts, minToMint);
}
/**
* @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly
* over period of 4 weeks since last deposit will apply.
* @dev Liquidity can always be removed, even when the pool is paused.
* @param amount the amount of LP tokens to burn
* @param minAmounts the minimum amounts of each token in the pool
* acceptable for this burn. Useful as a front-running mitigation
* @param deadline latest timestamp to accept this transaction
* @return amounts of tokens user received
*/
function removeLiquidity(
uint256 amount,
uint256[] calldata minAmounts,
uint256 deadline
)
external
virtual
nonReentrant
deadlineCheck(deadline)
returns (uint256[] memory)
{
return swapStorage.removeLiquidity(amount, minAmounts);
}
/**
* @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly
* over period of 4 weeks since last deposit will apply.
* @param tokenAmount the amount of the token you want to receive
* @param tokenIndex the index of the token you want to receive
* @param minAmount the minimum amount to withdraw, otherwise revert
* @param deadline latest timestamp to accept this transaction
* @return amount of chosen token user received
*/
function removeLiquidityOneToken(
uint256 tokenAmount,
uint8 tokenIndex,
uint256 minAmount,
uint256 deadline
)
external
virtual
nonReentrant
whenNotPaused
deadlineCheck(deadline)
returns (uint256)
{
return
swapStorage.removeLiquidityOneToken(
tokenAmount,
tokenIndex,
minAmount
);
}
/**
* @notice Remove liquidity from the pool, weighted differently than the
* pool's current balances. Withdraw fee that decays linearly
* over period of 4 weeks since last deposit will apply.
* @param amounts how much of each token to withdraw
* @param maxBurnAmount the max LP token provider is willing to pay to
* remove liquidity. Useful as a front-running mitigation.
* @param deadline latest timestamp to accept this transaction
* @return amount of LP tokens burned
*/
function removeLiquidityImbalance(
uint256[] calldata amounts,
uint256 maxBurnAmount,
uint256 deadline
)
external
virtual
nonReentrant
whenNotPaused
deadlineCheck(deadline)
returns (uint256)
{
return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount);
}
/*** ADMIN FUNCTIONS ***/
/**
* @notice Updates the user withdraw fee. This function can only be called by
* the pool token. Should be used to update the withdraw fee on transfer of pool tokens.
* Transferring your pool token will reset the 4 weeks period. If the recipient is already
* holding some pool tokens, the withdraw fee will be discounted in respective amounts.
* @param recipient address of the recipient of pool token
* @param transferAmount amount of pool token to transfer
*/
function updateUserWithdrawFee(address recipient, uint256 transferAmount)
external
{
require(
msg.sender == address(swapStorage.lpToken),
"Only callable by pool token"
);
swapStorage.updateUserWithdrawFee(recipient, transferAmount);
}
/**
* @notice Withdraw all admin fees to the contract owner
*/
function withdrawAdminFees() external onlyOwner {
swapStorage.withdrawAdminFees(owner());
}
/**
* @notice Update the admin fee. Admin fee takes portion of the swap fee.
* @param newAdminFee new admin fee to be applied on future transactions
*/
function setAdminFee(uint256 newAdminFee) external onlyOwner {
swapStorage.setAdminFee(newAdminFee);
}
/**
* @notice Update the swap fee to be applied on swaps
* @param newSwapFee new swap fee to be applied on future transactions
*/
function setSwapFee(uint256 newSwapFee) external onlyOwner {
swapStorage.setSwapFee(newSwapFee);
}
/**
* @notice Update the withdraw fee. This fee decays linearly over 4 weeks since
* user's last deposit.
* @param newWithdrawFee new withdraw fee to be applied on future deposits
*/
function setDefaultWithdrawFee(uint256 newWithdrawFee) external onlyOwner {
swapStorage.setDefaultWithdrawFee(newWithdrawFee);
}
/**
* @notice Start ramping up or down A parameter towards given futureA and futureTime
* Checks if the change is too rapid, and commits the new A value only when it falls under
* the limit range.
* @param futureA the new A to ramp towards
* @param futureTime timestamp when the new A should be reached
*/
function rampA(uint256 futureA, uint256 futureTime) external onlyOwner {
swapStorage.rampA(futureA, futureTime);
}
/**
* @notice Stop ramping A immediately. Reverts if ramp A is already stopped.
*/
function stopRampA() external onlyOwner {
swapStorage.stopRampA();
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./AmplificationUtils.sol";
import "./LPToken.sol";
import "./MathUtils.sol";
/**
* @title SwapUtils library
* @notice A library to be used within Swap.sol. Contains functions responsible for custody and AMM functionalities.
* @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library
* for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins.
* Admin functions should be protected within contracts using this library.
*/
library SwapUtils {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using MathUtils for uint256;
/*** EVENTS ***/
event TokenSwap(
address indexed buyer,
uint256 tokensSold,
uint256 tokensBought,
uint128 soldId,
uint128 boughtId
);
event AddLiquidity(
address indexed provider,
uint256[] tokenAmounts,
uint256[] fees,
uint256 invariant,
uint256 lpTokenSupply
);
event RemoveLiquidity(
address indexed provider,
uint256[] tokenAmounts,
uint256 lpTokenSupply
);
event RemoveLiquidityOne(
address indexed provider,
uint256 lpTokenAmount,
uint256 lpTokenSupply,
uint256 boughtId,
uint256 tokensBought
);
event RemoveLiquidityImbalance(
address indexed provider,
uint256[] tokenAmounts,
uint256[] fees,
uint256 invariant,
uint256 lpTokenSupply
);
event NewAdminFee(uint256 newAdminFee);
event NewSwapFee(uint256 newSwapFee);
event NewWithdrawFee(uint256 newWithdrawFee);
struct Swap {
// variables around the ramp management of A,
// the amplification coefficient * n * (n - 1)
// see https://www.curve.fi/stableswap-paper.pdf for details
uint256 initialA;
uint256 futureA;
uint256 initialATime;
uint256 futureATime;
// fee calculation
uint256 swapFee;
uint256 adminFee;
uint256 defaultWithdrawFee;
LPToken lpToken;
// contract references for all tokens being pooled
IERC20[] pooledTokens;
// multipliers for each pooled token's precision to get to POOL_PRECISION_DECIMALS
// for example, TBTC has 18 decimals, so the multiplier should be 1. WBTC
// has 8, so the multiplier should be 10 ** 18 / 10 ** 8 => 10 ** 10
uint256[] tokenPrecisionMultipliers;
// the pool balance of each token, in the token's precision
// the contract's actual token balance might differ
uint256[] balances;
mapping(address => uint256) depositTimestamp;
mapping(address => uint256) withdrawFeeMultiplier;
}
// Struct storing variables used in calculations in the
// calculateWithdrawOneTokenDY function to avoid stack too deep errors
struct CalculateWithdrawOneTokenDYInfo {
uint256 d0;
uint256 d1;
uint256 newY;
uint256 feePerToken;
uint256 preciseA;
}
// Struct storing variables used in calculations in the
// {add,remove}Liquidity functions to avoid stack too deep errors
struct ManageLiquidityInfo {
uint256 d0;
uint256 d1;
uint256 d2;
uint256 preciseA;
LPToken lpToken;
uint256 totalSupply;
uint256[] balances;
uint256[] multipliers;
}
// the precision all pools tokens will be converted to
uint8 public constant POOL_PRECISION_DECIMALS = 18;
// the denominator used to calculate admin and LP fees. For example, an
// LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR)
uint256 private constant FEE_DENOMINATOR = 10**10;
// Max swap fee is 1% or 100bps of each swap
uint256 public constant MAX_SWAP_FEE = 10**8;
// Max adminFee is 100% of the swapFee
// adminFee does not add additional fee on top of swapFee
// Instead it takes a certain % of the swapFee. Therefore it has no impact on the
// users but only on the earnings of LPs
uint256 public constant MAX_ADMIN_FEE = 10**10;
// Max withdrawFee is 1% of the value withdrawn
// Fee will be redistributed to the LPs in the pool, rewarding
// long term providers.
uint256 public constant MAX_WITHDRAW_FEE = 10**8;
// Constant value used as max loop limit
uint256 private constant MAX_LOOP_LIMIT = 256;
// Time that it should take for the withdraw fee to fully decay to 0
uint256 public constant WITHDRAW_FEE_DECAY_TIME = 4 weeks;
/*** VIEW & PURE FUNCTIONS ***/
/**
* @notice Retrieves the timestamp of last deposit made by the given address
* @param self Swap struct to read from
* @return timestamp of last deposit
*/
function getDepositTimestamp(Swap storage self, address user)
external
view
returns (uint256)
{
return self.depositTimestamp[user];
}
function _getAPrecise(Swap storage self) internal view returns (uint256) {
return AmplificationUtils._getAPrecise(self);
}
/**
* @notice Calculate the dy, the amount of selected token that user receives and
* the fee of withdrawing in one token
* @param account the address that is withdrawing
* @param tokenAmount the amount to withdraw in the pool's precision
* @param tokenIndex which token will be withdrawn
* @param self Swap struct to read from
* @return the amount of token user will receive
*/
function calculateWithdrawOneToken(
Swap storage self,
address account,
uint256 tokenAmount,
uint8 tokenIndex
) external view returns (uint256) {
(uint256 availableTokenAmount, ) =
_calculateWithdrawOneToken(
self,
account,
tokenAmount,
tokenIndex,
self.lpToken.totalSupply()
);
return availableTokenAmount;
}
function _calculateWithdrawOneToken(
Swap storage self,
address account,
uint256 tokenAmount,
uint8 tokenIndex,
uint256 totalSupply
) internal view returns (uint256, uint256) {
uint256 dy;
uint256 newY;
uint256 currentY;
(dy, newY, currentY) = calculateWithdrawOneTokenDY(
self,
tokenIndex,
tokenAmount,
totalSupply
);
// dy_0 (without fees)
// dy, dy_0 - dy
uint256 dySwapFee =
currentY
.sub(newY)
.div(self.tokenPrecisionMultipliers[tokenIndex])
.sub(dy);
dy = dy
.mul(
FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, account))
)
.div(FEE_DENOMINATOR);
return (dy, dySwapFee);
}
/**
* @notice Calculate the dy of withdrawing in one token
* @param self Swap struct to read from
* @param tokenIndex which token will be withdrawn
* @param tokenAmount the amount to withdraw in the pools precision
* @return the d and the new y after withdrawing one token
*/
function calculateWithdrawOneTokenDY(
Swap storage self,
uint8 tokenIndex,
uint256 tokenAmount,
uint256 totalSupply
)
internal
view
returns (
uint256,
uint256,
uint256
)
{
// Get the current D, then solve the stableswap invariant
// y_i for D - tokenAmount
uint256[] memory xp = _xp(self);
require(tokenIndex < xp.length, "Token index out of range");
CalculateWithdrawOneTokenDYInfo memory v =
CalculateWithdrawOneTokenDYInfo(0, 0, 0, 0, 0);
v.preciseA = _getAPrecise(self);
v.d0 = getD(xp, v.preciseA);
v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(totalSupply));
require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available");
v.newY = getYD(v.preciseA, tokenIndex, xp, v.d1);
uint256[] memory xpReduced = new uint256[](xp.length);
v.feePerToken = _feePerToken(self.swapFee, xp.length);
for (uint256 i = 0; i < xp.length; i++) {
uint256 xpi = xp[i];
// if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY
// else dxExpected = xp[i] - (xp[i] * d1 / d0)
// xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR
xpReduced[i] = xpi.sub(
(
(i == tokenIndex)
? xpi.mul(v.d1).div(v.d0).sub(v.newY)
: xpi.sub(xpi.mul(v.d1).div(v.d0))
)
.mul(v.feePerToken)
.div(FEE_DENOMINATOR)
);
}
uint256 dy =
xpReduced[tokenIndex].sub(
getYD(v.preciseA, tokenIndex, xpReduced, v.d1)
);
dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]);
return (dy, v.newY, xp[tokenIndex]);
}
/**
* @notice Calculate the price of a token in the pool with given
* precision-adjusted balances and a particular D.
*
* @dev This is accomplished via solving the invariant iteratively.
* See the StableSwap paper and Curve.fi implementation for further details.
*
* x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A)
* x_1**2 + b*x_1 = c
* x_1 = (x_1**2 + c) / (2*x_1 + b)
*
* @param a the amplification coefficient * n * (n - 1). See the StableSwap paper for details.
* @param tokenIndex Index of token we are calculating for.
* @param xp a precision-adjusted set of pool balances. Array should be
* the same cardinality as the pool.
* @param d the stableswap invariant
* @return the price of the token, in the same precision as in xp
*/
function getYD(
uint256 a,
uint8 tokenIndex,
uint256[] memory xp,
uint256 d
) internal pure returns (uint256) {
uint256 numTokens = xp.length;
require(tokenIndex < numTokens, "Token not found");
uint256 c = d;
uint256 s;
uint256 nA = a.mul(numTokens);
for (uint256 i = 0; i < numTokens; i++) {
if (i != tokenIndex) {
s = s.add(xp[i]);
c = c.mul(d).div(xp[i].mul(numTokens));
// If we were to protect the division loss we would have to keep the denominator separate
// and divide at the end. However this leads to overflow with large numTokens or/and D.
// c = c * D * D * D * ... overflow!
}
}
c = c.mul(d).mul(AmplificationUtils.A_PRECISION).div(nA.mul(numTokens));
uint256 b = s.add(d.mul(AmplificationUtils.A_PRECISION).div(nA));
uint256 yPrev;
uint256 y = d;
for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) {
yPrev = y;
y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d));
if (y.within1(yPrev)) {
return y;
}
}
revert("Approximation did not converge");
}
/**
* @notice Get D, the StableSwap invariant, based on a set of balances and a particular A.
* @param xp a precision-adjusted set of pool balances. Array should be the same cardinality
* as the pool.
* @param a the amplification coefficient * n * (n - 1) in A_PRECISION.
* See the StableSwap paper for details
* @return the invariant, at the precision of the pool
*/
function getD(uint256[] memory xp, uint256 a)
internal
pure
returns (uint256)
{
uint256 numTokens = xp.length;
uint256 s;
for (uint256 i = 0; i < numTokens; i++) {
s = s.add(xp[i]);
}
if (s == 0) {
return 0;
}
uint256 prevD;
uint256 d = s;
uint256 nA = a.mul(numTokens);
for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) {
uint256 dP = d;
for (uint256 j = 0; j < numTokens; j++) {
dP = dP.mul(d).div(xp[j].mul(numTokens));
// If we were to protect the division loss we would have to keep the denominator separate
// and divide at the end. However this leads to overflow with large numTokens or/and D.
// dP = dP * D * D * D * ... overflow!
}
prevD = d;
d = nA
.mul(s)
.div(AmplificationUtils.A_PRECISION)
.add(dP.mul(numTokens))
.mul(d)
.div(
nA
.sub(AmplificationUtils.A_PRECISION)
.mul(d)
.div(AmplificationUtils.A_PRECISION)
.add(numTokens.add(1).mul(dP))
);
if (d.within1(prevD)) {
return d;
}
}
// Convergence should occur in 4 loops or less. If this is reached, there may be something wrong
// with the pool. If this were to occur repeatedly, LPs should withdraw via `removeLiquidity()`
// function which does not rely on D.
revert("D does not converge");
}
/**
* @notice Given a set of balances and precision multipliers, return the
* precision-adjusted balances.
*
* @param balances an array of token balances, in their native precisions.
* These should generally correspond with pooled tokens.
*
* @param precisionMultipliers an array of multipliers, corresponding to
* the amounts in the balances array. When multiplied together they
* should yield amounts at the pool's precision.
*
* @return an array of amounts "scaled" to the pool's precision
*/
function _xp(
uint256[] memory balances,
uint256[] memory precisionMultipliers
) internal pure returns (uint256[] memory) {
uint256 numTokens = balances.length;
require(
numTokens == precisionMultipliers.length,
"Balances must match multipliers"
);
uint256[] memory xp = new uint256[](numTokens);
for (uint256 i = 0; i < numTokens; i++) {
xp[i] = balances[i].mul(precisionMultipliers[i]);
}
return xp;
}
/**
* @notice Return the precision-adjusted balances of all tokens in the pool
* @param self Swap struct to read from
* @return the pool balances "scaled" to the pool's precision, allowing
* them to be more easily compared.
*/
function _xp(Swap storage self) internal view returns (uint256[] memory) {
return _xp(self.balances, self.tokenPrecisionMultipliers);
}
/**
* @notice Get the virtual price, to help calculate profit
* @param self Swap struct to read from
* @return the virtual price, scaled to precision of POOL_PRECISION_DECIMALS
*/
function getVirtualPrice(Swap storage self)
external
view
returns (uint256)
{
uint256 d = getD(_xp(self), _getAPrecise(self));
LPToken lpToken = self.lpToken;
uint256 supply = lpToken.totalSupply();
if (supply > 0) {
return d.mul(10**uint256(POOL_PRECISION_DECIMALS)).div(supply);
}
return 0;
}
/**
* @notice Calculate the new balances of the tokens given the indexes of the token
* that is swapped from (FROM) and the token that is swapped to (TO).
* This function is used as a helper function to calculate how much TO token
* the user should receive on swap.
*
* @param preciseA precise form of amplification coefficient
* @param tokenIndexFrom index of FROM token
* @param tokenIndexTo index of TO token
* @param x the new total amount of FROM token
* @param xp balances of the tokens in the pool
* @return the amount of TO token that should remain in the pool
*/
function getY(
uint256 preciseA,
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 x,
uint256[] memory xp
) internal pure returns (uint256) {
uint256 numTokens = xp.length;
require(
tokenIndexFrom != tokenIndexTo,
"Can't compare token to itself"
);
require(
tokenIndexFrom < numTokens && tokenIndexTo < numTokens,
"Tokens must be in pool"
);
uint256 d = getD(xp, preciseA);
uint256 c = d;
uint256 s;
uint256 nA = numTokens.mul(preciseA);
uint256 _x;
for (uint256 i = 0; i < numTokens; i++) {
if (i == tokenIndexFrom) {
_x = x;
} else if (i != tokenIndexTo) {
_x = xp[i];
} else {
continue;
}
s = s.add(_x);
c = c.mul(d).div(_x.mul(numTokens));
// If we were to protect the division loss we would have to keep the denominator separate
// and divide at the end. However this leads to overflow with large numTokens or/and D.
// c = c * D * D * D * ... overflow!
}
c = c.mul(d).mul(AmplificationUtils.A_PRECISION).div(nA.mul(numTokens));
uint256 b = s.add(d.mul(AmplificationUtils.A_PRECISION).div(nA));
uint256 yPrev;
uint256 y = d;
// iterative approximation
for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) {
yPrev = y;
y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d));
if (y.within1(yPrev)) {
return y;
}
}
revert("Approximation did not converge");
}
/**
* @notice Externally calculates a swap between two tokens.
* @param self Swap struct to read from
* @param tokenIndexFrom the token to sell
* @param tokenIndexTo the token to buy
* @param dx the number of tokens to sell. If the token charges a fee on transfers,
* use the amount that gets transferred after the fee.
* @return dy the number of tokens the user will get
*/
function calculateSwap(
Swap storage self,
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx
) external view returns (uint256 dy) {
(dy, ) = _calculateSwap(
self,
tokenIndexFrom,
tokenIndexTo,
dx,
self.balances
);
}
/**
* @notice Internally calculates a swap between two tokens.
*
* @dev The caller is expected to transfer the actual amounts (dx and dy)
* using the token contracts.
*
* @param self Swap struct to read from
* @param tokenIndexFrom the token to sell
* @param tokenIndexTo the token to buy
* @param dx the number of tokens to sell. If the token charges a fee on transfers,
* use the amount that gets transferred after the fee.
* @return dy the number of tokens the user will get
* @return dyFee the associated fee
*/
function _calculateSwap(
Swap storage self,
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx,
uint256[] memory balances
) internal view returns (uint256 dy, uint256 dyFee) {
uint256[] memory multipliers = self.tokenPrecisionMultipliers;
uint256[] memory xp = _xp(balances, multipliers);
require(
tokenIndexFrom < xp.length && tokenIndexTo < xp.length,
"Token index out of range"
);
uint256 x = dx.mul(multipliers[tokenIndexFrom]).add(xp[tokenIndexFrom]);
uint256 y =
getY(_getAPrecise(self), tokenIndexFrom, tokenIndexTo, x, xp);
dy = xp[tokenIndexTo].sub(y).sub(1);
dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR);
dy = dy.sub(dyFee).div(multipliers[tokenIndexTo]);
}
/**
* @notice A simple method to calculate amount of each underlying
* tokens that is returned upon burning given amount of
* LP tokens
*
* @param account the address that is removing liquidity. required for withdraw fee calculation
* @param amount the amount of LP tokens that would to be burned on
* withdrawal
* @return array of amounts of tokens user will receive
*/
function calculateRemoveLiquidity(
Swap storage self,
address account,
uint256 amount
) external view returns (uint256[] memory) {
return
_calculateRemoveLiquidity(
self,
self.balances,
account,
amount,
self.lpToken.totalSupply()
);
}
function _calculateRemoveLiquidity(
Swap storage self,
uint256[] memory balances,
address account,
uint256 amount,
uint256 totalSupply
) internal view returns (uint256[] memory) {
require(amount <= totalSupply, "Cannot exceed total supply");
uint256 feeAdjustedAmount =
amount
.mul(
FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, account))
)
.div(FEE_DENOMINATOR);
uint256[] memory amounts = new uint256[](balances.length);
for (uint256 i = 0; i < balances.length; i++) {
amounts[i] = balances[i].mul(feeAdjustedAmount).div(totalSupply);
}
return amounts;
}
/**
* @notice Calculate the fee that is applied when the given user withdraws.
* Withdraw fee decays linearly over WITHDRAW_FEE_DECAY_TIME.
* @param user address you want to calculate withdraw fee of
* @return current withdraw fee of the user
*/
function calculateCurrentWithdrawFee(Swap storage self, address user)
external
view
returns (uint256)
{
return _calculateCurrentWithdrawFee(self, user);
}
function _calculateCurrentWithdrawFee(Swap storage self, address user)
internal
view
returns (uint256)
{
uint256 endTime =
self.depositTimestamp[user].add(WITHDRAW_FEE_DECAY_TIME);
if (endTime > block.timestamp) {
uint256 timeLeftover = endTime.sub(block.timestamp);
return
self
.defaultWithdrawFee
.mul(self.withdrawFeeMultiplier[user])
.mul(timeLeftover)
.div(WITHDRAW_FEE_DECAY_TIME)
.div(FEE_DENOMINATOR);
}
return 0;
}
/**
* @notice A simple method to calculate prices from deposits or
* withdrawals, excluding fees but including slippage. This is
* helpful as an input into the various "min" parameters on calls
* to fight front-running
*
* @dev This shouldn't be used outside frontends for user estimates.
*
* @param self Swap struct to read from
* @param account address of the account depositing or withdrawing tokens
* @param amounts an array of token amounts to deposit or withdrawal,
* corresponding to pooledTokens. The amount should be in each
* pooled token's native precision. If a token charges a fee on transfers,
* use the amount that gets transferred after the fee.
* @param deposit whether this is a deposit or a withdrawal
* @return if deposit was true, total amount of lp token that will be minted and if
* deposit was false, total amount of lp token that will be burned
*/
function calculateTokenAmount(
Swap storage self,
address account,
uint256[] calldata amounts,
bool deposit
) external view returns (uint256) {
uint256 a = _getAPrecise(self);
uint256[] memory balances = self.balances;
uint256[] memory multipliers = self.tokenPrecisionMultipliers;
uint256 d0 = getD(_xp(balances, multipliers), a);
for (uint256 i = 0; i < balances.length; i++) {
if (deposit) {
balances[i] = balances[i].add(amounts[i]);
} else {
balances[i] = balances[i].sub(
amounts[i],
"Cannot withdraw more than available"
);
}
}
uint256 d1 = getD(_xp(balances, multipliers), a);
uint256 totalSupply = self.lpToken.totalSupply();
if (deposit) {
return d1.sub(d0).mul(totalSupply).div(d0);
} else {
return
d0.sub(d1).mul(totalSupply).div(d0).mul(FEE_DENOMINATOR).div(
FEE_DENOMINATOR.sub(
_calculateCurrentWithdrawFee(self, account)
)
);
}
}
/**
* @notice return accumulated amount of admin fees of the token with given index
* @param self Swap struct to read from
* @param index Index of the pooled token
* @return admin balance in the token's precision
*/
function getAdminBalance(Swap storage self, uint256 index)
external
view
returns (uint256)
{
require(index < self.pooledTokens.length, "Token index out of range");
return
self.pooledTokens[index].balanceOf(address(this)).sub(
self.balances[index]
);
}
/**
* @notice internal helper function to calculate fee per token multiplier used in
* swap fee calculations
* @param swapFee swap fee for the tokens
* @param numTokens number of tokens pooled
*/
function _feePerToken(uint256 swapFee, uint256 numTokens)
internal
pure
returns (uint256)
{
return swapFee.mul(numTokens).div(numTokens.sub(1).mul(4));
}
/*** STATE MODIFYING FUNCTIONS ***/
/**
* @notice swap two tokens in the pool
* @param self Swap struct to read from and write to
* @param tokenIndexFrom the token the user wants to sell
* @param tokenIndexTo the token the user wants to buy
* @param dx the amount of tokens the user wants to sell
* @param minDy the min amount the user would like to receive, or revert.
* @return amount of token user received on swap
*/
function swap(
Swap storage self,
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx,
uint256 minDy
) external returns (uint256) {
{
IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom];
require(
dx <= tokenFrom.balanceOf(msg.sender),
"Cannot swap more than you own"
);
// Transfer tokens first to see if a fee was charged on transfer
uint256 beforeBalance = tokenFrom.balanceOf(address(this));
tokenFrom.safeTransferFrom(msg.sender, address(this), dx);
// Use the actual transferred amount for AMM math
dx = tokenFrom.balanceOf(address(this)).sub(beforeBalance);
}
uint256 dy;
uint256 dyFee;
uint256[] memory balances = self.balances;
(dy, dyFee) = _calculateSwap(
self,
tokenIndexFrom,
tokenIndexTo,
dx,
balances
);
require(dy >= minDy, "Swap didn't result in min tokens");
uint256 dyAdminFee =
dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div(
self.tokenPrecisionMultipliers[tokenIndexTo]
);
self.balances[tokenIndexFrom] = balances[tokenIndexFrom].add(dx);
self.balances[tokenIndexTo] = balances[tokenIndexTo].sub(dy).sub(
dyAdminFee
);
self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy);
emit TokenSwap(msg.sender, dx, dy, tokenIndexFrom, tokenIndexTo);
return dy;
}
/**
* @notice Add liquidity to the pool
* @param self Swap struct to read from and write to
* @param amounts the amounts of each token to add, in their native precision
* @param minToMint the minimum LP tokens adding this amount of liquidity
* should mint, otherwise revert. Handy for front-running mitigation
* allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored.
* @return amount of LP token user received
*/
function addLiquidity(
Swap storage self,
uint256[] memory amounts,
uint256 minToMint
) external returns (uint256) {
IERC20[] memory pooledTokens = self.pooledTokens;
require(
amounts.length == pooledTokens.length,
"Amounts must match pooled tokens"
);
// current state
ManageLiquidityInfo memory v =
ManageLiquidityInfo(
0,
0,
0,
_getAPrecise(self),
self.lpToken,
0,
self.balances,
self.tokenPrecisionMultipliers
);
v.totalSupply = v.lpToken.totalSupply();
if (v.totalSupply != 0) {
v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA);
}
uint256[] memory newBalances = new uint256[](pooledTokens.length);
for (uint256 i = 0; i < pooledTokens.length; i++) {
require(
v.totalSupply != 0 || amounts[i] > 0,
"Must supply all tokens in pool"
);
// Transfer tokens first to see if a fee was charged on transfer
if (amounts[i] != 0) {
uint256 beforeBalance =
pooledTokens[i].balanceOf(address(this));
pooledTokens[i].safeTransferFrom(
msg.sender,
address(this),
amounts[i]
);
// Update the amounts[] with actual transfer amount
amounts[i] = pooledTokens[i].balanceOf(address(this)).sub(
beforeBalance
);
}
newBalances[i] = v.balances[i].add(amounts[i]);
}
// invariant after change
v.d1 = getD(_xp(newBalances, v.multipliers), v.preciseA);
require(v.d1 > v.d0, "D should increase");
// updated to reflect fees and calculate the user's LP tokens
v.d2 = v.d1;
uint256[] memory fees = new uint256[](pooledTokens.length);
if (v.totalSupply != 0) {
uint256 feePerToken =
_feePerToken(self.swapFee, pooledTokens.length);
for (uint256 i = 0; i < pooledTokens.length; i++) {
uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0);
fees[i] = feePerToken
.mul(idealBalance.difference(newBalances[i]))
.div(FEE_DENOMINATOR);
self.balances[i] = newBalances[i].sub(
fees[i].mul(self.adminFee).div(FEE_DENOMINATOR)
);
newBalances[i] = newBalances[i].sub(fees[i]);
}
v.d2 = getD(_xp(newBalances, v.multipliers), v.preciseA);
} else {
// the initial depositor doesn't pay fees
self.balances = newBalances;
}
uint256 toMint;
if (v.totalSupply == 0) {
toMint = v.d1;
} else {
toMint = v.d2.sub(v.d0).mul(v.totalSupply).div(v.d0);
}
require(toMint >= minToMint, "Couldn't mint min requested");
// mint the user's LP tokens
v.lpToken.mint(msg.sender, toMint);
emit AddLiquidity(
msg.sender,
amounts,
fees,
v.d1,
v.totalSupply.add(toMint)
);
return toMint;
}
/**
* @notice Update the withdraw fee for `user`. If the user is currently
* not providing liquidity in the pool, sets to default value. If not, recalculate
* the starting withdraw fee based on the last deposit's time & amount relative
* to the new deposit.
*
* @param self Swap struct to read from and write to
* @param user address of the user depositing tokens
* @param toMint amount of pool tokens to be minted
*/
function updateUserWithdrawFee(
Swap storage self,
address user,
uint256 toMint
) public {
// If token is transferred to address 0 (or burned), don't update the fee.
if (user == address(0)) {
return;
}
if (self.defaultWithdrawFee == 0) {
// If current fee is set to 0%, set multiplier to FEE_DENOMINATOR
self.withdrawFeeMultiplier[user] = FEE_DENOMINATOR;
} else {
// Otherwise, calculate appropriate discount based on last deposit amount
uint256 currentFee = _calculateCurrentWithdrawFee(self, user);
uint256 currentBalance = self.lpToken.balanceOf(user);
// ((currentBalance * currentFee) + (toMint * defaultWithdrawFee)) * FEE_DENOMINATOR /
// ((toMint + currentBalance) * defaultWithdrawFee)
self.withdrawFeeMultiplier[user] = currentBalance
.mul(currentFee)
.add(toMint.mul(self.defaultWithdrawFee))
.mul(FEE_DENOMINATOR)
.div(toMint.add(currentBalance).mul(self.defaultWithdrawFee));
}
self.depositTimestamp[user] = block.timestamp;
}
/**
* @notice Burn LP tokens to remove liquidity from the pool.
* @dev Liquidity can always be removed, even when the pool is paused.
* @param self Swap struct to read from and write to
* @param amount the amount of LP tokens to burn
* @param minAmounts the minimum amounts of each token in the pool
* acceptable for this burn. Useful as a front-running mitigation
* @return amounts of tokens the user received
*/
function removeLiquidity(
Swap storage self,
uint256 amount,
uint256[] calldata minAmounts
) external returns (uint256[] memory) {
LPToken lpToken = self.lpToken;
IERC20[] memory pooledTokens = self.pooledTokens;
require(amount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf");
require(
minAmounts.length == pooledTokens.length,
"minAmounts must match poolTokens"
);
uint256[] memory balances = self.balances;
uint256 totalSupply = lpToken.totalSupply();
uint256[] memory amounts =
_calculateRemoveLiquidity(
self,
balances,
msg.sender,
amount,
totalSupply
);
for (uint256 i = 0; i < amounts.length; i++) {
require(amounts[i] >= minAmounts[i], "amounts[i] < minAmounts[i]");
self.balances[i] = balances[i].sub(amounts[i]);
pooledTokens[i].safeTransfer(msg.sender, amounts[i]);
}
lpToken.burnFrom(msg.sender, amount);
emit RemoveLiquidity(msg.sender, amounts, totalSupply.sub(amount));
return amounts;
}
/**
* @notice Remove liquidity from the pool all in one token.
* @param self Swap struct to read from and write to
* @param tokenAmount the amount of the lp tokens to burn
* @param tokenIndex the index of the token you want to receive
* @param minAmount the minimum amount to withdraw, otherwise revert
* @return amount chosen token that user received
*/
function removeLiquidityOneToken(
Swap storage self,
uint256 tokenAmount,
uint8 tokenIndex,
uint256 minAmount
) external returns (uint256) {
LPToken lpToken = self.lpToken;
IERC20[] memory pooledTokens = self.pooledTokens;
require(tokenAmount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf");
require(tokenIndex < pooledTokens.length, "Token not found");
uint256 totalSupply = lpToken.totalSupply();
(uint256 dy, uint256 dyFee) =
_calculateWithdrawOneToken(
self,
msg.sender,
tokenAmount,
tokenIndex,
totalSupply
);
require(dy >= minAmount, "dy < minAmount");
self.balances[tokenIndex] = self.balances[tokenIndex].sub(
dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR))
);
lpToken.burnFrom(msg.sender, tokenAmount);
pooledTokens[tokenIndex].safeTransfer(msg.sender, dy);
emit RemoveLiquidityOne(
msg.sender,
tokenAmount,
totalSupply,
tokenIndex,
dy
);
return dy;
}
/**
* @notice Remove liquidity from the pool, weighted differently than the
* pool's current balances.
*
* @param self Swap struct to read from and write to
* @param amounts how much of each token to withdraw
* @param maxBurnAmount the max LP token provider is willing to pay to
* remove liquidity. Useful as a front-running mitigation.
* @return actual amount of LP tokens burned in the withdrawal
*/
function removeLiquidityImbalance(
Swap storage self,
uint256[] memory amounts,
uint256 maxBurnAmount
) public returns (uint256) {
ManageLiquidityInfo memory v =
ManageLiquidityInfo(
0,
0,
0,
_getAPrecise(self),
self.lpToken,
0,
self.balances,
self.tokenPrecisionMultipliers
);
v.totalSupply = v.lpToken.totalSupply();
IERC20[] memory pooledTokens = self.pooledTokens;
require(
amounts.length == pooledTokens.length,
"Amounts should match pool tokens"
);
require(
maxBurnAmount <= v.lpToken.balanceOf(msg.sender) &&
maxBurnAmount != 0,
">LP.balanceOf"
);
uint256 feePerToken = _feePerToken(self.swapFee, pooledTokens.length);
uint256[] memory fees = new uint256[](pooledTokens.length);
{
uint256[] memory balances1 = new uint256[](pooledTokens.length);
v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA);
for (uint256 i = 0; i < pooledTokens.length; i++) {
balances1[i] = v.balances[i].sub(
amounts[i],
"Cannot withdraw more than available"
);
}
v.d1 = getD(_xp(balances1, v.multipliers), v.preciseA);
for (uint256 i = 0; i < pooledTokens.length; i++) {
uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0);
uint256 difference = idealBalance.difference(balances1[i]);
fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR);
self.balances[i] = balances1[i].sub(
fees[i].mul(self.adminFee).div(FEE_DENOMINATOR)
);
balances1[i] = balances1[i].sub(fees[i]);
}
v.d2 = getD(_xp(balances1, v.multipliers), v.preciseA);
}
uint256 tokenAmount = v.d0.sub(v.d2).mul(v.totalSupply).div(v.d0);
require(tokenAmount != 0, "Burnt amount cannot be zero");
tokenAmount = tokenAmount.add(1).mul(FEE_DENOMINATOR).div(
FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, msg.sender))
);
require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount");
v.lpToken.burnFrom(msg.sender, tokenAmount);
for (uint256 i = 0; i < pooledTokens.length; i++) {
pooledTokens[i].safeTransfer(msg.sender, amounts[i]);
}
emit RemoveLiquidityImbalance(
msg.sender,
amounts,
fees,
v.d1,
v.totalSupply.sub(tokenAmount)
);
return tokenAmount;
}
/**
* @notice withdraw all admin fees to a given address
* @param self Swap struct to withdraw fees from
* @param to Address to send the fees to
*/
function withdrawAdminFees(Swap storage self, address to) external {
IERC20[] memory pooledTokens = self.pooledTokens;
for (uint256 i = 0; i < pooledTokens.length; i++) {
IERC20 token = pooledTokens[i];
uint256 balance =
token.balanceOf(address(this)).sub(self.balances[i]);
if (balance != 0) {
token.safeTransfer(to, balance);
}
}
}
/**
* @notice Sets the admin fee
* @dev adminFee cannot be higher than 100% of the swap fee
* @param self Swap struct to update
* @param newAdminFee new admin fee to be applied on future transactions
*/
function setAdminFee(Swap storage self, uint256 newAdminFee) external {
require(newAdminFee <= MAX_ADMIN_FEE, "Fee is too high");
self.adminFee = newAdminFee;
emit NewAdminFee(newAdminFee);
}
/**
* @notice update the swap fee
* @dev fee cannot be higher than 1% of each swap
* @param self Swap struct to update
* @param newSwapFee new swap fee to be applied on future transactions
*/
function setSwapFee(Swap storage self, uint256 newSwapFee) external {
require(newSwapFee <= MAX_SWAP_FEE, "Fee is too high");
self.swapFee = newSwapFee;
emit NewSwapFee(newSwapFee);
}
/**
* @notice update the default withdraw fee. This also affects deposits made in the past as well.
* @param self Swap struct to update
* @param newWithdrawFee new withdraw fee to be applied
*/
function setDefaultWithdrawFee(Swap storage self, uint256 newWithdrawFee)
external
{
require(newWithdrawFee <= MAX_WITHDRAW_FEE, "Fee is too high");
self.defaultWithdrawFee = newWithdrawFee;
emit NewWithdrawFee(newWithdrawFee);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
interface ISwap {
// pool data view functions
function getA() external view returns (uint256);
function getToken(uint8 index) external view returns (IERC20);
function getTokenIndex(address tokenAddress) external view returns (uint8);
function getTokenBalance(uint8 index) external view returns (uint256);
function getVirtualPrice() external view returns (uint256);
// min return calculation functions
function calculateSwap(
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx
) external view returns (uint256);
function calculateTokenAmount(
address account,
uint256[] calldata amounts,
bool deposit
) external view returns (uint256);
function calculateRemoveLiquidity(address account, uint256 amount)
external
view
returns (uint256[] memory);
function calculateRemoveLiquidityOneToken(
address account,
uint256 tokenAmount,
uint8 tokenIndex
) external view returns (uint256 availableTokenAmount);
// state modifying functions
function initialize(
IERC20[] memory pooledTokens,
uint8[] memory decimals,
string memory lpTokenName,
string memory lpTokenSymbol,
uint256 a,
uint256 fee,
uint256 adminFee,
uint256 withdrawFee,
address lpTokenTargetAddress
) external;
function swap(
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx,
uint256 minDy,
uint256 deadline
) external returns (uint256);
function addLiquidity(
uint256[] calldata amounts,
uint256 minToMint,
uint256 deadline
) external returns (uint256);
function removeLiquidity(
uint256 amount,
uint256[] calldata minAmounts,
uint256 deadline
) external returns (uint256[] memory);
function removeLiquidityOneToken(
uint256 tokenAmount,
uint8 tokenIndex,
uint256 minAmount,
uint256 deadline
) external returns (uint256);
function removeLiquidityImbalance(
uint256[] calldata amounts,
uint256 maxBurnAmount,
uint256 deadline
) external returns (uint256);
// withdraw fee update function
function updateUserWithdrawFee(address recipient, uint256 transferAmount)
external;
}
|
Update the swap fee to be applied on swaps newSwapFee new swap fee to be applied on future transactions/
|
function setSwapFee(uint256 newSwapFee) external onlyOwner {
swapStorage.setSwapFee(newSwapFee);
}
| 35,144
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.5;
pragma abicoder v2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/SignedSafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "../../interfaces/IDiscreteOptionsProtocol.sol";
import "../../interfaces/IResellableOptionsProtocol.sol";
import "./interfaces/IOptionsFactory.sol";
import "./interfaces/IOptionsExchange.sol";
import "./interfaces/IoToken.sol";
import "./interfaces/IUniswapV1Factory.sol";
import "./interfaces/IUniswapV1Exchange.sol";
import "./interfaces/IOracle.sol";
import "../../libraries/strings.sol";
import "../domain/OptionsStore.sol";
import "../domain/OptionsModel.sol";
contract ConvexityAdapter is
IDiscreteOptionsProtocol,
IResellableOptionsProtocol
{
using SafeMath for uint256;
using SignedSafeMath for int256;
using strings for *;
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
IOptionsFactory private immutable _optionsFactory;
IOptionsExchange private immutable _optionsExchange;
IUniswapV1Factory private immutable _uniswapV1Factory;
IOracle private immutable _compoundOracle;
// Tokens that can be used as paymentToken and payoutToken throughout Opyn V1
// Trying to call functions with tokens not in this set could revert with:
// "execution reverted: No payout exchange"
EnumerableSet.AddressSet private _supportedExchangeTokens;
address private constant _WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
constructor(address[] memory supportedTokens) {
_optionsFactory = IOptionsFactory(
0xcC5d905b9c2c8C9329Eb4e25dc086369D6C7777C
);
_optionsExchange = IOptionsExchange(
0x39246c4F3F6592C974EBC44F80bA6dC69b817c71
);
_uniswapV1Factory = IUniswapV1Factory(
0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95
);
_compoundOracle = IOracle(0x7054e08461e3eCb7718B63540adDB3c3A1746415);
for (uint8 i = 0; i < supportedTokens.length; i++) {
_supportedExchangeTokens.add(supportedTokens[i]);
}
}
///@notice Get the option strikePrice
///@dev Handles negative exponents by considering oToken.decimals() and strike.decimals()
function _getStrikePrice(IoToken oToken, OptionsModel.OptionType optionType)
internal
view
returns (uint256 strikePrice)
{
(uint256 value, int32 exponent) = oToken.strikePrice();
uint8 strikeDecimals;
if (oToken.strike() != address(0)) {
ERC20 strike = ERC20(oToken.strike());
strikeDecimals = strike.decimals();
} else {
// strike is ETH
strikeDecimals = 18;
}
if (optionType == OptionsModel.OptionType.PUT) {
strikePrice = value.mul(
10 **
uint256(
int256(exponent).add(oToken.decimals()).add(
strikeDecimals
)
)
);
} else {
// oToken is a CALL option
strikePrice = (10 **
uint256(
int256(exponent).mul(-1).sub(oToken.decimals()).add(
strikeDecimals
)
))
.div(value);
}
}
function _getFilteredOptions(
OptionsModel.OptionType _optionType,
address baseAsset
) internal view returns (OptionsModel.Option[] memory) {
uint256 numOptionsContracts = _optionsFactory
.getNumberOfOptionsContracts();
OptionsModel.Option[] memory currentOptions = new OptionsModel.Option[](
numOptionsContracts
);
uint256 numFilteredOptions = 0;
for (uint256 i = 0; i < numOptionsContracts; i++) {
address oTokenAddress = _optionsFactory.optionsContracts(i);
IoToken oToken = IoToken(oTokenAddress);
string memory filter = _optionType == OptionsModel.OptionType.PUT
? "Put"
: "Call";
if (
!oToken.hasExpired() &&
((_optionType == OptionsModel.OptionType.PUT &&
oToken.underlying() == baseAsset) ||
(_optionType == OptionsModel.OptionType.CALL &&
oToken.strike() == baseAsset)) &&
(oToken.name().toSlice().contains(filter.toSlice()) ||
oToken.symbol().toSlice().contains(filter.toSlice()))
) {
currentOptions[numFilteredOptions] = OptionsModel.Option({
optionMarket: OptionsModel.OptionMarket.CONVEXITY,
optionType: _optionType,
strikePrice: _getStrikePrice(oToken, _optionType),
expiryDate: oToken.expiry(),
tokenAddress: oTokenAddress,
settlementAsset: oToken.strike(),
paymentAsset: address(0)
});
numFilteredOptions = numFilteredOptions.add(1);
}
}
// Trim array removing zero addresses, just for simplicity when it's consumed.
OptionsModel.Option[] memory filteredOptions
= new OptionsModel.Option[](numFilteredOptions);
for (uint256 i = 0; i < numFilteredOptions; i++) {
filteredOptions[i] = currentOptions[i];
}
return filteredOptions;
}
///@notice Checks if a given token is valid to be used as paymentToken and payoutToken
function _checkTokenValidity(address token)
internal
view
returns (bool isValid)
{
isValid =
_supportedExchangeTokens.contains(token) ||
_compoundOracle.getPrice(token) != 0;
}
function getPutOptions(address baseAsset)
external
view
override
returns (OptionsModel.Option[] memory)
{
return _getFilteredOptions(OptionsModel.OptionType.PUT, baseAsset);
}
function getCallOptions(address baseAsset)
external
view
override
returns (OptionsModel.Option[] memory)
{
return _getFilteredOptions(OptionsModel.OptionType.CALL, baseAsset);
}
function _getAvailableLiquidity(OptionsModel.Option memory option)
internal
view
returns (uint256)
{
IoToken optionToken = IoToken(option.tokenAddress);
return
optionToken
.balanceOf(
_uniswapV1Factory.getExchange(option.tokenAddress)
// subtract 1 since trying to get/use all the liquidity
// would raise a 'invalid jump destination' error
)
.sub(1);
}
function getAvailableBuyLiquidity(OptionsModel.Option memory option)
external
view
override
returns (uint256)
{
return _getAvailableLiquidity(option);
}
function _getAvailableLiquidityAtPrice(
OptionsModel.Option memory option,
uint256 optionPrice,
address tokenAddress
) internal view returns (uint256 availableLiquidity) {
// Make sure price is in ETH
if (tokenAddress != address(0) && tokenAddress != _WETH) {
optionPrice = optionPrice.mul(
_compoundOracle.getPrice(tokenAddress)
);
}
// Get the reserve of ETH in the Uniswap V1 ETH <-> oToken pair
address exchange = _uniswapV1Factory.getExchange(option.tokenAddress);
uint256 reserveETH = exchange.balance;
// Get the reserve of options (oToken)
IoToken oToken = IoToken(option.tokenAddress);
uint256 reserveOptions = oToken.balanceOf(exchange);
// An explanation for how the following formula was derived can be found at:
// https://ipfs.io/ipfs/bafybeid4u5dib37kbikwa77u6v2u3fzfhiu3r4zg4hxqjzhmnekpk3bspq
availableLiquidity = (
uint256(1000).mul(reserveOptions).mul(optionPrice)
)
.div((uint256(997).mul(reserveETH.sub(optionPrice))));
}
function getAvailableBuyLiquidityAtPrice(
OptionsModel.Option memory option,
uint256 maxPricePerOption,
address paymentTokenAddress
) external view override returns (uint256) {
require(
_checkTokenValidity(paymentTokenAddress),
"ConvexityAdapter.getAvailableBuyLiquidityAtPrice: paymentTokenAddress is not supported"
);
return
_getAvailableLiquidityAtPrice(
option,
maxPricePerOption,
paymentTokenAddress
);
}
function getBuyPrice(
OptionsModel.Option memory option,
uint256 amountToBuy,
address paymentTokenAddress
) external view override returns (uint256) {
require(
_checkTokenValidity(paymentTokenAddress),
"ConvexityAdapter.getBuyPrice: paymentTokenAddress is not supported"
);
return
_optionsExchange.premiumToPay(
option.tokenAddress,
paymentTokenAddress,
amountToBuy
);
}
function buyOptions(
OptionsModel.Option memory option,
uint256 amountToBuy,
address paymentTokenAddress
) external payable override returns (OptionsModel.OwnedOption memory) {
require(
_checkTokenValidity(paymentTokenAddress),
"ConvexityAdapter.buyOptions: paymentTokenAddress is not supported"
);
// Need to approve any ERC20 before spending it
IERC20 paymentToken = IERC20(paymentTokenAddress);
if (paymentTokenAddress != address(0)) {
paymentToken.safeApprove(address(_optionsExchange), 0);
paymentToken.safeApprove(address(_optionsExchange), amountToBuy);
}
_optionsExchange.buyOTokens(
address(this),
option.tokenAddress,
paymentTokenAddress,
amountToBuy
);
return OptionsModel.OwnedOption(option, amountToBuy, 0);
}
function exerciseOptions(
OptionsModel.OwnedOption memory ownedOption,
uint256 amountToExercise,
address[] memory vaultOwners
) external payable override {
OptionsModel.Option memory option = ownedOption.option;
IoToken optionToken = IoToken(option.tokenAddress);
address underlyingAddress = optionToken.underlying();
IERC20 underlyingToken = IERC20(underlyingAddress);
uint256 underlyingAmountRequired = optionToken
.underlyingRequiredToExercise(amountToExercise);
// Perform checks required for the exercising of options to succeed
require(
optionToken.isExerciseWindow() == true,
"ConvexityAdapter: can only exercise during the exericse window"
);
if (underlyingAddress == address(0)) {
require(
address(this).balance >= underlyingAmountRequired,
"ConvexityAdapter: insufficient underlying (ETH) to exercise"
);
} else {
require(
underlyingToken.balanceOf(address(this)) >=
underlyingAmountRequired,
"ConvexityAdapter: insufficient underlying to exercise"
);
}
// Approve the oToken contract to spend amountToExercise from the caller's balance
IERC20(option.tokenAddress).safeApprove(option.tokenAddress, 0);
IERC20(option.tokenAddress).safeApprove(
option.tokenAddress,
amountToExercise
);
// Approve the oToken contract to spend the caller's underlyingToken balance
if (underlyingAddress != address(0)) {
underlyingToken.safeApprove(option.tokenAddress, 0);
underlyingToken.safeApprove(
option.tokenAddress,
underlyingAmountRequired
);
}
optionToken.exercise{value: msg.value}(amountToExercise, vaultOwners);
}
function sellOptions(
OptionsModel.OwnedOption memory ownedOption,
uint256 amountToSell,
address payoutTokenAddress
) external override {
require(
_checkTokenValidity(payoutTokenAddress),
"ConvexityAdapter.sellOptions: payoutTokenAddress is not supported"
);
OptionsModel.Option memory option = ownedOption.option;
IERC20(option.tokenAddress).safeApprove(address(_optionsExchange), 0);
IERC20(option.tokenAddress).safeApprove(
address(_optionsExchange),
amountToSell
);
_optionsExchange.sellOTokens(
address(this),
option.tokenAddress,
payoutTokenAddress,
amountToSell
);
}
function getAvailableSellLiquidity(OptionsModel.Option memory option)
external
view
override
returns (uint256)
{
return _getAvailableLiquidity(option);
}
function getAvailableSellLiquidityAtPrice(
OptionsModel.Option memory option,
uint256 minPricePerOption,
address payoutTokenAddress
) external view override returns (uint256) {
require(
_checkTokenValidity(payoutTokenAddress),
"ConvexityAdapter.getAvailableSellLiquidityAtPrice: payoutTokenAddress is not supported"
);
return
_getAvailableLiquidityAtPrice(
option,
minPricePerOption,
payoutTokenAddress
);
}
function getSellPrice(
OptionsModel.Option memory option,
uint256 amountToSell,
address payoutTokenAddress
) external view override returns (uint256) {
require(
_checkTokenValidity(payoutTokenAddress),
"ConvexityAdapter.getSellPrice: payoutTokenAddress is not supported"
);
return
_optionsExchange.premiumReceived(
option.tokenAddress,
payoutTokenAddress,
amountToSell
);
}
}
|
Perform checks required for the exercising of options to succeed Approve the oToken contract to spend the caller's underlyingToken balance
|
function exerciseOptions(
OptionsModel.OwnedOption memory ownedOption,
uint256 amountToExercise,
address[] memory vaultOwners
) external payable override {
OptionsModel.Option memory option = ownedOption.option;
IoToken optionToken = IoToken(option.tokenAddress);
address underlyingAddress = optionToken.underlying();
IERC20 underlyingToken = IERC20(underlyingAddress);
uint256 underlyingAmountRequired = optionToken
.underlyingRequiredToExercise(amountToExercise);
require(
optionToken.isExerciseWindow() == true,
"ConvexityAdapter: can only exercise during the exericse window"
);
if (underlyingAddress == address(0)) {
require(
address(this).balance >= underlyingAmountRequired,
"ConvexityAdapter: insufficient underlying (ETH) to exercise"
);
require(
underlyingToken.balanceOf(address(this)) >=
underlyingAmountRequired,
"ConvexityAdapter: insufficient underlying to exercise"
);
}
IERC20(option.tokenAddress).safeApprove(
option.tokenAddress,
amountToExercise
);
if (underlyingAddress != address(0)) {
underlyingToken.safeApprove(option.tokenAddress, 0);
underlyingToken.safeApprove(
option.tokenAddress,
underlyingAmountRequired
);
}
}
| 12,541,026
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { Proxy } from '../Proxy.sol';
import { UpgradeableProxyStorage } from './UpgradeableProxyStorage.sol';
/**
* @title Proxy with upgradeable implementation
*/
abstract contract UpgradeableProxy is Proxy {
using UpgradeableProxyStorage for UpgradeableProxyStorage.Layout;
/**
* @inheritdoc Proxy
*/
function _getImplementation() internal view override returns (address) {
// inline storage layout retrieval uses less gas
UpgradeableProxyStorage.Layout storage l;
bytes32 slot = UpgradeableProxyStorage.STORAGE_SLOT;
assembly {
l.slot := slot
}
return l.implementation;
}
/**
* @notice set logic implementation address
* @param implementation implementation address
*/
function _setImplementation(address implementation) internal {
UpgradeableProxyStorage.layout().setImplementation(implementation);
}
}
|
set logic implementation address implementation implementation address/
|
function _setImplementation(address implementation) internal {
UpgradeableProxyStorage.layout().setImplementation(implementation);
}
| 14,023,077
|
./partial_match/1/0x52B976bdA3Bc65B5b36234C29Cda1A4f156E8CA4/sources/HumanOnlyArt.sol
|
Interface of the ERC20 standard as defined in the EIP./
|
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
Human Only Art: $HOA
pragma solidity ^0.8.4;
}
| 15,925,478
|
pragma solidity ^0.5.7;
library SafeMath {
int256 constant private int256_min606 = -2**255; //inject NONSTANDARD NAMING
function MUL578(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function MUL578(int256 a, int256 b) internal pure returns (int256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == int256_min606)); // This is the only case of overflow not detected by the check below
int256 c = a * b;
require(c / a == b);
return c;
}
function DIV266(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function DIV266(int256 a, int256 b) internal pure returns (int256) { //inject NONSTANDARD NAMING
require(b != 0); // Solidity only automatically asserts when dividing by 0
require(!(b == -1 && a == int256_min606)); // This is the only case of overflow
int256 c = a / b;
return c;
}
function SUB55(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a);
uint256 c = a - b;
return c;
}
function SUB55(int256 a, int256 b) internal pure returns (int256) { //inject NONSTANDARD NAMING
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
function ADD666(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a);
return c;
}
function ADD666(int256 a, int256 b) internal pure returns (int256) { //inject NONSTANDARD NAMING
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
function MOD120(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0);
return a % b;
}
}
interface IERC20 {
function TOTALSUPPLY304() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF735(address who) external view returns (uint256); //inject NONSTANDARD NAMING
function ALLOWANCE123(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER854(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function APPROVE531(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM522(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER418(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL780(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
contract ERC20Pistachio is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
// Token symbol (short)
string public symbol;
// Token name (Long)
string public name;
// Decimals (18 maximum)
uint8 public decimals;
constructor (address initialAccount, string memory _tokenSymbol, string memory _tokenName, uint256 initialBalance) public {
// Initialize Contract Parameters
symbol = _tokenSymbol;
name = _tokenName;
decimals = 18; // default decimals is going to be 18 always
_MINT600(initialAccount, initialBalance);
}
function TOTALSUPPLY304() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF735(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[owner];
}
function ALLOWANCE123(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowed[owner][spender];
}
function TRANSFER854(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER481(msg.sender, to, value);
return true;
}
function APPROVE531(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit APPROVAL780(msg.sender, spender, value);
return true;
}
function TRANSFERFROM522(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_allowed[from][msg.sender] = _allowed[from][msg.sender].SUB55(value);
_TRANSFER481(from, to, value);
emit APPROVAL780(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
function INCREASEALLOWANCE330(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].ADD666(addedValue);
emit APPROVAL780(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function DECREASEALLOWANCE446(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].SUB55(subtractedValue);
emit APPROVAL780(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function _TRANSFER481(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
require(to != address(0));
_balances[from] = _balances[from].SUB55(value);
_balances[to] = _balances[to].ADD666(value);
emit TRANSFER418(from, to, value);
}
function _MINT600(address account, uint256 value) internal { //inject NONSTANDARD NAMING
require(account != address(0));
_totalSupply = _totalSupply.ADD666(value);
_balances[account] = _balances[account].ADD666(value);
emit TRANSFER418(address(0), account, value);
}
function _BURN785(address account, uint256 value) internal { //inject NONSTANDARD NAMING
require(account != address(0));
_totalSupply = _totalSupply.SUB55(value);
_balances[account] = _balances[account].SUB55(value);
emit TRANSFER418(account, address(0), value);
}
function _BURNFROM615(address account, uint256 value) internal { //inject NONSTANDARD NAMING
_allowed[account][msg.sender] = _allowed[account][msg.sender].SUB55(value);
_BURN785(account, value);
emit APPROVAL780(account, msg.sender, _allowed[account][msg.sender]);
}
}
contract ERC20Burnable is ERC20Pistachio {
bool private _burnableActive;
function BURN665(uint256 value) public WHENBURNABLEACTIVE644 { //inject NONSTANDARD NAMING
_BURN785(msg.sender, value);
}
function BURNFROM948(address from, uint256 value) public WHENBURNABLEACTIVE644 { //inject NONSTANDARD NAMING
_BURNFROM615(from, value);
}
function _SETBURNABLEACTIVE519(bool _active) internal { //inject NONSTANDARD NAMING
_burnableActive = _active;
}
modifier WHENBURNABLEACTIVE644() { //inject NONSTANDARD NAMING
require(_burnableActive);
_;
}
}
library Roles {
struct Role {
mapping (address => bool) bearer;
}
function ADD666(Role storage role, address account) internal { //inject NONSTANDARD NAMING
require(account != address(0));
require(!HAS322(role, account));
role.bearer[account] = true;
}
function REMOVE231(Role storage role, address account) internal { //inject NONSTANDARD NAMING
require(account != address(0));
require(HAS322(role, account));
role.bearer[account] = false;
}
function HAS322(Role storage role, address account) internal view returns (bool) { //inject NONSTANDARD NAMING
require(account != address(0));
return role.bearer[account];
}
}
contract MinterRole {
using Roles for Roles.Role;
event MINTERADDED605(address indexed account); //inject NONSTANDARD NAMING
event MINTERREMOVED905(address indexed account); //inject NONSTANDARD NAMING
Roles.Role private _minters;
constructor () internal {
_ADDMINTER929(msg.sender);
}
modifier ONLYMINTER785() { //inject NONSTANDARD NAMING
require(ISMINTER455(msg.sender));
_;
}
function ISMINTER455(address account) public view returns (bool) { //inject NONSTANDARD NAMING
return _minters.HAS322(account);
}
function ADDMINTER562(address account) public ONLYMINTER785 { //inject NONSTANDARD NAMING
_ADDMINTER929(account);
}
function RENOUNCEMINTER297() public { //inject NONSTANDARD NAMING
_REMOVEMINTER917(msg.sender);
}
function _ADDMINTER929(address account) internal { //inject NONSTANDARD NAMING
_minters.ADD666(account);
emit MINTERADDED605(account);
}
function _REMOVEMINTER917(address account) internal { //inject NONSTANDARD NAMING
_minters.REMOVE231(account);
emit MINTERREMOVED905(account);
}
}
contract ERC20Mintable is ERC20Pistachio, MinterRole {
bool private _mintableActive;
function MINT525(address to, uint256 value) public ONLYMINTER785 WHENMINTABLEACTIVE702 returns (bool) { //inject NONSTANDARD NAMING
_MINT600(to, value);
return true;
}
function _SETMINTABLEACTIVE686(bool _active) internal { //inject NONSTANDARD NAMING
_mintableActive = _active;
}
modifier WHENMINTABLEACTIVE702() { //inject NONSTANDARD NAMING
require(_mintableActive);
_;
}
}
contract PauserRole {
using Roles for Roles.Role;
event PAUSERADDED252(address indexed account); //inject NONSTANDARD NAMING
event PAUSERREMOVED538(address indexed account); //inject NONSTANDARD NAMING
Roles.Role private _pausers;
constructor () internal {
_ADDPAUSER941(msg.sender);
}
modifier ONLYPAUSER672() { //inject NONSTANDARD NAMING
require(ISPAUSER604(msg.sender));
_;
}
function ISPAUSER604(address account) public view returns (bool) { //inject NONSTANDARD NAMING
return _pausers.HAS322(account);
}
function ADDPAUSER65(address account) public ONLYPAUSER672 { //inject NONSTANDARD NAMING
_ADDPAUSER941(account);
}
function RENOUNCEPAUSER647() public { //inject NONSTANDARD NAMING
_REMOVEPAUSER706(msg.sender);
}
function _ADDPAUSER941(address account) internal { //inject NONSTANDARD NAMING
_pausers.ADD666(account);
emit PAUSERADDED252(account);
}
function _REMOVEPAUSER706(address account) internal { //inject NONSTANDARD NAMING
_pausers.REMOVE231(account);
emit PAUSERREMOVED538(account);
}
}
contract Pausable is PauserRole {
event PAUSED114(address account); //inject NONSTANDARD NAMING
event UNPAUSED110(address account); //inject NONSTANDARD NAMING
bool private _pausableActive;
bool private _paused;
constructor () internal {
_paused = false;
}
function PAUSED723() public view returns (bool) { //inject NONSTANDARD NAMING
return _paused;
}
modifier WHENNOTPAUSED424() { //inject NONSTANDARD NAMING
require(!_paused);
_;
}
modifier WHENPAUSED745() { //inject NONSTANDARD NAMING
require(_paused);
_;
}
function PAUSE827() public ONLYPAUSER672 WHENNOTPAUSED424 WHENPAUSABLEACTIVE658 { //inject NONSTANDARD NAMING
_paused = true;
emit PAUSED114(msg.sender);
}
function UNPAUSE942() public ONLYPAUSER672 WHENPAUSED745 WHENPAUSABLEACTIVE658 { //inject NONSTANDARD NAMING
_paused = false;
emit UNPAUSED110(msg.sender);
}
function _SETPAUSABLEACTIVE337(bool _active) internal { //inject NONSTANDARD NAMING
_pausableActive = _active;
}
modifier WHENPAUSABLEACTIVE658() { //inject NONSTANDARD NAMING
require(_pausableActive);
_;
}
}
contract ERC20Chocolate is ERC20Pistachio, ERC20Burnable, ERC20Mintable, Pausable {
// maximum capital, if defined > 0
uint256 private _cap;
constructor (
address initialAccount, string memory _tokenSymbol, string memory _tokenName, uint256 initialBalance, uint256 cap,
bool _burnableOption, bool _mintableOption, bool _pausableOption
) public
ERC20Pistachio(initialAccount, _tokenSymbol, _tokenName, initialBalance) {
// we must add customer account as the first minter
ADDMINTER562(initialAccount);
// add customer as pauser
ADDPAUSER65(initialAccount);
if (cap > 0) {
_cap = cap; // maximum capitalization limited
} else {
_cap = 0; // unlimited capitalization
}
// activate or deactivate options
_SETBURNABLEACTIVE519(_burnableOption);
_SETMINTABLEACTIVE686(_mintableOption);
_SETPAUSABLEACTIVE337(_pausableOption);
}
function CAP794() public view returns (uint256) { //inject NONSTANDARD NAMING
return _cap;
}
function _MINT600(address account, uint256 value) internal { //inject NONSTANDARD NAMING
if (_cap > 0) {
require(TOTALSUPPLY304().ADD666(value) <= _cap);
}
super._MINT600(account, value);
}
function TRANSFER854(address to, uint256 value) public WHENNOTPAUSED424 returns (bool) { //inject NONSTANDARD NAMING
return super.TRANSFER854(to, value);
}
function TRANSFERFROM522(address from,address to, uint256 value) public WHENNOTPAUSED424 returns (bool) { //inject NONSTANDARD NAMING
return super.TRANSFERFROM522(from, to, value);
}
function APPROVE531(address spender, uint256 value) public WHENNOTPAUSED424 returns (bool) { //inject NONSTANDARD NAMING
return super.APPROVE531(spender, value);
}
function INCREASEALLOWANCE330(address spender, uint addedValue) public WHENNOTPAUSED424 returns (bool success) { //inject NONSTANDARD NAMING
return super.INCREASEALLOWANCE330(spender, addedValue);
}
function DECREASEALLOWANCE446(address spender, uint subtractedValue) public WHENNOTPAUSED424 returns (bool success) { //inject NONSTANDARD NAMING
return super.DECREASEALLOWANCE446(spender, subtractedValue);
}
}
contract ReentrancyGuard {
// 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;
}
modifier NONREENTRANT377() { //inject NONSTANDARD NAMING
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER714(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN667(token, abi.encodeWithSelector(token.TRANSFER854.selector, to, value));
}
function SAFETRANSFERFROM672(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN667(token, abi.encodeWithSelector(token.TRANSFERFROM522.selector, from, to, value));
}
function SAFEAPPROVE372(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.ALLOWANCE123(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN667(token, abi.encodeWithSelector(token.APPROVE531.selector, spender, value));
}
function SAFEINCREASEALLOWANCE265(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE123(address(this), spender).ADD666(value);
CALLOPTIONALRETURN667(token, abi.encodeWithSelector(token.APPROVE531.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE998(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE123(address(this), spender).SUB55(value);
CALLOPTIONALRETURN667(token, abi.encodeWithSelector(token.APPROVE531.selector, spender, newAllowance));
}
function CALLOPTIONALRETURN667(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).ISCONTRACT761(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
library Address {
function ISCONTRACT761(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
function TOPAYABLE851(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
}
contract Crowdsale is ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for ERC20Chocolate;
// The token being sold
ERC20Chocolate private _token;
// Address where funds are collected
address payable private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
event TOKENSPURCHASED287(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); //inject NONSTANDARD NAMING
constructor (uint256 rate, address payable wallet, ERC20Chocolate token) public {
require(rate > 0, "Crowdsale: rate is 0");
require(wallet != address(0), "Crowdsale: wallet is the zero address");
require(address(token) != address(0), "Crowdsale: token is the zero address");
_rate = rate;
_wallet = wallet;
_token = token;
}
function () external payable {
BUYTOKENS434(msg.sender);
}
function TOKEN293() public view returns (IERC20) { //inject NONSTANDARD NAMING
return _token;
}
function WALLET108() public view returns (address payable) { //inject NONSTANDARD NAMING
return _wallet;
}
function RATE426() public view returns (uint256) { //inject NONSTANDARD NAMING
return _rate;
}
function WEIRAISED13() public view returns (uint256) { //inject NONSTANDARD NAMING
return _weiRaised;
}
function BUYTOKENS434(address beneficiary) public NONREENTRANT377 payable { //inject NONSTANDARD NAMING
uint256 weiAmount = msg.value;
_PREVALIDATEPURCHASE289(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _GETTOKENAMOUNT276(weiAmount);
// update state
_weiRaised = _weiRaised.ADD666(weiAmount);
_PROCESSPURCHASE887(beneficiary, tokens);
emit TOKENSPURCHASED287(msg.sender, beneficiary, weiAmount, tokens);
_UPDATEPURCHASINGSTATE322(beneficiary, weiAmount);
_FORWARDFUNDS963();
_POSTVALIDATEPURCHASE368(beneficiary, weiAmount);
}
function _PREVALIDATEPURCHASE289(address beneficiary, uint256 weiAmount) internal view { //inject NONSTANDARD NAMING
require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address");
require(weiAmount != 0, "Crowdsale: weiAmount is 0");
}
function _POSTVALIDATEPURCHASE368(address beneficiary, uint256 weiAmount) internal view { //inject NONSTANDARD NAMING
// solhint-disable-previous-line no-empty-blocks
}
function _DELIVERTOKENS47(address beneficiary, uint256 tokenAmount) internal { //inject NONSTANDARD NAMING
_token.SAFETRANSFER714(beneficiary, tokenAmount);
}
function _PROCESSPURCHASE887(address beneficiary, uint256 tokenAmount) internal { //inject NONSTANDARD NAMING
_DELIVERTOKENS47(beneficiary, tokenAmount);
}
function _UPDATEPURCHASINGSTATE322(address beneficiary, uint256 weiAmount) internal { //inject NONSTANDARD NAMING
// solhint-disable-previous-line no-empty-blocks
}
function _GETTOKENAMOUNT276(uint256 weiAmount) internal view returns (uint256) { //inject NONSTANDARD NAMING
return weiAmount.MUL578(_rate);
}
function _FORWARDFUNDS963() internal { //inject NONSTANDARD NAMING
_wallet.transfer(msg.value);
}
}
contract MintedCrowdsale is Crowdsale {
function _DELIVERTOKENS47(address beneficiary, uint256 tokenAmount) internal { //inject NONSTANDARD NAMING
// Potentially dangerous assumption about the type of the token.
require(
ERC20Mintable(address(TOKEN293())).MINT525(beneficiary, tokenAmount),
"MintedCrowdsale: minting failed"
);
}
}
contract PausableCrowdsale is Crowdsale, Pausable {
function _PREVALIDATEPURCHASE289(address _beneficiary, uint256 _weiAmount) internal view WHENNOTPAUSED424 { //inject NONSTANDARD NAMING
return super._PREVALIDATEPURCHASE289(_beneficiary, _weiAmount);
}
}
contract CrowdsaleRaspberry is MintedCrowdsale, PausableCrowdsale {
constructor (uint256 rate, address payable wallet, ERC20Chocolate token, bool _isPausable) public
Crowdsale(rate, wallet, token) {
// solhint-disable-previous-line no-empty-blocks
_SETPAUSABLEACTIVE337(_isPausable);
}
}
|
inject NONSTANDARD NAMING
|
function ISMINTER455(address account) public view returns (bool) {
| 12,598,059
|
./full_match/1/0x911a768fF40e6477736AA009EF0055563982bE3a/sources/src/ExternalRefinancing.sol
|
Reads the uint184 at `rdPtr` in returndata.
|
function readUint184(
ReturndataPointer rdPtr
) internal pure returns (uint184 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
| 3,218,495
|
./full_match/1/0xc75f89C55fd71B07A54976575C774EA6Fa283d7A/sources/@mimic-fi/v2-helpers/contracts/math/UncheckedMath.sol
|
Unsafely divides two unsigned integers/
|
function uncheckedDiv(uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
return a / b;
}
}
| 17,143,867
|
./full_match/1/0xc7DE53a189A02ee37ece610b15a6796a46F074EE/sources/contracts/Kobolds.sol
|
/No Need To Check Zero Address Since It Is False In The Mapping
|
function batchStake(uint256[] calldata tokenIds) external {
if (!approvedStakingContract[_msgSender()])
revert NotApprovedStakingContract();
for (uint256 i; i < tokenIds.length;) {
startStake(tokenIds[i]);
}
}
| 8,338,222
|
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
// Utility Libraries
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol";
// Security Libraries
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
// Token Libraries
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol";
import "./ERC721EnumerableUpgradeable.sol";
import "./VRFConsumerBaseUpgradeable.sol";
import "./RoarGenX.sol";
import "./RiverGenX.sol";
interface Roar {
struct ManBear {bool isFisherman; uint8[14] traitarray; uint8 alphaIndex;}
function getPaidTokens() external view returns (uint256);
function getTokenTraits(uint256 tokenId) external view returns (ManBear memory);
function ownerOf(uint256 tokenId) external view returns (address);
function safeTransferFrom(address from,address to,uint256 tokenId) external;
function transferFrom(address from, address to, uint256 tokenId) external;
function safeTransferFrom(address from,address to,uint256 tokenId, bytes memory _data) external;
function transferFrom(address from, address to, uint256 tokenId, bytes memory _data) external;
}
interface GenXInterface {
struct ManBear {bool isFisherman; uint8[14] traitarray; uint8 alphaIndex;}
function getPaidTokens() external view returns (uint256);
function getTokenTraits(uint256 tokenId) external view returns (ManBear memory);
function ownerOf(uint256 tokenId) external view returns (address);
function safeTransferFrom(address from,address to,uint256 tokenId) external;
function transferFrom(address from, address to, uint256 tokenId) external;
function safeTransferFrom(address from,address to,uint256 tokenId, bytes memory _data) external;
function transferFrom(address from, address to, uint256 tokenId, bytes memory _data) external;
}
contract RiverSide is OwnableUpgradeable, IERC721ReceiverUpgradeable, PausableUpgradeable, VRFConsumerBaseUpgradeable, ReentrancyGuardUpgradeable {
using AddressUpgradeable for address;
using CountersUpgradeable for CountersUpgradeable.Counter;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;
struct Stake {
uint16 tokenId;
uint80 value;
address owner;
}
/** INTERFACES */
Roar roar; // reference to the Roar NFT contract
ITSalmon salmon; // reference to the $SALMON contract for minting $SALMON earnings
event TokenStaked(address owner, uint256 tokenId, uint256 value);
event FishermanClaimed(uint256 tokenId, uint256 earned, bool unstaked);
event BearClaimed(uint256 tokenId, uint256 earned, bool unstaked);
mapping (address => bool) whitelistedContracts;
mapping(uint256 => Stake) public riverside; // maps tokenId to stake
mapping(uint256 => Stake[]) public Bears; // maps alpha to all Bear stakes with that alpha
mapping(address => EnumerableSetUpgradeable.UintSet) private _deposits;
mapping(uint256 => uint256) public packIndices; // tracks location of each Bear in Pack
uint256 public totalAlphaStaked; // total alpha scores staked
uint256 public unaccountedRewards; // any rewards distributed when no bears are staked
uint256 public SalmonPerAlpha; // amount of $SALMON due for each alpha point staked
uint256 public DAILY_SALMON_RATE ; // Fisherman earn 10000 $SALMON per day
uint256 public MINIMUM_TO_EXIT; // Fisherman must have 2 days worth of $SALMON to unstake or else it's too cold
/** Constant Parameters*/
uint256 public SALMON_CLAIM_TAX_PERCENTAGE; // Bears take a 20% tax on all $SALMON claimed
uint256 public MAXIMUM_GLOBAL_SALMON; // there will only ever be (roughly) 2.4 billion $SALMON earned through staking
uint8 public MAX_ALPHA;
struct ManBear {bool isFisherman; uint8[14] traitarray; uint8 alphaIndex;}
uint256 public totalSalmonEarned; // amount of $SALMON earned so far
uint256 public totalFishermanStaked; // number of Fisherman staked in the Riverside
uint256 public lastClaimTimestamp; // the last time $SALMON was claimed
bool public rescueEnabled; // emergency rescue to allow unstaking without any checks but without $SALMON
//Chainlink Setup:
bytes32 internal keyHash;
uint256 public fee;
uint256 internal randomResult;
uint256 internal randomNumber;
address public linkToken;
uint256 public vrfcooldown;
CountersUpgradeable.Counter public vrfReqd;
function initialize(address _roar, address _salmon, address _vrfCoordinator, address _link) initializer public {
__Ownable_init();
__ReentrancyGuard_init();
__Pausable_init();
__VRFConsumerBase_init(_vrfCoordinator,_link);
roar = Roar(_roar); // reference to the Roar NFT contract
salmon = ITSalmon(_salmon); //reference to the $SALMON token
keyHash = 0x2ed0feb3e7fd2022120aa84fab1945545a9f2ffc9076fd6156fa96eaff4c1311;
fee = 0.1 * 10 ** 18; // 0.1 LINK (Varies by network)
linkToken = _link;
vrfcooldown = 1000;
totalAlphaStaked = 0;
unaccountedRewards = 0;
SalmonPerAlpha = 0;
MAXIMUM_GLOBAL_SALMON = 2400000000 ether;
MAX_ALPHA = 8;
DAILY_SALMON_RATE = 6000 ether; // Fisherman earn 10000 $SALMON per day
MINIMUM_TO_EXIT = 2 days; // Fisherman must have 2 days worth of $SALMON to unstake or else it's too cold
SALMON_CLAIM_TAX_PERCENTAGE = 20;
rescueEnabled = false;
}
function depositsOf(address account) external view returns (uint256[] memory) {
if (tx.origin != msg.sender) {
require(whitelistedContracts[msg.sender], "You're not allowed to call this function");
}
EnumerableSetUpgradeable.UintSet storage depositSet = _deposits[account];
uint256[] memory tokenIds = new uint256[] (depositSet.length());
for (uint256 i; i < depositSet.length(); i++) {
tokenIds[i] = depositSet.at(i);
}
return tokenIds;
}
// Migrated
function addManyToRiverSideAndFishing(address account, uint16[] calldata tokenIds) external { // called in mint
require(account == _msgSender() || _msgSender() == address(roar), "DONT GIVE YOUR TOKENS AWAY");
for (uint i = 0; i < tokenIds.length; i++) {
uint16 tokenID = tokenIds[i];
if (_msgSender() != address(roar)) {
if (tokenID > 10498) {
require(roar.ownerOf(tokenID) == _msgSender(), "AINT YO TOKEN");
roar.transferFrom(_msgSender(), address(this), tokenID);
} else {
require(genXRoar.ownerOf(tokenID) == _msgSender(), "AINT YO TOKEN");
genXRoar.transferFrom(_msgSender(), address(this), tokenID); // Needs Approval
}
} else if (tokenID == 0) {
continue;
}
if (isFisherman(tokenID))
_addFishermanToRiverside(account, tokenID);
else
_sendBearsFishing(account, tokenID);
}
}
// No need for migration
function _addFishermanToRiverside(address account, uint256 tokenId) internal whenNotPaused _updateEarnings {
riverside[tokenId] = Stake({
owner: account,
tokenId: uint16(tokenId),
value: uint80(block.timestamp)
});
totalFishermanStaked += 1;
emit TokenStaked(account, tokenId, block.timestamp);
_deposits[account].add(tokenId);
}
// No need for migration
function _sendBearsFishing(address account, uint256 tokenId) internal {
uint256 alpha = _alphaForBear(tokenId);
totalAlphaStaked += alpha; // Portion of earnings ranges from 8 to 5
packIndices[tokenId] = Bears[alpha].length; // Store the location of the Bear in the Pack
Bears[alpha].push(Stake({ // Add the Bear to the Pack
owner: account,
tokenId: uint16(tokenId),
value: uint80(SalmonPerAlpha)
}));
emit TokenStaked(account, tokenId, SalmonPerAlpha);
_deposits[account].add(tokenId);
}
// Migrated
function claimManyFromRiverAndFishing(uint16[] calldata tokenIds, bool unstake) external whenNotPaused _updateEarnings nonReentrant() {
require(backupclaimethod,"Method Not enabled");
require(!_msgSender().isContract(), "Contracts are not allowed big man");
require(tx.origin == _msgSender(), "Only EOA");
if (tx.origin != msg.sender) {
require(whitelistedContracts[msg.sender], "You're not allowed to call this function");
}
uint256 owed = 0;
for (uint i = 0; i < tokenIds.length; i++) {
uint16 tokenID = tokenIds[i];
if (tokenID > 10498)
require(roar.ownerOf(tokenID) == address(this), "Not Staked here yet.");
else
require(genXRoar.ownerOf(tokenID) == address(this), "AINT A PART OF THIS");
if (isFisherman(tokenID))
owed += _claimFisherFromRiver(tokenID, unstake);
else
owed += _claimBearFromFishing(tokenID, unstake);
}
if (owed == 0) return;
salmon.mint(_msgSender(), owed);
}
function claimManyFromRiverAndFishingV2(uint16[] calldata tokenIds, bool unstake) external whenNotPaused _updateEarnings nonReentrant() {
require(!_msgSender().isContract(), "Contracts are not allowed big man");
require(tx.origin == _msgSender(), "Only EOA");
if (tx.origin != msg.sender) {
require(whitelistedContracts[msg.sender], "You're not allowed to call this function");
}
uint256 owed = 0;
for (uint i = 0; i < tokenIds.length; i++) {
uint16 tokenID = tokenIds[i];
if (tokenID > 10498) {
// GEN Y NFT
require(roar.ownerOf(tokenID) == address(this), "Not Staked here yet.");
owed += _regularclaim(tokenID,unstake);
} else {
// GEN X
if (genXRoar.ownerOf(tokenID) == address(genXStaking)) {
// OLD STAKING CONTRACT
owed += _claimGenXReward(_msgSender(),tokenID);
} else {
// STAKED HERE
require(genXRoar.ownerOf(tokenID) == address(this), "AINT A PART OF THIS");
owed += _regularclaim(tokenID,unstake);
}
}
}
if (owed == 0) return;
salmon.mint(_msgSender(), owed);
}
function _regularclaim(uint256 tokenID, bool unstake) private returns (uint256 owed) {
if (isFisherman(tokenID))
owed = _claimFisherFromRiver(tokenID, unstake);
else
owed = _claimBearFromFishing(tokenID, unstake);
}
// No need for Migration
function calculateReward(uint16[] calldata tokenIds) public view returns (uint256 owed) {
if (tx.origin != msg.sender) {
require(whitelistedContracts[msg.sender], "You're not allowed to call this function");
}
for (uint i = 0; i < tokenIds.length; i++) {
if (isFisherman(tokenIds[i]))
owed += calcRewardFisherman(tokenIds[i]);
else
owed += calcRewardBear(tokenIds[i]);
}
}
// Migrated
function calcRewardFisherman(uint256 tokenId) public view returns (uint256 owed) {
if (tx.origin != msg.sender) {
require(whitelistedContracts[msg.sender], "You're not allowed to call this function");
}
Stake memory stake = riverside[tokenId];
uint256 rate;
if (tokenId > 10498) {
rate = DAILY_SALMON_RATE;
} else {
rate = DAILY_SALMON_RATEGenX;
}
if (totalSalmonEarned < MAXIMUM_GLOBAL_SALMON) {
owed = (block.timestamp - MathUpgradeable.max(resetTime,stake.value) ) * rate / 1 days;
} else if (stake.value > lastClaimTimestamp) {
owed = 0;
} else {
owed = (lastClaimTimestamp - MathUpgradeable.max(resetTime,stake.value)) * rate / 1 days; // stop earning additional $WOOL if it's all been earned
}
}
// No need for Migration - _alphaForBear (Migrated)
function calcRewardBear(uint256 tokenId) public view returns (uint256 owed) {
if (tx.origin != msg.sender) {
require(whitelistedContracts[msg.sender], "You're not allowed to call this function");
}
uint256 alpha = _alphaForBear(tokenId);
Stake memory stake = Bears[alpha][packIndices[tokenId]];
owed = (alpha) * (SalmonPerAlpha - stake.value);
}
// Migrated
function _claimFisherFromRiver(uint256 tokenId, bool unstake) private returns (uint256 owed) {
Stake memory stake = riverside[tokenId];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
require(!_msgSender().isContract(), "Contracts are not allowed big man");
require(!(unstake && block.timestamp - stake.value < MINIMUM_TO_EXIT), "GONNA BE COLD WITHOUT TWO DAY'S WOOL");
owed = calcRewardFisherman(tokenId);
if (unstake) {
if (random(tokenId) & 1 == 1) { // 50% chance of all $SALMON stolen
_payBearTax(owed);
owed = 0;
}
delete riverside[tokenId];
totalFishermanStaked -= 1;
_deposits[_msgSender()].remove(tokenId);
if (tokenId > 10498) {
roar.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // send back Fisherman
} else {
genXRoar.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // send back Fisherman
}
} else {
_payBearTax(owed * SALMON_CLAIM_TAX_PERCENTAGE / 100); // percentage tax to staked Bears
riverside[tokenId] = Stake({
owner: _msgSender(),
tokenId: uint16(tokenId),
value: uint80(block.timestamp)
}); // reset stake
owed = owed * (100 - SALMON_CLAIM_TAX_PERCENTAGE) / 100; // remainder goes to Fisherman owner
}
emit FishermanClaimed(tokenId, owed, unstake);
}
// Migrated
function _claimBearFromFishing(uint256 tokenId, bool unstake) private returns (uint256 owed) {
uint256 alpha = _alphaForBear(tokenId);
Stake memory stake = Bears[alpha][packIndices[tokenId]];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
owed = calcRewardBear(tokenId); // Calculate portion of tokens based on Alpha
if (unstake) {
totalAlphaStaked -= alpha; // Remove Alpha from total staked
Stake memory lastStake = Bears[alpha][Bears[alpha].length - 1]; // Shuffle last Bear to current position PT 1
Bears[alpha][packIndices[tokenId]] = lastStake; // Shuffle last Bear to current position PT 2
packIndices[lastStake.tokenId] = packIndices[tokenId]; // Shuffle last Bear to current position PT 3
Bears[alpha].pop(); // Remove duplicate
delete packIndices[tokenId]; // Delete old mapping
_deposits[_msgSender()].remove(tokenId);
if (tokenId > 10498) {
roar.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // send back Fisherman
} else {
genXRoar.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // send back Fisherman
}
} else {
Bears[alpha][packIndices[tokenId]] = Stake({
owner: _msgSender(),
tokenId: uint16(tokenId),
value: uint80(SalmonPerAlpha)
}); // reset stake
}
emit BearClaimed(tokenId, owed, unstake);
}
// NOT YET MIGRATED
function rescue(uint256[] calldata tokenIds) external nonReentrant() {
require(!_msgSender().isContract(), "Contracts are not allowed big man");
require(tx.origin == _msgSender(), "Only EOA");
require(rescueEnabled, "RESCUE DISABLED");
uint256 tokenId;
Stake memory stake;
Stake memory lastStake;
uint256 alpha;
for (uint i = 0; i < tokenIds.length; i++) {
tokenId = tokenIds[i];
if (tokenId > 10498)
require(roar.ownerOf(tokenId) == address(this), "Not Staked here yet.");
else
require(genXRoar.ownerOf(tokenId) == address(this), "AINT A PART OF THIS");
if (isFisherman(tokenId)) {
stake = riverside[tokenId];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
delete riverside[tokenId];
totalFishermanStaked -= 1;
if (tokenId > 10498) {
roar.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // send back Fisherman
} else {
genXRoar.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // send back Fisherman
}
emit FishermanClaimed(tokenId, 0, true);
} else {
alpha = _alphaForBear(tokenId);
stake = Bears[alpha][packIndices[tokenId]];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
totalAlphaStaked -= alpha; // Remove Alpha from total staked
lastStake = Bears[alpha][Bears[alpha].length - 1];
Bears[alpha][packIndices[tokenId]] = lastStake; // Shuffle last bear to current position
packIndices[lastStake.tokenId] = packIndices[tokenId];
Bears[alpha].pop(); // Remove duplicate
delete packIndices[tokenId]; // Delete old mapping
if (tokenId > 10498) {
roar.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // send back Fisherman
} else {
genXRoar.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // send back Fisherman
}
emit BearClaimed(tokenId, 0, true);
}
}
}
/** ACCOUNTING */
// No Need for Migration
function _payBearTax(uint256 amount) private {
if (totalAlphaStaked == 0) { // if there's no staked Bear > keep track of $SALMON due to Bear
unaccountedRewards += amount;
return;
}
SalmonPerAlpha += (amount + unaccountedRewards) / totalAlphaStaked; // makes sure to include any unaccounted $SALMON
unaccountedRewards = 0;
}
modifier _updateEarnings() {
if (totalSalmonEarned < MAXIMUM_GLOBAL_SALMON) {
totalSalmonEarned +=
(block.timestamp - lastClaimTimestamp)
* totalFishermanStaked
* DAILY_SALMON_RATE / 1 days;
lastClaimTimestamp = block.timestamp;
}
_;
}
function setWhitelistContract(address contract_address, bool status) public onlyOwner{
whitelistedContracts[contract_address] = status;
}
// Migrated
function isFisherman(uint256 tokenId) public view returns (bool fisherman) {
if (tx.origin != msg.sender) {
require(whitelistedContracts[msg.sender], "You're not allowed to call this function");
}
if (tokenId > 10498) {
Roar.ManBear memory yo = roar.getTokenTraits(tokenId);
return yo.isFisherman;
} else {
(fisherman, ) = genXRoar.tokenTraits(tokenId);
return fisherman;
}
}
// Migrated
function _alphaForBear(uint256 tokenId) private view returns (uint8) {
if (tokenId > 10498) {
Roar.ManBear memory yo = roar.getTokenTraits(tokenId);
return MAX_ALPHA - yo.alphaIndex;
} else {
GenXInterface.ManBear memory yo = genXRoarInterface.getTokenTraits(tokenId);
return MAX_ALPHA - yo.alphaIndex;
}
}
// Shouldnt need migration if we use same bear array for both genX and genY
function randomBearOwner(uint256 seed) external view returns (address) {
if (tx.origin != msg.sender) {
require(whitelistedContracts[msg.sender], "You're not allowed to call this function");
}
if (totalAlphaStaked == 0) return address(0x0);
uint256 bucket = (seed & 0xFFFFFFFF) % totalAlphaStaked; // choose a value from 0 to total alpha staked
uint256 cumulative;
seed >>= 32;
for (uint i = MAX_ALPHA - 3; i <= MAX_ALPHA; i++) { // loop through each bucket of Bears with the same alpha score
cumulative += Bears[i].length * i;
if (bucket >= cumulative) continue; // if the value is not inside of that bucket, keep going
return Bears[i][seed % Bears[i].length].owner; // get the address of a random Bear with that alpha score
}
return address(0x0);
}
/** CHANGE PARAMETERS */
function setInit(address _roar, address _salmon) external onlyOwner{
roar = Roar(_roar);
salmon = ITSalmon(_salmon);
}
function changeDailyRateGenY(uint256 _newRate) external onlyOwner{
DAILY_SALMON_RATE = _newRate;
}
function changeDailyRateGenX(uint256 _newRate) external onlyOwner{
DAILY_SALMON_RATEGenX = _newRate;
}
function changeMinExit(uint256 _newExit) external onlyOwner{
MINIMUM_TO_EXIT = _newExit ;
}
function changeSalmonTax(uint256 _newTax) external onlyOwner {
SALMON_CLAIM_TAX_PERCENTAGE = _newTax;
}
function changeMaxSalmon(uint256 _newMax) external onlyOwner {
MAXIMUM_GLOBAL_SALMON = _newMax;
}
function setRescueEnabled(bool _enabled) external onlyOwner {
rescueEnabled = _enabled;
}
function setPaused(bool _paused) external onlyOwner {
if (_paused) _pause();
else _unpause();
}
/** RANDOMNESSSS */
function changeLinkFee(uint256 _fee) external onlyOwner {
// fee = 0.1 * 10 ** 18; // 0.1 LINK (Varies by network)
fee = _fee;
}
function random(uint256 seed) private view returns (uint256) {
return uint256(keccak256(abi.encodePacked(
tx.origin,
blockhash(block.number - 1),
block.timestamp,
seed,
randomNumber
)));
}
function initChainLink() external onlyOwner {
vrfReqd.increment();
getRandomChainlink();
}
function getRandomChainlink() private returns (bytes32 requestId) {
if (tx.origin != msg.sender) {
require(whitelistedContracts[msg.sender], "You're not allowed to call this function");
}
if (vrfReqd.current() <= vrfcooldown) {
vrfReqd.increment();
return 0x000;
}
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
vrfReqd.reset();
return requestRandomness(keyHash, fee);
}
function changeVrfCooldown(uint256 _cooldown) external onlyOwner{
vrfcooldown = _cooldown;
}
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
bytes32 reqId = requestId;
randomNumber = randomness;
}
function withdrawLINK() external onlyOwner {
uint256 tokenSupply = IERC20Upgradeable(linkToken).balanceOf(address(this));
IERC20Upgradeable(linkToken).transfer(msg.sender, tokenSupply);
}
function changeLinkAddress(address _newaddress) external onlyOwner{
linkToken = _newaddress;
}
/** OTHERS */
function onERC721Received(address, address from, uint256, bytes calldata) external pure override returns (bytes4) {
require(from == address(0x0), "Cannot send tokens to Barn directly");
return IERC721ReceiverUpgradeable.onERC721Received.selector;
}
/** RESET EDITION */
uint256 public DAILY_SALMON_RATEGenX;
mapping(uint256 => bool) public migrated;
uint256 public resetTime;
RoarGenX genXRoar;
RiverGenX genXStaking;
GenXInterface genXRoarInterface;
function setGenXContract(address _staking,address _mint) external onlyOwner {
genXStaking = RiverGenX(_staking);
genXRoar = RoarGenX(_mint);
genXRoarInterface = GenXInterface(_mint);
DAILY_SALMON_RATEGenX = 10000 ether;
backupclaimethod = false;
}
function claimGenXRewards (address account, uint16[] calldata tokenIds) external whenNotPaused _updateEarnings nonReentrant() {
require(backupclaimethod,"Method Not enabled");
_claimGenXRewards(account,tokenIds);
}
function _claimGenXRewards(address account, uint16[] calldata tokenIds) private {
require(backupclaimethod,"Method Not enabled");
require(account == _msgSender() && !_msgSender().isContract(), "Contracts are not allowed big man");
if (tx.origin != msg.sender) {
require(whitelistedContracts[msg.sender], "You're not allowed to call this function");
}
bool unstake = false;
uint256 owed = 0;
for (uint i = 0; i < tokenIds.length; i++) {
uint16 tokenID = tokenIds[i];
require(tokenID <= 10498, "Not a Gen X Token");
require(genXRoar.ownerOf(tokenID) == address(genXStaking), "AINT A PART OF THE OLD CONTRACT");
bool fisherman = isFisherman(tokenID);
if (!migrated[tokenID]) {
// Token hasnt migrated yet - aka claiming for the first time.
if (fisherman) {
uint16 tokenId;
uint80 valueOLD;
address owner;
(tokenId,valueOLD,owner) = genXStaking.riverside(tokenID);
require(owner == _msgSender(), "Not your token bro");
// Calculate rewards
uint80 value = uint80(MathUpgradeable.min(block.timestamp,resetTime));
owed = calcFishermanSalmonGenX(value);
_payBearTax(owed * SALMON_CLAIM_TAX_PERCENTAGE / 100);
owed = owed * (100 - SALMON_CLAIM_TAX_PERCENTAGE) / 100;
// simulate adding fisherman to current contract
riverside[tokenID] = Stake({owner: _msgSender(), tokenId: uint16(tokenID), value: uint80(block.timestamp)});
migrated[tokenID] = true;
emit FishermanClaimed(tokenID, owed, unstake);
emit TokenStaked(account, tokenID, block.timestamp);
} else {
uint256 alpha = _alphaForBear(tokenID);
uint16 tokenId;
uint80 value;
address owner;
uint256 indic = genXStaking.packIndices(tokenID);
(tokenId,value,owner) = genXStaking.Bears(alpha,indic);
require(owner == _msgSender(), "SWIPER, NO SWIPING");
// Calculate rewards
owed = (alpha) * (SalmonPerAlpha - 0);
// simulate adding bear to current contract
totalAlphaStaked += alpha;
packIndices[tokenID] = Bears[alpha].length;
Bears[alpha].push(Stake({owner: account,tokenId: uint16(tokenID),value: uint80(0)}));
migrated[tokenID] = true;
emit TokenStaked(account, tokenID, SalmonPerAlpha);
}
} else {
if (fisherman) {
Stake memory stake = riverside[tokenID];
owed = calcFishermanSalmonGenX(stake.value);
_payBearTax(owed * SALMON_CLAIM_TAX_PERCENTAGE / 100);
riverside[tokenID] = Stake({owner: _msgSender(), tokenId: uint16(tokenID), value: uint80(block.timestamp)});
owed = owed * (100 - SALMON_CLAIM_TAX_PERCENTAGE) / 100;
emit FishermanClaimed(tokenID, owed, unstake);
} else {
owed = calcRewardBear(tokenID);
uint256 alpha = _alphaForBear(tokenID);
Bears[alpha][packIndices[tokenID]] = Stake({owner: _msgSender(),tokenId: uint16(tokenID),value: uint80(SalmonPerAlpha)}); // reset stake
}
}
if (owed == 0) return;
salmon.mint(_msgSender(), owed);
}
}
function _claimGenXReward(address account, uint16 tokenID) private returns (uint256 owed) {
require(tokenID <= 10498, "Not a Gen X Token");
require(account == _msgSender() && !_msgSender().isContract(), "Contracts are not allowed big man");
require(genXRoar.ownerOf(tokenID) == address(genXStaking), "AINT A PART OF THE OLD CONTRACT");
if (tx.origin != msg.sender) {
require(whitelistedContracts[msg.sender], "You're not allowed to call this function");
}
bool unstake = false;
owed = 0;
bool fisherman = isFisherman(tokenID);
if (!migrated[tokenID]) {
// Token hasnt migrated yet - aka claiming for the first time.
if (fisherman) {
uint16 tokenId;
uint80 valueOLD;
address owner;
(tokenId,valueOLD,owner) = genXStaking.riverside(tokenID);
require(owner == _msgSender(), "Not your token bro");
// Calculate rewards
uint80 value = uint80(MathUpgradeable.min(block.timestamp,resetTime));
owed = calcFishermanSalmonGenX(value);
_payBearTax(owed * SALMON_CLAIM_TAX_PERCENTAGE / 100);
owed = owed * (100 - SALMON_CLAIM_TAX_PERCENTAGE) / 100;
// simulate adding fisherman to current contract
riverside[tokenID] = Stake({owner: _msgSender(), tokenId: uint16(tokenID), value: uint80(block.timestamp)});
migrated[tokenID] = true;
emit FishermanClaimed(tokenID, owed, unstake);
emit TokenStaked(account, tokenID, block.timestamp);
} else {
uint256 alpha = _alphaForBear(tokenID);
uint16 tokenId;
uint80 value;
address owner;
uint256 indic = genXStaking.packIndices(tokenID);
(tokenId,value,owner) = genXStaking.Bears(alpha,indic);
require(owner == _msgSender(), "SWIPER, NO SWIPING");
// Calculate rewards
owed = (alpha) * (SalmonPerAlpha - 0);
// simulate adding bear to current contract
totalAlphaStaked += alpha;
packIndices[tokenID] = Bears[alpha].length;
Bears[alpha].push(Stake({owner: account,tokenId: uint16(tokenID),value: uint80(0)}));
migrated[tokenID] = true;
emit TokenStaked(account, tokenID, SalmonPerAlpha);
}
} else {
if (fisherman) {
Stake memory stake = riverside[tokenID];
owed = calcFishermanSalmonGenX(stake.value);
_payBearTax(owed * SALMON_CLAIM_TAX_PERCENTAGE / 100);
riverside[tokenID] = Stake({owner: _msgSender(), tokenId: uint16(tokenID), value: uint80(block.timestamp)});
owed = owed * (100 - SALMON_CLAIM_TAX_PERCENTAGE) / 100;
emit FishermanClaimed(tokenID, owed, unstake);
} else {
owed = calcRewardBear(tokenID);
uint256 alpha = _alphaForBear(tokenID);
Bears[alpha][packIndices[tokenID]] = Stake({owner: _msgSender(),tokenId: uint16(tokenID),value: uint80(SalmonPerAlpha)}); // reset stake
}
}
// if (owed == 0) return;
// salmon.mint(_msgSender(), owed);
return owed;
}
function calcFishermanSalmonGenX(uint80 value) internal view returns (uint256 owed) {
if (tx.origin != msg.sender) {
require(whitelistedContracts[msg.sender], "You're not allowed to call this function");
}
if (totalSalmonEarned < MAXIMUM_GLOBAL_SALMON) {
owed = (block.timestamp - value) * DAILY_SALMON_RATEGenX / 1 days;
} else if (value > lastClaimTimestamp) {
owed = 0;
} else {
owed = (lastClaimTimestamp - value) * DAILY_SALMON_RATEGenX / 1 days;
}
}
function setResetTime(uint256 _time) external onlyOwner {
resetTime = _time;
}
function enableBackupClaim (bool _status) external onlyOwner {
backupclaimethod = _status;
}
bool public backupclaimethod;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@chainlink/contracts/src/v0.8/interfaces/LinkTokenInterface.sol";
import "@chainlink/contracts/src/v0.8/VRFRequestIDBase.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
/** ****************************************************************************
* @notice Interface for contracts using VRF randomness
* *****************************************************************************
* @dev PURPOSE
*
* @dev Reggie the Random Oracle (not his real job) wants to provide randomness
* @dev to Vera the verifier in such a way that Vera can be sure he's not
* @dev making his output up to suit himself. Reggie provides Vera a public key
* @dev to which he knows the secret key. Each time Vera provides a seed to
* @dev Reggie, he gives back a value which is computed completely
* @dev deterministically from the seed and the secret key.
*
* @dev Reggie provides a proof by which Vera can verify that the output was
* @dev correctly computed once Reggie tells it to her, but without that proof,
* @dev the output is indistinguishable to her from a uniform random sample
* @dev from the output space.
*
* @dev The purpose of this contract is to make it easy for unrelated contracts
* @dev to talk to Vera the verifier about the work Reggie is doing, to provide
* @dev simple access to a verifiable source of randomness.
* *****************************************************************************
* @dev USAGE
*
* @dev Calling contracts must inherit from VRFConsumerBase, and can
* @dev initialize VRFConsumerBase's attributes in their constructor as
* @dev shown:
*
* @dev contract VRFConsumer {
* @dev constuctor(<other arguments>, address _vrfCoordinator, address _link)
* @dev VRFConsumerBase(_vrfCoordinator, _link) public {
* @dev <initialization with other arguments goes here>
* @dev }
* @dev }
*
* @dev The oracle will have given you an ID for the VRF keypair they have
* @dev committed to (let's call it keyHash), and have told you the minimum LINK
* @dev price for VRF service. Make sure your contract has sufficient LINK, and
* @dev call requestRandomness(keyHash, fee, seed), where seed is the input you
* @dev want to generate randomness from.
*
* @dev Once the VRFCoordinator has received and validated the oracle's response
* @dev to your request, it will call your contract's fulfillRandomness method.
*
* @dev The randomness argument to fulfillRandomness is the actual random value
* @dev generated from your seed.
*
* @dev The requestId argument is generated from the keyHash and the seed by
* @dev makeRequestId(keyHash, seed). If your contract could have concurrent
* @dev requests open, you can use the requestId to track which seed is
* @dev associated with which randomness. See VRFRequestIDBase.sol for more
* @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind,
* @dev if your contract could have multiple requests in flight simultaneously.)
*
* @dev Colliding `requestId`s are cryptographically impossible as long as seeds
* @dev differ. (Which is critical to making unpredictable randomness! See the
* @dev next section.)
*
* *****************************************************************************
* @dev SECURITY CONSIDERATIONS
*
* @dev A method with the ability to call your fulfillRandomness method directly
* @dev could spoof a VRF response with any random value, so it's critical that
* @dev it cannot be directly called by anything other than this base contract
* @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method).
*
* @dev For your users to trust that your contract's random behavior is free
* @dev from malicious interference, it's best if you can write it so that all
* @dev behaviors implied by a VRF response are executed *during* your
* @dev fulfillRandomness method. If your contract must store the response (or
* @dev anything derived from it) and use it later, you must ensure that any
* @dev user-significant behavior which depends on that stored value cannot be
* @dev manipulated by a subsequent VRF request.
*
* @dev Similarly, both miners and the VRF oracle itself have some influence
* @dev over the order in which VRF responses appear on the blockchain, so if
* @dev your contract could have multiple VRF requests in flight simultaneously,
* @dev you must ensure that the order in which the VRF responses arrive cannot
* @dev be used to manipulate your contract's user-significant behavior.
*
* @dev Since the ultimate input to the VRF is mixed with the block hash of the
* @dev block in which the request is made, user-provided seeds have no impact
* @dev on its economic security properties. They are only included for API
* @dev compatability with previous versions of this contract.
*
* @dev Since the block hash of the block which contains the requestRandomness
* @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
* @dev miner could, in principle, fork the blockchain to evict the block
* @dev containing the request, forcing the request to be included in a
* @dev different block with a different hash, and therefore a different input
* @dev to the VRF. However, such an attack would incur a substantial economic
* @dev cost. This cost scales with the number of blocks the VRF oracle waits
* @dev until it calls responds to a request.
*/
abstract contract VRFConsumerBaseUpgradeable is VRFRequestIDBase, Initializable {
/**
* @notice fulfillRandomness handles the VRF response. Your contract must
* @notice implement it. See "SECURITY CONSIDERATIONS" above for important
* @notice principles to keep in mind when implementing your fulfillRandomness
* @notice method.
*
* @dev VRFConsumerBase expects its subcontracts to have a method with this
* @dev signature, and will call it once it has verified the proof
* @dev associated with the randomness. (It is triggered via a call to
* @dev rawFulfillRandomness, below.)
*
* @param requestId The Id initially returned by requestRandomness
* @param randomness the VRF output
*/
function fulfillRandomness(
bytes32 requestId,
uint256 randomness
)
internal
virtual;
/**
* @dev In order to keep backwards compatibility we have kept the user
* seed field around. We remove the use of it because given that the blockhash
* enters later, it overrides whatever randomness the used seed provides.
* Given that it adds no security, and can easily lead to misunderstandings,
* we have removed it from usage and can now provide a simpler API.
*/
uint256 private USER_SEED_PLACEHOLDER;
/**
* @notice requestRandomness initiates a request for VRF output given _seed
*
* @dev The fulfillRandomness method receives the output, once it's provided
* @dev by the Oracle, and verified by the vrfCoordinator.
*
* @dev The _keyHash must already be registered with the VRFCoordinator, and
* @dev the _fee must exceed the fee specified during registration of the
* @dev _keyHash.
*
* @dev The _seed parameter is vestigial, and is kept only for API
* @dev compatibility with older versions. It can't *hurt* to mix in some of
* @dev your own randomness, here, but it's not necessary because the VRF
* @dev oracle will mix the hash of the block containing your request into the
* @dev VRF seed it ultimately uses.
*
* @param _keyHash ID of public key against which randomness is generated
* @param _fee The amount of LINK to send with the request
*
* @return requestId unique ID for this request
*
* @dev The returned requestId can be used to distinguish responses to
* @dev concurrent requests. It is passed as the first argument to
* @dev fulfillRandomness.
*/
function requestRandomness(
bytes32 _keyHash,
uint256 _fee
)
internal
returns (
bytes32 requestId
)
{
LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER));
// This is the seed passed to VRFCoordinator. The oracle will mix this with
// the hash of the block containing this request to obtain the seed/input
// which is finally passed to the VRF cryptographic machinery.
uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]);
// nonces[_keyHash] must stay in sync with
// VRFCoordinator.nonces[_keyHash][this], which was incremented by the above
// successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest).
// This provides protection against the user repeating their input seed,
// which would result in a predictable/duplicate output, if multiple such
// requests appeared in the same block.
nonces[_keyHash] = nonces[_keyHash] + 1;
return makeRequestId(_keyHash, vRFSeed);
}
LinkTokenInterface internal LINK;
address private vrfCoordinator;
// Nonces for each VRF key from which randomness has been requested.
//
// Must stay in sync with VRFCoordinator[_keyHash][this]
mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces;
/**
* @param _vrfCoordinator address of VRFCoordinator contract
* @param _link address of LINK token contract
*
* @dev https://docs.chain.link/docs/link-token-contracts
*/
function __VRFConsumerBase_init(address _vrfCoordinator, address _link) internal initializer {
vrfCoordinator = _vrfCoordinator;
LINK = LinkTokenInterface(_link);
USER_SEED_PLACEHOLDER = 0;
}
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
// proof. rawFulfillRandomness then calls fulfillRandomness, after validating
// the origin of the call
function rawFulfillRandomness(
bytes32 requestId,
uint256 randomness
)
external
{
require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill");
fulfillRandomness(requestId, randomness);
}
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
interface ISalmon {
function burn(address from, uint256 amount) external;
}
interface ITraits {
function tokenURI(uint256 tokenId) external view returns (string memory);
}
interface IRoar {
struct ManBear {bool isFisherman; uint8[14] traitarray; uint8 alphaIndex;}
function getPaidTokens() external view returns (uint256);
function getTokenTraits(uint256 tokenId) external view returns (ManBear memory);
}
interface IRiver {
function addManyToRiverSideAndFishing(address account, uint16[] calldata tokenIds) external;
function randomBearOwner(uint256 seed) external view returns (address);
}
contract RoarGenX is IRoar, ERC721Enumerable, Ownable, Pausable, VRFConsumerBase {
using Counters for Counters.Counter;
using EnumerableSet for EnumerableSet.UintSet;
// mint variables
uint256 public immutable MAX_TOKENS; // max number of tokens that can be minted - 50000 in production
uint256 public PAID_TOKENS; // number of tokens that can be claimed for free - 20% of MAX_TOKENS
uint16 public minted; // number of tokens have been minted so far
uint256 public constant MINT_PRICE = .069420 ether; // mint price
string public baseURI;
// mappings
mapping(address => uint256) public whitelists;
mapping(uint256 => ManBear) public tokenTraits; // mapping from tokenId to a struct containing the token's traits
mapping(uint256 => uint256) public existingCombinations; // mapping from hashed(tokenTrait) to the tokenId it's associated with, Why? used to ensure there are no duplicates
mapping(address => uint256[]) public _mints;
// Pobabilities & Aliases
// 0 - 8 are associated with fishermen, 9 - 13 are associated with Bears
uint8[][18] public rarities;
uint8[][18] public aliases;
IRiver public river; // STAKING - reference to the Barn for choosing random Bear thieves
ISalmon public salmon; // TOKEN - reference to $WOOL for burning on mint
ITraits public traits; // TRAITS - reference to Traits
// Team Wallets
address private project_wallet = 0x06e8198A5a4AB3E5F4B13DdC9e5c2FCDDD4f8838;
address private Bear1 = 0x9E4FaAA4EFd0fb8CbC653Ee68C01c066d078098D;
address private Bear2 = 0xe18195D4995D994fAa3663db0b6E2FFF4042D0a1;
address private Bear3 = 0x9c39cD2f557B5E851f44ab18714BbBB15FA7417E;
address private Bear4 = 0x24af21668F33C8C279025b0E53fCC3bFf48426A0;
//Chainlink Setup:
bytes32 internal keyHash;
uint256 public fee;
uint256 internal randomResult;
uint256 internal randomNumber;
address public linkToken;
uint256 public vrfcooldown = 10000;
Counters.Counter public vrfReqd;
constructor(address _salmon, uint256 _maxTokens, address _vrfCoordinator, address _link)
ERC721("BearGame", 'BEARGAME')
VRFConsumerBase(_vrfCoordinator, _link)
{
keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445;
fee = 2 * 10 ** 18; // 0.1 LINK (Varies by network)
linkToken = _link;
// Initate Interfaces
salmon = ISalmon(_salmon);
MAX_TOKENS = _maxTokens;
PAID_TOKENS = _maxTokens / 5;
// string[13] _traitTypes = ['Hat','Eyes','Body','Pants','Skintone','Mouth','Feet','Fishing Pole','Fish','Fur','Eyes','Clothes','Mouth','Alpha'];
rarities[0] = [31,49,51,69,113,187,204,207,225];
rarities[1] = [35,48,67,115,189,208,221];
rarities[2] = [59,97,136,159,197];
rarities[3] = [85,113,131,143,169];
rarities[4] = [255,255,255,255];
rarities[5] = [34,59,118,164,197,222];
rarities[6] = [59,111,145,197];
rarities[7] = [57,93,163,199];
rarities[8] = [255];
aliases[0] = [8,7,6,5,4,3,2,1,0];
aliases[1] = [6,5,4,3,2,1,0];
aliases[2] = [4,3,2,1,0];
aliases[3] = [4,3,2,1,0];
aliases[4] = [3,2,1,0];
aliases[5] = [5,4,3,2,1,0];
aliases[6] = [3,2,1,0];
aliases[7] = [3,2,1,0];
aliases[8] = [0];
rarities[9] = [255,255,255,255,255];
rarities[10] = [39,51,59,67,125,131,189,197,204,217];
rarities[11] = [51,54,57,64,72,90,194,199,202,207,212];
rarities[12] = [48,60,96,160,196,208];
rarities[13] = [51,102,153,204];
aliases[9] = [0,1,2,3,4];
aliases[10] = [9,8,7,6,5,4,3,2,1,0];
aliases[11] = [10,9,8,7,6,5,4,3,2,1,0];
aliases[12] = [5,4,3,2,1,0];
aliases[13] = [3,2,1,0];
}
/**
* mint a token - 90% Bears, 10% Fisherman
* The first 20% are free to claim, the remaining cost $SALMON
*/
// Calculates Mint Cost using $SALMON
function mintCost(uint256 tokenId) public view returns (uint256) {
if (tokenId <= PAID_TOKENS) return 0; // the first 20% are paid in ETH, Hence 0 $SALMON
if (tokenId <= MAX_TOKENS * 2 / 5) return 20000 ether; // the next 20% are 20000 $SALMON
if (tokenId <= MAX_TOKENS * 4 / 5) return 40000 ether; // the next 40% are 40000 $SALMON
return 80000 ether; // the final 20% are 80000 $SALMON
}
// Main Mint Functions
function mint(uint256 amount, bool stake) external payable whenNotPaused {
address msgSender = _msgSender();
require(tx.origin == msgSender, "Only EOA");
require(minted + amount <= MAX_TOKENS, "All tokens minted");
require(amount > 0 && amount <= 10, "Invalid mint amount");
if (minted < PAID_TOKENS) {
uint256 mintCostEther = MINT_PRICE * amount;
if (whitelists[msgSender] == 1) {
mintCostEther = ( amount - 1) * MINT_PRICE;
whitelists[msgSender] = 0;
}
require(minted + amount <= PAID_TOKENS, "All tokens on-sale already sold");
require(mintCostEther == msg.value, "Invalid payment amount");
} else {
require(msg.value == 0);
}
uint256 totalSalmonCost = 0; // $SALMON Cost to mint. 0 is Gen0
uint16[] memory tokenIds = stake ? new uint16[](amount) : new uint16[](0);
uint256 seed;
for (uint i = 0; i < amount; i++) {
minted++;
seed = random(minted); // NOTES: SUS
generate(minted, seed); // Generates Token Traits and adds it to the array
address recipient = selectRecipient(seed); // Selects who the NFT is going to. Gen0 always will be minter.
if (!stake || recipient != msgSender) { // recipient != _msgSender() -- IF I BAN CONTRACT, SHIT MIGHT BE GOOOOOFY
_safeMint(recipient, minted);
} else {
_safeMint(address(river), minted);
tokenIds[i] = minted;
}
totalSalmonCost += mintCost(minted);
}
if (totalSalmonCost > 0) salmon.burn(msgSender, totalSalmonCost);
if (stake) river.addManyToRiverSideAndFishing(msgSender, tokenIds);
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
// Hardcode the River's approval so that users don't have to waste gas approving
if (_msgSender() != address(river))
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
// generates traits for a specific token, checking to make sure it's unique
function generate(uint256 tokenId, uint256 seed) internal returns (ManBear memory t) {
getRandomChainlink();
t = selectTraits(seed);
if (existingCombinations[structToHash(t.isFisherman, t.traitarray, t.alphaIndex)] == 0) {
tokenTraits[tokenId] = t;
existingCombinations[structToHash(t.isFisherman, t.traitarray, t.alphaIndex)] = tokenId;
return t;
}
return generate(tokenId, random(seed));
}
// Selects Trait using A.J. Walker's Alias algorithm for O(1) rarity table lookup
function selectTrait(uint16 seed, uint8 traitType) internal view returns (uint8) {
uint8 trait = uint8(seed) % uint8(rarities[traitType].length);
if (seed >> 8 < rarities[traitType][trait]) return trait;
return aliases[traitType][trait];
}
// selects the species and all of its traits based on the seed value
function selectTraits(uint256 seed) internal view returns (ManBear memory t) {
t.isFisherman = (seed & 0xFFFF) % 10 != 0;
uint8 shift = t.isFisherman ? 0 : 9; // 0 if its a Fisherman, 9 if its Bear
seed >>= 16;
if (t.isFisherman) {
// / 0 - 8 are associated with fishermen,
t.traitarray[0] = selectTrait(uint16(seed & 0xFFFF), 0 + shift);
seed >>= 16;
t.traitarray[1] = selectTrait(uint16(seed & 0xFFFF), 1 + shift);
seed >>= 16;
t.traitarray[2] = selectTrait(uint16(seed & 0xFFFF), 2 + shift);
seed >>= 16;
t.traitarray[3] = selectTrait(uint16(seed & 0xFFFF), 3 + shift);
seed >>= 16;
t.traitarray[4] = selectTrait(uint16(seed & 0xFFFF), 4 + shift);
seed >>= 16;
t.traitarray[5] = selectTrait(uint16(seed & 0xFFFF), 5 + shift);
seed >>= 16;
t.traitarray[6] = selectTrait(uint16(seed & 0xFFFF), 6 + shift);
seed >>= 16;
t.traitarray[7] = selectTrait(uint16(seed & 0xFFFF), 7 + shift);
seed >>= 16;
t.traitarray[8] = selectTrait(uint16(seed & 0xFFFF), 8 + shift);
t.alphaIndex = 0;
} else {
// 9 - 13 are associated with Bears
t.traitarray[9] = selectTrait(uint16(seed & 0xFFFF), 0 + shift);
seed >>= 16;
t.traitarray[10] = selectTrait(uint16(seed & 0xFFFF), 1 + shift);
seed >>= 16;
t.traitarray[11] = selectTrait(uint16(seed & 0xFFFF), 2 + shift);
seed >>= 16;
t.traitarray[12] = selectTrait(uint16(seed & 0xFFFF), 3 + shift);
seed >>= 16;
t.traitarray[13] = selectTrait(uint16(seed & 0xFFFF), 4 + shift);
t.alphaIndex = t.traitarray[13];
}
}
// converts a struct to a 256 bit hash to check for uniqueness
function structToHash(bool isFisherman, uint8[14] memory traitarray, uint8 alphaIndex) internal pure returns (uint256) {
if(isFisherman){
return uint256(bytes32(abi.encodePacked(true,
traitarray[0],
traitarray[1],
traitarray[2],
traitarray[3],
traitarray[4],
traitarray[5],
traitarray[6],
traitarray[7],
traitarray[8],
"0",
"0",
"0",
"0",
"0",
alphaIndex)));
}
else{
return uint256(bytes32(abi.encodePacked(false,
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
traitarray[9],
traitarray[10],
traitarray[11],
traitarray[12],
traitarray[13],
alphaIndex)));
}
}
// Select who the NFT goes to --- The first 20% (ETH purchases) go to the minter & the remaining 80% have a 10% chance to be given to a random staked Bear
function selectRecipient(uint256 seed) internal view returns (address) {
if (minted <= PAID_TOKENS || ((seed >> 245) % 10) != 0) return _msgSender(); // top 10 bits haven't been used
address thief = river.randomBearOwner(seed >> 144); // 144 bits reserved for trait selection
if (thief == address(0x0)) return _msgSender();
return thief;
}
/** READ */
function getTokenTraits(uint256 tokenId) external view override returns (ManBear memory) {
return tokenTraits[tokenId];
}
function getPaidTokens() external view override returns (uint256) {
return PAID_TOKENS;
}
// called after deployment so that the contract can get random Bear thieves
function setRiver(address _river) external onlyOwner {
river = IRiver(_river);
getRandomChainlink();
}
// Set Interfaces
function setInit(address _river, address erc20Address, address _traits ) public onlyOwner {
river = IRiver(_river);
salmon = ISalmon(erc20Address);
// salmon = IERC20(_salmon);
traits = ITraits(_traits);
getRandomChainlink();
}
// Set Base URL
function setURI(string memory _newBaseURI) external onlyOwner {
baseURI = _newBaseURI;
}
// withdraw functions
function withdraw() public payable onlyOwner {
uint256 _project = (address(this).balance * 10) / 100;
uint256 _bear1 = (address(this).balance * 225) / 1000;
uint256 _bear2 = (address(this).balance * 225) / 1000;
uint256 _bear3 = (address(this).balance * 225) / 1000;
uint256 _bear4 = (address(this).balance * 225) / 1000;
payable(project_wallet).transfer(_project);
payable(Bear1).transfer(_bear1);
payable(Bear2).transfer(_bear2);
payable(Bear3).transfer(_bear3);
payable(Bear4).transfer(_bear4);
}
// updates the number of tokens for sale
function setPaidTokens(uint256 _paidTokens) external onlyOwner {
PAID_TOKENS = _paidTokens;
// MAX_TOKENS = _maxTokens;
// PAID_TOKENS = _maxTokens / 5;
}
// enables owner to pause / unpause minting
function setPaused(bool _paused) external onlyOwner {
if (_paused) _pause();
else _unpause();
}
function addWhitelist(address[] calldata addressArrays) external onlyOwner {
uint256 addylength = addressArrays.length;
for (uint256 i; i < addylength; i++ ){
whitelists[addressArrays[i]] = 1;
}
}
/** RENDER */
function setBaseURI(string memory newUri) public onlyOwner {
baseURI = newUri;
}
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function getTokenIds(address _owner) public view returns (uint256[] memory _tokensOfOwner) {
_tokensOfOwner = new uint256[](balanceOf(_owner));
for (uint256 i;i<balanceOf(_owner);i++){
_tokensOfOwner[i] = tokenOfOwnerByIndex(_owner, i);
}
}
/** RANDOMNESSSS */
function random(uint256 seed) internal view returns (uint256) {
return uint256(keccak256(abi.encodePacked(
tx.origin,
blockhash(block.number - 1),
block.timestamp,
seed,
randomNumber
)));
}
function changeLinkFee(uint256 _fee) external onlyOwner {
// fee = 0.1 * 10 ** 18; // 0.1 LINK (Varies by network)
fee = _fee;
}
function initChainLink() external onlyOwner {
getRandomChainlink();
}
function getRandomChainlink() internal returns (bytes32 requestId) {
if (vrfReqd.current() <= vrfcooldown) {
vrfReqd.increment();
return 0x000;
}
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
vrfReqd.reset();
return requestRandomness(keyHash, fee);
}
function changeVrfCooldown(uint256 _cooldown) external onlyOwner{
vrfcooldown = _cooldown;
}
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
bytes32 reqId = requestId;
randomNumber = randomness;
}
function withdrawLINK() external onlyOwner {
uint256 tokenSupply = IERC20(linkToken).balanceOf(address(this));
IERC20(linkToken).transfer(msg.sender, tokenSupply);
}
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./RoarGenX.sol";
interface ITSalmon {
function mint(address to, uint256 amount) external;
}
contract RiverGenX is Ownable, IERC721Receiver, Pausable, VRFConsumerBase,ReentrancyGuard {
using Address for address;
using Counters for Counters.Counter;
using EnumerableSet for EnumerableSet.UintSet;
struct Stake {
uint16 tokenId;
uint80 value;
address owner;
}
/** INTERFACES */
RoarGenX roar; // reference to the RoarGenX NFT contract
ITSalmon salmon; // reference to the $SALMON contract for minting $SALMON earnings
event TokenStaked(address owner, uint256 tokenId, uint256 value);
event FishermanClaimed(uint256 tokenId, uint256 earned, bool unstaked);
event BearClaimed(uint256 tokenId, uint256 earned, bool unstaked);
mapping(uint256 => Stake) public riverside; // maps tokenId to stake
mapping(uint256 => Stake[]) public Bears; // maps alpha to all Bear stakes with that alpha
mapping(address => EnumerableSet.UintSet) private _deposits;
mapping(uint256 => uint256) public packIndices; // tracks location of each Bear in Pack
uint256 public totalAlphaStaked = 0; // total alpha scores staked
uint256 public unaccountedRewards = 0; // any rewards distributed when no bears are staked
uint256 public SalmonPerAlpha = 0; // amount of $SALMON due for each alpha point staked
uint256 public DAILY_SALMON_RATE = 10000 ether; // Fisherman earn 10000 $SALMON per day
uint256 public MINIMUM_TO_EXIT = 2 days; // Fisherman must have 2 days worth of $SALMON to unstake or else it's too cold
/** Constant Parameters*/
uint256 public constant SALMON_CLAIM_TAX_PERCENTAGE = 20; // Bears take a 20% tax on all $SALMON claimed
uint256 public constant MAXIMUM_GLOBAL_WOOL = 2400000000 ether; // there will only ever be (roughly) 2.4 billion $SALMON earned through staking
uint8 public constant MAX_ALPHA = 8;
uint256 public totalSalmonEarned; // amount of $SALMON earned so far
uint256 public totalFishermanStaked; // number of Fisherman staked in the Riverside
uint256 public lastClaimTimestamp; // the last time $SALMON was claimed
bool public rescueEnabled = false; // emergency rescue to allow unstaking without any checks but without $SALMON
//Chainlink Setup:
bytes32 internal keyHash;
uint256 public fee;
uint256 internal randomResult;
uint256 internal randomNumber;
address public linkToken;
uint256 public vrfcooldown = 10000;
Counters.Counter public vrfReqd;
constructor(address _roar, address _salmon, address _vrfCoordinator, address _link)
VRFConsumerBase(_vrfCoordinator, _link)
{
roar = RoarGenX(_roar); // reference to the RoarGenX NFT contract
salmon = ITSalmon(_salmon); //reference to the $SALMON token
keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445;
fee = 2 * 10 ** 18; // 0.1 LINK (Varies by network)
linkToken = _link;
}
function depositsOf(address account) external view returns (uint256[] memory) {
EnumerableSet.UintSet storage depositSet = _deposits[account];
uint256[] memory tokenIds = new uint256[] (depositSet.length());
for (uint256 i; i < depositSet.length(); i++) {
tokenIds[i] = depositSet.at(i);
}
return tokenIds;
}
/** STAKING */
function addManyToRiverSideAndFishing(address account, uint16[] calldata tokenIds) external { // called in mint
require(account == _msgSender() || _msgSender() == address(roar), "DONT GIVE YOUR TOKENS AWAY"); /// SEE IF I CAN ADD THE MF CONTRACT BAN
for (uint i = 0; i < tokenIds.length; i++) {
if (_msgSender() != address(roar)) { // dont do this step if its a mint + stake
require(roar.ownerOf(tokenIds[i]) == _msgSender(), "AINT YO TOKEN");
roar.transferFrom(_msgSender(), address(this), tokenIds[i]);
} else if (tokenIds[i] == 0) {
continue; // there may be gaps in the array for stolen tokens
}
if (isFisherman(tokenIds[i]))
_addFishermanToRiverside(account, tokenIds[i]);
else
_sendBearsFishing(account, tokenIds[i]);
}
}
function _addFishermanToRiverside(address account, uint256 tokenId) internal whenNotPaused _updateEarnings {
riverside[tokenId] = Stake({
owner: account,
tokenId: uint16(tokenId),
value: uint80(block.timestamp)
});
totalFishermanStaked += 1;
emit TokenStaked(account, tokenId, block.timestamp);
_deposits[account].add(tokenId);
}
function _sendBearsFishing(address account, uint256 tokenId) internal {
uint256 alpha = _alphaForBear(tokenId);
totalAlphaStaked += alpha; // Portion of earnings ranges from 8 to 5
packIndices[tokenId] = Bears[alpha].length; // Store the location of the Bear in the Pack
Bears[alpha].push(Stake({ // Add the Bear to the Pack
owner: account,
tokenId: uint16(tokenId),
value: uint80(SalmonPerAlpha)
}));
emit TokenStaked(account, tokenId, SalmonPerAlpha);
_deposits[account].add(tokenId);
}
/** CLAIMING / UNSTAKING */
// realize $SALMON earnings and optionally unstake tokens from the RIVER / FISHING
function claimManyFromRiverAndFishing(uint16[] calldata tokenIds, bool unstake) external whenNotPaused _updateEarnings nonReentrant() {
require(!_msgSender().isContract(), "Contracts are not allowed big man");
uint256 owed = 0;
for (uint i = 0; i < tokenIds.length; i++) {
if (isFisherman(tokenIds[i]))
owed += _claimFisherFromRiver(tokenIds[i], unstake);
else
owed += _claimBearFromFishing(tokenIds[i], unstake);
}
if (owed == 0) return;
salmon.mint(_msgSender(), owed);
}
function calculateReward(uint16[] calldata tokenIds) public view returns (uint256 owed) {
for (uint i = 0; i < tokenIds.length; i++) {
if (isFisherman(tokenIds[i]))
owed += calcRewardFisherman(tokenIds[i]);
else
owed += calcRewardBear(tokenIds[i]);
}
}
function calcRewardFisherman(uint256 tokenId) public view returns (uint256 owed) {
Stake memory stake = riverside[tokenId];
if (totalSalmonEarned < MAXIMUM_GLOBAL_WOOL) {
owed = (block.timestamp - stake.value) * DAILY_SALMON_RATE / 1 days;
} else if (stake.value > lastClaimTimestamp) {
owed = 0; // $WOOL production stopped already
} else {
owed = (lastClaimTimestamp - stake.value) * DAILY_SALMON_RATE / 1 days; // stop earning additional $WOOL if it's all been earned
}
}
function calcRewardBear(uint256 tokenId) public view returns (uint256 owed) {
uint256 alpha = _alphaForBear(tokenId);
Stake memory stake = Bears[alpha][packIndices[tokenId]];
owed = (alpha) * (SalmonPerAlpha - stake.value);
// Calculate portion of tokens based on Alpha
}
// Basically, withdraws $SALMON earnings for a single Fisherman and optionally unstake it.
// 20% Bear Tax, 50% chance all goes to Bear if unstaking.
function _claimFisherFromRiver(uint256 tokenId, bool unstake) internal returns (uint256 owed) {
Stake memory stake = riverside[tokenId];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
require(!(unstake && block.timestamp - stake.value < MINIMUM_TO_EXIT), "GONNA BE COLD WITHOUT TWO DAY'S WOOL");
owed = calcRewardFisherman(tokenId);
if (unstake) {
getRandomChainlink();
if (random(tokenId) & 1 == 1) { // 50% chance of all $SALMON stolen
_payBearTax(owed);
owed = 0;
}
delete riverside[tokenId];
totalFishermanStaked -= 1;
_deposits[_msgSender()].remove(tokenId);
roar.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // send back Fisherman
} else {
_payBearTax(owed * SALMON_CLAIM_TAX_PERCENTAGE / 100); // percentage tax to staked Bears
riverside[tokenId] = Stake({
owner: _msgSender(),
tokenId: uint16(tokenId),
value: uint80(block.timestamp)
}); // reset stake
owed = owed * (100 - SALMON_CLAIM_TAX_PERCENTAGE) / 100; // remainder goes to Fisherman owner
}
emit FishermanClaimed(tokenId, owed, unstake);
}
// Basically, withdraws $SALMON earnings for a single BEAR and optionally unstake it.
function _claimBearFromFishing(uint256 tokenId, bool unstake) internal returns (uint256 owed) {
uint256 alpha = _alphaForBear(tokenId);
Stake memory stake = Bears[alpha][packIndices[tokenId]];
require(roar.ownerOf(tokenId) == address(this), "AINT A PART OF THE PACK");
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
owed = calcRewardBear(tokenId); // Calculate portion of tokens based on Alpha
if (unstake) {
totalAlphaStaked -= alpha; // Remove Alpha from total staked
Stake memory lastStake = Bears[alpha][Bears[alpha].length - 1]; // Shuffle last Bear to current position PT 1
Bears[alpha][packIndices[tokenId]] = lastStake; // Shuffle last Bear to current position PT 2
packIndices[lastStake.tokenId] = packIndices[tokenId]; // Shuffle last Bear to current position PT 3
Bears[alpha].pop(); // Remove duplicate
delete packIndices[tokenId]; // Delete old mapping
_deposits[_msgSender()].remove(tokenId);
roar.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // Send back Bear
} else {
Bears[alpha][packIndices[tokenId]] = Stake({
owner: _msgSender(),
tokenId: uint16(tokenId),
value: uint80(SalmonPerAlpha)
}); // reset stake
}
emit BearClaimed(tokenId, owed, unstake);
}
// emergency unstake tokens
function rescue(uint256[] calldata tokenIds) external nonReentrant() {
require(!_msgSender().isContract(), "Contracts are not allowed big man");
require(rescueEnabled, "RESCUE DISABLED");
uint256 tokenId;
Stake memory stake;
Stake memory lastStake;
uint256 alpha;
for (uint i = 0; i < tokenIds.length; i++) {
tokenId = tokenIds[i];
if (isFisherman(tokenId)) {
stake = riverside[tokenId];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
delete riverside[tokenId];
totalFishermanStaked -= 1;
roar.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // send back Fisherman
emit FishermanClaimed(tokenId, 0, true);
} else {
alpha = _alphaForBear(tokenId);
stake = Bears[alpha][packIndices[tokenId]];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
totalAlphaStaked -= alpha; // Remove Alpha from total staked
lastStake = Bears[alpha][Bears[alpha].length - 1];
Bears[alpha][packIndices[tokenId]] = lastStake; // Shuffle last bear to current position
packIndices[lastStake.tokenId] = packIndices[tokenId];
Bears[alpha].pop(); // Remove duplicate
delete packIndices[tokenId]; // Delete old mapping
roar.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // Send back Fisherman
emit BearClaimed(tokenId, 0, true);
}
}
}
/** ACCOUNTING */
// add $SALMON to claimable pot for the Pack
function _payBearTax(uint256 amount) internal {
if (totalAlphaStaked == 0) { // if there's no staked Bear > keep track of $SALMON due to Bear
unaccountedRewards += amount;
return;
}
SalmonPerAlpha += (amount + unaccountedRewards) / totalAlphaStaked; // makes sure to include any unaccounted $SALMON
unaccountedRewards = 0;
}
// tracks $SALMIN earnings to ensure it stops once 2.4 billion is eclipsed
modifier _updateEarnings() {
if (totalSalmonEarned < MAXIMUM_GLOBAL_WOOL) {
totalSalmonEarned +=
(block.timestamp - lastClaimTimestamp)
* totalFishermanStaked
* DAILY_SALMON_RATE / 1 days;
lastClaimTimestamp = block.timestamp;
}
_;
}
function isFisherman(uint256 tokenId) public view returns (bool fisherman) {
// SheepWolf memory t = roar.getTokenTraits(tokenId);(sheep, , , , , , , , , ) = roar.tokenTraits(tokenId);
(fisherman, ) = roar.tokenTraits(tokenId);
}
// gets the alpha score for a Bear
function _alphaForBear(uint256 tokenId) public view returns (uint8) {
( ,uint8 alphaIndex) = roar.tokenTraits(tokenId);
return MAX_ALPHA - alphaIndex; // alpha index is 0-3
}
// chooses a random Bear thief when a newly minted token is stolen
function randomBearOwner(uint256 seed) external view returns (address) {
if (totalAlphaStaked == 0) return address(0x0);
uint256 bucket = (seed & 0xFFFFFFFF) % totalAlphaStaked; // choose a value from 0 to total alpha staked
uint256 cumulative;
seed >>= 32;
for (uint i = MAX_ALPHA - 3; i <= MAX_ALPHA; i++) { // loop through each bucket of Bears with the same alpha score
cumulative += Bears[i].length * i;
if (bucket >= cumulative) continue; // if the value is not inside of that bucket, keep going
return Bears[i][seed % Bears[i].length].owner; // get the address of a random Bear with that alpha score
}
return address(0x0);
}
/** CHANGE PARAMETERS */
function setInit(address _roar, address _salmon) external onlyOwner{
roar = RoarGenX(_roar); // reference to the RoarGenX NFT contract
salmon = ITSalmon(_salmon); //reference to the $SALMON token
}
function changeDailyRate(uint256 _newRate) external onlyOwner{
DAILY_SALMON_RATE = _newRate;
}
function changeMinExit(uint256 _newExit) external onlyOwner{
_newExit = _newExit ;
}
function setRescueEnabled(bool _enabled) external onlyOwner {
rescueEnabled = _enabled;
}
function setPaused(bool _paused) external onlyOwner {
if (_paused) _pause();
else _unpause();
}
/** RANDOMNESSSS */
function changeLinkFee(uint256 _fee) external onlyOwner {
// fee = 0.1 * 10 ** 18; // 0.1 LINK (Varies by network)
fee = _fee;
}
function random(uint256 seed) internal view returns (uint256) {
return uint256(keccak256(abi.encodePacked(
tx.origin,
blockhash(block.number - 1),
block.timestamp,
seed,
randomNumber
)));
}
function initChainLink() external onlyOwner {
getRandomChainlink();
}
function getRandomChainlink() internal returns (bytes32 requestId) {
if (vrfReqd.current() <= vrfcooldown) {
vrfReqd.increment();
return 0x000;
}
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
vrfReqd.reset();
return requestRandomness(keyHash, fee);
}
function changeVrfCooldown(uint256 _cooldown) external onlyOwner{
vrfcooldown = _cooldown;
}
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
bytes32 reqId = requestId;
randomNumber = randomness;
}
function withdrawLINK() external onlyOwner {
uint256 tokenSupply = IERC20(linkToken).balanceOf(address(this));
IERC20(linkToken).transfer(msg.sender, tokenSupply);
}
/** OTHERS */
function onERC721Received(address, address from, uint256, bytes calldata) external pure override returns (bytes4) {
require(from == address(0x0), "Cannot send tokens to Barn directly");
return IERC721Receiver.onERC721Received.selector;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721EnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable {
using AddressUpgradeable for address;
function __ERC721Enumerable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721Enumerable_init_unchained();
}
function __ERC721Enumerable_init_unchained() internal initializer {
}
// 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(IERC165Upgradeable, ERC721Upgradeable) returns (bool) {
return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(!_msgSender().isContract(), "Contracts are not allowed big man");
require(index < ERC721Upgradeable.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(!_msgSender().isContract(), "Contracts are not allowed big man");
require(index < ERC721EnumerableUpgradeable.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 = ERC721Upgradeable.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 = ERC721Upgradeable.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();
}
uint256[46] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library 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;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/math/Math.sol)
pragma solidity ^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.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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 IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.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 ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library CountersUpgradeable {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
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 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.0 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @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.0 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @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.0 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @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.0 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.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 ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable 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.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).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 = ERC721Upgradeable.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 = ERC721Upgradeable.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 = ERC721Upgradeable.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(ERC721Upgradeable.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(ERC721Upgradeable.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 IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable.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 {}
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and 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;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_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);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract VRFRequestIDBase {
/**
* @notice returns the seed which is actually input to the VRF coordinator
*
* @dev To prevent repetition of VRF output due to repetition of the
* @dev user-supplied seed, that seed is combined in a hash with the
* @dev user-specific nonce, and the address of the consuming contract. The
* @dev risk of repetition is mostly mitigated by inclusion of a blockhash in
* @dev the final seed, but the nonce does protect against repetition in
* @dev requests which are included in a single block.
*
* @param _userSeed VRF seed input provided by user
* @param _requester Address of the requesting contract
* @param _nonce User-specific nonce at the time of the request
*/
function makeVRFInputSeed(
bytes32 _keyHash,
uint256 _userSeed,
address _requester,
uint256 _nonce
)
internal
pure
returns (
uint256
)
{
return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce)));
}
/**
* @notice Returns the id for this request
* @param _keyHash The serviceAgreement ID to be used for this request
* @param _vRFInputSeed The seed to be passed directly to the VRF
* @return The id for this request
*
* @dev Note that _vRFInputSeed is not the seed passed by the consuming
* @dev contract, but the one generated by makeVRFInputSeed
*/
function makeRequestId(
bytes32 _keyHash,
uint256 _vRFInputSeed
)
internal
pure
returns (
bytes32
)
{
return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./interfaces/LinkTokenInterface.sol";
import "./VRFRequestIDBase.sol";
/** ****************************************************************************
* @notice Interface for contracts using VRF randomness
* *****************************************************************************
* @dev PURPOSE
*
* @dev Reggie the Random Oracle (not his real job) wants to provide randomness
* @dev to Vera the verifier in such a way that Vera can be sure he's not
* @dev making his output up to suit himself. Reggie provides Vera a public key
* @dev to which he knows the secret key. Each time Vera provides a seed to
* @dev Reggie, he gives back a value which is computed completely
* @dev deterministically from the seed and the secret key.
*
* @dev Reggie provides a proof by which Vera can verify that the output was
* @dev correctly computed once Reggie tells it to her, but without that proof,
* @dev the output is indistinguishable to her from a uniform random sample
* @dev from the output space.
*
* @dev The purpose of this contract is to make it easy for unrelated contracts
* @dev to talk to Vera the verifier about the work Reggie is doing, to provide
* @dev simple access to a verifiable source of randomness.
* *****************************************************************************
* @dev USAGE
*
* @dev Calling contracts must inherit from VRFConsumerBase, and can
* @dev initialize VRFConsumerBase's attributes in their constructor as
* @dev shown:
*
* @dev contract VRFConsumer {
* @dev constuctor(<other arguments>, address _vrfCoordinator, address _link)
* @dev VRFConsumerBase(_vrfCoordinator, _link) public {
* @dev <initialization with other arguments goes here>
* @dev }
* @dev }
*
* @dev The oracle will have given you an ID for the VRF keypair they have
* @dev committed to (let's call it keyHash), and have told you the minimum LINK
* @dev price for VRF service. Make sure your contract has sufficient LINK, and
* @dev call requestRandomness(keyHash, fee, seed), where seed is the input you
* @dev want to generate randomness from.
*
* @dev Once the VRFCoordinator has received and validated the oracle's response
* @dev to your request, it will call your contract's fulfillRandomness method.
*
* @dev The randomness argument to fulfillRandomness is the actual random value
* @dev generated from your seed.
*
* @dev The requestId argument is generated from the keyHash and the seed by
* @dev makeRequestId(keyHash, seed). If your contract could have concurrent
* @dev requests open, you can use the requestId to track which seed is
* @dev associated with which randomness. See VRFRequestIDBase.sol for more
* @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind,
* @dev if your contract could have multiple requests in flight simultaneously.)
*
* @dev Colliding `requestId`s are cryptographically impossible as long as seeds
* @dev differ. (Which is critical to making unpredictable randomness! See the
* @dev next section.)
*
* *****************************************************************************
* @dev SECURITY CONSIDERATIONS
*
* @dev A method with the ability to call your fulfillRandomness method directly
* @dev could spoof a VRF response with any random value, so it's critical that
* @dev it cannot be directly called by anything other than this base contract
* @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method).
*
* @dev For your users to trust that your contract's random behavior is free
* @dev from malicious interference, it's best if you can write it so that all
* @dev behaviors implied by a VRF response are executed *during* your
* @dev fulfillRandomness method. If your contract must store the response (or
* @dev anything derived from it) and use it later, you must ensure that any
* @dev user-significant behavior which depends on that stored value cannot be
* @dev manipulated by a subsequent VRF request.
*
* @dev Similarly, both miners and the VRF oracle itself have some influence
* @dev over the order in which VRF responses appear on the blockchain, so if
* @dev your contract could have multiple VRF requests in flight simultaneously,
* @dev you must ensure that the order in which the VRF responses arrive cannot
* @dev be used to manipulate your contract's user-significant behavior.
*
* @dev Since the ultimate input to the VRF is mixed with the block hash of the
* @dev block in which the request is made, user-provided seeds have no impact
* @dev on its economic security properties. They are only included for API
* @dev compatability with previous versions of this contract.
*
* @dev Since the block hash of the block which contains the requestRandomness
* @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
* @dev miner could, in principle, fork the blockchain to evict the block
* @dev containing the request, forcing the request to be included in a
* @dev different block with a different hash, and therefore a different input
* @dev to the VRF. However, such an attack would incur a substantial economic
* @dev cost. This cost scales with the number of blocks the VRF oracle waits
* @dev until it calls responds to a request.
*/
abstract contract VRFConsumerBase is VRFRequestIDBase {
/**
* @notice fulfillRandomness handles the VRF response. Your contract must
* @notice implement it. See "SECURITY CONSIDERATIONS" above for important
* @notice principles to keep in mind when implementing your fulfillRandomness
* @notice method.
*
* @dev VRFConsumerBase expects its subcontracts to have a method with this
* @dev signature, and will call it once it has verified the proof
* @dev associated with the randomness. (It is triggered via a call to
* @dev rawFulfillRandomness, below.)
*
* @param requestId The Id initially returned by requestRandomness
* @param randomness the VRF output
*/
function fulfillRandomness(
bytes32 requestId,
uint256 randomness
)
internal
virtual;
/**
* @dev In order to keep backwards compatibility we have kept the user
* seed field around. We remove the use of it because given that the blockhash
* enters later, it overrides whatever randomness the used seed provides.
* Given that it adds no security, and can easily lead to misunderstandings,
* we have removed it from usage and can now provide a simpler API.
*/
uint256 constant private USER_SEED_PLACEHOLDER = 0;
/**
* @notice requestRandomness initiates a request for VRF output given _seed
*
* @dev The fulfillRandomness method receives the output, once it's provided
* @dev by the Oracle, and verified by the vrfCoordinator.
*
* @dev The _keyHash must already be registered with the VRFCoordinator, and
* @dev the _fee must exceed the fee specified during registration of the
* @dev _keyHash.
*
* @dev The _seed parameter is vestigial, and is kept only for API
* @dev compatibility with older versions. It can't *hurt* to mix in some of
* @dev your own randomness, here, but it's not necessary because the VRF
* @dev oracle will mix the hash of the block containing your request into the
* @dev VRF seed it ultimately uses.
*
* @param _keyHash ID of public key against which randomness is generated
* @param _fee The amount of LINK to send with the request
*
* @return requestId unique ID for this request
*
* @dev The returned requestId can be used to distinguish responses to
* @dev concurrent requests. It is passed as the first argument to
* @dev fulfillRandomness.
*/
function requestRandomness(
bytes32 _keyHash,
uint256 _fee
)
internal
returns (
bytes32 requestId
)
{
LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER));
// This is the seed passed to VRFCoordinator. The oracle will mix this with
// the hash of the block containing this request to obtain the seed/input
// which is finally passed to the VRF cryptographic machinery.
uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]);
// nonces[_keyHash] must stay in sync with
// VRFCoordinator.nonces[_keyHash][this], which was incremented by the above
// successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest).
// This provides protection against the user repeating their input seed,
// which would result in a predictable/duplicate output, if multiple such
// requests appeared in the same block.
nonces[_keyHash] = nonces[_keyHash] + 1;
return makeRequestId(_keyHash, vRFSeed);
}
LinkTokenInterface immutable internal LINK;
address immutable private vrfCoordinator;
// Nonces for each VRF key from which randomness has been requested.
//
// Must stay in sync with VRFCoordinator[_keyHash][this]
mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces;
/**
* @param _vrfCoordinator address of VRFCoordinator contract
* @param _link address of LINK token contract
*
* @dev https://docs.chain.link/docs/link-token-contracts
*/
constructor(
address _vrfCoordinator,
address _link
) {
vrfCoordinator = _vrfCoordinator;
LINK = LinkTokenInterface(_link);
}
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
// proof. rawFulfillRandomness then calls fulfillRandomness, after validating
// the origin of the call
function rawFulfillRandomness(
bytes32 requestId,
uint256 randomness
)
external
{
require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill");
fulfillRandomness(requestId, randomness);
}
}
|
No need for migration
|
function _sendBearsFishing(address account, uint256 tokenId) internal {
uint256 alpha = _alphaForBear(tokenId);
owner: account,
tokenId: uint16(tokenId),
value: uint80(SalmonPerAlpha)
}));
| 10,251,711
|
./partial_match/42220/0x56E44A9f86C2e3a53e816335cBE6deaE440b0856/sources/WitnetPriceFeedBypass.sol
|
Decode a `CBOR` structure into a native `uint64` value. cbor An instance of `CBOR`. return The value represented by the input, as an `uint64` value.
|
function readUint(CBOR memory cbor)
internal pure
isMajorType(cbor, MAJOR_TYPE_INT)
returns (uint)
{
return readLength(
cbor.buffer,
cbor.additionalInformation
);
}
| 3,498,305
|
pragma solidity ^0.4.18;
pragma experimental ABIEncoderV2;
contract agricultureContract {
uint8 numberOfProducts; // 총 제품의 수입니다.
address contractOwner;
struct myStruct {
uint number;
string productName;
uint timestamp;
}
myStruct[] public productes;
constructor() public {
contractOwner = msg.sender;
}
function addProStru (uint _initNumber, string _firstString) public {
productes.push(myStruct(_initNumber,_firstString, now)) -1;
numberOfProducts++;
}
//제품 등록의 수를 리턴합니다.
function getNumOfProducts() public constant returns(uint8) {
return numberOfProducts;
}
function getAllproducts() public view returns (myStruct[]) {
return productes;
}
//번호에 해당하는 제품의 이름을 리턴합니다.
function getProductStruct(uint _index) public view returns (uint, string, uint) {
return (productes[_index].number, productes[_index].productName, productes[_index].timestamp);
}
//컨트랙트를 삭제합니다.
function killContract() public {
if(contractOwner == msg.sender)
selfdestruct(contractOwner);
}
}
|
번호에 해당하는 제품의 이름을 리턴합니다.
|
function getProductStruct(uint _index) public view returns (uint, string, uint) {
return (productes[_index].number, productes[_index].productName, productes[_index].timestamp);
}
| 5,496,673
|
pragma solidity ^0.4.21;
contract Ownable {
address public owner;
event OwnershipTransferred(address previousOwner, address newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract StorageBase is Ownable {
function withdrawBalance() external onlyOwner returns (bool) {
// The owner has a method to withdraw balance from multiple contracts together,
// use send here to make sure even if one withdrawBalance fails the others will still work
bool res = msg.sender.send(address(this).balance);
return res;
}
}
// owner of ActivityStorage should be ActivityCore contract address
contract ActivityStorage is StorageBase {
struct Activity {
// accept bid or not
bool isPause;
// limit max num of monster buyable per address
uint16 buyLimit;
// price (in wei)
uint128 packPrice;
// startDate (in seconds)
uint64 startDate;
// endDate (in seconds)
uint64 endDate;
// packId => address of bid winner
mapping(uint16 => address) soldPackToAddress;
// address => number of success bid
mapping(address => uint16) addressBoughtCount;
}
// limit max activityId to 65536, big enough
mapping(uint16 => Activity) public activities;
function createActivity(
uint16 _activityId,
uint16 _buyLimit,
uint128 _packPrice,
uint64 _startDate,
uint64 _endDate
)
external
onlyOwner
{
// activity should not exist and can only be initialized once
require(activities[_activityId].buyLimit == 0);
activities[_activityId] = Activity({
isPause: false,
buyLimit: _buyLimit,
packPrice: _packPrice,
startDate: _startDate,
endDate: _endDate
});
}
function sellPackToAddress(
uint16 _activityId,
uint16 _packId,
address buyer
)
external
onlyOwner
{
Activity storage activity = activities[_activityId];
activity.soldPackToAddress[_packId] = buyer;
activity.addressBoughtCount[buyer]++;
}
function pauseActivity(uint16 _activityId) external onlyOwner {
activities[_activityId].isPause = true;
}
function unpauseActivity(uint16 _activityId) external onlyOwner {
activities[_activityId].isPause = false;
}
function deleteActivity(uint16 _activityId) external onlyOwner {
delete activities[_activityId];
}
function getAddressBoughtCount(uint16 _activityId, address buyer) external view returns (uint16) {
return activities[_activityId].addressBoughtCount[buyer];
}
function getBuyerAddress(uint16 _activityId, uint16 packId) external view returns (address) {
return activities[_activityId].soldPackToAddress[packId];
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused {
require(paused);
_;
}
function pause() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
}
contract HasNoContracts is Pausable {
function reclaimContract(address _contractAddr) external onlyOwner whenPaused {
Ownable contractInst = Ownable(_contractAddr);
contractInst.transferOwnership(owner);
}
}
contract ERC721 {
// Required methods
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
// Events
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
// function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
contract LogicBase is HasNoContracts {
/// The ERC-165 interface signature for ERC-721.
/// Ref: https://github.com/ethereum/EIPs/issues/165
/// Ref: https://github.com/ethereum/EIPs/issues/721
bytes4 constant InterfaceSignature_NFC = bytes4(0x9f40b779);
// Reference to contract tracking NFT ownership
ERC721 public nonFungibleContract;
// Reference to storage contract
StorageBase public storageContract;
function LogicBase(address _nftAddress, address _storageAddress) public {
// paused by default
paused = true;
setNFTAddress(_nftAddress);
require(_storageAddress != address(0));
storageContract = StorageBase(_storageAddress);
}
// Very dangerous action, only when new contract has been proved working
// Requires storageContract already transferOwnership to the new contract
// This method is only used to transfer the balance to owner
function destroy() external onlyOwner whenPaused {
address storageOwner = storageContract.owner();
// owner of storageContract must not be the current contract otherwise the storageContract will forever not accessible
require(storageOwner != address(this));
// Transfers the current balance to the owner and terminates the contract
selfdestruct(owner);
}
// Very dangerous action, only when new contract has been proved working
// Requires storageContract already transferOwnership to the new contract
// This method is only used to transfer the balance to the new contract
function destroyAndSendToStorageOwner() external onlyOwner whenPaused {
address storageOwner = storageContract.owner();
// owner of storageContract must not be the current contract otherwise the storageContract will forever not accessible
require(storageOwner != address(this));
// Transfers the current balance to the new owner of the storage contract and terminates the contract
selfdestruct(storageOwner);
}
// override to make sure everything is initialized before the unpause
function unpause() public onlyOwner whenPaused {
// can not unpause when the logic contract is not initialzed
require(nonFungibleContract != address(0));
require(storageContract != address(0));
// can not unpause when ownership of storage contract is not the current contract
require(storageContract.owner() == address(this));
super.unpause();
}
function setNFTAddress(address _nftAddress) public onlyOwner {
require(_nftAddress != address(0));
ERC721 candidateContract = ERC721(_nftAddress);
require(candidateContract.supportsInterface(InterfaceSignature_NFC));
nonFungibleContract = candidateContract;
}
// Withdraw balance to the Core Contract
function withdrawBalance() external returns (bool) {
address nftAddress = address(nonFungibleContract);
// either Owner or Core Contract can trigger the withdraw
require(msg.sender == owner || msg.sender == nftAddress);
// The owner has a method to withdraw balance from multiple contracts together,
// use send here to make sure even if one withdrawBalance fails the others will still work
bool res = nftAddress.send(address(this).balance);
return res;
}
function withdrawBalanceFromStorageContract() external returns (bool) {
address nftAddress = address(nonFungibleContract);
// either Owner or Core Contract can trigger the withdraw
require(msg.sender == owner || msg.sender == nftAddress);
// The owner has a method to withdraw balance from multiple contracts together,
// use send here to make sure even if one withdrawBalance fails the others will still work
bool res = storageContract.withdrawBalance();
return res;
}
}
contract ActivityCore is LogicBase {
bool public isActivityCore = true;
ActivityStorage activityStorage;
event ActivityCreated(uint16 activityId);
event ActivityBidSuccess(uint16 activityId, uint16 packId, address winner);
function ActivityCore(address _nftAddress, address _storageAddress)
LogicBase(_nftAddress, _storageAddress) public {
activityStorage = ActivityStorage(_storageAddress);
}
function createActivity(
uint16 _activityId,
uint16 _buyLimit,
uint128 _packPrice,
uint64 _startDate,
uint64 _endDate
)
external
onlyOwner
whenNotPaused
{
activityStorage.createActivity(_activityId, _buyLimit, _packPrice, _startDate, _endDate);
emit ActivityCreated(_activityId);
}
// Very dangerous action and should be only used for testing
// Must pause the contract first
function deleteActivity(
uint16 _activityId
)
external
onlyOwner
whenPaused
{
activityStorage.deleteActivity(_activityId);
}
function getActivity(
uint16 _activityId
)
external
view
returns (
bool isPause,
uint16 buyLimit,
uint128 packPrice,
uint64 startDate,
uint64 endDate
)
{
return activityStorage.activities(_activityId);
}
function bid(uint16 _activityId, uint16 _packId)
external
payable
whenNotPaused
{
bool isPause;
uint16 buyLimit;
uint128 packPrice;
uint64 startDate;
uint64 endDate;
(isPause, buyLimit, packPrice, startDate, endDate) = activityStorage.activities(_activityId);
// not allow to bid when activity is paused
require(!isPause);
// not allow to bid when activity is not initialized (buyLimit == 0)
require(buyLimit > 0);
// should send enough ether
require(msg.value >= packPrice);
// verify startDate & endDate
require(now >= startDate && now <= endDate);
// this pack is not sold out
require(activityStorage.getBuyerAddress(_activityId, _packId) == address(0));
// buyer not exceed buyLimit
require(activityStorage.getAddressBoughtCount(_activityId, msg.sender) < buyLimit);
// record in blockchain
activityStorage.sellPackToAddress(_activityId, _packId, msg.sender);
// emit the success event
emit ActivityBidSuccess(_activityId, _packId, msg.sender);
}
}
contract CryptoStorage is StorageBase {
struct Monster {
uint32 matronId;
uint32 sireId;
uint32 siringWithId;
uint16 cooldownIndex;
uint16 generation;
uint64 cooldownEndBlock;
uint64 birthTime;
uint16 monsterId;
uint32 monsterNum;
bytes properties;
}
// ERC721 tokens
Monster[] internal monsters;
// total number of monster created from system instead of breeding
uint256 public promoCreatedCount;
// total number of monster created by system sale address
uint256 public systemCreatedCount;
// number of monsters in pregnant
uint256 public pregnantMonsters;
// monsterId => total number
mapping (uint256 => uint32) public monsterCurrentNumber;
// tokenId => owner address
mapping (uint256 => address) public monsterIndexToOwner;
// owner address => balance of tokens
mapping (address => uint256) public ownershipTokenCount;
// tokenId => approved address
mapping (uint256 => address) public monsterIndexToApproved;
function CryptoStorage() public {
// placeholder to make the first available monster to have a tokenId starts from 1
createMonster(0, 0, 0, 0, 0, "");
}
function createMonster(
uint256 _matronId,
uint256 _sireId,
uint256 _generation,
uint256 _birthTime,
uint256 _monsterId,
bytes _properties
)
public
onlyOwner
returns (uint256)
{
require(_matronId == uint256(uint32(_matronId)));
require(_sireId == uint256(uint32(_sireId)));
require(_generation == uint256(uint16(_generation)));
require(_birthTime == uint256(uint64(_birthTime)));
require(_monsterId == uint256(uint16(_monsterId)));
monsterCurrentNumber[_monsterId]++;
Monster memory monster = Monster({
matronId: uint32(_matronId),
sireId: uint32(_sireId),
siringWithId: 0,
cooldownIndex: 0,
generation: uint16(_generation),
cooldownEndBlock: 0,
birthTime: uint64(_birthTime),
monsterId: uint16(_monsterId),
monsterNum: monsterCurrentNumber[_monsterId],
properties: _properties
});
uint256 tokenId = monsters.push(monster) - 1;
// overflow check
require(tokenId == uint256(uint32(tokenId)));
return tokenId;
}
function getMonster(uint256 _tokenId)
external
view
returns (
bool isGestating,
bool isReady,
uint16 cooldownIndex,
uint64 nextActionAt,
uint32 siringWithId,
uint32 matronId,
uint32 sireId,
uint64 cooldownEndBlock,
uint16 generation,
uint64 birthTime,
uint32 monsterNum,
uint16 monsterId,
bytes properties
)
{
Monster storage monster = monsters[_tokenId];
isGestating = (monster.siringWithId != 0);
isReady = (monster.cooldownEndBlock <= block.number);
cooldownIndex = monster.cooldownIndex;
nextActionAt = monster.cooldownEndBlock;
siringWithId = monster.siringWithId;
matronId = monster.matronId;
sireId = monster.sireId;
cooldownEndBlock = monster.cooldownEndBlock;
generation = monster.generation;
birthTime = monster.birthTime;
monsterNum = monster.monsterNum;
monsterId = monster.monsterId;
properties = monster.properties;
}
function getMonsterCount() external view returns (uint256) {
return monsters.length - 1;
}
function getMatronId(uint256 _tokenId) external view returns (uint32) {
return monsters[_tokenId].matronId;
}
function getSireId(uint256 _tokenId) external view returns (uint32) {
return monsters[_tokenId].sireId;
}
function getSiringWithId(uint256 _tokenId) external view returns (uint32) {
return monsters[_tokenId].siringWithId;
}
function setSiringWithId(uint256 _tokenId, uint32 _siringWithId) external onlyOwner {
monsters[_tokenId].siringWithId = _siringWithId;
}
function deleteSiringWithId(uint256 _tokenId) external onlyOwner {
delete monsters[_tokenId].siringWithId;
}
function getCooldownIndex(uint256 _tokenId) external view returns (uint16) {
return monsters[_tokenId].cooldownIndex;
}
function setCooldownIndex(uint256 _tokenId) external onlyOwner {
monsters[_tokenId].cooldownIndex += 1;
}
function getGeneration(uint256 _tokenId) external view returns (uint16) {
return monsters[_tokenId].generation;
}
function getCooldownEndBlock(uint256 _tokenId) external view returns (uint64) {
return monsters[_tokenId].cooldownEndBlock;
}
function setCooldownEndBlock(uint256 _tokenId, uint64 _cooldownEndBlock) external onlyOwner {
monsters[_tokenId].cooldownEndBlock = _cooldownEndBlock;
}
function getBirthTime(uint256 _tokenId) external view returns (uint64) {
return monsters[_tokenId].birthTime;
}
function getMonsterId(uint256 _tokenId) external view returns (uint16) {
return monsters[_tokenId].monsterId;
}
function getMonsterNum(uint256 _tokenId) external view returns (uint32) {
return monsters[_tokenId].monsterNum;
}
function getProperties(uint256 _tokenId) external view returns (bytes) {
return monsters[_tokenId].properties;
}
function updateProperties(uint256 _tokenId, bytes _properties) external onlyOwner {
monsters[_tokenId].properties = _properties;
}
function setMonsterIndexToOwner(uint256 _tokenId, address _owner) external onlyOwner {
monsterIndexToOwner[_tokenId] = _owner;
}
function increaseOwnershipTokenCount(address _owner) external onlyOwner {
ownershipTokenCount[_owner]++;
}
function decreaseOwnershipTokenCount(address _owner) external onlyOwner {
ownershipTokenCount[_owner]--;
}
function setMonsterIndexToApproved(uint256 _tokenId, address _approved) external onlyOwner {
monsterIndexToApproved[_tokenId] = _approved;
}
function deleteMonsterIndexToApproved(uint256 _tokenId) external onlyOwner {
delete monsterIndexToApproved[_tokenId];
}
function increasePromoCreatedCount() external onlyOwner {
promoCreatedCount++;
}
function increaseSystemCreatedCount() external onlyOwner {
systemCreatedCount++;
}
function increasePregnantCounter() external onlyOwner {
pregnantMonsters++;
}
function decreasePregnantCounter() external onlyOwner {
pregnantMonsters--;
}
}
contract ClockAuctionStorage is StorageBase {
// Represents an auction on an NFT
struct Auction {
// Current owner of NFT
address seller;
// Price (in wei) at beginning of auction
uint128 startingPrice;
// Price (in wei) at end of auction
uint128 endingPrice;
// Duration (in seconds) of auction
uint64 duration;
// Time when auction started
// NOTE: 0 if this auction has been concluded
uint64 startedAt;
}
// Map from token ID to their corresponding auction.
mapping (uint256 => Auction) tokenIdToAuction;
function addAuction(
uint256 _tokenId,
address _seller,
uint128 _startingPrice,
uint128 _endingPrice,
uint64 _duration,
uint64 _startedAt
)
external
onlyOwner
{
tokenIdToAuction[_tokenId] = Auction(
_seller,
_startingPrice,
_endingPrice,
_duration,
_startedAt
);
}
function removeAuction(uint256 _tokenId) public onlyOwner {
delete tokenIdToAuction[_tokenId];
}
function getAuction(uint256 _tokenId)
external
view
returns (
address seller,
uint128 startingPrice,
uint128 endingPrice,
uint64 duration,
uint64 startedAt
)
{
Auction storage auction = tokenIdToAuction[_tokenId];
return (
auction.seller,
auction.startingPrice,
auction.endingPrice,
auction.duration,
auction.startedAt
);
}
function isOnAuction(uint256 _tokenId) external view returns (bool) {
return (tokenIdToAuction[_tokenId].startedAt > 0);
}
function getSeller(uint256 _tokenId) external view returns (address) {
return tokenIdToAuction[_tokenId].seller;
}
function transfer(ERC721 _nonFungibleContract, address _receiver, uint256 _tokenId) external onlyOwner {
// it will throw if transfer fails
_nonFungibleContract.transfer(_receiver, _tokenId);
}
}
contract SaleClockAuctionStorage is ClockAuctionStorage {
bool public isSaleClockAuctionStorage = true;
// total accumulate sold count
uint256 public totalSoldCount;
// last 3 sale price
uint256[3] public lastSoldPrices;
// current on sale auction count from system
uint256 public systemOnSaleCount;
// map of on sale token ids from system
mapping (uint256 => bool) systemOnSaleTokens;
function removeAuction(uint256 _tokenId) public onlyOwner {
// first remove auction from state variable
super.removeAuction(_tokenId);
// update system on sale record
if (systemOnSaleTokens[_tokenId]) {
delete systemOnSaleTokens[_tokenId];
if (systemOnSaleCount > 0) {
systemOnSaleCount--;
}
}
}
function recordSystemOnSaleToken(uint256 _tokenId) external onlyOwner {
if (!systemOnSaleTokens[_tokenId]) {
systemOnSaleTokens[_tokenId] = true;
systemOnSaleCount++;
}
}
function recordSoldPrice(uint256 _price) external onlyOwner {
lastSoldPrices[totalSoldCount % 3] = _price;
totalSoldCount++;
}
function averageSoldPrice() external view returns (uint256) {
if (totalSoldCount == 0) return 0;
uint256 sum = 0;
uint256 len = (totalSoldCount < 3 ? totalSoldCount : 3);
for (uint256 i = 0; i < len; i++) {
sum += lastSoldPrices[i];
}
return sum / len;
}
}
contract ClockAuction is LogicBase {
// Reference to contract tracking auction state variables
ClockAuctionStorage public clockAuctionStorage;
// Cut owner takes on each auction, measured in basis points (1/100 of a percent).
// Values 0-10,000 map to 0%-100%
uint256 public ownerCut;
// Minimum cut value on each auction (in WEI)
uint256 public minCutValue;
event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration);
event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner, address seller, uint256 sellerProceeds);
event AuctionCancelled(uint256 tokenId);
function ClockAuction(address _nftAddress, address _storageAddress, uint256 _cut, uint256 _minCutValue)
LogicBase(_nftAddress, _storageAddress) public
{
setOwnerCut(_cut);
setMinCutValue(_minCutValue);
clockAuctionStorage = ClockAuctionStorage(_storageAddress);
}
function setOwnerCut(uint256 _cut) public onlyOwner {
require(_cut <= 10000);
ownerCut = _cut;
}
function setMinCutValue(uint256 _minCutValue) public onlyOwner {
minCutValue = _minCutValue;
}
function getMinPrice() public view returns (uint256) {
// return ownerCut > 0 ? (minCutValue / ownerCut * 10000) : 0;
// use minCutValue directly, when the price == minCutValue seller will get no profit
return minCutValue;
}
// Only auction from none system user need to verify the price
// System auction can set any price
function isValidPrice(uint256 _startingPrice, uint256 _endingPrice) public view returns (bool) {
return (_startingPrice < _endingPrice ? _startingPrice : _endingPrice) >= getMinPrice();
}
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
public
whenNotPaused
{
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(msg.sender == address(nonFungibleContract));
// assigning ownership to this clockAuctionStorage when in auction
// it will throw if transfer fails
nonFungibleContract.transferFrom(_seller, address(clockAuctionStorage), _tokenId);
// Require that all auctions have a duration of at least one minute.
require(_duration >= 1 minutes);
clockAuctionStorage.addAuction(
_tokenId,
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
emit AuctionCreated(_tokenId, _startingPrice, _endingPrice, _duration);
}
function cancelAuction(uint256 _tokenId) external {
require(clockAuctionStorage.isOnAuction(_tokenId));
address seller = clockAuctionStorage.getSeller(_tokenId);
require(msg.sender == seller);
_cancelAuction(_tokenId, seller);
}
function cancelAuctionWhenPaused(uint256 _tokenId) external whenPaused onlyOwner {
require(clockAuctionStorage.isOnAuction(_tokenId));
address seller = clockAuctionStorage.getSeller(_tokenId);
_cancelAuction(_tokenId, seller);
}
function getAuction(uint256 _tokenId)
public
view
returns
(
address seller,
uint256 startingPrice,
uint256 endingPrice,
uint256 duration,
uint256 startedAt
) {
require(clockAuctionStorage.isOnAuction(_tokenId));
return clockAuctionStorage.getAuction(_tokenId);
}
function getCurrentPrice(uint256 _tokenId)
external
view
returns (uint256)
{
require(clockAuctionStorage.isOnAuction(_tokenId));
return _currentPrice(_tokenId);
}
function _cancelAuction(uint256 _tokenId, address _seller) internal {
clockAuctionStorage.removeAuction(_tokenId);
clockAuctionStorage.transfer(nonFungibleContract, _seller, _tokenId);
emit AuctionCancelled(_tokenId);
}
function _bid(uint256 _tokenId, uint256 _bidAmount, address bidder) internal returns (uint256) {
require(clockAuctionStorage.isOnAuction(_tokenId));
// Check that the bid is greater than or equal to the current price
uint256 price = _currentPrice(_tokenId);
require(_bidAmount >= price);
address seller = clockAuctionStorage.getSeller(_tokenId);
uint256 sellerProceeds = 0;
// Remove the auction before sending the fees to the sender so we can't have a reentrancy attack
clockAuctionStorage.removeAuction(_tokenId);
// Transfer proceeds to seller (if there are any!)
if (price > 0) {
// Calculate the auctioneer's cut, so this subtraction can't go negative
uint256 auctioneerCut = _computeCut(price);
sellerProceeds = price - auctioneerCut;
// transfer the sellerProceeds
seller.transfer(sellerProceeds);
}
// Calculate any excess funds included with the bid
// transfer it back to bidder.
// this cannot underflow.
uint256 bidExcess = _bidAmount - price;
bidder.transfer(bidExcess);
emit AuctionSuccessful(_tokenId, price, bidder, seller, sellerProceeds);
return price;
}
function _currentPrice(uint256 _tokenId) internal view returns (uint256) {
uint256 secondsPassed = 0;
address seller;
uint128 startingPrice;
uint128 endingPrice;
uint64 duration;
uint64 startedAt;
(seller, startingPrice, endingPrice, duration, startedAt) = clockAuctionStorage.getAuction(_tokenId);
if (now > startedAt) {
secondsPassed = now - startedAt;
}
return _computeCurrentPrice(
startingPrice,
endingPrice,
duration,
secondsPassed
);
}
function _computeCurrentPrice(
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
uint256 _secondsPassed
)
internal
pure
returns (uint256)
{
if (_secondsPassed >= _duration) {
return _endingPrice;
} else {
// this delta can be negative.
int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice);
// This multiplication can't overflow, _secondsPassed will easily fit within
// 64-bits, and totalPriceChange will easily fit within 128-bits, their product
// will always fit within 256-bits.
int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration);
// this result will always end up positive.
int256 currentPrice = int256(_startingPrice) + currentPriceChange;
return uint256(currentPrice);
}
}
function _computeCut(uint256 _price) internal view returns (uint256) {
uint256 cutValue = _price * ownerCut / 10000;
if (_price < minCutValue) return cutValue;
if (cutValue > minCutValue) return cutValue;
return minCutValue;
}
}
contract SaleClockAuction is ClockAuction {
bool public isSaleClockAuction = true;
address public systemSaleAddress;
uint256 public systemStartingPriceMin = 20 finney;
uint256 public systemEndingPrice = 0;
uint256 public systemAuctionDuration = 1 days;
function SaleClockAuction(address _nftAddr, address _storageAddress, address _systemSaleAddress, uint256 _cut, uint256 _minCutValue)
ClockAuction(_nftAddr, _storageAddress, _cut, _minCutValue) public
{
require(SaleClockAuctionStorage(_storageAddress).isSaleClockAuctionStorage());
setSystemSaleAddress(_systemSaleAddress);
}
function bid(uint256 _tokenId) external payable {
uint256 price = _bid(_tokenId, msg.value, msg.sender);
clockAuctionStorage.transfer(nonFungibleContract, msg.sender, _tokenId);
SaleClockAuctionStorage(clockAuctionStorage).recordSoldPrice(price);
}
function createSystemAuction(uint256 _tokenId) external {
require(msg.sender == address(nonFungibleContract));
createAuction(
_tokenId,
computeNextSystemSalePrice(),
systemEndingPrice,
systemAuctionDuration,
systemSaleAddress
);
SaleClockAuctionStorage(clockAuctionStorage).recordSystemOnSaleToken(_tokenId);
}
function setSystemSaleAddress(address _systemSaleAddress) public onlyOwner {
require(_systemSaleAddress != address(0));
systemSaleAddress = _systemSaleAddress;
}
function setSystemStartingPriceMin(uint256 _startingPrice) external onlyOwner {
require(_startingPrice == uint256(uint128(_startingPrice)));
systemStartingPriceMin = _startingPrice;
}
function setSystemEndingPrice(uint256 _endingPrice) external onlyOwner {
require(_endingPrice == uint256(uint128(_endingPrice)));
systemEndingPrice = _endingPrice;
}
function setSystemAuctionDuration(uint256 _duration) external onlyOwner {
require(_duration == uint256(uint64(_duration)));
systemAuctionDuration = _duration;
}
function totalSoldCount() external view returns (uint256) {
return SaleClockAuctionStorage(clockAuctionStorage).totalSoldCount();
}
function systemOnSaleCount() external view returns (uint256) {
return SaleClockAuctionStorage(clockAuctionStorage).systemOnSaleCount();
}
function averageSoldPrice() external view returns (uint256) {
return SaleClockAuctionStorage(clockAuctionStorage).averageSoldPrice();
}
function computeNextSystemSalePrice() public view returns (uint256) {
uint256 avePrice = SaleClockAuctionStorage(clockAuctionStorage).averageSoldPrice();
require(avePrice == uint256(uint128(avePrice)));
uint256 nextPrice = avePrice + (avePrice / 2);
if (nextPrice < systemStartingPriceMin) {
nextPrice = systemStartingPriceMin;
}
return nextPrice;
}
}
contract SiringClockAuctionStorage is ClockAuctionStorage {
bool public isSiringClockAuctionStorage = true;
}
contract SiringClockAuction is ClockAuction {
bool public isSiringClockAuction = true;
function SiringClockAuction(address _nftAddr, address _storageAddress, uint256 _cut, uint256 _minCutValue)
ClockAuction(_nftAddr, _storageAddress, _cut, _minCutValue) public
{
require(SiringClockAuctionStorage(_storageAddress).isSiringClockAuctionStorage());
}
function bid(uint256 _tokenId, address bidder) external payable {
// can only be called by CryptoZoo
require(msg.sender == address(nonFungibleContract));
// get seller before the _bid for the auction will be removed once the bid success
address seller = clockAuctionStorage.getSeller(_tokenId);
// _bid checks that token ID is valid and will throw if bid fails
_bid(_tokenId, msg.value, bidder);
// transfer the monster back to the seller, the winner will get the child
clockAuctionStorage.transfer(nonFungibleContract, seller, _tokenId);
}
}
contract ZooAccessControl is HasNoContracts {
address public ceoAddress;
address public cfoAddress;
address public cooAddress;
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
modifier onlyCLevel() {
require(
msg.sender == cooAddress ||
msg.sender == ceoAddress ||
msg.sender == cfoAddress
);
_;
}
function setCEO(address _newCEO) public onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
function setCFO(address _newCFO) public onlyCEO {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
function setCOO(address _newCOO) public onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
}
contract Zoo721 is ZooAccessControl, ERC721 {
// ERC721 Required
string public constant name = "Giftomon";
// ERC721 Required
string public constant symbol = "GTOM";
bytes4 constant InterfaceSignature_ERC165 =
bytes4(keccak256("supportsInterface(bytes4)"));
bytes4 constant InterfaceSignature_ERC721 =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('transfer(address,uint256)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('tokensOfOwner(address)'));
CryptoStorage public cryptoStorage;
function Zoo721(address _storageAddress) public {
require(_storageAddress != address(0));
cryptoStorage = CryptoStorage(_storageAddress);
}
// ERC165 Required
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
// ERC721 Required
function totalSupply() public view returns (uint) {
return cryptoStorage.getMonsterCount();
}
// ERC721 Required
function balanceOf(address _owner) public view returns (uint256 count) {
return cryptoStorage.ownershipTokenCount(_owner);
}
// ERC721 Required
function ownerOf(uint256 _tokenId) external view returns (address owner) {
owner = cryptoStorage.monsterIndexToOwner(_tokenId);
require(owner != address(0));
}
// ERC721 Required
function approve(address _to, uint256 _tokenId) external whenNotPaused {
require(_owns(msg.sender, _tokenId));
_approve(_tokenId, _to);
emit Approval(msg.sender, _to, _tokenId);
}
// ERC721 Required
function transfer(address _to, uint256 _tokenId) external whenNotPaused {
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Not allow to transfer to the contract itself except for system sale monsters
require(_to != address(this));
// You can only send your own cat.
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
// ERC721 Required
function transferFrom(address _from, address _to, uint256 _tokenId) external whenNotPaused {
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
require(_to != address(this));
// Check for approval and valid ownership
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
// ERC721 Optional
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalTokens = totalSupply();
uint256 resultIndex = 0;
uint256 tokenId;
for (tokenId = 1; tokenId <= totalTokens; tokenId++) {
if (cryptoStorage.monsterIndexToOwner(tokenId) == _owner) {
result[resultIndex] = tokenId;
resultIndex++;
}
}
return result;
}
}
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// increase number of token owned by _to
cryptoStorage.increaseOwnershipTokenCount(_to);
// transfer ownership
cryptoStorage.setMonsterIndexToOwner(_tokenId, _to);
// new monster born does not have previous owner
if (_from != address(0)) {
// decrease number of token owned by _from
cryptoStorage.decreaseOwnershipTokenCount(_from);
// clear any previously approved ownership exchange
cryptoStorage.deleteMonsterIndexToApproved(_tokenId);
}
emit Transfer(_from, _to, _tokenId);
}
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return cryptoStorage.monsterIndexToOwner(_tokenId) == _claimant;
}
function _approve(uint256 _tokenId, address _approved) internal {
cryptoStorage.setMonsterIndexToApproved(_tokenId, _approved);
}
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return cryptoStorage.monsterIndexToApproved(_tokenId) == _claimant;
}
}
contract CryptoZoo is Zoo721 {
uint256 public constant SYSTEM_CREATION_LIMIT = 10000;
// new monster storage fee for the coo
uint256 public autoBirthFee = 2 finney;
// an approximation of currently how many seconds are in between blocks.
uint256 public secondsPerBlock = 15;
// hatch duration in second by hatch times (start from 0)
// default to 1 minute if not set and minimum to 1 minute
// must be an integral multiple of 1 minute
uint32[] public hatchDurationByTimes = [uint32(1 minutes)];
// hatch duration multiple value by generation (start from 0)
// multiple = value / 60, 60 is the base value
// default to 60 if not set and minimum to 60
// must be an integral multiple of secondsPerBlock
uint32[] public hatchDurationMultiByGeneration = [uint32(60)];
// sale auctions
SaleClockAuction public saleAuction;
// siring auctions
SiringClockAuction public siringAuction;
// activity core
ActivityCore public activityCore;
// events
event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 matronCooldownEndBlock, uint256 sireCooldownEndBlock, uint256 breedCost);
event Birth(address owner, uint256 tokenId, uint256 matronId, uint256 sireId);
// Core Contract of Giftomon
function CryptoZoo(address _storageAddress, address _cooAddress, address _cfoAddress) Zoo721(_storageAddress) public {
// paused by default
paused = true;
// ceo defaults the the contract creator
ceoAddress = msg.sender;
setCOO(_cooAddress);
setCFO(_cfoAddress);
}
function() external payable {
require(
msg.sender == address(saleAuction) ||
msg.sender == address(siringAuction) ||
msg.sender == address(activityCore) ||
msg.sender == cooAddress
);
}
// override to allow any CLevel to pause the contract
function pause() public onlyCLevel whenNotPaused {
super.pause();
}
// override to make sure everything is initialized before the unpause
function unpause() public onlyCEO whenPaused {
// can not unpause when CLevel addresses is not initialized
require(ceoAddress != address(0));
require(cooAddress != address(0));
require(cfoAddress != address(0));
// can not unpause when the logic contract is not initialzed
require(saleAuction != address(0));
require(siringAuction != address(0));
require(activityCore != address(0));
require(cryptoStorage != address(0));
// can not unpause when ownership of storage contract is not the current contract
require(cryptoStorage.owner() == address(this));
super.unpause();
}
// Very dangerous action, only when new contract has been proved working
// Requires cryptoStorage already transferOwnership to the new contract
// This method is only used to transfer the balance (authBirthFee used for giveBirth) to ceo
function destroy() external onlyCEO whenPaused {
address storageOwner = cryptoStorage.owner();
// owner of cryptoStorage must not be the current contract otherwise the cryptoStorage will forever in accessable
require(storageOwner != address(this));
// Transfers the current balance to the ceo and terminates the contract
selfdestruct(ceoAddress);
}
// Very dangerous action, only when new contract has been proved working
// Requires cryptoStorage already transferOwnership to the new contract
// This method is only used to transfer the balance (authBirthFee used for giveBirth) to the new contract
function destroyAndSendToStorageOwner() external onlyCEO whenPaused {
address storageOwner = cryptoStorage.owner();
// owner of cryptoStorage must not be the current contract otherwise the cryptoStorage will forever in accessable
require(storageOwner != address(this));
// Transfers the current balance to the new owner of the storage contract and terminates the contract
selfdestruct(storageOwner);
}
function setSaleAuctionAddress(address _address) external onlyCEO {
SaleClockAuction candidateContract = SaleClockAuction(_address);
require(candidateContract.isSaleClockAuction());
saleAuction = candidateContract;
}
function setSiringAuctionAddress(address _address) external onlyCEO {
SiringClockAuction candidateContract = SiringClockAuction(_address);
require(candidateContract.isSiringClockAuction());
siringAuction = candidateContract;
}
function setActivityCoreAddress(address _address) external onlyCEO {
ActivityCore candidateContract = ActivityCore(_address);
require(candidateContract.isActivityCore());
activityCore = candidateContract;
}
function withdrawBalance() external onlyCLevel {
uint256 balance = address(this).balance;
// Subtract all the currently pregnant kittens we have, plus 1 of margin.
uint256 subtractFees = (cryptoStorage.pregnantMonsters() + 1) * autoBirthFee;
if (balance > subtractFees) {
cfoAddress.transfer(balance - subtractFees);
}
}
function withdrawBalancesToNFC() external onlyCLevel {
saleAuction.withdrawBalance();
siringAuction.withdrawBalance();
activityCore.withdrawBalance();
cryptoStorage.withdrawBalance();
}
function withdrawBalancesToLogic() external onlyCLevel {
saleAuction.withdrawBalanceFromStorageContract();
siringAuction.withdrawBalanceFromStorageContract();
activityCore.withdrawBalanceFromStorageContract();
}
function setAutoBirthFee(uint256 val) external onlyCOO {
autoBirthFee = val;
}
function setAllHatchConfigs(
uint32[] _durationByTimes,
uint256 _secs,
uint32[] _multiByGeneration
)
external
onlyCLevel
{
setHatchDurationByTimes(_durationByTimes);
setSecondsPerBlock(_secs);
setHatchDurationMultiByGeneration(_multiByGeneration);
}
function setSecondsPerBlock(uint256 _secs) public onlyCLevel {
require(_secs < hatchDurationByTimes[0]);
secondsPerBlock = _secs;
}
// we must do a carefully check when set hatch duration configuration, since wrong value may break the whole cooldown logic
function setHatchDurationByTimes(uint32[] _durationByTimes) public onlyCLevel {
uint256 len = _durationByTimes.length;
// hatch duration should not be empty
require(len > 0);
// check overflow
require(len == uint256(uint16(len)));
delete hatchDurationByTimes;
uint32 value;
for (uint256 idx = 0; idx < len; idx++) {
value = _durationByTimes[idx];
// duration must be larger than 1 minute, and must be an integral multiple of 1 minute
require(value >= 1 minutes && value % 1 minutes == 0);
hatchDurationByTimes.push(value);
}
}
function getHatchDurationByTimes() external view returns (uint32[]) {
return hatchDurationByTimes;
}
// we must do a carefully check when set hatch duration multi configuration, since wrong value may break the whole cooldown logic
function setHatchDurationMultiByGeneration(uint32[] _multiByGeneration) public onlyCLevel {
uint256 len = _multiByGeneration.length;
// multi configuration should not be empty
require(len > 0);
// check overflow
require(len == uint256(uint16(len)));
delete hatchDurationMultiByGeneration;
uint32 value;
for (uint256 idx = 0; idx < len; idx++) {
value = _multiByGeneration[idx];
// multiple must be larger than 60, and must be an integral multiple of secondsPerBlock
require(value >= 60 && value % secondsPerBlock == 0);
hatchDurationMultiByGeneration.push(value);
}
}
function getHatchDurationMultiByGeneration() external view returns (uint32[]) {
return hatchDurationMultiByGeneration;
}
function createPromoMonster(
uint32 _monsterId,
bytes _properties,
address _owner
)
public
onlyCOO
whenNotPaused
{
require(_owner != address(0));
_createMonster(
0,
0,
0,
uint64(now),
_monsterId,
_properties,
_owner
);
cryptoStorage.increasePromoCreatedCount();
}
function createPromoMonsterWithTokenId(
uint32 _monsterId,
bytes _properties,
address _owner,
uint256 _tokenId
)
external
onlyCOO
whenNotPaused
{
require(_tokenId > 0 && cryptoStorage.getMonsterCount() + 1 == _tokenId);
createPromoMonster(_monsterId, _properties, _owner);
}
function createSystemSaleAuction(
uint32 _monsterId,
bytes _properties,
uint16 _generation
)
external
onlyCOO
whenNotPaused
{
require(cryptoStorage.systemCreatedCount() < SYSTEM_CREATION_LIMIT);
uint256 tokenId = _createMonster(
0,
0,
_generation,
uint64(now),
_monsterId,
_properties,
saleAuction.systemSaleAddress()
);
_approve(tokenId, saleAuction);
saleAuction.createSystemAuction(tokenId);
cryptoStorage.increaseSystemCreatedCount();
}
function createSaleAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
external
whenNotPaused
{
require(_tokenId > 0);
require(_owns(msg.sender, _tokenId));
// the monster must not pregnant othewise the birth child may owned by the the sale auction or the buyer
require(!isPregnant(_tokenId));
require(saleAuction.isValidPrice(_startingPrice, _endingPrice));
_approve(_tokenId, saleAuction);
// Sale auction throws if inputs are invalid and approve status will be reverted
saleAuction.createAuction(
_tokenId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
function createSiringAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
external
whenNotPaused
{
require(_tokenId > 0);
require(_owns(msg.sender, _tokenId));
require(isReadyToBreed(_tokenId));
require(siringAuction.isValidPrice(_startingPrice, _endingPrice));
_approve(_tokenId, siringAuction);
// Siring auction throws if inputs are invalid and approve status will be reverted
siringAuction.createAuction(
_tokenId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
// breed with the monster siring on market
function bidOnSiringAuction(
uint256 _sireId,
uint256 _matronId
)
external
payable
whenNotPaused
{
require(_matronId > 0);
require(_owns(msg.sender, _matronId));
require(isReadyToBreed(_matronId));
require(isValidMatingPair(_matronId, _sireId));
// Define the current price of the auction.
uint256 currentPrice = siringAuction.getCurrentPrice(_sireId);
uint256 breedCost = currentPrice + autoBirthFee;
require(msg.value >= breedCost);
// Siring auction will throw if the bid fails.
siringAuction.bid.value(msg.value - autoBirthFee)(_sireId, msg.sender);
_breedWith(_matronId, _sireId, breedCost);
}
// breed with the monster of one's own
function breedWithAuto(uint256 _matronId, uint256 _sireId)
external
payable
whenNotPaused
{
// Checks for payment.
require(msg.value >= autoBirthFee);
// Caller must own the matron and sire
require(_owns(msg.sender, _matronId));
require(_owns(msg.sender, _sireId));
// any monster in auction will be owned by the auction contract address,
// so the monster must not in auction if it's owned by the msg.sender
// Make sure matron isn't pregnant, or in the middle of a siring cooldown
require(isReadyToBreed(_matronId));
// Make sure sire isn't pregnant, or in the middle of a siring cooldown
require(isReadyToBreed(_sireId));
// Test that these cats are a valid mating pair.
require(isValidMatingPair(_matronId, _sireId));
// All checks passed, monster gets pregnant!
_breedWith(_matronId, _sireId, autoBirthFee);
}
function giveBirth(uint256 _matronId, uint256 _monsterId, uint256 _birthTime, bytes _properties)
external
whenNotPaused
onlyCOO
returns (uint256)
{
// the matron is a valid monster
require(cryptoStorage.getBirthTime(_matronId) != 0);
uint256 sireId = cryptoStorage.getSiringWithId(_matronId);
// the matron is pregnant if and only if this field is set
require(sireId != 0);
// no need to check cooldown of matron or sire
// since giveBirth can only be called by COO
// determine higher generation of the parents
uint16 parentGen = cryptoStorage.getGeneration(_matronId);
uint16 sireGen = cryptoStorage.getGeneration(sireId);
if (sireGen > parentGen) parentGen = sireGen;
address owner = cryptoStorage.monsterIndexToOwner(_matronId);
uint256 tokenId = _createMonster(
_matronId,
sireId,
parentGen + 1,
_birthTime,
_monsterId,
_properties,
owner
);
// clear pregnant related info
cryptoStorage.deleteSiringWithId(_matronId);
// decrease pregnant counter.
cryptoStorage.decreasePregnantCounter();
// send the blockchain storage fee to the coo
msg.sender.transfer(autoBirthFee);
return tokenId;
}
function computeCooldownSeconds(uint16 _hatchTimes, uint16 _generation) public view returns (uint32) {
require(hatchDurationByTimes.length > 0);
require(hatchDurationMultiByGeneration.length > 0);
uint16 hatchTimesMax = uint16(hatchDurationByTimes.length - 1);
uint16 hatchTimes = (_hatchTimes > hatchTimesMax ? hatchTimesMax : _hatchTimes);
uint16 generationMax = uint16(hatchDurationMultiByGeneration.length - 1);
uint16 generation = (_generation > generationMax ? generationMax : _generation);
return hatchDurationByTimes[hatchTimes] * hatchDurationMultiByGeneration[generation] / 60;
}
function isReadyToBreed(uint256 _tokenId) public view returns (bool) {
// not pregnant and not in cooldown
return (cryptoStorage.getSiringWithId(_tokenId) == 0) && (cryptoStorage.getCooldownEndBlock(_tokenId) <= uint64(block.number));
}
function isPregnant(uint256 _tokenId) public view returns (bool) {
// A monster is pregnant if and only if this field is set
return cryptoStorage.getSiringWithId(_tokenId) != 0;
}
function isValidMatingPair(uint256 _matronId, uint256 _sireId) public view returns (bool) {
// can't breed with itself!
if (_matronId == _sireId) {
return false;
}
uint32 matron_of_matron = cryptoStorage.getMatronId(_matronId);
uint32 sire_of_matron = cryptoStorage.getSireId(_matronId);
uint32 matron_of_sire = cryptoStorage.getMatronId(_sireId);
uint32 sire_of_sire = cryptoStorage.getSireId(_sireId);
// can't breed with their parents.
if (matron_of_matron == _sireId || sire_of_matron == _sireId) return false;
if (matron_of_sire == _matronId || sire_of_sire == _matronId) return false;
// if either cat is gen zero, they can breed without siblings check
if (matron_of_sire == 0 || matron_of_matron == 0) return true;
// can't breed with full or half siblings.
if (matron_of_sire == matron_of_matron || matron_of_sire == sire_of_matron) return false;
if (sire_of_sire == matron_of_matron || sire_of_sire == sire_of_matron) return false;
return true;
}
function _createMonster(
uint256 _matronId,
uint256 _sireId,
uint256 _generation,
uint256 _birthTime,
uint256 _monsterId,
bytes _properties,
address _owner
)
internal
returns (uint256)
{
uint256 tokenId = cryptoStorage.createMonster(
_matronId,
_sireId,
_generation,
_birthTime,
_monsterId,
_properties
);
_transfer(0, _owner, tokenId);
emit Birth(_owner, tokenId, _matronId, _sireId);
return tokenId;
}
function _breedWith(uint256 _matronId, uint256 _sireId, uint256 _breedCost) internal {
// Mark the matron as pregnant, keeping track of who the sire is.
cryptoStorage.setSiringWithId(_matronId, uint32(_sireId));
// Trigger the cooldown for both parents.
uint64 sireCooldownEndBlock = _triggerCooldown(_sireId);
uint64 matronCooldownEndBlock = _triggerCooldown(_matronId);
// increase pregnant counter.
cryptoStorage.increasePregnantCounter();
// give birth time depends on the shorter cooldown of the two parents
emit Pregnant(
cryptoStorage.monsterIndexToOwner(_matronId),
_matronId,
_sireId,
matronCooldownEndBlock,
sireCooldownEndBlock,
_breedCost
);
}
// Compute an estimation of the cooldown time in blocks (based on current cooldownIndex).
function _triggerCooldown(uint256 _tokenId) internal returns (uint64) {
uint32 cooldownSeconds = computeCooldownSeconds(cryptoStorage.getCooldownIndex(_tokenId), cryptoStorage.getGeneration(_tokenId));
uint64 cooldownEndBlock = uint64((cooldownSeconds / secondsPerBlock) + block.number);
cryptoStorage.setCooldownEndBlock(_tokenId, cooldownEndBlock);
// increate hatch times by 1
cryptoStorage.setCooldownIndex(_tokenId);
return cooldownEndBlock;
}
}
|
Only auction from none system user need to verify the price System auction can set any price
|
function isValidPrice(uint256 _startingPrice, uint256 _endingPrice) public view returns (bool) {
return (_startingPrice < _endingPrice ? _startingPrice : _endingPrice) >= getMinPrice();
}
| 34,050
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./interfaces/vesper/IVesperPool.sol";
import "./interfaces/aave/IAave.sol";
import "./interfaces/dydx/ISoloMargin.sol";
/**
* @title FlashLoanHelper:: This contract does all heavy lifting to get flash loan via Aave and DyDx.
* @dev End user has to override _flashLoanLogic() function to perform logic after flash loan is done.
* Also needs to approve token to aave and dydx via _approveToken function.
* 2 utility internal functions are also provided to activate/deactivate flash loan providers.
* Utility function are provided as internal so that end user can choose controlled access via public functions.
*/
abstract contract FlashLoanHelper {
using SafeERC20 for IERC20;
AaveLendingPoolAddressesProvider internal aaveAddressesProvider;
address internal constant SOLO = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
uint256 public dyDxMarketId;
bytes32 private constant AAVE_PROVIDER_ID = 0x0100000000000000000000000000000000000000000000000000000000000000;
bool public isAaveActive = false;
bool public isDyDxActive = false;
constructor(address _aaveAddressesProvider) {
require(_aaveAddressesProvider != address(0), "invalid-aave-provider");
aaveAddressesProvider = AaveLendingPoolAddressesProvider(_aaveAddressesProvider);
}
function _updateAaveStatus(bool _status) internal {
isAaveActive = _status;
}
function _updateDyDxStatus(bool _status, address _token) internal {
if (_status) {
dyDxMarketId = _getMarketIdFromTokenAddress(SOLO, _token);
}
isDyDxActive = _status;
}
/// @notice Approve all required tokens for flash loan
function _approveToken(address _token, uint256 _amount) internal {
IERC20(_token).safeApprove(SOLO, _amount);
IERC20(_token).safeApprove(aaveAddressesProvider.getLendingPool(), _amount);
}
/// @dev Override this function to execute logic which uses flash loan amount
function _flashLoanLogic(bytes memory _data, uint256 _repayAmount) internal virtual;
/***************************** Aave flash loan functions ***********************************/
bool private awaitingFlash = false;
/**
* @notice This is entry point for Aave flash loan
* @param _token Token for which we are taking flash loan
* @param _amountDesired Flash loan amount
* @param _data This will be passed downstream for processing. It can be empty.
*/
function _doAaveFlashLoan(
address _token,
uint256 _amountDesired,
bytes memory _data
) internal returns (uint256 _amount) {
require(isAaveActive, "aave-flash-loan-is-not-active");
AaveLendingPool _aaveLendingPool = AaveLendingPool(aaveAddressesProvider.getLendingPool());
AaveProtocolDataProvider _aaveProtocolDataProvider =
AaveProtocolDataProvider(aaveAddressesProvider.getAddress(AAVE_PROVIDER_ID));
// Check token liquidity in Aave
(uint256 _availableLiquidity, , , , , , , , , ) = _aaveProtocolDataProvider.getReserveData(_token);
if (_amountDesired > _availableLiquidity) {
_amountDesired = _availableLiquidity;
}
address[] memory assets = new address[](1);
assets[0] = _token;
uint256[] memory amounts = new uint256[](1);
amounts[0] = _amountDesired;
// 0 = no debt, 1 = stable, 2 = variable
uint256[] memory modes = new uint256[](1);
modes[0] = 0;
// Anyone can call aave flash loan to us, so we need some protection
awaitingFlash = true;
// function params: receiver, assets, amounts, modes, onBehalfOf, data, referralCode
_aaveLendingPool.flashLoan(address(this), assets, amounts, modes, address(this), _data, 0);
_amount = _amountDesired;
awaitingFlash = false;
}
/// @dev Aave will call this function after doing flash loan
function executeOperation(
address[] calldata, /*_assets*/
uint256[] calldata _amounts,
uint256[] calldata _premiums,
address _initiator,
bytes calldata _data
) external returns (bool) {
require(msg.sender == aaveAddressesProvider.getLendingPool(), "!aave-pool");
require(awaitingFlash, "invalid-flash-loan");
require(_initiator == address(this), "invalid-initiator");
// Flash loan amount + flash loan fee
uint256 _repayAmount = _amounts[0] + _premiums[0];
_flashLoanLogic(_data, _repayAmount);
return true;
}
/***************************** Aave flash loan functions ends ***********************************/
/***************************** DyDx flash loan functions ***************************************/
/**
* @notice This is entry point for DyDx flash loan
* @param _token Token for which we are taking flash loan
* @param _amountDesired Flash loan amount
* @param _data This will be passed downstream for processing. It can be empty.
*/
function _doDyDxFlashLoan(
address _token,
uint256 _amountDesired,
bytes memory _data
) internal returns (uint256 _amount) {
require(isDyDxActive, "dydx-flash-loan-is-not-active");
// Check token liquidity in DyDx
uint256 amountInSolo = IERC20(_token).balanceOf(SOLO);
if (_amountDesired > amountInSolo) {
_amountDesired = amountInSolo;
}
// Repay amount, amount with fee, can be 2 wei higher. Consider 2 wei as fee
uint256 repayAmount = _amountDesired + 2;
// Encode custom data for callFunction
bytes memory _callData = abi.encode(_data, repayAmount);
// 1. Withdraw _token
// 2. Call callFunction(...) which will call loanLogic
// 3. Deposit _token back
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(dyDxMarketId, _amountDesired);
operations[1] = _getCallAction(_callData);
operations[2] = _getDepositAction(dyDxMarketId, repayAmount);
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
ISoloMargin(SOLO).operate(accountInfos, operations);
_amount = _amountDesired;
}
/// @dev DyDx calls this function after doing flash loan
function callFunction(
address _sender,
Account.Info memory, /* _account */
bytes memory _callData
) external {
(bytes memory _data, uint256 _repayAmount) = abi.decode(_callData, (bytes, uint256));
require(msg.sender == SOLO, "!solo");
require(_sender == address(this), "invalid-initiator");
_flashLoanLogic(_data, _repayAmount);
}
/********************************* DyDx helper functions *********************************/
function _getAccountInfo() internal view returns (Account.Info memory) {
return Account.Info({owner: address(this), number: 1});
}
function _getMarketIdFromTokenAddress(address _solo, address token) internal view returns (uint256) {
ISoloMargin solo = ISoloMargin(_solo);
uint256 numMarkets = solo.getNumMarkets();
address curToken;
for (uint256 i = 0; i < numMarkets; i++) {
curToken = solo.getMarketTokenAddress(i);
if (curToken == token) {
return i;
}
}
revert("no-marketId-found-for-token");
}
function _getWithdrawAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) {
return
Actions.ActionArgs({
actionType: Actions.ActionType.Withdraw,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: ""
});
}
function _getCallAction(bytes memory data) internal view returns (Actions.ActionArgs memory) {
return
Actions.ActionArgs({
actionType: Actions.ActionType.Call,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: 0
}),
primaryMarketId: 0,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: data
});
}
function _getDepositAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) {
return
Actions.ActionArgs({
actionType: Actions.ActionType.Deposit,
accountId: 0,
amount: Types.AssetAmount({
sign: true,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: ""
});
}
/***************************** DyDx flash loan functions end *****************************/
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface AaveLendingPoolAddressesProvider {
function getLendingPool() external view returns (address);
function getAddress(bytes32 id) external view returns (address);
}
interface AToken is IERC20 {
/**
* @dev Returns the address of the incentives controller contract
**/
function getIncentivesController() external view returns (address);
}
interface AaveIncentivesController {
function getRewardsBalance(address[] calldata assets, address user) external view returns (uint256);
function claimRewards(
address[] calldata assets,
uint256 amount,
address to
) external returns (uint256);
}
interface AaveLendingPool {
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
function withdraw(
address asset,
uint256 amount,
address to
) external returns (uint256);
function flashLoan(
address receiverAddress,
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata modes,
address onBehalfOf,
bytes calldata params,
uint16 referralCode
) external;
}
interface AaveProtocolDataProvider {
function getReserveTokensAddresses(address asset)
external
view
returns (
address aTokenAddress,
address stableDebtTokenAddress,
address variableDebtTokenAddress
);
function getReserveData(address asset)
external
view
returns (
uint256 availableLiquidity,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 stableBorrowRate,
uint256 averageStableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
uint40 lastUpdateTimestamp
);
}
//solhint-disable func-name-mixedcase
interface StakedAave is IERC20 {
function claimRewards(address to, uint256 amount) external;
function cooldown() external;
function stake(address onBehalfOf, uint256 amount) external;
function redeem(address to, uint256 amount) external;
function getTotalRewardsBalance(address staker) external view returns (uint256);
function stakersCooldowns(address staker) external view returns (uint256);
function COOLDOWN_SECONDS() external view returns (uint256);
function UNSTAKE_WINDOW() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
/* solhint-disable func-name-mixedcase */
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
interface ISwapManager {
event OracleCreated(address indexed _sender, address indexed _newOracle, uint256 _period);
function N_DEX() external view returns (uint256);
function ROUTERS(uint256 i) external view returns (IUniswapV2Router02);
function bestOutputFixedInput(
address _from,
address _to,
uint256 _amountIn
)
external
view
returns (
address[] memory path,
uint256 amountOut,
uint256 rIdx
);
function bestPathFixedInput(
address _from,
address _to,
uint256 _amountIn,
uint256 _i
) external view returns (address[] memory path, uint256 amountOut);
function bestInputFixedOutput(
address _from,
address _to,
uint256 _amountOut
)
external
view
returns (
address[] memory path,
uint256 amountIn,
uint256 rIdx
);
function bestPathFixedOutput(
address _from,
address _to,
uint256 _amountOut,
uint256 _i
) external view returns (address[] memory path, uint256 amountIn);
function safeGetAmountsOut(
uint256 _amountIn,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function unsafeGetAmountsOut(
uint256 _amountIn,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function safeGetAmountsIn(
uint256 _amountOut,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function unsafeGetAmountsIn(
uint256 _amountOut,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function comparePathsFixedInput(
address[] memory pathA,
address[] memory pathB,
uint256 _amountIn,
uint256 _i
) external view returns (address[] memory path, uint256 amountOut);
function comparePathsFixedOutput(
address[] memory pathA,
address[] memory pathB,
uint256 _amountOut,
uint256 _i
) external view returns (address[] memory path, uint256 amountIn);
function ours(address a) external view returns (bool);
function oracleCount() external view returns (uint256);
function oracleAt(uint256 idx) external view returns (address);
function getOracle(
address _tokenA,
address _tokenB,
uint256 _period,
uint256 _i
) external view returns (address);
function createOrUpdateOracle(
address _tokenA,
address _tokenB,
uint256 _period,
uint256 _i
) external returns (address oracleAddr);
function consultForFree(
address _from,
address _to,
uint256 _amountIn,
uint256 _period,
uint256 _i
) external view returns (uint256 amountOut, uint256 lastUpdatedAt);
/// get the data we want and pay the gas to update
function consult(
address _from,
address _to,
uint256 _amountIn,
uint256 _period,
uint256 _i
)
external
returns (
uint256 amountOut,
uint256 lastUpdatedAt,
bool updated
);
function updateOracles() external returns (uint256 updated, uint256 expected);
function updateOracles(address[] memory _oracleAddrs) external returns (uint256 updated, uint256 expected);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface CToken {
function accrueInterest() external returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function balanceOfUnderlying(address owner) 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 getAccountSnapshot(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function borrow(uint256 borrowAmount) external returns (uint256);
function mint() external payable; // For ETH
function mint(uint256 mintAmount) external returns (uint256); // For ERC20
function redeem(uint256 redeemTokens) external returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
function repayBorrow() external payable; // For ETH
function repayBorrow(uint256 repayAmount) external returns (uint256); // For ERC20
function transfer(address user, uint256 amount) external returns (bool);
function getCash() external view returns (uint256);
function transferFrom(
address owner,
address user,
uint256 amount
) external returns (bool);
function underlying() external view returns (address);
}
interface Comptroller {
function claimComp(address holder, address[] memory) external;
function enterMarkets(address[] memory cTokens) external returns (uint256[] memory);
function exitMarket(address cToken) external returns (uint256);
function compAccrued(address holder) external view returns (uint256);
function getAccountLiquidity(address account)
external
view
returns (
uint256,
uint256,
uint256
);
function markets(address market)
external
view
returns (
bool isListed,
uint256 collateralFactorMantissa,
bool isCompted
);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
/** In order to keep code/files short, all libraries and interfaces are trimmed as per Vesper need */
library Account {
enum Status {Normal, Liquid, Vapor}
struct Info {
address owner; // The address that owns the account
uint256 number; // A nonce that allows a single address to control many accounts
}
}
library Actions {
enum ActionType {
Deposit, // supply tokens
Withdraw, // borrow tokens
Transfer, // transfer balance between accounts
Buy, // buy an amount of some token (publicly)
Sell, // sell an amount of some token (publicly)
Trade, // trade tokens against another account
Liquidate, // liquidate an undercollateralized or expiring account
Vaporize, // use excess tokens to zero-out a completely negative account
Call // send arbitrary data to an address
}
struct ActionArgs {
ActionType actionType;
uint256 accountId;
Types.AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
}
library Types {
enum AssetDenomination {
Wei, // the amount is denominated in wei
Par // the amount is denominated in par
}
enum AssetReference {
Delta, // the amount is given as a delta from the current value
Target // the amount is given as an exact number to end up at
}
struct AssetAmount {
bool sign; // true if positive
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
}
interface ISoloMargin {
function getMarketTokenAddress(uint256 marketId) external view returns (address);
function getNumMarkets() external view returns (uint256);
function operate(Account.Info[] memory accounts, Actions.ActionArgs[] memory actions) external;
}
/**
* @title ICallee
* @author dYdX
*
* Interface that Callees for Solo must implement in order to ingest data.
*/
interface ICallee {
// ============ Public Functions ============
/**
* Allows users to send this contract arbitrary data.
*
* @param sender The msg.sender to Solo
* @param accountInfo The account from which the data is being sent
* @param data Arbitrary data given by the sender
*/
function callFunction(
address sender,
Account.Info memory accountInfo,
bytes memory data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
// Interface to use 3rd party Uniswap V3 oracle utility contract deployed at https://etherscan.io/address/0x0f1f5a87f99f0918e6c81f16e59f3518698221ff#code
/// @title UniswapV3 oracle with ability to query across an intermediate liquidity pool
interface IUniswapV3Oracle {
function assetToEth(
address _tokenIn,
uint256 _amountIn,
uint32 _twapPeriod
) external view returns (uint256 ethAmountOut);
function ethToAsset(
uint256 _ethAmountIn,
address _tokenOut,
uint32 _twapPeriod
) external view returns (uint256 amountOut);
function assetToAsset(
address _tokenIn,
uint256 _amountIn,
address _tokenOut,
uint32 _twapPeriod
) external view returns (uint256 amountOut);
function assetToAssetThruRoute(
address _tokenIn,
uint256 _amountIn,
address _tokenOut,
uint32 _twapPeriod,
address _routeThruToken,
uint24[2] memory _poolFees
) external view returns (uint256 amountOut);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface TokenLike is IERC20 {
function deposit() external payable;
function withdraw(uint256) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IStrategy {
function rebalance() external;
function sweepERC20(address _fromToken) external;
function withdraw(uint256 _amount) external;
function feeCollector() external view returns (address);
function isReservedToken(address _token) external view returns (bool);
function keepers() external view returns (address[] memory);
function migrate(address _newStrategy) external;
function token() external view returns (address);
function totalValue() external view returns (uint256);
function totalValueCurrent() external returns (uint256);
function pool() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IVesperPool is IERC20 {
function deposit() external payable;
function deposit(uint256 _share) external;
function multiTransfer(address[] memory _recipients, uint256[] memory _amounts) external returns (bool);
function excessDebt(address _strategy) external view returns (uint256);
function permit(
address,
address,
uint256,
uint256,
uint8,
bytes32,
bytes32
) external;
function poolRewards() external returns (address);
function reportEarning(
uint256 _profit,
uint256 _loss,
uint256 _payback
) external;
function reportLoss(uint256 _loss) external;
function resetApproval() external;
function sweepERC20(address _fromToken) external;
function withdraw(uint256 _amount) external;
function withdrawETH(uint256 _amount) external;
function whitelistedWithdraw(uint256 _amount) external;
function governor() external view returns (address);
function keepers() external view returns (address[] memory);
function isKeeper(address _address) external view returns (bool);
function maintainers() external view returns (address[] memory);
function isMaintainer(address _address) external view returns (bool);
function feeCollector() external view returns (address);
function pricePerShare() external view returns (uint256);
function strategy(address _strategy)
external
view
returns (
bool _active,
uint256 _interestFee,
uint256 _debtRate,
uint256 _lastRebalance,
uint256 _totalDebt,
uint256 _totalLoss,
uint256 _totalProfit,
uint256 _debtRatio
);
function stopEverything() external view returns (bool);
function token() external view returns (IERC20);
function tokensHere() external view returns (uint256);
function totalDebtOf(address _strategy) external view returns (uint256);
function totalValue() external view returns (uint256);
function withdrawFee() external view returns (uint256);
// Function to get pricePerShare from V2 pools
function getPricePerShare() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "../dependencies/openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "../interfaces/bloq/ISwapManager.sol";
import "../interfaces/vesper/IStrategy.sol";
import "../interfaces/vesper/IVesperPool.sol";
abstract contract Strategy is IStrategy, Context {
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
address internal constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint256 internal constant MAX_UINT_VALUE = type(uint256).max;
// solhint-disable-next-line var-name-mixedcase
address internal WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
IERC20 public immutable collateralToken;
address public receiptToken;
address public immutable override pool;
address public override feeCollector;
ISwapManager public swapManager;
uint256 public oraclePeriod = 3600; // 1h
uint256 public oracleRouterIdx = 0; // Uniswap V2
uint256 public swapSlippage = 10000; // 100% Don't use oracles by default
EnumerableSet.AddressSet private _keepers;
event UpdatedFeeCollector(address indexed previousFeeCollector, address indexed newFeeCollector);
event UpdatedSwapManager(address indexed previousSwapManager, address indexed newSwapManager);
event UpdatedSwapSlippage(uint256 oldSwapSlippage, uint256 newSwapSlippage);
event UpdatedOracleConfig(uint256 oldPeriod, uint256 newPeriod, uint256 oldRouterIdx, uint256 newRouterIdx);
constructor(
address _pool,
address _swapManager,
address _receiptToken
) {
require(_pool != address(0), "pool-address-is-zero");
require(_swapManager != address(0), "sm-address-is-zero");
swapManager = ISwapManager(_swapManager);
pool = _pool;
collateralToken = IVesperPool(_pool).token();
receiptToken = _receiptToken;
require(_keepers.add(_msgSender()), "add-keeper-failed");
}
modifier onlyGovernor {
require(_msgSender() == IVesperPool(pool).governor(), "caller-is-not-the-governor");
_;
}
modifier onlyKeeper() {
require(_keepers.contains(_msgSender()), "caller-is-not-a-keeper");
_;
}
modifier onlyPool() {
require(_msgSender() == pool, "caller-is-not-vesper-pool");
_;
}
/**
* @notice Add given address in keepers list.
* @param _keeperAddress keeper address to add.
*/
function addKeeper(address _keeperAddress) external onlyGovernor {
require(_keepers.add(_keeperAddress), "add-keeper-failed");
}
/// @notice Return list of keepers
function keepers() external view override returns (address[] memory) {
return _keepers.values();
}
/**
* @notice Migrate all asset and vault ownership,if any, to new strategy
* @dev _beforeMigration hook can be implemented in child strategy to do extra steps.
* @param _newStrategy Address of new strategy
*/
function migrate(address _newStrategy) external virtual override onlyPool {
require(_newStrategy != address(0), "new-strategy-address-is-zero");
require(IStrategy(_newStrategy).pool() == pool, "not-valid-new-strategy");
_beforeMigration(_newStrategy);
IERC20(receiptToken).safeTransfer(_newStrategy, IERC20(receiptToken).balanceOf(address(this)));
collateralToken.safeTransfer(_newStrategy, collateralToken.balanceOf(address(this)));
}
/**
* @notice Remove given address from keepers list.
* @param _keeperAddress keeper address to remove.
*/
function removeKeeper(address _keeperAddress) external onlyGovernor {
require(_keepers.remove(_keeperAddress), "remove-keeper-failed");
}
/**
* @notice Update fee collector
* @param _feeCollector fee collector address
*/
function updateFeeCollector(address _feeCollector) external onlyGovernor {
require(_feeCollector != address(0), "fee-collector-address-is-zero");
require(_feeCollector != feeCollector, "fee-collector-is-same");
emit UpdatedFeeCollector(feeCollector, _feeCollector);
feeCollector = _feeCollector;
}
/**
* @notice Update swap manager address
* @param _swapManager swap manager address
*/
function updateSwapManager(address _swapManager) external onlyGovernor {
require(_swapManager != address(0), "sm-address-is-zero");
require(_swapManager != address(swapManager), "sm-is-same");
emit UpdatedSwapManager(address(swapManager), _swapManager);
swapManager = ISwapManager(_swapManager);
}
function updateSwapSlippage(uint256 _newSwapSlippage) external onlyGovernor {
require(_newSwapSlippage <= 10000, "invalid-slippage-value");
emit UpdatedSwapSlippage(swapSlippage, _newSwapSlippage);
swapSlippage = _newSwapSlippage;
}
function updateOracleConfig(uint256 _newPeriod, uint256 _newRouterIdx) external onlyGovernor {
require(_newRouterIdx < swapManager.N_DEX(), "invalid-router-index");
if (_newPeriod == 0) _newPeriod = oraclePeriod;
require(_newPeriod > 59, "invalid-oracle-period");
emit UpdatedOracleConfig(oraclePeriod, _newPeriod, oracleRouterIdx, _newRouterIdx);
oraclePeriod = _newPeriod;
oracleRouterIdx = _newRouterIdx;
}
/// @dev Approve all required tokens
function approveToken() external onlyKeeper {
_approveToken(0);
_approveToken(MAX_UINT_VALUE);
}
function setupOracles() external onlyKeeper {
_setupOracles();
}
/**
* @dev Withdraw collateral token from lending pool.
* @param _amount Amount of collateral token
*/
function withdraw(uint256 _amount) external override onlyPool {
_withdraw(_amount);
}
/**
* @dev Rebalance profit, loss and investment of this strategy
*/
function rebalance() external virtual override onlyKeeper {
(uint256 _profit, uint256 _loss, uint256 _payback) = _generateReport();
IVesperPool(pool).reportEarning(_profit, _loss, _payback);
_reinvest();
}
/**
* @dev sweep given token to feeCollector of strategy
* @param _fromToken token address to sweep
*/
function sweepERC20(address _fromToken) external override onlyKeeper {
require(feeCollector != address(0), "fee-collector-not-set");
require(_fromToken != address(collateralToken), "not-allowed-to-sweep-collateral");
require(!isReservedToken(_fromToken), "not-allowed-to-sweep");
if (_fromToken == ETH) {
Address.sendValue(payable(feeCollector), address(this).balance);
} else {
uint256 _amount = IERC20(_fromToken).balanceOf(address(this));
IERC20(_fromToken).safeTransfer(feeCollector, _amount);
}
}
/// @notice Returns address of token correspond to collateral token
function token() external view override returns (address) {
return receiptToken;
}
/**
* @notice Calculate total value of asset under management
* @dev Report total value in collateral token
*/
function totalValue() public view virtual override returns (uint256 _value);
/**
* @notice Calculate total value of asset under management (in real-time)
* @dev Report total value in collateral token
*/
function totalValueCurrent() external virtual override returns (uint256) {
return totalValue();
}
/// @notice Check whether given token is reserved or not. Reserved tokens are not allowed to sweep.
function isReservedToken(address _token) public view virtual override returns (bool);
/**
* @notice some strategy may want to prepare before doing migration.
Example In Maker old strategy want to give vault ownership to new strategy
* @param _newStrategy .
*/
function _beforeMigration(address _newStrategy) internal virtual;
/**
* @notice Generate report for current profit and loss. Also liquidate asset to payback
* excess debt, if any.
* @return _profit Calculate any realized profit and convert it to collateral, if not already.
* @return _loss Calculate any loss that strategy has made on investment. Convert into collateral token.
* @return _payback If strategy has any excess debt, we have to liquidate asset to payback excess debt.
*/
function _generateReport()
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _payback
)
{
uint256 _excessDebt = IVesperPool(pool).excessDebt(address(this));
uint256 _totalDebt = IVesperPool(pool).totalDebtOf(address(this));
_profit = _realizeProfit(_totalDebt);
_loss = _realizeLoss(_totalDebt);
_payback = _liquidate(_excessDebt);
}
function _calcAmtOutAfterSlippage(uint256 _amount, uint256 _slippage) internal pure returns (uint256) {
return (_amount * (10000 - _slippage)) / (10000);
}
function _simpleOraclePath(address _from, address _to) internal view returns (address[] memory path) {
if (_from == WETH || _to == WETH) {
path = new address[](2);
path[0] = _from;
path[1] = _to;
} else {
path = new address[](3);
path[0] = _from;
path[1] = WETH;
path[2] = _to;
}
}
function _consultOracle(
address _from,
address _to,
uint256 _amt
) internal returns (uint256, bool) {
for (uint256 i = 0; i < swapManager.N_DEX(); i++) {
(bool _success, bytes memory _returnData) =
address(swapManager).call(
abi.encodePacked(swapManager.consult.selector, abi.encode(_from, _to, _amt, oraclePeriod, i))
);
if (_success) {
(uint256 rate, uint256 lastUpdate, ) = abi.decode(_returnData, (uint256, uint256, bool));
if ((lastUpdate > (block.timestamp - oraclePeriod)) && (rate != 0)) return (rate, true);
return (0, false);
}
}
return (0, false);
}
function _getOracleRate(address[] memory path, uint256 _amountIn) internal returns (uint256 amountOut) {
require(path.length > 1, "invalid-oracle-path");
amountOut = _amountIn;
bool isValid;
for (uint256 i = 0; i < path.length - 1; i++) {
(amountOut, isValid) = _consultOracle(path[i], path[i + 1], amountOut);
require(isValid, "invalid-oracle-rate");
}
}
/**
* @notice Safe swap via Uniswap / Sushiswap (better rate of the two)
* @dev There are many scenarios when token swap via Uniswap can fail, so this
* method will wrap Uniswap call in a 'try catch' to make it fail safe.
* however, this method will throw minAmountOut is not met
* @param _from address of from token
* @param _to address of to token
* @param _amountIn Amount to be swapped
* @param _minAmountOut minimum amount out
*/
function _safeSwap(
address _from,
address _to,
uint256 _amountIn,
uint256 _minAmountOut
) internal {
(address[] memory path, uint256 amountOut, uint256 rIdx) =
swapManager.bestOutputFixedInput(_from, _to, _amountIn);
if (_minAmountOut == 0) _minAmountOut = 1;
if (amountOut != 0) {
swapManager.ROUTERS(rIdx).swapExactTokensForTokens(
_amountIn,
_minAmountOut,
path,
address(this),
block.timestamp
);
}
}
// These methods can be implemented by the inheriting strategy.
/* solhint-disable no-empty-blocks */
function _claimRewardsAndConvertTo(address _toToken) internal virtual {}
/**
* @notice Set up any oracles that are needed for this strategy.
*/
function _setupOracles() internal virtual {}
/* solhint-enable */
// These methods must be implemented by the inheriting strategy
function _withdraw(uint256 _amount) internal virtual;
function _approveToken(uint256 _amount) internal virtual;
/**
* @notice Withdraw collateral to payback excess debt in pool.
* @param _excessDebt Excess debt of strategy in collateral token
* @return _payback amount in collateral token. Usually it is equal to excess debt.
*/
function _liquidate(uint256 _excessDebt) internal virtual returns (uint256 _payback);
/**
* @notice Calculate earning and withdraw/convert it into collateral token.
* @param _totalDebt Total collateral debt of this strategy
* @return _profit Profit in collateral token
*/
function _realizeProfit(uint256 _totalDebt) internal virtual returns (uint256 _profit);
/**
* @notice Calculate loss
* @param _totalDebt Total collateral debt of this strategy
* @return _loss Realized loss in collateral token
*/
function _realizeLoss(uint256 _totalDebt) internal virtual returns (uint256 _loss);
/**
* @notice Reinvest collateral.
* @dev Once we file report back in pool, we might have some collateral in hand
* which we want to reinvest aka deposit in lender/provider.
*/
function _reinvest() internal virtual;
}
// SPDX-License-Identifier: GNU LGPLv3
// Heavily inspired from CompoundLeverage strategy of Yearn. https://etherscan.io/address/0x4031afd3B0F71Bace9181E554A9E680Ee4AbE7dF#code
pragma solidity 0.8.3;
import "../Strategy.sol";
import "../../interfaces/compound/ICompound.sol";
import "../../interfaces/oracle/IUniswapV3Oracle.sol";
import "../../FlashLoanHelper.sol";
/// @title This strategy will deposit collateral token in Compound and based on position
/// it will borrow same collateral token. It will use borrowed asset as supply and borrow again.
contract CompoundLeverageStrategy is Strategy, FlashLoanHelper {
using SafeERC20 for IERC20;
// solhint-disable-next-line var-name-mixedcase
string public NAME;
string public constant VERSION = "4.0.0";
uint256 internal constant MAX_BPS = 10_000; //100%
uint256 public minBorrowRatio = 5_000; // 50%
uint256 public maxBorrowRatio = 6_000; // 60%
CToken internal cToken;
IUniswapV3Oracle internal constant ORACLE = IUniswapV3Oracle(0x0F1f5A87f99f0918e6C81F16E59F3518698221Ff);
uint32 internal constant TWAP_PERIOD = 3600;
Comptroller public immutable comptroller;
address public immutable rewardToken;
address public rewardDistributor;
event UpdatedBorrowRatio(
uint256 previousMinBorrowRatio,
uint256 newMinBorrowRatio,
uint256 previousMaxBorrowRatio,
uint256 newMaxBorrowRatio
);
constructor(
address _pool,
address _swapManager,
address _comptroller,
address _rewardDistributor,
address _rewardToken,
address _aaveAddressesProvider,
address _receiptToken,
string memory _name
) Strategy(_pool, _swapManager, _receiptToken) FlashLoanHelper(_aaveAddressesProvider) {
NAME = _name;
require(_comptroller != address(0), "comptroller-address-is-zero");
comptroller = Comptroller(_comptroller);
rewardToken = _rewardToken;
require(_receiptToken != address(0), "cToken-address-is-zero");
cToken = CToken(_receiptToken);
require(_rewardDistributor != address(0), "invalid-reward-distributor-addr");
rewardDistributor = _rewardDistributor;
}
/**
* @notice Update upper and lower borrow ratio
* @dev It is possible to set 0 as _minBorrowRatio to not borrow anything
* @param _minBorrowRatio Minimum % we want to borrow
* @param _maxBorrowRatio Maximum % we want to borrow
*/
function updateBorrowRatio(uint256 _minBorrowRatio, uint256 _maxBorrowRatio) external onlyGovernor {
(, uint256 _collateralFactor, ) = comptroller.markets(address(cToken));
require(_maxBorrowRatio < (_collateralFactor / 1e14), "invalid-max-borrow-limit");
require(_maxBorrowRatio > _minBorrowRatio, "max-should-be-higher-than-min");
emit UpdatedBorrowRatio(minBorrowRatio, _minBorrowRatio, maxBorrowRatio, _maxBorrowRatio);
minBorrowRatio = _minBorrowRatio;
maxBorrowRatio = _maxBorrowRatio;
}
function updateAaveStatus(bool _status) external onlyGovernor {
_updateAaveStatus(_status);
}
function updateDyDxStatus(bool _status) external virtual onlyGovernor {
_updateDyDxStatus(_status, address(collateralToken));
}
/**
* @notice Calculate total value based on rewardToken claimed, supply and borrow position
* @dev Report total value in collateral token
* @dev Claimed rewardToken will stay in strategy until next rebalance
*/
function totalValueCurrent() public override returns (uint256 _totalValue) {
cToken.exchangeRateCurrent();
_claimRewards();
_totalValue = _calculateTotalValue(IERC20(rewardToken).balanceOf(address(this)));
}
/**
* @notice Current borrow ratio, calculated as current borrow divide by max allowed borrow
* Return value is based on basis points, i.e. 7500 = 75% ratio
*/
function currentBorrowRatio() external view returns (uint256) {
(uint256 _supply, uint256 _borrow) = getPosition();
return _borrow == 0 ? 0 : (_borrow * MAX_BPS) / _supply;
}
/**
* @notice Calculate total value using rewardToken accrued, supply and borrow position
* @dev Compound calculate rewardToken accrued and store it when user interact with
* Compound contracts, i.e. deposit, withdraw or transfer tokens.
* So compAccrued() will return stored rewardToken accrued amount, which is older
* @dev For up to date value check totalValueCurrent()
*/
function totalValue() public view virtual override returns (uint256 _totalValue) {
_totalValue = _calculateTotalValue(_getRewardAccrued());
}
/**
* @notice Calculate current position using claimed rewardToken and current borrow.
*/
function isLossMaking() external returns (bool) {
// It's loss making if _totalValue < totalDebt
return totalValueCurrent() < IVesperPool(pool).totalDebtOf(address(this));
}
function isReservedToken(address _token) public view virtual override returns (bool) {
return _token == address(cToken) || _token == rewardToken || _token == address(collateralToken);
}
/// @notice Return supply and borrow position. Position may return few block old value
function getPosition() public view returns (uint256 _supply, uint256 _borrow) {
(, uint256 _cTokenBalance, uint256 _borrowBalance, uint256 _exchangeRate) =
cToken.getAccountSnapshot(address(this));
_supply = (_cTokenBalance * _exchangeRate) / 1e18;
_borrow = _borrowBalance;
}
/// @notice Approve all required tokens
function _approveToken(uint256 _amount) internal virtual override {
collateralToken.safeApprove(pool, _amount);
collateralToken.safeApprove(address(cToken), _amount);
for (uint256 i = 0; i < swapManager.N_DEX(); i++) {
IERC20(rewardToken).safeApprove(address(swapManager.ROUTERS(i)), _amount);
}
FlashLoanHelper._approveToken(address(collateralToken), _amount);
}
/**
* @notice Claim rewardToken and transfer to new strategy
* @param _newStrategy Address of new strategy.
*/
function _beforeMigration(address _newStrategy) internal virtual override {
require(IStrategy(_newStrategy).token() == address(cToken), "wrong-receipt-token");
minBorrowRatio = 0;
// It will calculate amount to repay based on borrow limit and payback all
_reinvest();
}
/**
* @notice Calculate borrow position based on borrow ratio, current supply, borrow, amount
* being deposited or withdrawn.
* @param _amount Collateral amount
* @param _isDeposit Flag indicating whether we are depositing _amount or withdrawing
* @return _position Amount of borrow that need to be adjusted
* @return _shouldRepay Flag indicating whether _position is borrow amount or repay amount
*/
function _calculateDesiredPosition(uint256 _amount, bool _isDeposit)
internal
returns (uint256 _position, bool _shouldRepay)
{
uint256 _totalSupply = cToken.balanceOfUnderlying(address(this));
uint256 _currentBorrow = cToken.borrowBalanceStored(address(this));
// If minimum borrow limit set to 0 then repay borrow
if (minBorrowRatio == 0) {
return (_currentBorrow, true);
}
uint256 _supply = _totalSupply - _currentBorrow;
// In case of withdraw, _amount can be greater than _supply
uint256 _newSupply = _isDeposit ? _supply + _amount : _supply > _amount ? _supply - _amount : 0;
// (supply * borrowRatio)/(BPS - borrowRatio)
uint256 _borrowUpperBound = (_newSupply * maxBorrowRatio) / (MAX_BPS - maxBorrowRatio);
uint256 _borrowLowerBound = (_newSupply * minBorrowRatio) / (MAX_BPS - minBorrowRatio);
// If our current borrow is greater than max borrow allowed, then we will have to repay
// some to achieve safe position else borrow more.
if (_currentBorrow > _borrowUpperBound) {
_shouldRepay = true;
// If borrow > upperBound then it is greater than lowerBound too.
_position = _currentBorrow - _borrowLowerBound;
} else if (_currentBorrow < _borrowLowerBound) {
_shouldRepay = false;
// We can borrow more.
_position = _borrowLowerBound - _currentBorrow;
}
}
/// @notice Get main Rewards accrued
function _getRewardAccrued() internal view virtual returns (uint256 _rewardAccrued) {
_rewardAccrued = comptroller.compAccrued(address(this));
}
/**
* @dev rewardToken is converted to collateral and if we have some borrow interest to pay,
* it will go come from collateral.
* @dev Report total value in collateral token
*/
function _calculateTotalValue(uint256 _rewardAccrued) internal view returns (uint256 _totalValue) {
uint256 _compAsCollateral;
if (_rewardAccrued != 0) {
(, _compAsCollateral, ) = swapManager.bestOutputFixedInput(
rewardToken,
address(collateralToken),
_rewardAccrued
);
}
(uint256 _supply, uint256 _borrow) = getPosition();
_totalValue = _compAsCollateral + collateralToken.balanceOf(address(this)) + _supply - _borrow;
}
/// @notice Claim comp
function _claimRewards() internal virtual {
address[] memory _markets = new address[](1);
_markets[0] = address(cToken);
comptroller.claimComp(address(this), _markets);
}
/// @notice Claim rewardToken and convert rewardToken into collateral token.
function _claimRewardsAndConvertTo(address _toToken) internal override {
_claimRewards();
uint256 _rewardAmount = IERC20(rewardToken).balanceOf(address(this));
if (_rewardAmount != 0) {
_safeSwap(rewardToken, _toToken, _rewardAmount);
}
}
/**
* @notice Generate report for pools accounting and also send profit and any payback to pool.
* @dev Claim rewardToken and convert to collateral.
*/
function _generateReport()
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _payback
)
{
uint256 _excessDebt = IVesperPool(pool).excessDebt(address(this));
(, , , , uint256 _totalDebt, , , uint256 _debtRatio) = IVesperPool(pool).strategy(address(this));
// Claim rewardToken and convert to collateral token
_claimRewardsAndConvertTo(address(collateralToken));
uint256 _supply = cToken.balanceOfUnderlying(address(this));
uint256 _borrow = cToken.borrowBalanceStored(address(this));
uint256 _investedCollateral = _supply - _borrow;
uint256 _collateralHere = collateralToken.balanceOf(address(this));
uint256 _totalCollateral = _investedCollateral + _collateralHere;
uint256 _profitToWithdraw;
if (_totalCollateral > _totalDebt) {
_profit = _totalCollateral - _totalDebt;
if (_collateralHere <= _profit) {
_profitToWithdraw = _profit - _collateralHere;
} else if (_collateralHere >= (_profit + _excessDebt)) {
_payback = _excessDebt;
} else {
// _profit < CollateralHere < _profit + _excessDebt
_payback = _collateralHere - _profit;
}
} else {
_loss = _totalDebt - _totalCollateral;
}
uint256 _paybackToWithdraw = _excessDebt - _payback;
uint256 _totalAmountToWithdraw = _paybackToWithdraw + _profitToWithdraw;
if (_totalAmountToWithdraw != 0) {
uint256 _withdrawn = _withdrawHere(_totalAmountToWithdraw);
// Any amount withdrawn over _profitToWithdraw is payback for pool
if (_withdrawn > _profitToWithdraw) {
_payback += (_withdrawn - _profitToWithdraw);
}
}
// Handle scenario if debtRatio is zero and some supply left.
// Remaining tokens, after payback withdrawal, are profit
(_supply, _borrow) = getPosition();
if (_debtRatio == 0 && _supply != 0 && _borrow == 0) {
// This will redeem all cTokens this strategy has
_redeemUnderlying(MAX_UINT_VALUE);
_profit += _supply;
}
}
/**
* Adjust position by normal leverage and deleverage.
* @param _adjustBy Amount by which we want to increase or decrease _borrow
* @param _shouldRepay True indicate we want to deleverage
* @return amount Actual adjusted amount
*/
function _adjustPosition(uint256 _adjustBy, bool _shouldRepay) internal returns (uint256 amount) {
// We can get position via view function, as this function will be called after _calculateDesiredPosition
(uint256 _supply, uint256 _borrow) = getPosition();
// If no borrow then there is nothing to deleverage
if (_borrow == 0 && _shouldRepay) {
return 0;
}
(, uint256 collateralFactor, ) = comptroller.markets(address(cToken));
if (_shouldRepay) {
amount = _normalDeleverage(_adjustBy, _supply, _borrow, collateralFactor);
} else {
amount = _normalLeverage(_adjustBy, _supply, _borrow, collateralFactor);
}
}
/**
* Deleverage: Reduce borrow to achieve safe position
* @param _maxDeleverage Reduce borrow by this amount
* @return _deleveragedAmount Amount we actually reduced
*/
function _normalDeleverage(
uint256 _maxDeleverage,
uint256 _supply,
uint256 _borrow,
uint256 _collateralFactor
) internal returns (uint256 _deleveragedAmount) {
uint256 _theoreticalSupply;
if (_collateralFactor != 0) {
// Calculate minimum supply required to support _borrow
_theoreticalSupply = (_borrow * 1e18) / _collateralFactor;
}
_deleveragedAmount = _supply - _theoreticalSupply;
if (_deleveragedAmount >= _borrow) {
_deleveragedAmount = _borrow;
}
if (_deleveragedAmount >= _maxDeleverage) {
_deleveragedAmount = _maxDeleverage;
}
_redeemUnderlying(_deleveragedAmount);
_repayBorrow(_deleveragedAmount);
}
/**
* Leverage: Borrow more
* @param _maxLeverage Max amount to borrow
* @return _leveragedAmount Amount we actually borrowed
*/
function _normalLeverage(
uint256 _maxLeverage,
uint256 _supply,
uint256 _borrow,
uint256 _collateralFactor
) internal returns (uint256 _leveragedAmount) {
// Calculate maximum we can borrow at current _supply
uint256 theoreticalBorrow = (_supply * _collateralFactor) / 1e18;
_leveragedAmount = theoreticalBorrow - _borrow;
if (_leveragedAmount >= _maxLeverage) {
_leveragedAmount = _maxLeverage;
}
_borrowCollateral(_leveragedAmount);
_mint(collateralToken.balanceOf(address(this)));
}
/// @notice Deposit collateral in Compound and adjust borrow position
function _reinvest() internal virtual override {
uint256 _collateralBalance = collateralToken.balanceOf(address(this));
(uint256 _position, bool _shouldRepay) = _calculateDesiredPosition(_collateralBalance, true);
// Supply collateral to compound.
_mint(_collateralBalance);
// During reinvest, _shouldRepay will be false which indicate that we will borrow more.
_position -= _doFlashLoan(_position, _shouldRepay);
uint256 i = 0;
while (_position > 0 && i <= 6) {
_position -= _adjustPosition(_position, _shouldRepay);
i++;
}
}
/// @dev Withdraw collateral and transfer it to pool
function _withdraw(uint256 _amount) internal override {
collateralToken.safeTransfer(pool, _withdrawHere(_amount));
}
/// @dev Withdraw collateral here. Do not transfer to pool
function _withdrawHere(uint256 _amount) internal returns (uint256) {
(uint256 _position, bool _shouldRepay) = _calculateDesiredPosition(_amount, false);
if (_shouldRepay) {
// Do deleverage by flash loan
_position -= _doFlashLoan(_position, _shouldRepay);
// If we still have _position to deleverage do it via normal deleverage
uint256 i = 0;
while (_position > 0 && i <= 10) {
_position -= _adjustPosition(_position, true);
i++;
}
// There may be scenario where we are not able to deleverage enough
if (_position != 0) {
// Calculate redeemable at current borrow and supply.
(uint256 _supply, uint256 _borrow) = getPosition();
uint256 _supplyToSupportBorrow;
if (maxBorrowRatio != 0) {
_supplyToSupportBorrow = (_borrow * MAX_BPS) / maxBorrowRatio;
}
// Current supply minus supply required to support _borrow at _maxBorrowRatio
uint256 _redeemable = _supply - _supplyToSupportBorrow;
if (_amount > _redeemable) {
_amount = _redeemable;
}
}
}
uint256 _collateralBefore = collateralToken.balanceOf(address(this));
// If we do not have enough collateral, try to get some via COMP
// This scenario is rare and will happen during last withdraw
if (_amount > cToken.balanceOfUnderlying(address(this))) {
// Use all collateral for withdraw
_collateralBefore = 0;
_claimRewardsAndConvertTo(address(collateralToken));
// Updated amount
_amount = _amount - collateralToken.balanceOf(address(this));
}
_redeemUnderlying(_amount);
uint256 _collateralAfter = collateralToken.balanceOf(address(this));
return _collateralAfter - _collateralBefore;
}
/**
* @dev Aave flash is used only for withdrawal due to high fee compare to DyDx
* @param _flashAmount Amount for flash loan
* @param _shouldRepay Flag indicating we want to leverage or deleverage
* @return Total amount we leverage or deleverage using flash loan
*/
function _doFlashLoan(uint256 _flashAmount, bool _shouldRepay) internal returns (uint256) {
uint256 _totalFlashAmount;
// Due to less fee DyDx is our primary flash loan provider
if (isDyDxActive && _flashAmount > 0) {
bytes memory _data = abi.encode(_flashAmount, _shouldRepay);
_totalFlashAmount = _doDyDxFlashLoan(address(collateralToken), _flashAmount, _data);
_flashAmount -= _totalFlashAmount;
}
if (isAaveActive && _shouldRepay && _flashAmount > 0) {
bytes memory _data = abi.encode(_flashAmount, _shouldRepay);
_totalFlashAmount += _doAaveFlashLoan(address(collateralToken), _flashAmount, _data);
}
return _totalFlashAmount;
}
/**
* @notice This function will be called by flash loan
* @dev In case of borrow, DyDx is preferred as fee is so low that it does not effect
* our collateralRatio and liquidation risk.
*/
function _flashLoanLogic(bytes memory _data, uint256 _repayAmount) internal override {
(uint256 _amount, bool _deficit) = abi.decode(_data, (uint256, bool));
uint256 _collateralHere = collateralToken.balanceOf(address(this));
require(_collateralHere >= _amount, "FLASH_FAILED"); // to stop malicious calls
//if in deficit we repay amount and then withdraw
if (_deficit) {
_repayBorrow(_amount);
//if we are withdrawing we take more to cover fee
_redeemUnderlying(_repayAmount);
} else {
_mint(_collateralHere);
//borrow more to cover fee
_borrowCollateral(_repayAmount);
}
}
/**
* @dev If swap slippage is defined then use oracle to get amountOut and calculate minAmountOut
*/
function _safeSwap(
address _tokenIn,
address _tokenOut,
uint256 _amountIn
) internal virtual {
uint256 _minAmountOut =
swapSlippage != 10000
? _calcAmtOutAfterSlippage(
ORACLE.assetToAsset(_tokenIn, _amountIn, _tokenOut, TWAP_PERIOD),
swapSlippage
)
: 1;
_safeSwap(_tokenIn, _tokenOut, _amountIn, _minAmountOut);
}
//////////////////// Compound wrapper functions //////////////////////////////
/**
* @dev Compound support ETH as collateral not WETH. So ETH strategy can override
* below functions and handle wrap/unwrap of WETH.
*/
function _mint(uint256 _amount) internal virtual {
require(cToken.mint(_amount) == 0, "supply-to-compound-failed");
}
function _redeemUnderlying(uint256 _amount) internal virtual {
if (_amount == MAX_UINT_VALUE) {
// Withdraw all cTokens
require(cToken.redeem(cToken.balanceOf(address(this))) == 0, "withdraw-from-compound-failed");
} else {
// Withdraw underlying
require(cToken.redeemUnderlying(_amount) == 0, "withdraw-from-compound-failed");
}
}
function _borrowCollateral(uint256 _amount) internal virtual {
require(cToken.borrow(_amount) == 0, "borrow-from-compound-failed");
}
function _repayBorrow(uint256 _amount) internal virtual {
require(cToken.repayBorrow(_amount) == 0, "repay-to-compound-failed");
}
//////////////////////////////////////////////////////////////////////////////
/* solhint-disable no-empty-blocks */
// We overridden _generateReport which eliminates need of below function.
function _liquidate(uint256 _excessDebt) internal override returns (uint256 _payback) {}
function _realizeProfit(uint256 _totalDebt) internal virtual override returns (uint256) {}
function _realizeLoss(uint256 _totalDebt) internal view override returns (uint256 _loss) {}
/* solhint-enable no-empty-blocks */
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "./CompoundLeverageStrategy.sol";
import "../../interfaces/token/IToken.sol";
// solhint-disable no-empty-blocks
/// @title Deposit ETH in Compound and earn interest.
contract CompoundLeverageStrategyETH is CompoundLeverageStrategy {
constructor(
address _pool,
address _swapManager,
address _comptroller,
address _rewardDistributor,
address _rewardToken,
address _aaveAddressesProvider,
address _receiptToken,
string memory _name
)
CompoundLeverageStrategy(
_pool,
_swapManager,
_comptroller,
_rewardDistributor,
_rewardToken,
_aaveAddressesProvider,
_receiptToken,
_name
)
{}
/// @dev Only receive ETH from either cToken or WETH
receive() external payable {
require(msg.sender == address(cToken) || msg.sender == WETH, "not-allowed-to-send-ether");
}
/// @dev Compound support ETH as collateral. Convert WETH to ETH and mint cETH
function _mint(uint256 _amount) internal override {
_withdrawETH(_amount);
cToken.mint{value: _amount}();
}
/// @dev On redeem we will receive ETH. Convert received ETH into WETH
function _redeemUnderlying(uint256 _amount) internal override {
super._redeemUnderlying(_amount);
_depositETH();
}
/// @dev On borrow we will receive ETH. Convert received ETH into WETH
function _borrowCollateral(uint256 _amount) internal override {
super._borrowCollateral(_amount);
_depositETH();
}
/// @dev Repay will take ETH. Convert WETH to ETH and call payable repay function
function _repayBorrow(uint256 _amount) internal override {
_withdrawETH(_amount);
cToken.repayBorrow{value: _amount}();
}
/// @dev Deposit ETH and get WETH in return
function _depositETH() internal {
TokenLike(WETH).deposit{value: address(this).balance}();
}
/// @dev Withdraw ETH by burning similar amount of WETH
function _withdrawETH(uint256 _amount) internal {
TokenLike(WETH).withdraw(_amount);
}
}
|
Calculate total value using rewardToken accrued, supply and borrow position Compound calculate rewardToken accrued and store it when user interact with Compound contracts, i.e. deposit, withdraw or transfer tokens. So compAccrued() will return stored rewardToken accrued amount, which is older For up to date value check totalValueCurrent()/
|
function totalValue() public view virtual override returns (uint256 _totalValue) {
_totalValue = _calculateTotalValue(_getRewardAccrued());
}
| 1,539,082
|
pragma solidity 0.4.26;
import "../../LiquidityPoolConverter.sol";
import "../../../token/interfaces/ISmartToken.sol";
import "../../../utility/interfaces/IOracle.sol";
/**
* @dev Liquidity Pool v1 Converter
*
* The liquidity pool v1 converter is a specialized version of a converter that manages
* a classic SovrynSwap liquidity pool.
*
* Even though classic pools can have many reserves, the most common configuration of
* the pool has 2 reserves with 50%/50% weights.
*/
contract LiquidityPoolV1Converter is LiquidityPoolConverter {
IEtherToken internal etherToken = IEtherToken(0xc0829421C1d260BD3cB3E0F06cfE2D52db2cE315);
uint256 private constant CONVERTER_TYPE = 1;
///@dev used to calculate 0.1% of the amount
uint256 public constant DENOMINATOR = 1000;
IOracle public oracle;
uint256 public token0Decimal;
uint256 public token1Decimal;
/**
* @dev triggered after a conversion with new price data
* deprecated, use `TokenRateUpdate` from version 28 and up
*
* @param _connectorToken reserve token
* @param _tokenSupply smart token supply
* @param _connectorBalance reserve balance
* @param _connectorWeight reserve weight
*/
event PriceDataUpdate(address indexed _connectorToken, uint256 _tokenSupply, uint256 _connectorBalance, uint32 _connectorWeight);
/**
* @dev initializes a new LiquidityPoolV1Converter instance
*
* @param _token pool token governed by the converter
* @param _registry address of a contract registry contract
* @param _maxConversionFee maximum conversion fee, represented in ppm
*/
constructor(
ISmartToken _token,
IContractRegistry _registry,
uint32 _maxConversionFee
) public LiquidityPoolConverter(_token, _registry, _maxConversionFee) {}
/**
* @dev returns the converter type
*
* @return see the converter types in the the main contract doc
*/
function converterType() public pure returns (uint16) {
return uint16(CONVERTER_TYPE);
}
/**
* @dev set oracle contract address
* can be called by owner of the contract only
*/
function setOracle(address _oracle) external ownerOnly {
oracle = IOracle(_oracle);
}
/**
* @dev accepts ownership of the anchor after an ownership transfer
* also activates the converter
* can only be called by the contract owner
* note that prior to version 28, you should use 'acceptTokenOwnership' instead
*/
function acceptAnchorOwnership() public ownerOnly {
super.acceptAnchorOwnership();
emit Activation(converterType(), anchor, true);
}
/**
* @dev defines a new reserve token for the converter
* can only be called by the owner while the converter is inactive and
* 2 reserves aren't defined yet
*
* @param _token address of the reserve token
* @param _weight reserve weight, represented in ppm, 1-1000000
*/
function addReserve(IERC20Token _token, uint32 _weight) public {
// verify that the converter doesn't have 2 reserves yet
uint256 tokenCount = reserveTokenCount();
require(tokenCount < 2, "ERR_INVALID_RESERVE_COUNT");
if(tokenCount == 0) {
token0Decimal = IERC20Token(_token).decimals();
} else {
token1Decimal = IERC20Token(_token).decimals();
}
super.addReserve(_token, _weight);
}
/**
* @dev returns the expected target amount of converting one reserve to another along with the fee
*
* @param _sourceToken contract address of the source reserve token
* @param _targetToken contract address of the target reserve token
* @param _amount amount of tokens received from the user
*
* @return expected target amount
* @return expected fee
*/
function targetAmountAndFee(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount)
public
view
active
validReserve(_sourceToken)
validReserve(_targetToken)
returns (uint256, uint256)
{
// validate input
require(_sourceToken != _targetToken, "ERR_SAME_SOURCE_TARGET");
uint256 amount = ISovrynSwapFormula(addressOf(SOVRYNSWAP_FORMULA)).crossReserveTargetAmount(
reserveBalance(_sourceToken),
reserves[_sourceToken].weight,
reserveBalance(_targetToken),
reserves[_targetToken].weight,
_amount
);
// return the amount minus the conversion fee and the conversion fee
uint256 fee = calculateFee(amount);
return (amount - fee, fee);
}
/**
* @dev converts a specific amount of source tokens to target tokens
* can only be called by the SovrynSwap network contract
*
* @param _sourceToken source ERC20 token
* @param _targetToken target ERC20 token
* @param _amount amount of tokens to convert (in units of the source token)
* @param _trader address of the caller who executed the conversion
* @param _beneficiary wallet to receive the conversion result
*
* @return amount of tokens received (in units of the target token)
*/
function doConvert(
IERC20Token _sourceToken,
IERC20Token _targetToken,
uint256 _amount,
address _trader,
address _beneficiary
) internal returns (uint256) {
//record oracle observations
if(address(oracle) != address(0)) _write();
// get expected target amount and fee
(uint256 amount, uint256 fee) = targetAmountAndFee(_sourceToken, _targetToken, _amount);
// ensure that the trade gives something in return
require(amount != 0, "ERR_ZERO_TARGET_AMOUNT");
// ensure that the trade won't deplete the reserve balance
uint256 targetReserveBalance = reserveBalance(_targetToken);
assert(amount < targetReserveBalance);
// ensure that the input amount was already deposited
if (_sourceToken == ETH_RESERVE_ADDRESS)
require(msg.value == _amount, "ERR_ETH_AMOUNT_MISMATCH");
else
require(msg.value == 0 && _sourceToken.balanceOf(this).sub(reserveBalance(_sourceToken)) >= _amount, "ERR_INVALID_AMOUNT");
// sync the reserve balances
syncReserveBalance(_sourceToken);
reserves[_targetToken].balance = reserves[_targetToken].balance.sub(amount);
// transfer funds to the beneficiary in the to reserve token
if (_targetToken == ETH_RESERVE_ADDRESS)
_beneficiary.transfer(amount);
else
safeTransfer(_targetToken, _beneficiary, amount);
// dispatch the conversion event
dispatchConversionEvent(_sourceToken, _targetToken, _trader, _amount, amount, fee);
// dispatch rate updates
dispatchRateEvents(_sourceToken, _targetToken);
return amount;
}
function _write() internal {
IERC20Token token0 = IERC20Token(reserveTokens[0]);
IERC20Token token1 = IERC20Token(reserveTokens[1]);
uint256 reserve0Balance = reserveBalance(token0);
uint256 reserve1Balance = reserveBalance(token1);
uint32 reserve0Weight = reserves[token0].weight;
uint32 reserve1Weight = reserves[token1].weight;
uint256 partialReserves0 = reserve0Balance.div(DENOMINATOR);
uint256 partialReserves1 = reserve1Balance.div(DENOMINATOR);
ISovrynSwapFormula sovrynSwapFormula = ISovrynSwapFormula(addressOf(SOVRYNSWAP_FORMULA));
uint256 price0 = sovrynSwapFormula.crossReserveTargetAmount(
reserve0Balance,
reserve0Weight,
reserve1Balance,
reserve1Weight,
partialReserves0
);
uint256 price1 = sovrynSwapFormula.crossReserveTargetAmount(
reserve1Balance,
reserve1Weight,
reserve0Balance,
reserve0Weight,
partialReserves1
);
price0 = price0.mul(10**token0Decimal).div(partialReserves0);
price1 = price1.mul(10**token1Decimal).div(partialReserves1);
oracle.write(price0, price1);
}
/**
* @dev increases the pool's liquidity and mints new shares in the pool to the caller
* note that prior to version 28, you should use 'fund' instead
*
* @param _reserveTokens address of each reserve token
* @param _reserveAmounts amount of each reserve token
* @param _minReturn token minimum return-amount
*/
function addLiquidity(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts, uint256 _minReturn)
public
payable
protected
active
{
// verify the user input
verifyLiquidityInput(_reserveTokens, _reserveAmounts, _minReturn);
// if one of the reserves is ETH, then verify that the input amount of ETH is equal to the input value of ETH
for (uint256 i = 0; i < _reserveTokens.length; i++)
if (_reserveTokens[i] == ETH_RESERVE_ADDRESS)
require(_reserveAmounts[i] == msg.value, "ERR_ETH_AMOUNT_MISMATCH");
// if the input value of ETH is larger than zero, then verify that one of the reserves is ETH
if (msg.value > 0)
require(reserves[ETH_RESERVE_ADDRESS].isSet, "ERR_NO_ETH_RESERVE");
// get the total supply
uint256 totalSupply = ISmartToken(anchor).totalSupply();
// transfer from the user an equally-worth amount of each one of the reserve tokens
uint256 amount = addLiquidityToPool(_reserveTokens, _reserveAmounts, totalSupply);
// verify that the equivalent amount of tokens is equal to or larger than the user's expectation
require(amount >= _minReturn, "ERR_RETURN_TOO_LOW");
// issue the tokens to the user
ISmartToken(anchor).issue(msg.sender, amount);
}
/**
* @dev decreases the pool's liquidity and burns the caller's shares in the pool
* note that prior to version 28, you should use 'liquidate' instead
*
* @param _amount token amount
* @param _reserveTokens address of each reserve token
* @param _reserveMinReturnAmounts minimum return-amount of each reserve token
*/
function removeLiquidity(uint256 _amount, IERC20Token[] memory _reserveTokens, uint256[] memory _reserveMinReturnAmounts)
public
protected
active
{
// verify the user input
verifyLiquidityInput(_reserveTokens, _reserveMinReturnAmounts, _amount);
// get the total supply BEFORE destroying the user tokens
uint256 totalSupply = ISmartToken(anchor).totalSupply();
// destroy the user tokens
ISmartToken(anchor).destroy(msg.sender, _amount);
// transfer to the user an equivalent amount of each one of the reserve tokens
removeLiquidityFromPool(_reserveTokens, _reserveMinReturnAmounts, totalSupply, _amount);
}
/**
* @dev increases the pool's liquidity and mints new shares in the pool to the caller
* for example, if the caller increases the supply by 10%,
* then it will cost an amount equal to 10% of each reserve token balance
* note that starting from version 28, you should use 'addLiquidity' instead
*
* @param _amount amount to increase the supply by (in the pool token)
*/
function fund(uint256 _amount) external payable protected {
syncReserveBalances();
reserves[ETH_RESERVE_ADDRESS].balance = reserves[ETH_RESERVE_ADDRESS].balance.sub(msg.value);
uint256 supply = ISmartToken(anchor).totalSupply();
ISovrynSwapFormula formula = ISovrynSwapFormula(addressOf(SOVRYNSWAP_FORMULA));
// iterate through the reserve tokens and transfer a percentage equal to the weight between
// _amount and the total supply in each reserve from the caller to the converter
uint256 reserveCount = reserveTokens.length;
for (uint256 i = 0; i < reserveCount; i++) {
IERC20Token reserveToken = reserveTokens[i];
uint256 rsvBalance = reserves[reserveToken].balance;
uint256 reserveAmount = formula.fundCost(supply, rsvBalance, reserveRatio, _amount);
// transfer funds from the caller in the reserve token
if (reserveToken == ETH_RESERVE_ADDRESS) {
if (msg.value > reserveAmount) {
msg.sender.transfer(msg.value - reserveAmount);
}
else if (msg.value < reserveAmount) {
require(msg.value == 0, "ERR_INVALID_ETH_VALUE");
safeTransferFrom(etherToken, msg.sender, this, reserveAmount);
etherToken.withdraw(reserveAmount);
}
}
else {
safeTransferFrom(reserveToken, msg.sender, this, reserveAmount);
}
// sync the reserve balance
uint256 newReserveBalance = rsvBalance.add(reserveAmount);
reserves[reserveToken].balance = newReserveBalance;
uint256 newPoolTokenSupply = supply.add(_amount);
// dispatch liquidity update for the pool token/reserve
emit LiquidityAdded(msg.sender, reserveToken, reserveAmount, newReserveBalance, newPoolTokenSupply);
// dispatch the `TokenRateUpdate` event for the pool token
uint32 reserveWeight = reserves[reserveToken].weight;
dispatchPoolTokenRateEvent(newPoolTokenSupply, reserveToken, newReserveBalance, reserveWeight);
}
// issue new funds to the caller in the pool token
ISmartToken(anchor).issue(msg.sender, _amount);
}
/**
* @dev decreases the pool's liquidity and burns the caller's shares in the pool
* for example, if the holder sells 10% of the supply,
* then they will receive 10% of each reserve token balance in return
* note that starting from version 28, you should use 'removeLiquidity' instead
*
* @param _amount amount to liquidate (in the pool token)
*/
function liquidate(uint256 _amount) external protected {
require(_amount > 0, "ERR_ZERO_AMOUNT");
uint256 totalSupply = ISmartToken(anchor).totalSupply();
ISmartToken(anchor).destroy(msg.sender, _amount);
uint256[] memory reserveMinReturnAmounts = new uint256[](reserveTokens.length);
for (uint256 i = 0; i < reserveMinReturnAmounts.length; i++)
reserveMinReturnAmounts[i] = 1;
removeLiquidityFromPool(reserveTokens, reserveMinReturnAmounts, totalSupply, _amount);
}
/**
* @dev verifies that a given array of tokens is identical to the converter's array of reserve tokens
* we take this input in order to allow specifying the corresponding reserve amounts in any order
*
* @param _reserveTokens array of reserve tokens
* @param _reserveAmounts array of reserve amounts
* @param _amount token amount
*/
function verifyLiquidityInput(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts, uint256 _amount) private view {
uint256 i;
uint256 j;
uint256 length = reserveTokens.length;
require(length == _reserveTokens.length, "ERR_INVALID_RESERVE");
require(length == _reserveAmounts.length, "ERR_INVALID_AMOUNT");
for (i = 0; i < length; i++) {
// verify that every input reserve token is included in the reserve tokens
require(reserves[_reserveTokens[i]].isSet, "ERR_INVALID_RESERVE");
for (j = 0; j < length; j++) {
if (reserveTokens[i] == _reserveTokens[j])
break;
}
// verify that every reserve token is included in the input reserve tokens
require(j < length, "ERR_INVALID_RESERVE");
// verify that every input reserve token amount is larger than zero
require(_reserveAmounts[i] > 0, "ERR_INVALID_AMOUNT");
}
// verify that the input token amount is larger than zero
require(_amount > 0, "ERR_ZERO_AMOUNT");
}
/**
* @dev adds liquidity (reserve) to the pool
*
* @param _reserveTokens address of each reserve token
* @param _reserveAmounts amount of each reserve token
* @param _totalSupply token total supply
*/
function addLiquidityToPool(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts, uint256 _totalSupply)
private
returns (uint256)
{
if (_totalSupply == 0)
return addLiquidityToEmptyPool(_reserveTokens, _reserveAmounts);
return addLiquidityToNonEmptyPool(_reserveTokens, _reserveAmounts, _totalSupply);
}
/**
* @dev adds liquidity (reserve) to the pool when it's empty
*
* @param _reserveTokens address of each reserve token
* @param _reserveAmounts amount of each reserve token
*/
function addLiquidityToEmptyPool(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts)
private
returns (uint256)
{
// calculate the geometric-mean of the reserve amounts approved by the user
uint256 amount = geometricMean(_reserveAmounts);
// transfer each one of the reserve amounts from the user to the pool
for (uint256 i = 0; i < _reserveTokens.length; i++) {
if (_reserveTokens[i] != ETH_RESERVE_ADDRESS) // ETH has already been transferred as part of the transaction
safeTransferFrom(_reserveTokens[i], msg.sender, this, _reserveAmounts[i]);
reserves[_reserveTokens[i]].balance = _reserveAmounts[i];
emit LiquidityAdded(msg.sender, _reserveTokens[i], _reserveAmounts[i], _reserveAmounts[i], amount);
// dispatch the `TokenRateUpdate` event for the pool token
uint32 reserveWeight = reserves[_reserveTokens[i]].weight;
dispatchPoolTokenRateEvent(amount, _reserveTokens[i], _reserveAmounts[i], reserveWeight);
}
return amount;
}
/**
* @dev adds liquidity (reserve) to the pool when it's not empty
*
* @param _reserveTokens address of each reserve token
* @param _reserveAmounts amount of each reserve token
* @param _totalSupply token total supply
*/
function addLiquidityToNonEmptyPool(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts, uint256 _totalSupply)
private
returns (uint256)
{
syncReserveBalances();
reserves[ETH_RESERVE_ADDRESS].balance = reserves[ETH_RESERVE_ADDRESS].balance.sub(msg.value);
ISovrynSwapFormula formula = ISovrynSwapFormula(addressOf(SOVRYNSWAP_FORMULA));
uint256 amount = getMinShare(formula, _totalSupply, _reserveTokens, _reserveAmounts);
uint256 newPoolTokenSupply = _totalSupply.add(amount);
for (uint256 i = 0; i < _reserveTokens.length; i++) {
IERC20Token reserveToken = _reserveTokens[i];
uint256 rsvBalance = reserves[reserveToken].balance;
uint256 reserveAmount = formula.fundCost(_totalSupply, rsvBalance, reserveRatio, amount);
require(reserveAmount > 0, "ERR_ZERO_TARGET_AMOUNT");
assert(reserveAmount <= _reserveAmounts[i]);
// transfer each one of the reserve amounts from the user to the pool
if (reserveToken != ETH_RESERVE_ADDRESS) // ETH has already been transferred as part of the transaction
safeTransferFrom(reserveToken, msg.sender, this, reserveAmount);
else if (_reserveAmounts[i] > reserveAmount) // transfer the extra amount of ETH back to the user
msg.sender.transfer(_reserveAmounts[i] - reserveAmount);
uint256 newReserveBalance = rsvBalance.add(reserveAmount);
reserves[reserveToken].balance = newReserveBalance;
emit LiquidityAdded(msg.sender, reserveToken, reserveAmount, newReserveBalance, newPoolTokenSupply);
// dispatch the `TokenRateUpdate` event for the pool token
uint32 reserveWeight = reserves[_reserveTokens[i]].weight;
dispatchPoolTokenRateEvent(newPoolTokenSupply, _reserveTokens[i], newReserveBalance, reserveWeight);
}
return amount;
}
/**
* @dev removes liquidity (reserve) from the pool
*
* @param _reserveTokens address of each reserve token
* @param _reserveMinReturnAmounts minimum return-amount of each reserve token
* @param _totalSupply token total supply
* @param _amount token amount
*/
function removeLiquidityFromPool(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveMinReturnAmounts, uint256 _totalSupply, uint256 _amount)
private
{
syncReserveBalances();
ISovrynSwapFormula formula = ISovrynSwapFormula(addressOf(SOVRYNSWAP_FORMULA));
uint256 newPoolTokenSupply = _totalSupply.sub(_amount);
for (uint256 i = 0; i < _reserveTokens.length; i++) {
IERC20Token reserveToken = _reserveTokens[i];
uint256 rsvBalance = reserves[reserveToken].balance;
uint256 reserveAmount = formula.liquidateReserveAmount(_totalSupply, rsvBalance, reserveRatio, _amount);
require(reserveAmount >= _reserveMinReturnAmounts[i], "ERR_ZERO_TARGET_AMOUNT");
uint256 newReserveBalance = rsvBalance.sub(reserveAmount);
reserves[reserveToken].balance = newReserveBalance;
// transfer each one of the reserve amounts from the pool to the user
if (reserveToken == ETH_RESERVE_ADDRESS)
msg.sender.transfer(reserveAmount);
else
safeTransfer(reserveToken, msg.sender, reserveAmount);
emit LiquidityRemoved(msg.sender, reserveToken, reserveAmount, newReserveBalance, newPoolTokenSupply);
// dispatch the `TokenRateUpdate` event for the pool token
uint32 reserveWeight = reserves[reserveToken].weight;
dispatchPoolTokenRateEvent(newPoolTokenSupply, reserveToken, newReserveBalance, reserveWeight);
}
}
function getMinShare(ISovrynSwapFormula formula, uint256 _totalSupply, IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts) private view returns (uint256) {
uint256 minIndex = 0;
for (uint256 i = 1; i < _reserveTokens.length; i++) {
if (_reserveAmounts[i].mul(reserves[_reserveTokens[minIndex]].balance) < _reserveAmounts[minIndex].mul(reserves[_reserveTokens[i]].balance))
minIndex = i;
}
return formula.fundSupplyAmount(_totalSupply, reserves[_reserveTokens[minIndex]].balance, reserveRatio, _reserveAmounts[minIndex]);
}
function getExpectedOutAmount(uint256 lpTokens) external view returns (uint256[2] memory amountOut) {
ISovrynSwapFormula formula = ISovrynSwapFormula(addressOf(SOVRYNSWAP_FORMULA));
uint256 supply = ISmartToken(anchor).totalSupply();
uint256 reserveCount = reserveTokens.length;
for (uint256 i = 0; i < reserveCount; i++) {
IERC20Token reserveToken = reserveTokens[i];
uint256 rsvBalance = reserves[reserveToken].balance;
amountOut[i] = formula.liquidateReserveAmount(supply, rsvBalance, reserveRatio, lpTokens);
}
}
/**
* @dev calculates the number of decimal digits in a given value
*
* @param _x value (assumed positive)
* @return the number of decimal digits in the given value
*/
function decimalLength(uint256 _x) public pure returns (uint256) {
uint256 y = 0;
for (uint256 x = _x; x > 0; x /= 10)
y++;
return y;
}
/**
* @dev calculates the nearest integer to a given quotient
*
* @param _n quotient numerator
* @param _d quotient denominator
* @return the nearest integer to the given quotient
*/
function roundDiv(uint256 _n, uint256 _d) public pure returns (uint256) {
return (_n + _d / 2) / _d;
}
/**
* @dev calculates the average number of decimal digits in a given list of values
*
* @param _values list of values (each of which assumed positive)
* @return the average number of decimal digits in the given list of values
*/
function geometricMean(uint256[] memory _values) public pure returns (uint256) {
uint256 numOfDigits = 0;
uint256 length = _values.length;
for (uint256 i = 0; i < length; i++)
numOfDigits += decimalLength(_values[i]);
return uint256(10) ** (roundDiv(numOfDigits, length) - 1);
}
/**
* @dev dispatches rate events for both reserves / pool tokens
* only used to circumvent the `stack too deep` compiler error
*
* @param _sourceToken address of the source reserve token
* @param _targetToken address of the target reserve token
*/
function dispatchRateEvents(IERC20Token _sourceToken, IERC20Token _targetToken) private {
uint256 poolTokenSupply = ISmartToken(anchor).totalSupply();
uint256 sourceReserveBalance = reserveBalance(_sourceToken);
uint256 targetReserveBalance = reserveBalance(_targetToken);
uint32 sourceReserveWeight = reserves[_sourceToken].weight;
uint32 targetReserveWeight = reserves[_targetToken].weight;
// dispatch token rate update event
uint256 rateN = targetReserveBalance.mul(sourceReserveWeight);
uint256 rateD = sourceReserveBalance.mul(targetReserveWeight);
emit TokenRateUpdate(_sourceToken, _targetToken, rateN, rateD);
// dispatch the `TokenRateUpdate` event for the pool token
dispatchPoolTokenRateEvent(poolTokenSupply, _sourceToken, sourceReserveBalance, sourceReserveWeight);
dispatchPoolTokenRateEvent(poolTokenSupply, _targetToken, targetReserveBalance, targetReserveWeight);
// dispatch price data update events (deprecated events)
emit PriceDataUpdate(_sourceToken, poolTokenSupply, sourceReserveBalance, sourceReserveWeight);
emit PriceDataUpdate(_targetToken, poolTokenSupply, targetReserveBalance, targetReserveWeight);
}
/**
* @dev dispatches the `TokenRateUpdate` for the pool token
* only used to circumvent the `stack too deep` compiler error
*
* @param _poolTokenSupply total pool token supply
* @param _reserveToken address of the reserve token
* @param _reserveBalance reserve balance
* @param _reserveWeight reserve weight
*/
function dispatchPoolTokenRateEvent(uint256 _poolTokenSupply, IERC20Token _reserveToken, uint256 _reserveBalance, uint32 _reserveWeight) private {
emit TokenRateUpdate(anchor, _reserveToken, _reserveBalance.mul(WEIGHT_RESOLUTION), _poolTokenSupply.mul(_reserveWeight));
}
}
|
returns the converter type return see the converter types in the the main contract doc/
|
function converterType() public pure returns (uint16) {
return uint16(CONVERTER_TYPE);
}
| 5,547,335
|
./full_match/11155111/0x3f9C6646CCFa4597C45761B3e9a1Da0cF00253D5/sources/src/Drips.sol
|
Returns user's received funds already split and ready to be collected. userId The user ID. erc20 The used ERC-20 token. It must preserve amounts, so if some amount of tokens is transferred to an address, then later the same amount must be transferable from that address. Tokens which rebase the holders' balances, collect taxes on transfers, or impose any restrictions on holding or transferring tokens are not supported. If you use such tokens in the protocol, they can get stuck or lost. return amt The collectable amount.
|
function collectable(uint256 userId, IERC20 erc20) public view returns (uint128 amt) {
return Splits._collectable(userId, _assetId(erc20));
}
| 3,824,008
|
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.2;
/**
* @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);
}
// File: openzeppelin-solidity/contracts/math/Math.sol
pragma solidity ^0.5.2;
/**
* @title Math
* @dev Assorted math operations
*/
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 Calculates the average of two numbers. Since these are integers,
* averages of an even and odd number cannot be represented, and will be
* rounded down.
*/
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);
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.2;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.5.2;
/**
* @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;
}
}
// File: solidity-rlp/contracts/RLPReader.sol
/*
* @author Hamdi Allam hamdi.allam97@gmail.com
* Please reach out with any questions or concerns
*/
pragma solidity ^0.5.0;
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;
}
struct Iterator {
RLPItem item; // Item that's being iterated over.
uint nextPtr; // Position of the next item in the list.
}
/*
* @dev Returns the next element in the iteration. Reverts if it has not next element.
* @param self The iterator.
* @return The next element in the iteration.
*/
function next(Iterator memory self) internal pure returns (RLPItem memory) {
require(hasNext(self));
uint ptr = self.nextPtr;
uint itemLength = _itemLength(ptr);
self.nextPtr = ptr + itemLength;
return RLPItem(itemLength, ptr);
}
/*
* @dev Returns true if the iteration has more elements.
* @param self The iterator.
* @return true if the iteration has more elements.
*/
function hasNext(Iterator memory self) internal pure returns (bool) {
RLPItem memory item = self.item;
return self.nextPtr < item.memPtr + item.len;
}
/*
* @param item RLP encoded bytes
*/
function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) {
uint memPtr;
assembly {
memPtr := add(item, 0x20)
}
return RLPItem(item.length, memPtr);
}
/*
* @dev Create an iterator. Reverts if item is not a list.
* @param self The RLP item.
* @return An 'Iterator' over the item.
*/
function iterator(RLPItem memory self) internal pure returns (Iterator memory) {
require(isList(self));
uint ptr = self.memPtr + _payloadOffset(self.memPtr);
return Iterator(self, ptr);
}
/*
* @param item RLP encoded bytes
*/
function rlpLen(RLPItem memory item) internal pure returns (uint) {
return item.len;
}
/*
* @param item RLP encoded bytes
*/
function payloadLen(RLPItem memory item) internal pure returns (uint) {
return item.len - _payloadOffset(item.memPtr);
}
/*
* @param item RLP encoded list in bytes
*/
function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) {
require(isList(item));
uint items = numItems(item);
RLPItem[] memory 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;
}
return result;
}
// @return indicator whether encoded payload is a list. negate this function call for isData.
function isList(RLPItem memory item) internal pure returns (bool) {
if (item.len == 0) return false;
uint8 byte0;
uint memPtr = item.memPtr;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < LIST_SHORT_START)
return false;
return true;
}
/** 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);
if (result.length == 0) return result;
uint ptr;
assembly {
ptr := add(0x20, result)
}
copy(item.memPtr, ptr, item.len);
return result;
}
// any non-zero byte is considered true
function toBoolean(RLPItem memory item) internal pure returns (bool) {
require(item.len == 1);
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
require(item.len == 21);
return address(toUint(item));
}
function toUint(RLPItem memory item) internal pure returns (uint) {
require(item.len > 0 && item.len <= 33);
uint offset = _payloadOffset(item.memPtr);
uint len = item.len - offset;
uint result;
uint memPtr = item.memPtr + offset;
assembly {
result := mload(memPtr)
// shfit to the correct location if neccesary
if lt(len, 32) {
result := div(result, exp(256, sub(32, len)))
}
}
return result;
}
// enforces 32 byte length
function toUintStrict(RLPItem memory item) internal pure returns (uint) {
// one byte prefix
require(item.len == 33);
uint result;
uint memPtr = item.memPtr + 1;
assembly {
result := mload(memPtr)
}
return result;
}
function toBytes(RLPItem memory item) internal pure returns (bytes memory) {
require(item.len > 0);
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;
}
/*
* Private Helpers
*/
// @return number of payload items inside an encoded list.
function numItems(RLPItem memory item) private pure returns (uint) {
if (item.len == 0) return 0;
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) private pure returns (uint) {
uint itemLen;
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
itemLen = 1;
else if (byte0 < STRING_LONG_START)
itemLen = 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
itemLen := add(dataLen, add(byteLen, 1))
}
}
else if (byte0 < LIST_LONG_START) {
itemLen = 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
itemLen := add(dataLen, add(byteLen, 1))
}
}
return itemLen;
}
// @return number of bytes until the data
function _payloadOffset(uint memPtr) private 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;
}
/*
* @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) private pure {
if (len == 0) return;
// 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))
}
}
}
// File: contracts/common/lib/BytesLib.sol
pragma solidity ^0.5.2;
library BytesLib {
function concat(bytes memory _preBytes, bytes memory _postBytes)
internal
pure
returns (bytes memory)
{
bytes memory tempBytes;
assembly {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// Store the length of the first bytes array at the beginning of
// the memory for tempBytes.
let length := mload(_preBytes)
mstore(tempBytes, length)
// Maintain a memory counter for the current write location in the
// temp bytes array by adding the 32 bytes for the array length to
// the starting location.
let mc := add(tempBytes, 0x20)
// Stop copying when the memory counter reaches the length of the
// first bytes array.
let end := add(mc, length)
for {
// Initialize a copy counter to the start of the _preBytes data,
// 32 bytes into its memory.
let cc := add(_preBytes, 0x20)
} lt(mc, end) {
// Increase both counters by 32 bytes each iteration.
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// Write the _preBytes data into the tempBytes memory 32 bytes
// at a time.
mstore(mc, mload(cc))
}
// Add the length of _postBytes to the current length of tempBytes
// and store it as the new length in the first 32 bytes of the
// tempBytes memory.
length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
// Move the memory counter back from a multiple of 0x20 to the
// actual end of the _preBytes data.
mc := end
// Stop copying when the memory counter reaches the new combined
// length of the arrays.
end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
// Update the free-memory pointer by padding our last write location
// to 32 bytes: add 31 bytes to the end of tempBytes to move to the
// next 32 byte block, then round down to the nearest multiple of
// 32. If the sum of the length of the two arrays is zero then add
// one before rounding down to leave a blank 32 bytes (the length block with 0).
mstore(
0x40,
and(
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
not(31) // Round down to the nearest 32 bytes.
)
)
}
return tempBytes;
}
function slice(bytes memory _bytes, uint256 _start, uint256 _length)
internal
pure
returns (bytes memory)
{
require(_bytes.length >= (_start + _length));
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(
add(tempBytes, lengthmod),
mul(0x20, iszero(lengthmod))
)
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(
add(
add(_bytes, lengthmod),
mul(0x20, iszero(lengthmod))
),
_start
)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
// Pad a bytes array to 32 bytes
function leftPad(bytes memory _bytes) internal pure returns (bytes memory) {
// may underflow if bytes.length < 32. Hence using SafeMath.sub
bytes memory newBytes = new bytes(SafeMath.sub(32, _bytes.length));
return concat(newBytes, _bytes);
}
function toBytes32(bytes memory b) internal pure returns (bytes32) {
require(b.length >= 32, "Bytes array should atleast be 32 bytes");
bytes32 out;
for (uint256 i = 0; i < 32; i++) {
out |= bytes32(b[i] & 0xFF) >> (i * 8);
}
return out;
}
function toBytes4(bytes memory b) internal pure returns (bytes4 result) {
assembly {
result := mload(add(b, 32))
}
}
function fromBytes32(bytes32 x) internal pure returns (bytes memory) {
bytes memory b = new bytes(32);
for (uint256 i = 0; i < 32; i++) {
b[i] = bytes1(uint8(uint256(x) / (2**(8 * (31 - i)))));
}
return b;
}
function fromUint(uint256 _num) internal pure returns (bytes memory _ret) {
_ret = new bytes(32);
assembly {
mstore(add(_ret, 32), _num)
}
}
function toUint(bytes memory _bytes, uint256 _start)
internal
pure
returns (uint256)
{
require(_bytes.length >= (_start + 32));
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function toAddress(bytes memory _bytes, uint256 _start)
internal
pure
returns (address)
{
require(_bytes.length >= (_start + 20));
address tempAddress;
assembly {
tempAddress := div(
mload(add(add(_bytes, 0x20), _start)),
0x1000000000000000000000000
)
}
return tempAddress;
}
}
// File: contracts/common/lib/ECVerify.sol
pragma solidity ^0.5.2;
library ECVerify {
function ecrecovery(bytes32 hash, bytes memory sig)
public
pure
returns (address)
{
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65) {
return address(0x0);
}
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := and(mload(add(sig, 65)), 255)
}
// https://github.com/ethereum/go-ethereum/issues/2053
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
return address(0x0);
}
// get address out of hash and signature
address result = ecrecover(hash, v, r, s);
// ecrecover returns zero on error
require(result != address(0x0));
return result;
}
function ecrecovery(bytes32 hash, uint8 v, bytes32 r, bytes32 s)
public
pure
returns (address)
{
// get address out of hash and signature
address result = ecrecover(hash, v, r, s);
// ecrecover returns zero on error
require(result != address(0x0), "signature verification failed");
return result;
}
function ecverify(bytes32 hash, bytes memory sig, address signer)
public
pure
returns (bool)
{
return signer == ecrecovery(hash, sig);
}
}
// File: contracts/common/lib/Merkle.sol
pragma solidity ^0.5.2;
library Merkle {
function checkMembership(
bytes32 leaf,
uint256 index,
bytes32 rootHash,
bytes memory proof
) public pure returns (bool) {
require(proof.length % 32 == 0, "Invalid proof length");
uint256 proofHeight = proof.length / 32;
// Proof of size n means, height of the tree is n+1.
// In a tree of height n+1, max #leafs possible is 2 ^ n
require(index < 2 ** proofHeight, "Leaf index is too big");
bytes32 proofElement;
bytes32 computedHash = leaf;
for (uint256 i = 32; i <= proof.length; i += 32) {
assembly {
proofElement := mload(add(proof, i))
}
if (index % 2 == 0) {
computedHash = keccak256(
abi.encodePacked(computedHash, proofElement)
);
} else {
computedHash = keccak256(
abi.encodePacked(proofElement, computedHash)
);
}
index = index / 2;
}
return computedHash == rootHash;
}
}
// File: contracts/common/governance/IGovernance.sol
pragma solidity ^0.5.2;
interface IGovernance {
function update(address target, bytes calldata data) external;
}
// File: contracts/common/governance/Governable.sol
pragma solidity ^0.5.2;
contract Governable {
IGovernance public governance;
constructor(address _governance) public {
governance = IGovernance(_governance);
}
modifier onlyGovernance() {
require(
msg.sender == address(governance),
"Only governance contract is authorized"
);
_;
}
}
// File: contracts/common/mixin/Lockable.sol
pragma solidity ^0.5.2;
contract Lockable {
bool public locked;
modifier onlyWhenUnlocked() {
_assertUnlocked();
_;
}
function _assertUnlocked() private view {
require(!locked, "locked");
}
function lock() public {
locked = true;
}
function unlock() public {
locked = false;
}
}
// File: contracts/common/mixin/GovernanceLockable.sol
pragma solidity ^0.5.2;
contract GovernanceLockable is Lockable, Governable {
constructor(address governance) public Governable(governance) {}
function lock() public onlyGovernance {
super.lock();
}
function unlock() public onlyGovernance {
super.unlock();
}
}
// File: contracts/common/mixin/RootChainable.sol
pragma solidity ^0.5.2;
/**
* @title RootChainable
*/
contract RootChainable is Ownable {
address public rootChain;
// Rootchain changed
event RootChainChanged(
address indexed previousRootChain,
address indexed newRootChain
);
//
// Only root chain
//
// only root chain
modifier onlyRootChain() {
require(msg.sender == rootChain);
_;
}
/**
* @dev Allows the current owner to change root chain address.
* @param newRootChain The address to new rootchain.
*/
function changeRootChain(address newRootChain) public onlyOwner {
require(newRootChain != address(0));
emit RootChainChanged(rootChain, newRootChain);
rootChain = newRootChain;
}
}
// File: contracts/root/withdrawManager/IWithdrawManager.sol
pragma solidity ^0.5.2;
contract IWithdrawManager {
function createExitQueue(address token) external;
function verifyInclusion(
bytes calldata data,
uint8 offset,
bool verifyTxInclusion
) external view returns (uint256 age);
function addExitToQueue(
address exitor,
address childToken,
address rootToken,
uint256 exitAmountOrTokenId,
bytes32 txHash,
bool isRegularExit,
uint256 priority
) external;
function addInput(
uint256 exitId,
uint256 age,
address utxoOwner,
address token
) external;
function challengeExit(
uint256 exitId,
uint256 inputId,
bytes calldata challengeData,
address adjudicatorPredicate
) external;
}
// File: contracts/common/Registry.sol
pragma solidity ^0.5.2;
contract Registry is Governable {
// @todo hardcode constants
bytes32 private constant WETH_TOKEN = keccak256("wethToken");
bytes32 private constant DEPOSIT_MANAGER = keccak256("depositManager");
bytes32 private constant STAKE_MANAGER = keccak256("stakeManager");
bytes32 private constant VALIDATOR_SHARE = keccak256("validatorShare");
bytes32 private constant WITHDRAW_MANAGER = keccak256("withdrawManager");
bytes32 private constant CHILD_CHAIN = keccak256("childChain");
bytes32 private constant STATE_SENDER = keccak256("stateSender");
bytes32 private constant SLASHING_MANAGER = keccak256("slashingManager");
address public erc20Predicate;
address public erc721Predicate;
mapping(bytes32 => address) public contractMap;
mapping(address => address) public rootToChildToken;
mapping(address => address) public childToRootToken;
mapping(address => bool) public proofValidatorContracts;
mapping(address => bool) public isERC721;
enum Type {Invalid, ERC20, ERC721, Custom}
struct Predicate {
Type _type;
}
mapping(address => Predicate) public predicates;
event TokenMapped(address indexed rootToken, address indexed childToken);
event ProofValidatorAdded(address indexed validator, address indexed from);
event ProofValidatorRemoved(address indexed validator, address indexed from);
event PredicateAdded(address indexed predicate, address indexed from);
event PredicateRemoved(address indexed predicate, address indexed from);
event ContractMapUpdated(bytes32 indexed key, address indexed previousContract, address indexed newContract);
constructor(address _governance) public Governable(_governance) {}
function updateContractMap(bytes32 _key, address _address) external onlyGovernance {
emit ContractMapUpdated(_key, contractMap[_key], _address);
contractMap[_key] = _address;
}
/**
* @dev Map root token to child token
* @param _rootToken Token address on the root chain
* @param _childToken Token address on the child chain
* @param _isERC721 Is the token being mapped ERC721
*/
function mapToken(
address _rootToken,
address _childToken,
bool _isERC721
) external onlyGovernance {
require(_rootToken != address(0x0) && _childToken != address(0x0), "INVALID_TOKEN_ADDRESS");
rootToChildToken[_rootToken] = _childToken;
childToRootToken[_childToken] = _rootToken;
isERC721[_rootToken] = _isERC721;
IWithdrawManager(contractMap[WITHDRAW_MANAGER]).createExitQueue(_rootToken);
emit TokenMapped(_rootToken, _childToken);
}
function addErc20Predicate(address predicate) public onlyGovernance {
require(predicate != address(0x0), "Can not add null address as predicate");
erc20Predicate = predicate;
addPredicate(predicate, Type.ERC20);
}
function addErc721Predicate(address predicate) public onlyGovernance {
erc721Predicate = predicate;
addPredicate(predicate, Type.ERC721);
}
function addPredicate(address predicate, Type _type) public onlyGovernance {
require(predicates[predicate]._type == Type.Invalid, "Predicate already added");
predicates[predicate]._type = _type;
emit PredicateAdded(predicate, msg.sender);
}
function removePredicate(address predicate) public onlyGovernance {
require(predicates[predicate]._type != Type.Invalid, "Predicate does not exist");
delete predicates[predicate];
emit PredicateRemoved(predicate, msg.sender);
}
function getValidatorShareAddress() public view returns (address) {
return contractMap[VALIDATOR_SHARE];
}
function getWethTokenAddress() public view returns (address) {
return contractMap[WETH_TOKEN];
}
function getDepositManagerAddress() public view returns (address) {
return contractMap[DEPOSIT_MANAGER];
}
function getStakeManagerAddress() public view returns (address) {
return contractMap[STAKE_MANAGER];
}
function getSlashingManagerAddress() public view returns (address) {
return contractMap[SLASHING_MANAGER];
}
function getWithdrawManagerAddress() public view returns (address) {
return contractMap[WITHDRAW_MANAGER];
}
function getChildChainAndStateSender() public view returns (address, address) {
return (contractMap[CHILD_CHAIN], contractMap[STATE_SENDER]);
}
function isTokenMapped(address _token) public view returns (bool) {
return rootToChildToken[_token] != address(0x0);
}
function isTokenMappedAndIsErc721(address _token) public view returns (bool) {
require(isTokenMapped(_token), "TOKEN_NOT_MAPPED");
return isERC721[_token];
}
function isTokenMappedAndGetPredicate(address _token) public view returns (address) {
if (isTokenMappedAndIsErc721(_token)) {
return erc721Predicate;
}
return erc20Predicate;
}
function isChildTokenErc721(address childToken) public view returns (bool) {
address rootToken = childToRootToken[childToken];
require(rootToken != address(0x0), "Child token is not mapped");
return isERC721[rootToken];
}
}
// File: contracts/staking/stakeManager/IStakeManager.sol
pragma solidity ^0.5.2;
contract IStakeManager {
// validator replacement
function startAuction(
uint256 validatorId,
uint256 amount,
bool acceptDelegation,
bytes calldata signerPubkey
) external;
function confirmAuctionBid(uint256 validatorId, uint256 heimdallFee) external;
function transferFunds(
uint256 validatorId,
uint256 amount,
address delegator
) external returns (bool);
function delegationDeposit(
uint256 validatorId,
uint256 amount,
address delegator
) external returns (bool);
function stake(
uint256 amount,
uint256 heimdallFee,
bool acceptDelegation,
bytes calldata signerPubkey
) external;
function unstake(uint256 validatorId) external;
function totalStakedFor(address addr) external view returns (uint256);
function stakeFor(
address user,
uint256 amount,
uint256 heimdallFee,
bool acceptDelegation,
bytes memory signerPubkey
) public;
function checkSignatures(
uint256 blockInterval,
bytes32 voteHash,
bytes32 stateRoot,
address proposer,
bytes memory sigs
) public returns (uint256);
function updateValidatorState(uint256 validatorId, int256 amount) public;
function ownerOf(uint256 tokenId) public view returns (address);
function slash(bytes memory slashingInfoList) public returns (uint256);
function validatorStake(uint256 validatorId) public view returns (uint256);
function epoch() public view returns (uint256);
function withdrawalDelay() public view returns (uint256);
}
// File: contracts/staking/validatorShare/IValidatorShare.sol
pragma solidity ^0.5.2;
// note this contract interface is only for stakeManager use
contract IValidatorShare {
function withdrawRewardsValidator() external returns (uint256);
function addProposerBonus(uint256 _rewards, uint256 valStake) public;
function withdrawRewards() public;
function unstakeClaimTokens() public;
function getLiquidRewards(address user) public view returns (uint256);
function getActiveAmount() external view returns (uint256);
function owner() public view returns (address);
function restake() public;
function updateRewards(
uint256 _reward,
uint256 _totalStake,
uint256 validatorStake
) external returns (uint256);
function unlockContract() external returns (uint256);
function lockContract() external returns (uint256);
function drain(
address token,
address payable destination,
uint256 amount
) external;
function slash(uint256 valPow, uint256 totalAmountToSlash) external returns (uint256);
function updateDelegation(bool delegation) external;
function migrateOut(address user, uint256 amount) external;
function migrateIn(address user, uint256 amount) external;
}
// File: contracts/staking/StakingInfo.sol
pragma solidity ^0.5.2;
// dummy interface to avoid cyclic dependency
contract IStakeManagerLocal {
enum Status {Inactive, Active, Locked, Unstaked}
struct Validator {
uint256 amount;
uint256 reward;
uint256 activationEpoch;
uint256 deactivationEpoch;
uint256 jailTime;
address signer;
address contractAddress;
Status status;
}
mapping(uint256 => Validator) public validators;
bytes32 public accountStateRoot;
uint256 public activeAmount; // delegation amount from validator contract
uint256 public validatorRewards;
function currentValidatorSetTotalStake() public view returns (uint256);
// signer to Validator mapping
function signerToValidator(address validatorAddress)
public
view
returns (uint256);
function isValidator(uint256 validatorId) public view returns (bool);
}
contract StakingInfo is Ownable {
using SafeMath for uint256;
mapping(uint256 => uint256) public validatorNonce;
/// @dev Emitted when validator stakes in '_stakeFor()' in StakeManager.
/// @param signer validator address.
/// @param validatorId unique integer to identify a validator.
/// @param nonce to synchronize the events in heimdal.
/// @param activationEpoch validator's first epoch as proposer.
/// @param amount staking amount.
/// @param total total staking amount.
/// @param signerPubkey public key of the validator
event Staked(
address indexed signer,
uint256 indexed validatorId,
uint256 nonce,
uint256 indexed activationEpoch,
uint256 amount,
uint256 total,
bytes signerPubkey
);
/// @dev Emitted when validator unstakes in 'unstakeClaim()'
/// @param user address of the validator.
/// @param validatorId unique integer to identify a validator.
/// @param amount staking amount.
/// @param total total staking amount.
event Unstaked(
address indexed user,
uint256 indexed validatorId,
uint256 amount,
uint256 total
);
/// @dev Emitted when validator unstakes in '_unstake()'.
/// @param user address of the validator.
/// @param validatorId unique integer to identify a validator.
/// @param nonce to synchronize the events in heimdal.
/// @param deactivationEpoch last epoch for validator.
/// @param amount staking amount.
event UnstakeInit(
address indexed user,
uint256 indexed validatorId,
uint256 nonce,
uint256 deactivationEpoch,
uint256 indexed amount
);
/// @dev Emitted when the validator public key is updated in 'updateSigner()'.
/// @param validatorId unique integer to identify a validator.
/// @param nonce to synchronize the events in heimdal.
/// @param oldSigner old address of the validator.
/// @param newSigner new address of the validator.
/// @param signerPubkey public key of the validator.
event SignerChange(
uint256 indexed validatorId,
uint256 nonce,
address indexed oldSigner,
address indexed newSigner,
bytes signerPubkey
);
event Restaked(uint256 indexed validatorId, uint256 amount, uint256 total);
event Jailed(
uint256 indexed validatorId,
uint256 indexed exitEpoch,
address indexed signer
);
event UnJailed(uint256 indexed validatorId, address indexed signer);
event Slashed(uint256 indexed nonce, uint256 indexed amount);
event ThresholdChange(uint256 newThreshold, uint256 oldThreshold);
event DynastyValueChange(uint256 newDynasty, uint256 oldDynasty);
event ProposerBonusChange(
uint256 newProposerBonus,
uint256 oldProposerBonus
);
event RewardUpdate(uint256 newReward, uint256 oldReward);
/// @dev Emitted when validator confirms the auction bid and at the time of restaking in confirmAuctionBid() and restake().
/// @param validatorId unique integer to identify a validator.
/// @param nonce to synchronize the events in heimdal.
/// @param newAmount the updated stake amount.
event StakeUpdate(
uint256 indexed validatorId,
uint256 indexed nonce,
uint256 indexed newAmount
);
event ClaimRewards(
uint256 indexed validatorId,
uint256 indexed amount,
uint256 indexed totalAmount
);
event StartAuction(
uint256 indexed validatorId,
uint256 indexed amount,
uint256 indexed auctionAmount
);
event ConfirmAuction(
uint256 indexed newValidatorId,
uint256 indexed oldValidatorId,
uint256 indexed amount
);
event TopUpFee(address indexed user, uint256 indexed fee);
event ClaimFee(address indexed user, uint256 indexed fee);
// Delegator events
event ShareMinted(
uint256 indexed validatorId,
address indexed user,
uint256 indexed amount,
uint256 tokens
);
event ShareBurned(
uint256 indexed validatorId,
address indexed user,
uint256 indexed amount,
uint256 tokens
);
event DelegatorClaimedRewards(
uint256 indexed validatorId,
address indexed user,
uint256 indexed rewards
);
event DelegatorRestaked(
uint256 indexed validatorId,
address indexed user,
uint256 indexed totalStaked
);
event DelegatorUnstaked(
uint256 indexed validatorId,
address indexed user,
uint256 amount
);
event UpdateCommissionRate(
uint256 indexed validatorId,
uint256 indexed newCommissionRate,
uint256 indexed oldCommissionRate
);
Registry public registry;
modifier onlyValidatorContract(uint256 validatorId) {
address _contract;
(, , , , , , _contract, ) = IStakeManagerLocal(
registry.getStakeManagerAddress()
)
.validators(validatorId);
require(_contract == msg.sender,
"Invalid sender, not validator");
_;
}
modifier StakeManagerOrValidatorContract(uint256 validatorId) {
address _contract;
address _stakeManager = registry.getStakeManagerAddress();
(, , , , , , _contract, ) = IStakeManagerLocal(_stakeManager).validators(
validatorId
);
require(_contract == msg.sender || _stakeManager == msg.sender,
"Invalid sender, not stake manager or validator contract");
_;
}
modifier onlyStakeManager() {
require(registry.getStakeManagerAddress() == msg.sender,
"Invalid sender, not stake manager");
_;
}
modifier onlySlashingManager() {
require(registry.getSlashingManagerAddress() == msg.sender,
"Invalid sender, not slashing manager");
_;
}
constructor(address _registry) public {
registry = Registry(_registry);
}
function updateNonce(
uint256[] calldata validatorIds,
uint256[] calldata nonces
) external onlyOwner {
require(validatorIds.length == nonces.length, "args length mismatch");
for (uint256 i = 0; i < validatorIds.length; ++i) {
validatorNonce[validatorIds[i]] = nonces[i];
}
}
function logStaked(
address signer,
bytes memory signerPubkey,
uint256 validatorId,
uint256 activationEpoch,
uint256 amount,
uint256 total
) public onlyStakeManager {
validatorNonce[validatorId] = validatorNonce[validatorId].add(1);
emit Staked(
signer,
validatorId,
validatorNonce[validatorId],
activationEpoch,
amount,
total,
signerPubkey
);
}
function logUnstaked(
address user,
uint256 validatorId,
uint256 amount,
uint256 total
) public onlyStakeManager {
emit Unstaked(user, validatorId, amount, total);
}
function logUnstakeInit(
address user,
uint256 validatorId,
uint256 deactivationEpoch,
uint256 amount
) public onlyStakeManager {
validatorNonce[validatorId] = validatorNonce[validatorId].add(1);
emit UnstakeInit(
user,
validatorId,
validatorNonce[validatorId],
deactivationEpoch,
amount
);
}
function logSignerChange(
uint256 validatorId,
address oldSigner,
address newSigner,
bytes memory signerPubkey
) public onlyStakeManager {
validatorNonce[validatorId] = validatorNonce[validatorId].add(1);
emit SignerChange(
validatorId,
validatorNonce[validatorId],
oldSigner,
newSigner,
signerPubkey
);
}
function logRestaked(uint256 validatorId, uint256 amount, uint256 total)
public
onlyStakeManager
{
emit Restaked(validatorId, amount, total);
}
function logJailed(uint256 validatorId, uint256 exitEpoch, address signer)
public
onlyStakeManager
{
emit Jailed(validatorId, exitEpoch, signer);
}
function logUnjailed(uint256 validatorId, address signer)
public
onlyStakeManager
{
emit UnJailed(validatorId, signer);
}
function logSlashed(uint256 nonce, uint256 amount)
public
onlySlashingManager
{
emit Slashed(nonce, amount);
}
function logThresholdChange(uint256 newThreshold, uint256 oldThreshold)
public
onlyStakeManager
{
emit ThresholdChange(newThreshold, oldThreshold);
}
function logDynastyValueChange(uint256 newDynasty, uint256 oldDynasty)
public
onlyStakeManager
{
emit DynastyValueChange(newDynasty, oldDynasty);
}
function logProposerBonusChange(
uint256 newProposerBonus,
uint256 oldProposerBonus
) public onlyStakeManager {
emit ProposerBonusChange(newProposerBonus, oldProposerBonus);
}
function logRewardUpdate(uint256 newReward, uint256 oldReward)
public
onlyStakeManager
{
emit RewardUpdate(newReward, oldReward);
}
function logStakeUpdate(uint256 validatorId)
public
StakeManagerOrValidatorContract(validatorId)
{
validatorNonce[validatorId] = validatorNonce[validatorId].add(1);
emit StakeUpdate(
validatorId,
validatorNonce[validatorId],
totalValidatorStake(validatorId)
);
}
function logClaimRewards(
uint256 validatorId,
uint256 amount,
uint256 totalAmount
) public onlyStakeManager {
emit ClaimRewards(validatorId, amount, totalAmount);
}
function logStartAuction(
uint256 validatorId,
uint256 amount,
uint256 auctionAmount
) public onlyStakeManager {
emit StartAuction(validatorId, amount, auctionAmount);
}
function logConfirmAuction(
uint256 newValidatorId,
uint256 oldValidatorId,
uint256 amount
) public onlyStakeManager {
emit ConfirmAuction(newValidatorId, oldValidatorId, amount);
}
function logTopUpFee(address user, uint256 fee) public onlyStakeManager {
emit TopUpFee(user, fee);
}
function logClaimFee(address user, uint256 fee) public onlyStakeManager {
emit ClaimFee(user, fee);
}
function getStakerDetails(uint256 validatorId)
public
view
returns (
uint256 amount,
uint256 reward,
uint256 activationEpoch,
uint256 deactivationEpoch,
address signer,
uint256 _status
)
{
IStakeManagerLocal stakeManager = IStakeManagerLocal(
registry.getStakeManagerAddress()
);
address _contract;
IStakeManagerLocal.Status status;
(
amount,
reward,
activationEpoch,
deactivationEpoch,
,
signer,
_contract,
status
) = stakeManager.validators(validatorId);
_status = uint256(status);
if (_contract != address(0x0)) {
reward += IStakeManagerLocal(_contract).validatorRewards();
}
}
function totalValidatorStake(uint256 validatorId)
public
view
returns (uint256 validatorStake)
{
address contractAddress;
(validatorStake, , , , , , contractAddress, ) = IStakeManagerLocal(
registry.getStakeManagerAddress()
)
.validators(validatorId);
if (contractAddress != address(0x0)) {
validatorStake += IStakeManagerLocal(contractAddress).activeAmount();
}
}
function getAccountStateRoot()
public
view
returns (bytes32 accountStateRoot)
{
accountStateRoot = IStakeManagerLocal(registry.getStakeManagerAddress())
.accountStateRoot();
}
function getValidatorContractAddress(uint256 validatorId)
public
view
returns (address ValidatorContract)
{
(, , , , , , ValidatorContract, ) = IStakeManagerLocal(
registry.getStakeManagerAddress()
)
.validators(validatorId);
}
// validator Share contract logging func
function logShareMinted(
uint256 validatorId,
address user,
uint256 amount,
uint256 tokens
) public onlyValidatorContract(validatorId) {
emit ShareMinted(validatorId, user, amount, tokens);
}
function logShareBurned(
uint256 validatorId,
address user,
uint256 amount,
uint256 tokens
) public onlyValidatorContract(validatorId) {
emit ShareBurned(validatorId, user, amount, tokens);
}
function logDelegatorClaimRewards(
uint256 validatorId,
address user,
uint256 rewards
) public onlyValidatorContract(validatorId) {
emit DelegatorClaimedRewards(validatorId, user, rewards);
}
function logDelegatorRestaked(
uint256 validatorId,
address user,
uint256 totalStaked
) public onlyValidatorContract(validatorId) {
emit DelegatorRestaked(validatorId, user, totalStaked);
}
function logDelegatorUnstaked(uint256 validatorId, address user, uint256 amount)
public
onlyValidatorContract(validatorId)
{
emit DelegatorUnstaked(validatorId, user, amount);
}
function logUpdateCommissionRate(
uint256 validatorId,
uint256 newCommissionRate,
uint256 oldCommissionRate
) public onlyValidatorContract(validatorId) {
emit UpdateCommissionRate(
validatorId,
newCommissionRate,
oldCommissionRate
);
}
}
// File: openzeppelin-solidity/contracts/introspection/IERC165.sol
pragma solidity ^0.5.2;
/**
* @title IERC165
* @dev https://eips.ethereum.org/EIPS/eip-165
*/
interface IERC165 {
/**
* @notice Query if a contract implements an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: openzeppelin-solidity/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.5.2;
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function balanceOf(address owner) public view returns (uint256 balance);
function ownerOf(uint256 tokenId) public view returns (address owner);
function approve(address to, uint256 tokenId) public;
function getApproved(uint256 tokenId) public view returns (address operator);
function setApprovalForAll(address operator, bool _approved) public;
function isApprovedForAll(address owner, address operator) public view returns (bool);
function transferFrom(address from, address to, uint256 tokenId) public;
function safeTransferFrom(address from, address to, uint256 tokenId) public;
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public;
}
// File: openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.5.2;
/**
* @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 `safeTransfer`. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data)
public returns (bytes4);
}
// File: openzeppelin-solidity/contracts/utils/Address.sol
pragma solidity ^0.5.2;
/**
* Utility library of inline functions on addresses
*/
library Address {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
// File: openzeppelin-solidity/contracts/drafts/Counters.sol
pragma solidity ^0.5.2;
/**
* @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 {
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// File: openzeppelin-solidity/contracts/introspection/ERC165.sol
pragma solidity ^0.5.2;
/**
* @title ERC165
* @author Matt Condon (@shrugs)
* @dev Implements ERC165 using a lookup table.
*/
contract ERC165 is IERC165 {
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/*
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) private _supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor () internal {
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev internal method for registering an interface
*/
function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff);
_supportedInterfaces[interfaceId] = true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.5.2;
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is 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 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
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));
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));
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);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
_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));
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 != 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
* 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 {
require(_isApprovedOrOwner(msg.sender, tokenId));
_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 `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public {
transferFrom(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data));
}
/**
* @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) {
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @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));
require(!_exists(tokenId));
_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(uint256) 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);
_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);
require(to != address(0));
_clearApproval(tokenId);
_ownedTokensCount[from].decrement();
_ownedTokensCount[to].increment();
_tokenOwner[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Internal function to invoke `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)
internal returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data);
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Private function to clear current approval of a given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(uint256 tokenId) private {
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
// File: openzeppelin-solidity/contracts/token/ERC721/IERC721Enumerable.sol
pragma solidity ^0.5.2;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract IERC721Enumerable is IERC721 {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId);
function tokenByIndex(uint256 index) public view returns (uint256);
}
// File: openzeppelin-solidity/contracts/token/ERC721/ERC721Enumerable.sol
pragma solidity ^0.5.2;
/**
* @title ERC-721 Non-Fungible Token with optional enumeration extension logic
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Enumerable is ERC165, ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/*
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
/**
* @dev Constructor function
*/
constructor () public {
// register the supported interface to conform to ERC721Enumerable via ERC165
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner
* @param owner address owning the tokens list to be accessed
* @param index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) {
require(index < balanceOf(owner));
return _ownedTokens[owner][index];
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return _allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens
* @param index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 index) public view returns (uint256) {
require(index < totalSupply());
return _allTokens[index];
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to transferFrom, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transferFrom(address from, address to, uint256 tokenId) internal {
super._transferFrom(from, to, tokenId);
_removeTokenFromOwnerEnumeration(from, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param to address the beneficiary that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, uint256 tokenId) internal {
super._mint(to, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
_addTokenToAllTokensEnumeration(tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* Deprecated, use _burn(uint256) instead
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
_removeTokenFromOwnerEnumeration(owner, tokenId);
// Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund
_ownedTokensIndex[tokenId] = 0;
_removeTokenFromAllTokensEnumeration(tokenId);
}
/**
* @dev Gets the list of token IDs of the requested owner
* @param owner address owning the tokens
* @return uint256[] List of token IDs owned by the requested address
*/
function _tokensOfOwner(address owner) internal view returns (uint256[] storage) {
return _ownedTokens[owner];
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
_ownedTokensIndex[tokenId] = _ownedTokens[to].length;
_ownedTokens[to].push(tokenId);
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the _ownedTokensIndex mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _ownedTokens[from].length.sub(1);
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
_ownedTokens[from].length--;
// Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by
// lastTokenId, or just over the end of the array if the token was the last one).
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length.sub(1);
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
_allTokens.length--;
_allTokensIndex[tokenId] = 0;
}
}
// File: openzeppelin-solidity/contracts/token/ERC721/IERC721Metadata.sol
pragma solidity ^0.5.2;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: openzeppelin-solidity/contracts/token/ERC721/ERC721Metadata.sol
pragma solidity ^0.5.2;
contract ERC721Metadata is ERC165, ERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
/**
* @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 an URI for a given token ID
* Throws if the token ID does not exist. May return an empty string.
* @param tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId));
return _tokenURIs[tokenId];
}
/**
* @dev Internal function to set the token URI for a given token
* Reverts if the token ID does not exist
* @param tokenId uint256 ID of the token to set its URI
* @param uri string URI to assign
*/
function _setTokenURI(uint256 tokenId, string memory uri) internal {
require(_exists(tokenId));
_tokenURIs[tokenId] = uri;
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* Deprecated, use _burn(uint256) instead
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// File: openzeppelin-solidity/contracts/token/ERC721/ERC721Full.sol
pragma solidity ^0.5.2;
/**
* @title Full ERC721 Token
* This implementation includes all the required and some optional functionality of the ERC721 standard
* Moreover, it includes approve all functionality using operator terminology
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata {
constructor (string memory name, string memory symbol) public ERC721Metadata(name, symbol) {
// solhint-disable-previous-line no-empty-blocks
}
}
// File: contracts/staking/stakeManager/StakingNFT.sol
pragma solidity ^0.5.2;
contract StakingNFT is ERC721Full, Ownable {
constructor(string memory name, string memory symbol)
public
ERC721Full(name, symbol)
{
// solhint-disable-previous-line no-empty-blocks
}
function mint(address to, uint256 tokenId) public onlyOwner {
require(
balanceOf(to) == 0,
"Validators MUST NOT own multiple stake position"
);
_mint(to, tokenId);
}
function burn(uint256 tokenId) public onlyOwner {
_burn(tokenId);
}
function _transferFrom(address from, address to, uint256 tokenId) internal {
require(
balanceOf(to) == 0,
"Validators MUST NOT own multiple stake position"
);
super._transferFrom(from, to, tokenId);
}
}
// File: contracts/common/misc/ProxyStorage.sol
pragma solidity ^0.5.2;
contract ProxyStorage is Ownable {
address internal proxyTo;
}
// File: contracts/common/misc/ERCProxy.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.5.2;
// See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-897.md
interface ERCProxy {
function proxyType() external pure returns (uint256 proxyTypeId);
function implementation() external view returns (address codeAddr);
}
// File: contracts/common/misc/DelegateProxy.sol
pragma solidity ^0.5.2;
contract DelegateProxy is ERCProxy {
function proxyType() external pure returns (uint256 proxyTypeId) {
// Upgradeable proxy
proxyTypeId = 2;
}
function implementation() external view returns (address);
function delegatedFwd(address _dst, bytes memory _calldata) internal {
// solium-disable-next-line security/no-inline-assembly
assembly {
let result := delegatecall(
sub(gas, 10000),
_dst,
add(_calldata, 0x20),
mload(_calldata),
0,
0
)
let size := returndatasize
let ptr := mload(0x40)
returndatacopy(ptr, 0, size)
// revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas.
// if the call returned error data, forward it
switch result
case 0 {
revert(ptr, size)
}
default {
return(ptr, size)
}
}
}
}
// File: contracts/common/misc/UpgradableProxy.sol
pragma solidity ^0.5.2;
contract UpgradableProxy is DelegateProxy {
event ProxyUpdated(address indexed _new, address indexed _old);
event OwnerUpdate(address _new, address _old);
bytes32 constant IMPLEMENTATION_SLOT = keccak256("matic.network.proxy.implementation");
bytes32 constant OWNER_SLOT = keccak256("matic.network.proxy.owner");
constructor(address _proxyTo) public {
setOwner(msg.sender);
setImplementation(_proxyTo);
}
function() external payable {
// require(currentContract != 0, "If app code has not been set yet, do not call");
// Todo: filter out some calls or handle in the end fallback
delegatedFwd(loadImplementation(), msg.data);
}
modifier onlyProxyOwner() {
require(loadOwner() == msg.sender, "NOT_OWNER");
_;
}
function owner() external view returns(address) {
return loadOwner();
}
function loadOwner() internal view returns(address) {
address _owner;
bytes32 position = OWNER_SLOT;
assembly {
_owner := sload(position)
}
return _owner;
}
function implementation() external view returns (address) {
return loadImplementation();
}
function loadImplementation() internal view returns(address) {
address _impl;
bytes32 position = IMPLEMENTATION_SLOT;
assembly {
_impl := sload(position)
}
return _impl;
}
function transferOwnership(address newOwner) public onlyProxyOwner {
require(newOwner != address(0), "ZERO_ADDRESS");
emit OwnerUpdate(newOwner, loadOwner());
setOwner(newOwner);
}
function setOwner(address newOwner) private {
bytes32 position = OWNER_SLOT;
assembly {
sstore(position, newOwner)
}
}
function updateImplementation(address _newProxyTo) public onlyProxyOwner {
require(_newProxyTo != address(0x0), "INVALID_PROXY_ADDRESS");
require(isContract(_newProxyTo), "DESTINATION_ADDRESS_IS_NOT_A_CONTRACT");
emit ProxyUpdated(_newProxyTo, loadImplementation());
setImplementation(_newProxyTo);
}
function updateAndCall(address _newProxyTo, bytes memory data) payable public onlyProxyOwner {
updateImplementation(_newProxyTo);
(bool success, bytes memory returnData) = address(this).call.value(msg.value)(data);
require(success, string(returnData));
}
function setImplementation(address _newProxyTo) private {
bytes32 position = IMPLEMENTATION_SLOT;
assembly {
sstore(position, _newProxyTo)
}
}
function isContract(address _target) internal view returns (bool) {
if (_target == address(0)) {
return false;
}
uint256 size;
assembly {
size := extcodesize(_target)
}
return size > 0;
}
}
// File: contracts/staking/validatorShare/ValidatorShareProxy.sol
pragma solidity ^0.5.2;
contract ValidatorShareProxy is UpgradableProxy {
constructor(address _registry) public UpgradableProxy(_registry) {}
function loadImplementation() internal view returns (address) {
return Registry(super.loadImplementation()).getValidatorShareAddress();
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.5.2;
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to 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) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @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) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][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
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][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
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @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) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, 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) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
// File: contracts/common/tokens/ERC20NonTransferable.sol
pragma solidity ^0.5.2;
contract ERC20NonTransferable is ERC20 {
function _transfer(
address from,
address to,
uint256 value
) internal {
revert("Disabled");
}
}
// File: contracts/common/mixin/OwnableLockable.sol
pragma solidity ^0.5.2;
contract OwnableLockable is Lockable, Ownable {
function lock() public onlyOwner {
super.lock();
}
function unlock() public onlyOwner {
super.unlock();
}
}
// File: contracts/common/mixin/Initializable.sol
pragma solidity ^0.5.2;
contract Initializable {
bool inited = false;
modifier initializer() {
require(!inited, "already inited");
inited = true;
_;
}
}
// File: contracts/staking/validatorShare/ValidatorShare.sol
pragma solidity ^0.5.2;
contract ValidatorShare is IValidatorShare, ERC20NonTransferable, OwnableLockable, Initializable {
struct DelegatorUnbond {
uint256 shares;
uint256 withdrawEpoch;
}
uint256 constant EXCHANGE_RATE_PRECISION = 100;
// maximum matic possible, even if rate will be 1 and all matic will be staken in one go, it will result in 10 ^ 58 shares
uint256 constant EXCHANGE_RATE_HIGH_PRECISION = 10 ** 29;
uint256 constant MAX_COMMISION_RATE = 100;
uint256 constant REWARD_PRECISION = 10**25;
StakingInfo public stakingLogger;
IStakeManager public stakeManager;
uint256 public validatorId;
uint256 public validatorRewards;
uint256 public commissionRate;
//last checkpoint where validator updated commission rate
uint256 public lastCommissionUpdate;
uint256 public minAmount = 10**18;
// deprecated
uint256 public __totalStake;
uint256 public rewardPerShare;
uint256 public activeAmount;
bool public delegation = true;
uint256 public withdrawPool;
uint256 public withdrawShares;
// deprecated
mapping(address => uint256) __amountStaked;
mapping(address => DelegatorUnbond) public unbonds;
mapping(address => uint256) public initalRewardPerShare;
modifier onlyValidator() {
require(stakeManager.ownerOf(validatorId) == msg.sender, "not validator");
_;
}
// onlyOwner will prevent this contract from initializing, since it's owner is going to be 0x0 address
function initialize(uint256 _validatorId, address _stakingLogger, address _stakeManager) external initializer {
validatorId = _validatorId;
stakingLogger = StakingInfo(_stakingLogger);
stakeManager = IStakeManager(_stakeManager);
_transferOwnership(_stakeManager);
minAmount = 10**18;
delegation = true;
}
function updateCommissionRate(uint256 newCommissionRate) external onlyValidator {
uint256 epoch = stakeManager.epoch();
uint256 _lastCommissionUpdate = lastCommissionUpdate;
require( // withdrawalDelay == dynasty
(_lastCommissionUpdate.add(stakeManager.withdrawalDelay()) <= epoch) || _lastCommissionUpdate == 0, // For initial setting of commission rate
"Commission rate update cooldown period"
);
require(newCommissionRate <= MAX_COMMISION_RATE, "Commission rate should be in range of 0-100");
stakingLogger.logUpdateCommissionRate(validatorId, newCommissionRate, commissionRate);
commissionRate = newCommissionRate;
lastCommissionUpdate = epoch;
}
function updateRewards(uint256 reward, uint256 checkpointStakePower, uint256 validatorStake)
external
onlyOwner
returns (uint256)
{
uint256 combinedStakePower = validatorStake.add(activeAmount); // validator + delegation stake power
uint256 rewards = combinedStakePower.mul(reward).div(checkpointStakePower);
_updateRewards(rewards, validatorStake, combinedStakePower);
return combinedStakePower;
}
function addProposerBonus(uint256 rewards, uint256 validatorStake) public onlyOwner {
uint256 combinedStakePower = validatorStake.add(activeAmount);
_updateRewards(rewards, validatorStake, combinedStakePower);
}
function _updateRewards(uint256 rewards, uint256 validatorStake, uint256 combinedStakePower) internal {
uint256 _validatorRewards = validatorStake.mul(rewards).div(combinedStakePower);
// add validator commission from delegation rewards
if (commissionRate > 0) {
_validatorRewards = _validatorRewards.add(
rewards.sub(_validatorRewards).mul(commissionRate).div(MAX_COMMISION_RATE)
);
}
validatorRewards = validatorRewards.add(_validatorRewards);
uint256 delegatorsRewards = rewards.sub(_validatorRewards);
uint256 totalShares = totalSupply();
if (totalShares > 0) {
rewardPerShare = rewardPerShare.add(
delegatorsRewards.mul(REWARD_PRECISION).div(totalShares)
);
}
}
function withdrawRewardsValidator() external onlyOwner returns (uint256) {
uint256 _validatorRewards = validatorRewards;
validatorRewards = 0;
return _validatorRewards;
}
function _getRatePrecision() private view returns(uint256) {
// if foundation validator, use old precision
if (validatorId < 8) {
return EXCHANGE_RATE_PRECISION;
}
return EXCHANGE_RATE_HIGH_PRECISION;
}
function exchangeRate() public view returns (uint256) {
uint256 totalShares = totalSupply();
uint256 precision = _getRatePrecision();
return
totalShares == 0
? precision
: activeAmount.mul(precision).div(totalShares);
}
function withdrawExchangeRate() public view returns (uint256) {
uint256 precision = _getRatePrecision();
if (validatorId < 8) {
// fix of potentially broken withdrawals for future unbonding
// foundation validators have no slashing enabled and thus we can return default exchange rate
// because without slashing rate will stay constant
return precision;
}
uint256 _withdrawShares = withdrawShares;
return
_withdrawShares == 0
? precision
: withdrawPool.mul(precision).div(_withdrawShares);
}
function buyVoucher(uint256 _amount, uint256 _minSharesToMint) public {
_buyVoucher(_amount, _minSharesToMint);
}
function _buyVoucher(uint256 _amount, uint256 _minSharesToMint) internal returns(uint256) {
_withdrawAndTransferReward(msg.sender);
uint256 amountToDeposit = _buyShares(_amount, _minSharesToMint, msg.sender);
require(stakeManager.delegationDeposit(validatorId, amountToDeposit, msg.sender), "deposit failed");
return amountToDeposit;
}
function _getTotalStake(address user) internal view returns(uint256, uint256) {
uint256 shares = balanceOf(user);
uint256 rate = exchangeRate();
if (shares == 0) {
return (0, rate);
}
return (rate.mul(shares).div(_getRatePrecision()), rate);
}
function restake() public {
_restake();
}
function _restake() internal returns(uint256) {
uint256 liquidReward = _withdrawReward(msg.sender);
require(liquidReward >= minAmount, "Too small rewards to restake");
uint256 amountRestaked = _buyShares(liquidReward, 0, msg.sender);
if (liquidReward > amountRestaked) {
// return change to the user
require(stakeManager.transferFunds(validatorId, liquidReward - amountRestaked, msg.sender), "Insufficent rewards");
stakingLogger.logDelegatorClaimRewards(validatorId, msg.sender, liquidReward - amountRestaked);
}
(uint256 totalStaked, ) = _getTotalStake(msg.sender);
stakingLogger.logDelegatorRestaked(validatorId, msg.sender, totalStaked);
return amountRestaked;
}
function _buyShares(uint256 _amount, uint256 _minSharesToMint, address user) private onlyWhenUnlocked returns(uint256) {
require(delegation, "Delegation is disabled");
uint256 rate = exchangeRate();
uint256 precision = _getRatePrecision();
uint256 shares = _amount.mul(precision).div(rate);
require(shares >= _minSharesToMint, "Too much slippage");
require(unbonds[user].shares == 0, "Ongoing exit");
_mint(user, shares);
// clamp amount of tokens in case resulted shares requires less tokens than anticipated
_amount = _amount.sub(_amount % rate.mul(shares).div(precision));
activeAmount = activeAmount.add(_amount);
stakeManager.updateValidatorState(validatorId, int256(_amount));
StakingInfo logger = stakingLogger;
logger.logShareMinted(validatorId, user, _amount, shares);
logger.logStakeUpdate(validatorId);
return _amount;
}
function _reduceActiveStake(uint256 activeStakeReduce) private {
activeAmount = activeAmount.sub(activeStakeReduce);
}
function _reduceWithdrawPool(uint256 withdrawPoolReduce) private {
withdrawPool = withdrawPool.sub(withdrawPoolReduce);
}
function sellVoucher(uint256 claimAmount, uint256 maximumSharesToBurn) public {
// first get how much staked in total and compare to target unstake amount
(uint256 totalStaked, uint256 rate) = _getTotalStake(msg.sender);
require(totalStaked > 0 && totalStaked >= claimAmount, "Too much requested");
// convert requested amount back to shares
uint256 precision = _getRatePrecision();
uint256 shares = claimAmount.mul(precision).div(rate);
require(shares <= maximumSharesToBurn, "too much slippage");
_withdrawAndTransferReward(msg.sender);
_burn(msg.sender, shares);
stakeManager.updateValidatorState(validatorId, -int256(claimAmount));
_reduceActiveStake(claimAmount);
uint256 _withdrawPoolShare = claimAmount.mul(precision).div(withdrawExchangeRate());
withdrawPool = withdrawPool.add(claimAmount);
withdrawShares = withdrawShares.add(_withdrawPoolShare);
DelegatorUnbond memory unbond = unbonds[msg.sender];
unbond.shares = unbond.shares.add(_withdrawPoolShare);
// refresh undond period
unbond.withdrawEpoch = stakeManager.epoch();
unbonds[msg.sender] = unbond;
StakingInfo logger = stakingLogger;
logger.logShareBurned(validatorId, msg.sender, claimAmount, shares);
logger.logStakeUpdate(validatorId);
}
function _withdrawReward(address user) private returns(uint256) {
uint256 liquidRewards = getLiquidRewards(user);
initalRewardPerShare[user] = rewardPerShare;
return liquidRewards;
}
function _withdrawAndTransferReward(address user) private returns(uint256) {
uint256 liquidRewards = _withdrawReward(user);
if (liquidRewards > 0) {
require(stakeManager.transferFunds(validatorId, liquidRewards, user), "Insufficent rewards");
stakingLogger.logDelegatorClaimRewards(validatorId, user, liquidRewards);
}
return liquidRewards;
}
function withdrawRewards() public {
uint256 rewards = _withdrawAndTransferReward(msg.sender);
require(rewards >= minAmount, "Too small rewards amount");
}
function migrateOut(address user, uint256 amount) external onlyOwner {
_withdrawAndTransferReward(user);
(uint256 totalStaked, uint256 rate) = _getTotalStake(user);
require(totalStaked >= amount, "Migrating too much");
uint256 precision = _getRatePrecision();
uint256 shares = amount.mul(precision).div(rate);
_burn(user, shares);
stakeManager.updateValidatorState(validatorId, -int256(amount));
_reduceActiveStake(amount);
stakingLogger.logShareBurned(validatorId, user, amount, shares);
stakingLogger.logStakeUpdate(validatorId);
stakingLogger.logDelegatorUnstaked(validatorId, user, amount);
}
function migrateIn(address user, uint256 amount) external onlyOwner {
_buyShares(amount, 0, user);
}
function getLiquidRewards(address user) public view returns (uint256) {
uint256 shares = balanceOf(user);
if (shares == 0) {
return 0;
}
return rewardPerShare.sub(initalRewardPerShare[user]).mul(shares).div(REWARD_PRECISION);
}
function unstakeClaimTokens() public {
_claimUnstakedTokens();
}
function _claimUnstakedTokens() internal returns(uint256) {
DelegatorUnbond memory unbond = unbonds[msg.sender];
uint256 shares = unbond.shares;
require(
unbond.withdrawEpoch.add(stakeManager.withdrawalDelay()) <= stakeManager.epoch() && shares > 0,
"Incomplete withdrawal period"
);
uint256 _amount = withdrawExchangeRate().mul(shares).div(_getRatePrecision());
withdrawShares = withdrawShares.sub(shares);
withdrawPool = withdrawPool.sub(_amount);
require(stakeManager.transferFunds(validatorId, _amount, msg.sender), "Insufficent rewards");
stakingLogger.logDelegatorUnstaked(validatorId, msg.sender, _amount);
delete unbonds[msg.sender];
return _amount;
}
function slash(uint256 valPow, uint256 totalAmountToSlash) external onlyOwner returns (uint256) {
uint256 _withdrawPool = withdrawPool;
uint256 delegationAmount = activeAmount.add(_withdrawPool);
if (delegationAmount == 0) {
return 0;
}
// total amount to be slashed from delegation pool (active + inactive)
uint256 _amountToSlash = delegationAmount.mul(totalAmountToSlash).div(valPow.add(delegationAmount));
uint256 _amountToSlashWithdrawalPool = _withdrawPool.mul(_amountToSlash).div(delegationAmount);
// slash inactive pool
_reduceActiveStake(_amountToSlash.sub(_amountToSlashWithdrawalPool));
_reduceWithdrawPool(_amountToSlashWithdrawalPool);
return _amountToSlash;
}
function updateDelegation(bool _delegation) external onlyOwner {
delegation = _delegation;
}
function drain(
address token,
address payable destination,
uint256 amount
) external onlyOwner {
if (token == address(0x0)) {
destination.transfer(amount);
} else {
require(ERC20(token).transfer(destination, amount), "Drain failed");
}
}
function getActiveAmount() external view returns(uint256) {
return activeAmount;
}
function unlockContract() external onlyOwner returns (uint256) {
unlock();
return activeAmount;
}
function lockContract() external onlyOwner returns (uint256) {
lock();
return activeAmount;
}
}
// File: contracts/staking/validatorShare/ValidatorShareFactory.sol
pragma solidity ^0.5.2;
contract ValidatorShareFactory {
/**
- factory to create new validatorShare contracts
*/
function create(uint256 validatorId, address loggerAddress, address registry) public returns (address) {
ValidatorShareProxy proxy = new ValidatorShareProxy(registry);
proxy.transferOwnership(msg.sender);
address proxyAddr = address(proxy);
(bool success, bytes memory data) = proxyAddr.call.gas(gasleft())(
abi.encodeWithSelector(
ValidatorShare(proxyAddr).initialize.selector,
validatorId,
loggerAddress,
msg.sender
)
);
require(success, string(data));
return proxyAddr;
}
}
// File: contracts/staking/stakeManager/StakeManagerStorage.sol
pragma solidity ^0.5.2;
contract StakeManagerStorage is GovernanceLockable, RootChainable {
IERC20 public token;
address public registry;
StakingInfo public logger;
StakingNFT public NFTContract;
ValidatorShareFactory public factory;
uint256 public WITHDRAWAL_DELAY; // unit: epoch
uint256 public currentEpoch;
// genesis/governance variables
uint256 public dynasty ; // unit: epoch 50 days
uint256 public CHECKPOINT_REWARD; // update via governance
uint256 public minDeposit; // in ERC20 token
uint256 public minHeimdallFee; // in ERC20 token
uint256 public checkPointBlockInterval;
uint256 public signerUpdateLimit;
uint256 public validatorThreshold; //128
uint256 public totalStaked;
uint256 public NFTCounter;
uint256 public totalRewards;
uint256 public totalRewardsLiquidated;
uint256 public auctionPeriod; // 1 week in epochs
uint256 public proposerBonus; // 10 % of total rewards
bytes32 public accountStateRoot;
// Stop validator auction for some time when updating dynasty value
uint256 public replacementCoolDown;
bool public delegationEnabled;
struct Auction {
uint256 amount;
uint256 startEpoch;
address user;
bool acceptDelegation;
bytes signerPubkey;
}
struct State {
uint256 amount;
uint256 stakerCount;
}
struct StateChange {
int256 amount;
int256 stakerCount;
}
enum Status {Inactive, Active, Locked, Unstaked}
struct Validator {
uint256 amount;
uint256 reward;
uint256 activationEpoch;
uint256 deactivationEpoch;
uint256 jailTime;
address signer;
address contractAddress;
Status status;
}
mapping(uint256 => Validator) public validators;
// signer to Validator mapping
mapping(address => uint256) public signerToValidator;
State public validatorState;
mapping(uint256 => StateChange) public validatorStateChanges;
mapping(address => uint256) public userFeeExit;
//Ongoing auctions for validatorId
mapping(uint256 => Auction) public validatorAuction;
// validatorId to last signer update epoch
mapping(uint256 => uint256) public latestSignerUpdateEpoch;
uint256 public totalHeimdallFee;
}
// File: contracts/staking/stakeManager/StakeManager.sol
pragma solidity ^0.5.2;
contract StakeManager is IStakeManager, StakeManagerStorage, Initializable {
using SafeMath for uint256;
using ECVerify for bytes32;
using Merkle for bytes32;
using RLPReader for bytes;
using RLPReader for RLPReader.RLPItem;
uint256 private constant INCORRECT_VALIDATOR_ID = 2**256 - 1;
modifier onlyStaker(uint256 validatorId) {
_assertOnlyStaker(validatorId);
_;
}
function _assertOnlyStaker(uint256 validatorId) private view {
require(NFTContract.ownerOf(validatorId) == msg.sender);
}
constructor() public GovernanceLockable(address(0x0)) {}
function initialize(
address _registry,
address _rootchain,
address _token,
address _NFTContract,
address _stakingLogger,
address _validatorShareFactory,
address _governance,
address _owner
) external initializer {
governance = IGovernance(_governance);
registry = _registry;
rootChain = _rootchain;
token = IERC20(_token);
NFTContract = StakingNFT(_NFTContract);
logger = StakingInfo(_stakingLogger);
factory = ValidatorShareFactory(_validatorShareFactory);
_transferOwnership(_owner);
WITHDRAWAL_DELAY = (2**13); // unit: epoch
currentEpoch = 1;
dynasty = 886; // unit: epoch 50 days
CHECKPOINT_REWARD = 20188 * (10**18); // update via governance
minDeposit = (10**18); // in ERC20 token
minHeimdallFee = (10**18); // in ERC20 token
checkPointBlockInterval = 1024;
signerUpdateLimit = 100;
validatorThreshold = 7; //128
NFTCounter = 1;
auctionPeriod = (2**13) / 4; // 1 week in epochs
proposerBonus = 10; // 10 % of total rewards
delegationEnabled = true;
}
function setDelegationEnabled(bool enabled) public onlyGovernance {
delegationEnabled = enabled;
}
// TopUp heimdall fee
function topUpForFee(address user, uint256 heimdallFee) public onlyWhenUnlocked {
_transferAndTopUp(user, heimdallFee, 0);
}
function ownerOf(uint256 tokenId) public view returns (address) {
return NFTContract.ownerOf(tokenId);
}
function epoch() public view returns (uint256) {
return currentEpoch;
}
function withdrawalDelay() public view returns (uint256) {
return WITHDRAWAL_DELAY;
}
function validatorStake(uint256 validatorId) public view returns (uint256) {
return validators[validatorId].amount;
}
function _transferAndTopUp(
address user,
uint256 fee,
uint256 additionalAmount
) private {
require(fee >= minHeimdallFee, "Not enough heimdall fee");
require(token.transferFrom(msg.sender, address(this), fee.add(additionalAmount)), "Fee transfer failed");
totalHeimdallFee = totalHeimdallFee.add(fee);
logger.logTopUpFee(user, fee);
}
function _claimFee(address user, uint256 amount) private {
totalHeimdallFee = totalHeimdallFee.sub(amount);
logger.logClaimFee(user, amount);
}
function claimFee(
uint256 accumFeeAmount,
uint256 index,
bytes memory proof
) public {
//Ignoring other params becuase rewards distribution is on chain
require(
keccak256(abi.encode(msg.sender, accumFeeAmount)).checkMembership(index, accountStateRoot, proof),
"Wrong acc proof"
);
uint256 withdrawAmount = accumFeeAmount.sub(userFeeExit[msg.sender]);
_claimFee(msg.sender, withdrawAmount);
userFeeExit[msg.sender] = accumFeeAmount;
require(token.transfer(msg.sender, withdrawAmount));
}
function stake(
uint256 amount,
uint256 heimdallFee,
bool acceptDelegation,
bytes calldata signerPubkey
) external {
stakeFor(msg.sender, amount, heimdallFee, acceptDelegation, signerPubkey);
}
function totalStakedFor(address user) external view returns (uint256) {
if (user == address(0x0) || NFTContract.balanceOf(user) == 0) {
return 0;
}
return validators[NFTContract.tokenOfOwnerByIndex(user, 0)].amount;
}
function startAuction(
uint256 validatorId,
uint256 amount,
bool _acceptDelegation,
bytes calldata _signerPubkey
) external onlyWhenUnlocked {
uint256 currentValidatorAmount = validators[validatorId].amount;
require(
validators[validatorId].deactivationEpoch == 0 && currentValidatorAmount != 0,
"Invalid validator for an auction"
);
uint256 senderValidatorId = signerToValidator[msg.sender];
// make sure that signer wasn't used already
require(
NFTContract.balanceOf(msg.sender) == 0 && // existing validators can't bid
senderValidatorId != INCORRECT_VALIDATOR_ID,
"Already used address"
);
uint256 _currentEpoch = currentEpoch;
uint256 _replacementCoolDown = replacementCoolDown;
// when dynasty period is updated validators are in cooldown period
require(_replacementCoolDown == 0 || _replacementCoolDown <= _currentEpoch, "Cooldown period");
// (auctionPeriod--dynasty)--(auctionPeriod--dynasty)--(auctionPeriod--dynasty)
// if it's auctionPeriod then will get residue smaller then auctionPeriod
// from (CurrentPeriod of validator )%(auctionPeriod--dynasty)
// make sure that its `auctionPeriod` window
// dynasty = 30, auctionPeriod = 7, activationEpoch = 1, currentEpoch = 39
// residue 1 = (39-1)% (7+30), if residue <= auctionPeriod it's `auctionPeriod`
require(
(_currentEpoch.sub(validators[validatorId].activationEpoch) % dynasty.add(auctionPeriod)) < auctionPeriod,
"Invalid auction period"
);
uint256 perceivedStake = currentValidatorAmount;
address _contract = validators[validatorId].contractAddress;
if (_contract != address(0x0)) {
perceivedStake = perceivedStake.add(IValidatorShare(_contract).getActiveAmount());
}
Auction storage auction = validatorAuction[validatorId];
uint256 currentAuctionAmount = auction.amount;
perceivedStake = Math.max(perceivedStake, currentAuctionAmount);
require(perceivedStake < amount, "Must bid higher");
require(token.transferFrom(msg.sender, address(this), amount), "Transfer amount failed");
//replace prev auction
if (currentAuctionAmount != 0) {
require(token.transfer(auction.user, currentAuctionAmount), "Bid return failed");
}
// create new auction
auction.amount = amount;
auction.user = msg.sender;
auction.acceptDelegation = _acceptDelegation;
auction.signerPubkey = _signerPubkey;
logger.logStartAuction(validatorId, currentValidatorAmount, amount);
}
function confirmAuctionBid(
uint256 validatorId,
uint256 heimdallFee /** for new validator */
) external onlyWhenUnlocked {
Auction storage auction = validatorAuction[validatorId];
address auctionUser = auction.user;
require(
msg.sender == auctionUser || getValidatorId(msg.sender) == validatorId,
"Only bidder or validator can confirm"
);
uint256 _currentEpoch = currentEpoch;
require(
_currentEpoch.sub(auction.startEpoch) % auctionPeriod.add(dynasty) >= auctionPeriod,
"Not allowed before auctionPeriod"
);
require(auction.user != address(0x0), "Invalid auction");
uint256 validatorAmount = validators[validatorId].amount;
uint256 perceivedStake = validatorAmount;
uint256 auctionAmount = auction.amount;
address contractAddr = validators[validatorId].contractAddress;
if (contractAddr != address(0x0)) {
perceivedStake = perceivedStake.add(IValidatorShare(contractAddr).getActiveAmount());
}
// validator is last auctioner
if (perceivedStake >= auctionAmount && validators[validatorId].deactivationEpoch == 0) {
require(token.transfer(auctionUser, auctionAmount), "Bid return failed");
//cleanup auction data
auction.startEpoch = _currentEpoch;
logger.logConfirmAuction(validatorId, validatorId, validatorAmount);
} else {
// dethrone
_transferAndTopUp(auctionUser, heimdallFee, 0);
_unstake(validatorId, _currentEpoch);
uint256 newValidatorId = _stakeFor(
auctionUser,
auctionAmount,
auction.acceptDelegation,
auction.signerPubkey
);
logger.logConfirmAuction(newValidatorId, validatorId, auctionAmount);
}
uint256 startEpoch = auction.startEpoch;
delete validatorAuction[validatorId];
validatorAuction[validatorId].startEpoch = startEpoch;
}
function unstake(uint256 validatorId) external onlyStaker(validatorId) {
require(validatorAuction[validatorId].amount == 0, "Wait for auction completion");
require(
validators[validatorId].activationEpoch > 0 &&
validators[validatorId].deactivationEpoch == 0 &&
(validators[validatorId].status == Status.Active || validators[validatorId].status == Status.Locked)
);
uint256 exitEpoch = currentEpoch.add(1); // notice period
_unstake(validatorId, exitEpoch);
}
// Housekeeping function. @todo remove later
function forceUnstake(uint256 validatorId) external onlyGovernance {
_unstake(validatorId, currentEpoch);
}
function setCurrentEpoch(uint256 _currentEpoch) external onlyGovernance {
currentEpoch = _currentEpoch;
}
function transferFunds(
uint256 validatorId,
uint256 amount,
address delegator
) external returns (bool) {
require(
validators[validatorId].contractAddress == msg.sender ||
Registry(registry).getSlashingManagerAddress() == msg.sender,
"Invalid contract address"
);
return token.transfer(delegator, amount);
}
function delegationDeposit(
uint256 validatorId,
uint256 amount,
address delegator
) external returns (bool) {
require(validators[validatorId].contractAddress == msg.sender, "Invalid contract address");
return token.transferFrom(delegator, address(this), amount);
}
function stakeFor(
address user,
uint256 amount,
uint256 heimdallFee,
bool acceptDelegation,
bytes memory signerPubkey
) public onlyWhenUnlocked {
require(currentValidatorSetSize() < validatorThreshold, "Validator set Threshold exceeded!");
require(amount > minDeposit, "min deposit limit failed!");
_transferAndTopUp(user, heimdallFee, amount);
_stakeFor(user, amount, acceptDelegation, signerPubkey);
}
function unstakeClaim(uint256 validatorId) public onlyStaker(validatorId) {
uint256 deactivationEpoch = validators[validatorId].deactivationEpoch;
// can only claim stake back after WITHDRAWAL_DELAY
require(
deactivationEpoch > 0 &&
deactivationEpoch.add(WITHDRAWAL_DELAY) <= currentEpoch &&
validators[validatorId].status != Status.Unstaked
);
uint256 amount = validators[validatorId].amount;
uint256 newTotalStaked = totalStaked.sub(amount);
totalStaked = newTotalStaked;
NFTContract.burn(validatorId);
signerToValidator[validators[validatorId].signer] = INCORRECT_VALIDATOR_ID;
validators[validatorId].status = Status.Unstaked;
require(token.transfer(msg.sender, amount), "Transfer stake failed");
logger.logUnstaked(msg.sender, validatorId, amount, newTotalStaked);
}
// slashing and jail interface
function restake(
uint256 validatorId,
uint256 amount,
bool stakeRewards
) public onlyWhenUnlocked onlyStaker(validatorId) {
require(validators[validatorId].deactivationEpoch == 0, "No use of restaking");
if (amount > 0) {
require(token.transferFrom(msg.sender, address(this), amount), "Transfer stake failed");
}
if (stakeRewards) {
amount = amount.add(validators[validatorId].reward);
address contractAddr = validators[validatorId].contractAddress;
if (contractAddr != address(0x0)) {
amount = amount.add(IValidatorShare(contractAddr).withdrawRewardsValidator());
}
validators[validatorId].reward = 0;
}
uint256 newTotalStaked = totalStaked.add(amount);
totalStaked = newTotalStaked;
validators[validatorId].amount = validators[validatorId].amount.add(amount);
updateTimeline(int256(amount), 0, 0);
logger.logStakeUpdate(validatorId);
logger.logRestaked(validatorId, validators[validatorId].amount, newTotalStaked);
}
function _liquidateRewards(uint256 validatorId, address validatorUser, uint256 reward) private {
totalRewardsLiquidated = totalRewardsLiquidated.add(reward);
validators[validatorId].reward = 0;
require(token.transfer(validatorUser, reward), "Insufficent rewards");
logger.logClaimRewards(validatorId, reward, totalRewardsLiquidated);
}
function withdrawRewards(uint256 validatorId) public onlyStaker(validatorId) {
uint256 reward = validators[validatorId].reward;
address contractAddr = validators[validatorId].contractAddress;
if (contractAddr != address(0x0)) {
reward = reward.add(IValidatorShare(contractAddr).withdrawRewardsValidator());
}
_liquidateRewards(validatorId, msg.sender, reward);
}
function migrateDelegation(uint256 fromValidatorId, uint256 toValidatorId, uint256 amount) public {
require(fromValidatorId < 8 && toValidatorId > 7, "Invalid migration");
IValidatorShare(validators[fromValidatorId].contractAddress).migrateOut(msg.sender, amount);
IValidatorShare(validators[toValidatorId].contractAddress).migrateIn(msg.sender, amount);
}
function getValidatorId(address user) public view returns (uint256) {
return NFTContract.tokenOfOwnerByIndex(user, 0);
}
// set staking Token
function setToken(address _token) public onlyGovernance {
require(_token != address(0x0));
token = IERC20(_token);
}
// Change the number of validators required to allow a passed header root
function updateValidatorThreshold(uint256 newThreshold) public onlyGovernance {
require(newThreshold > 0);
logger.logThresholdChange(newThreshold, validatorThreshold);
validatorThreshold = newThreshold;
}
function updateCheckPointBlockInterval(uint256 _blocks) public onlyGovernance {
require(_blocks > 0, "Blocks interval must be non-zero");
checkPointBlockInterval = _blocks;
}
// Change reward for each checkpoint
function updateCheckpointReward(uint256 newReward) public onlyGovernance {
require(newReward > 0);
logger.logRewardUpdate(newReward, CHECKPOINT_REWARD);
CHECKPOINT_REWARD = newReward;
}
// Change delegation contract for a validator
// @note: Users must exit before this update or all funds may get lost
function updateContractAddress(uint256 validatorId, address newContractAddress) public onlyGovernance {
require(IValidatorShare(newContractAddress).owner() == address(this), "Owner of contract must be stakeManager");
validators[validatorId].contractAddress = newContractAddress;
}
function updateValidatorState(uint256 validatorId, int256 amount) public {
if (amount > 0) {
// deposit during shares purchase
require(delegationEnabled, "Delegation is disabled");
}
require(validators[validatorId].contractAddress == msg.sender, "Invalid contract address");
updateTimeline(amount, 0, 0);
}
function updateDynastyValue(uint256 newDynasty) public onlyGovernance {
require(newDynasty > 0);
logger.logDynastyValueChange(newDynasty, dynasty);
dynasty = newDynasty;
WITHDRAWAL_DELAY = newDynasty;
auctionPeriod = newDynasty.div(4);
// set cooldown period
replacementCoolDown = currentEpoch.add(auctionPeriod);
}
// Housekeeping function. @todo remove later
function stopAuctions(uint256 forNCheckpoints) public onlyGovernance {
replacementCoolDown = currentEpoch.add(forNCheckpoints);
}
function updateProposerBonus(uint256 newProposerBonus) public onlyGovernance {
logger.logProposerBonusChange(newProposerBonus, proposerBonus);
require(newProposerBonus <= 100, "too big");
proposerBonus = newProposerBonus;
}
function updateSignerUpdateLimit(uint256 _limit) public onlyGovernance {
signerUpdateLimit = _limit;
}
function updateMinAmounts(uint256 _minDeposit, uint256 _minHeimdallFee) public onlyGovernance {
minDeposit = _minDeposit;
minHeimdallFee = _minHeimdallFee;
}
function updateSigner(uint256 validatorId, bytes memory signerPubkey) public onlyStaker(validatorId) {
address signer = pubToAddress(signerPubkey);
require(signer != address(0x0) && signerToValidator[signer] == 0, "Invalid signer");
uint256 _currentEpoch = currentEpoch;
require(
_currentEpoch >= latestSignerUpdateEpoch[validatorId].add(signerUpdateLimit),
"Invalid checkpoint number!"
);
address currentSigner = validators[validatorId].signer;
// update signer event
logger.logSignerChange(validatorId, currentSigner, signer, signerPubkey);
signerToValidator[currentSigner] = INCORRECT_VALIDATOR_ID;
signerToValidator[signer] = validatorId;
validators[validatorId].signer = signer;
// reset update time to current time
latestSignerUpdateEpoch[validatorId] = _currentEpoch;
}
function currentValidatorSetSize() public view returns (uint256) {
return validatorState.stakerCount;
}
function currentValidatorSetTotalStake() public view returns (uint256) {
return validatorState.amount;
}
function getValidatorContract(uint256 validatorId) public view returns (address) {
return validators[validatorId].contractAddress;
}
function isValidator(uint256 validatorId) public view returns (bool) {
uint256 activationEpoch = validators[validatorId].activationEpoch;
uint256 deactivationEpoch = validators[validatorId].deactivationEpoch;
uint256 amount = validators[validatorId].amount;
Status status = validators[validatorId].status;
uint256 _currentEpoch = currentEpoch;
return (amount > 0 &&
(activationEpoch != 0 && activationEpoch <= _currentEpoch) &&
(deactivationEpoch == 0 || deactivationEpoch > _currentEpoch) &&
status == Status.Active);
}
function checkSignatures(
uint256 blockInterval,
bytes32 voteHash,
bytes32 stateRoot,
address proposer,
bytes memory sigs
) public onlyRootChain returns (uint256) {
// checkpoint rewards are based on BlockInterval multiplied on `CHECKPOINT_REWARD`
// for bigger checkpoints reward is capped at `CHECKPOINT_REWARD`
// if interval is 50% of checkPointBlockInterval then reward R is half of `CHECKPOINT_REWARD`
// and then stakePower is 90% of currentValidatorSetTotalStake then final reward is 90% of R
uint256 reward = blockInterval.mul(CHECKPOINT_REWARD).div(checkPointBlockInterval);
reward = Math.min(CHECKPOINT_REWARD, reward);
uint256 _proposerBonus = reward.mul(proposerBonus).div(100);
Validator storage _proposer = validators[signerToValidator[proposer]];
if (_proposer.contractAddress != address(0x0)) {
IValidatorShare(_proposer.contractAddress).addProposerBonus(_proposerBonus, _proposer.amount);
} else {
_proposer.reward = _proposer.reward.add(_proposerBonus);
}
reward = reward.sub(_proposerBonus);
uint256 stakePower = currentValidatorSetTotalStake();
// update stateMerkleTree root for accounts balance on heimdall chain
accountStateRoot = stateRoot;
_finalizeCommit();
return checkSignature(stakePower, reward, voteHash, sigs);
}
function checkSignature(
uint256 checkpointStakePower,
uint256 reward,
bytes32 voteHash,
bytes memory sigs
) internal returns (uint256) {
// total voting power
uint256 totalStakePower;
address lastAdd; // cannot have address(0x0) as an owner
for (uint64 i = 0; i < sigs.length; i += 65) {
address signer = voteHash.ecrecovery(BytesLib.slice(sigs, i, 65));
uint256 validatorId = signerToValidator[signer];
// check if signer is staker and not proposer
if (signer == lastAdd) {
break;
} else if (isValidator(validatorId) && signer > lastAdd) {
lastAdd = signer;
Validator storage validator = validators[validatorId];
uint256 valPow;
// add delegation power
address contractAddr = validator.contractAddress;
if (contractAddr != address(0x0)) {
valPow = IValidatorShare(contractAddr).updateRewards(
reward,
checkpointStakePower,
validatorStake(validatorId)
);
} else {
valPow = validator.amount;
validator.reward = validator.reward.add(valPow.mul(reward).div(checkpointStakePower));
}
totalStakePower = totalStakePower.add(valPow);
}
}
reward = CHECKPOINT_REWARD.mul(totalStakePower).div(currentValidatorSetTotalStake());
totalRewards = totalRewards.add(reward);
require(totalStakePower >= currentValidatorSetTotalStake().mul(2).div(3).add(1), "2/3+1 non-majority!");
return reward;
}
function slash(bytes memory _slashingInfoList) public returns (uint256) {
require(Registry(registry).getSlashingManagerAddress() == msg.sender, "Sender must be slashing manager!");
RLPReader.RLPItem[] memory slashingInfoList = _slashingInfoList.toRlpItem().toList();
int256 valJailed = 0;
uint256 jailedAmount = 0;
uint256 totalAmount;
for (uint256 i = 0; i < slashingInfoList.length; i++) {
RLPReader.RLPItem[] memory slashData = slashingInfoList[i].toList();
uint256 validatorId = slashData[0].toUint();
uint256 _amount = slashData[1].toUint();
totalAmount = totalAmount.add(_amount);
if (validators[validatorId].contractAddress != address(0x0)) {
uint256 delSlashedAmount = IValidatorShare(validators[validatorId].contractAddress).slash(
validators[validatorId].amount,
_amount
);
_amount = _amount.sub(delSlashedAmount);
}
uint256 validatorStakeSlashed = validators[validatorId].amount.sub(_amount);
validators[validatorId].amount = validatorStakeSlashed;
if (validatorStakeSlashed == 0) {
_unstake(validatorId, currentEpoch);
} else if (slashData[2].toBoolean()) {
jailedAmount = jailedAmount.add(_jail(validatorId, 1));
valJailed++;
}
}
//update timeline
updateTimeline(-int256(totalAmount.add(jailedAmount)), -valJailed, 0);
return totalAmount;
}
function unjail(uint256 validatorId) public onlyStaker(validatorId) {
require(validators[validatorId].status == Status.Locked, "Validator is not jailed");
require(validators[validatorId].deactivationEpoch == 0, "Validator already unstaking");
uint256 _currentEpoch = currentEpoch;
require(validators[validatorId].jailTime <= _currentEpoch, "Incomplete jail period");
uint256 amount = validators[validatorId].amount;
require(amount >= minDeposit);
uint256 delegationAmount = 0;
if (validators[validatorId].contractAddress != address(0x0)) {
delegationAmount = IValidatorShare(validators[validatorId].contractAddress).unlockContract();
}
// undo timline so that validator is normal validator
updateTimeline(int256(amount.add(delegationAmount)), 1, 0);
validators[validatorId].status = Status.Active;
logger.logUnjailed(validatorId, validators[validatorId].signer);
}
function _jail(uint256 validatorId, uint256 jailCheckpoints) internal returns (uint256) {
uint256 delegationAmount = 0;
if (validators[validatorId].contractAddress != address(0x0)) {
delegationAmount = IValidatorShare(validators[validatorId].contractAddress).lockContract();
}
uint256 _currentEpoch = currentEpoch;
validators[validatorId].jailTime = _currentEpoch.add(jailCheckpoints);
validators[validatorId].status = Status.Locked;
logger.logJailed(validatorId, _currentEpoch, validators[validatorId].signer);
return validators[validatorId].amount.add(delegationAmount);
}
function _stakeFor(
address user,
uint256 amount,
bool acceptDelegation,
bytes memory signerPubkey
) internal returns (uint256) {
address signer = pubToAddress(signerPubkey);
require(signer != address(0x0) && signerToValidator[signer] == 0, "Invalid signer");
uint256 _currentEpoch = currentEpoch;
uint256 validatorId = NFTCounter;
StakingInfo _logger = logger;
uint256 newTotalStaked = totalStaked.add(amount);
totalStaked = newTotalStaked;
validators[validatorId] = Validator({
reward: 0,
amount: amount,
activationEpoch: _currentEpoch,
deactivationEpoch: 0,
jailTime: 0,
signer: signer,
contractAddress: acceptDelegation ? factory.create(validatorId, address(_logger), registry) : address(0x0),
status: Status.Active
});
latestSignerUpdateEpoch[validatorId] = _currentEpoch;
NFTContract.mint(user, validatorId);
signerToValidator[signer] = validatorId;
updateTimeline(int256(amount), 1, 0);
// no Auctions for 1 dynasty
validatorAuction[validatorId].startEpoch = _currentEpoch;
_logger.logStaked(signer, signerPubkey, validatorId, _currentEpoch, amount, newTotalStaked);
NFTCounter = validatorId.add(1);
return validatorId;
}
function _unstake(uint256 validatorId, uint256 exitEpoch) internal {
uint256 amount = validators[validatorId].amount;
address validator = ownerOf(validatorId);
validators[validatorId].deactivationEpoch = exitEpoch;
// unbond all delegators in future
int256 delegationAmount = 0;
uint256 rewards = validators[validatorId].reward;
address contractAddr = validators[validatorId].contractAddress;
if (contractAddr != address(0x0)) {
IValidatorShare validatorShare = IValidatorShare(contractAddr);
rewards = rewards.add(validatorShare.withdrawRewardsValidator());
delegationAmount = int256(validatorShare.lockContract());
}
_liquidateRewards(validatorId, validator, rewards);
// update future
uint256 targetEpoch = exitEpoch <= currentEpoch ? 0 : exitEpoch;
updateTimeline(-(int256(amount) + delegationAmount), -1, targetEpoch);
logger.logUnstakeInit(validator, validatorId, exitEpoch, amount);
}
function _finalizeCommit() internal {
uint256 _currentEpoch = currentEpoch;
uint256 nextEpoch = _currentEpoch.add(1);
StateChange memory changes = validatorStateChanges[nextEpoch];
updateTimeline(changes.amount, changes.stakerCount, 0);
delete validatorStateChanges[_currentEpoch];
currentEpoch = nextEpoch;
}
function updateTimeline(
int256 amount,
int256 stakerCount,
uint256 targetEpoch
) private {
if (targetEpoch == 0) {
// update totalstake and validator count
if (amount > 0) {
validatorState.amount = validatorState.amount.add(uint256(amount));
} else if (amount < 0) {
validatorState.amount = validatorState.amount.sub(uint256(amount * -1));
}
if (stakerCount > 0) {
validatorState.stakerCount = validatorState.stakerCount.add(uint256(stakerCount));
} else if (stakerCount < 0) {
validatorState.stakerCount = validatorState.stakerCount.sub(uint256(stakerCount * -1));
}
} else {
validatorStateChanges[targetEpoch].amount += amount;
validatorStateChanges[targetEpoch].stakerCount += stakerCount;
}
}
function pubToAddress(bytes memory pub) private pure returns (address) {
require(pub.length == 64, "Invalid pubkey");
return address(uint160(uint256(keccak256(pub))));
}
function reinitialize(
address _NFTContract,
address _stakingLogger,
address _validatorShareFactory
) external onlyGovernance {
NFTContract = StakingNFT(_NFTContract);
logger = StakingInfo(_stakingLogger);
factory = ValidatorShareFactory(_validatorShareFactory);
}
function updateValidatorDelegation(bool delegation) external {
uint256 validatorId = signerToValidator[msg.sender];
require(isValidator(validatorId), "not a validator");
address contractAddr = validators[validatorId].contractAddress;
require(contractAddr != address(0x0), "delegation not enabled");
IValidatorShare(contractAddr).updateDelegation(delegation);
}
}
|
Change the number of validators required to allow a passed header root
|
function updateValidatorThreshold(uint256 newThreshold) public onlyGovernance {
require(newThreshold > 0);
logger.logThresholdChange(newThreshold, validatorThreshold);
validatorThreshold = newThreshold;
}
| 1,356,628
|
/**
*Submitted for verification at Etherscan.io on 2022-03-02
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @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;
}
}
/**
* @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;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev 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);
}
}
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface IRandomNumberGenerator {
/**
* Requests randomness from a user-provided seed
*/
function getRandomNumber(uint256 _seed) external;
/**
* View latest lotteryId numbers
*/
function viewLatestLotteryId() external view returns (uint256);
/**
* Views random result
*/
function viewRandomResult() external view returns (uint32);
}
interface IArchienekoLottery {
/**
* @notice Buy tickets for the current lottery
* @param _lotteryId: lotteryId
* @param _ticketNumbers: array of ticket numbers between 1,000,000 and 1,999,999
* @dev Callable by users
*/
function buyTickets(uint256 _lotteryId, uint32[] calldata _ticketNumbers) external;
/**
* @notice Claim a set of winning tickets for a lottery
* @param _lotteryId: lottery id
* @param _ticketIds: array of ticket ids
* @param _brackets: array of brackets for the ticket ids
* @dev Callable by users only, not contract!
*/
function claimTickets(
uint256 _lotteryId,
uint256[] calldata _ticketIds,
uint32[] calldata _brackets
) external;
/**
* @notice Close lottery
* @param _lotteryId: lottery id
* @dev Callable by operator
*/
function closeLottery(uint256 _lotteryId) external;
/**
* @notice Draw the final number, calculate reward in ARCHIENEKO per group, and make lottery claimable
* @param _lotteryId: lottery id
* @param _autoInjection: reinjects funds into next lottery (vs. withdrawing all)
* @dev Callable by operator
*/
function drawFinalNumberAndMakeLotteryClaimable(uint256 _lotteryId, bool _autoInjection) external;
/**
* @notice Inject funds
* @param _lotteryId: lottery id
* @param _amount: amount to inject in ARCHIENEKO token
* @dev Callable by operator
*/
function injectFunds(uint256 _lotteryId, uint256 _amount) external;
/**
* @notice Start the lottery
* @dev Callable by operator
* @param _endTime: endTime of the lottery
* @param _priceTicketInArchieneko: price of a ticket in ARCHIENEKO
* @param _discountDivisor: the divisor to calculate the discount magnitude for bulks
* @param _rewardsBreakdown: breakdown of rewards per bracket (must sum to 10,000)
* @param _treasuryFee: treasury fee (10,000 = 100%, 100 = 1%)
*/
function startLottery(
uint256 _endTime,
uint256 _priceTicketInArchieneko,
uint256 _discountDivisor,
uint256[6] calldata _rewardsBreakdown,
uint256 _treasuryFee
) external;
/**
* @notice View current lottery id
*/
function viewCurrentLotteryId() external returns (uint256);
}
pragma abicoder v2;
contract ArchienekoLuckyStrike is ReentrancyGuard, IArchienekoLottery, Ownable {
using SafeERC20 for IERC20;
address public injectorAddress;
address public operatorAddress;
address public treasuryAddress;
uint256 public currentLotteryId;
uint256 public currentTicketId;
uint256 public maxNumberTicketsPerBuyOrClaim = 100;
uint256 public maxPriceTicketInArchieneko = 10 * 10 ** 27;
uint256 public minPriceTicketInArchieneko = 10 * 10 ** 9;
uint256 public pendingInjectionNextLottery;
uint256 public constant MIN_DISCOUNT_DIVISOR = 300;
uint256 public constant MIN_LENGTH_LOTTERY = 4 hours - 5 minutes; // 4 hours
uint256 public constant MAX_LENGTH_LOTTERY = 4 days + 5 minutes; // 4 days
uint256 public constant MAX_TREASURY_FEE = 3000; // 30%
IERC20 public archienekoToken;
IRandomNumberGenerator public randomGenerator;
enum Status {
Pending,
Open,
Close,
Claimable
}
struct Lottery {
Status status;
uint256 startTime;
uint256 endTime;
uint256 priceTicketInArchieneko;
uint256 discountDivisor;
uint256[6] rewardsBreakdown; // 0: 1 matching number // 5: 6 matching numbers
uint256 treasuryFee; // 500: 5% // 200: 2% // 50: 0.5%
uint256[6] ArchienekoPerBracket;
uint256[6] countWinnersPerBracket;
uint256 firstTicketId;
uint256 firstTicketIdNextLottery;
uint256 amountCollectedInArchieneko;
uint32 finalNumber;
}
struct Ticket {
uint32 number;
address owner;
}
// Mapping are cheaper than arrays
mapping(uint256 => Lottery) private _lotteries;
mapping(uint256 => Ticket) private _tickets;
// Bracket calculator is used for verifying claims for ticket prizes
mapping(uint32 => uint32) private _bracketCalculator;
// Keeps track of number of ticket per unique combination for each lotteryId
mapping(uint256 => mapping(uint32 => uint256)) private _numberTicketsPerLotteryId;
// Keep track of user ticket ids for a given lotteryId
mapping(address => mapping(uint256 => uint256[])) private _userTicketIdsPerLotteryId;
modifier notContract() {
require(!_isContract(msg.sender), "Contract not allowed");
require(msg.sender == tx.origin, "Proxy contract not allowed");
_;
}
modifier onlyOperator() {
require(msg.sender == operatorAddress, "Not operator");
_;
}
modifier onlyOwnerOrInjector() {
require((msg.sender == owner()) || (msg.sender == injectorAddress), "Not owner or injector");
_;
}
event AdminTokenRecovery(address token, uint256 amount);
event LotteryClose(uint256 indexed lotteryId, uint256 firstTicketIdNextLottery);
event LotteryInjection(uint256 indexed lotteryId, uint256 injectedAmount);
event LotteryOpen(
uint256 indexed lotteryId,
uint256 startTime,
uint256 endTime,
uint256 priceTicketInArchieneko,
uint256 firstTicketId,
uint256 injectedAmount
);
event LotteryNumberDrawn(uint256 indexed lotteryId, uint256 finalNumber, uint256 countWinningTickets);
event NewOperatorAndTreasuryAndInjectorAddresses(address operator, address treasury, address injector);
event NewRandomGenerator(address indexed randomGenerator);
event TicketsPurchase(address indexed buyer, uint256 indexed lotteryId, uint256 numberTickets);
event TicketsClaim(address indexed claimer, uint256 amount, uint256 indexed lotteryId, uint256 numberTickets);
/**
* @notice Constructor
* @dev RandomNumberGenerator must be deployed prior to this contract
* @param _archienekoTokenAddress: address of the Archieneko token
* @param _randomGeneratorAddress: address of the RandomGenerator contract used to work with ChainLink VRF
*/
constructor(address _archienekoTokenAddress, address _randomGeneratorAddress) {
archienekoToken = IERC20(_archienekoTokenAddress);
randomGenerator = IRandomNumberGenerator(_randomGeneratorAddress);
// Initializes a mapping
_bracketCalculator[0] = 1;
_bracketCalculator[1] = 11;
_bracketCalculator[2] = 111;
_bracketCalculator[3] = 1111;
_bracketCalculator[4] = 11111;
_bracketCalculator[5] = 111111;
}
/**
* @notice Buy tickets for the current lottery
* @param _lotteryId: lotteryId
* @param _ticketNumbers: array of ticket numbers between 1,000,000 and 1,999,999
* @dev Callable by users
*/
function buyTickets(uint256 _lotteryId, uint32[] calldata _ticketNumbers)
external
override
notContract
nonReentrant
{
require(_ticketNumbers.length != 0, "No ticket specified");
require(_ticketNumbers.length <= maxNumberTicketsPerBuyOrClaim, "Too many tickets");
require(_lotteries[_lotteryId].status == Status.Open, "Lottery is not open");
require(block.timestamp < _lotteries[_lotteryId].endTime, "Lottery is over");
// Calculate number of Archieneko to this contract
uint256 amountArchienekoToTransfer = _calculateTotalPriceForBulkTickets(
_lotteries[_lotteryId].discountDivisor,
_lotteries[_lotteryId].priceTicketInArchieneko,
_ticketNumbers.length
);
// Transfer archieneko tokens to this contract
archienekoToken.safeTransferFrom(address(msg.sender), address(this), amountArchienekoToTransfer);
// Increment the total amount collected for the lottery round
_lotteries[_lotteryId].amountCollectedInArchieneko += amountArchienekoToTransfer;
for (uint256 i = 0; i < _ticketNumbers.length; i++) {
uint32 thisTicketNumber = _ticketNumbers[i];
require((thisTicketNumber >= 1000000) && (thisTicketNumber <= 1999999), "Outside range");
_numberTicketsPerLotteryId[_lotteryId][1 + (thisTicketNumber % 10)]++;
_numberTicketsPerLotteryId[_lotteryId][11 + (thisTicketNumber % 100)]++;
_numberTicketsPerLotteryId[_lotteryId][111 + (thisTicketNumber % 1000)]++;
_numberTicketsPerLotteryId[_lotteryId][1111 + (thisTicketNumber % 10000)]++;
_numberTicketsPerLotteryId[_lotteryId][11111 + (thisTicketNumber % 100000)]++;
_numberTicketsPerLotteryId[_lotteryId][111111 + (thisTicketNumber % 1000000)]++;
_userTicketIdsPerLotteryId[msg.sender][_lotteryId].push(currentTicketId);
_tickets[currentTicketId] = Ticket({number: thisTicketNumber, owner: msg.sender});
// Increase lottery ticket number
currentTicketId++;
}
emit TicketsPurchase(msg.sender, _lotteryId, _ticketNumbers.length);
}
/**
* @notice Claim a set of winning tickets for a lottery
* @param _lotteryId: lottery id
* @param _ticketIds: array of ticket ids
* @param _brackets: array of brackets for the ticket ids
* @dev Callable by users only, not contract!
*/
function claimTickets(
uint256 _lotteryId,
uint256[] calldata _ticketIds,
uint32[] calldata _brackets
) external override notContract nonReentrant {
require(_ticketIds.length == _brackets.length, "Not same length");
require(_ticketIds.length != 0, "Length must be >0");
require(_ticketIds.length <= maxNumberTicketsPerBuyOrClaim, "Too many tickets");
require(_lotteries[_lotteryId].status == Status.Claimable, "Lottery not claimable");
// Initializes the rewardInArchienekoToTransfer
uint256 rewardInArchienekoToTransfer;
for (uint256 i = 0; i < _ticketIds.length; i++) {
require(_brackets[i] < 6, "Bracket out of range"); // Must be between 0 and 5
uint256 thisTicketId = _ticketIds[i];
require(_lotteries[_lotteryId].firstTicketIdNextLottery > thisTicketId, "TicketId too high");
require(_lotteries[_lotteryId].firstTicketId <= thisTicketId, "TicketId too low");
require(msg.sender == _tickets[thisTicketId].owner, "Not the owner");
// Update the lottery ticket owner to 0x address
_tickets[thisTicketId].owner = address(0);
uint256 rewardForTicketId = _calculateRewardsForTicketId(_lotteryId, thisTicketId, _brackets[i]);
// Check user is claiming the correct bracket
require(rewardForTicketId != 0, "No prize for this bracket");
if (_brackets[i] != 5) {
require(
_calculateRewardsForTicketId(_lotteryId, thisTicketId, _brackets[i] + 1) == 0,
"Bracket must be higher"
);
}
// Increment the reward to transfer
rewardInArchienekoToTransfer += rewardForTicketId;
}
// Transfer money to msg.sender
archienekoToken.safeTransfer(msg.sender, rewardInArchienekoToTransfer);
emit TicketsClaim(msg.sender, rewardInArchienekoToTransfer, _lotteryId, _ticketIds.length);
}
/**
* @notice Close lottery
* @param _lotteryId: lottery id
* @dev Callable by operator
*/
function closeLottery(uint256 _lotteryId) external override onlyOperator nonReentrant {
require(_lotteries[_lotteryId].status == Status.Open, "Lottery not open");
require(block.timestamp > _lotteries[_lotteryId].endTime, "Lottery not over");
_lotteries[_lotteryId].firstTicketIdNextLottery = currentTicketId;
// Request a random number from the generator based on a seed
randomGenerator.getRandomNumber(uint256(keccak256(abi.encodePacked(_lotteryId, currentTicketId))));
_lotteries[_lotteryId].status = Status.Close;
emit LotteryClose(_lotteryId, currentTicketId);
}
/**
* @notice Draw the final number, calculate reward in ARCHIENEKO per group, and make lottery claimable
* @param _lotteryId: lottery id
* @param _autoInjection: reinjects funds into next lottery (vs. withdrawing all)
* @dev Callable by operator
*/
function drawFinalNumberAndMakeLotteryClaimable(uint256 _lotteryId, bool _autoInjection)
external
override
onlyOperator
nonReentrant
{
require(_lotteries[_lotteryId].status == Status.Close, "Lottery not close");
require(_lotteryId == randomGenerator.viewLatestLotteryId(), "Numbers not drawn");
// Calculate the finalNumber based on the randomResult generated by ChainLink's fallback
uint32 finalNumber = randomGenerator.viewRandomResult();
// Initialize a number to count addresses in the previous bracket
uint256 numberAddressesInPreviousBracket;
// Calculate the amount to share post-treasury fee
uint256 amountToShareToWinners = (
((_lotteries[_lotteryId].amountCollectedInArchieneko) * (10000 - _lotteries[_lotteryId].treasuryFee))
) / 10000;
// Initializes the amount to withdraw to treasury
uint256 amountToWithdrawToTreasury;
// Calculate prizes in Archieneko for each bracket by starting from the highest one
for (uint32 i = 0; i < 6; i++) {
uint32 j = 5 - i;
uint32 transformedWinningNumber = _bracketCalculator[j] + (finalNumber % (uint32(10)**(j + 1)));
_lotteries[_lotteryId].countWinnersPerBracket[j] =
_numberTicketsPerLotteryId[_lotteryId][transformedWinningNumber] -
numberAddressesInPreviousBracket;
// A. If number of users for this _bracket number is superior to 0
if (
(_numberTicketsPerLotteryId[_lotteryId][transformedWinningNumber] - numberAddressesInPreviousBracket) !=
0
) {
// B. If rewards at this bracket are > 0, calculate, else, report the numberAddresses from previous bracket
if (_lotteries[_lotteryId].rewardsBreakdown[j] != 0) {
_lotteries[_lotteryId].ArchienekoPerBracket[j] =
((_lotteries[_lotteryId].rewardsBreakdown[j] * amountToShareToWinners) /
(_numberTicketsPerLotteryId[_lotteryId][transformedWinningNumber] -
numberAddressesInPreviousBracket)) /
10000;
// Update numberAddressesInPreviousBracket
numberAddressesInPreviousBracket = _numberTicketsPerLotteryId[_lotteryId][transformedWinningNumber];
}
// A. No ARCHIENEKO to distribute, they are added to the amount to withdraw to treasury address
} else {
_lotteries[_lotteryId].ArchienekoPerBracket[j] = 0;
amountToWithdrawToTreasury +=
(_lotteries[_lotteryId].rewardsBreakdown[j] * amountToShareToWinners) /
10000;
}
}
// Update internal statuses for lottery
_lotteries[_lotteryId].finalNumber = finalNumber;
_lotteries[_lotteryId].status = Status.Claimable;
if (_autoInjection) {
pendingInjectionNextLottery = amountToWithdrawToTreasury;
amountToWithdrawToTreasury = 0;
}
amountToWithdrawToTreasury += (_lotteries[_lotteryId].amountCollectedInArchieneko - amountToShareToWinners);
// Transfer Archieneko to treasury address
archienekoToken.safeTransfer(treasuryAddress, amountToWithdrawToTreasury);
emit LotteryNumberDrawn(currentLotteryId, finalNumber, numberAddressesInPreviousBracket);
}
/**
* @notice Change the random generator
* @dev The calls to functions are used to verify the new generator implements them properly.
* It is necessary to wait for the VRF response before starting a round.
* Callable only by the contract owner
* @param _randomGeneratorAddress: address of the random generator
*/
function changeRandomGenerator(address _randomGeneratorAddress) external onlyOwner {
require(_lotteries[currentLotteryId].status == Status.Claimable, "Lottery not in claimable");
// Request a random number from the generator based on a seed
IRandomNumberGenerator(_randomGeneratorAddress).getRandomNumber(
uint256(keccak256(abi.encodePacked(currentLotteryId, currentTicketId)))
);
// Calculate the finalNumber based on the randomResult generated by ChainLink's fallback
IRandomNumberGenerator(_randomGeneratorAddress).viewRandomResult();
randomGenerator = IRandomNumberGenerator(_randomGeneratorAddress);
emit NewRandomGenerator(_randomGeneratorAddress);
}
/**
* @notice Inject funds
* @param _lotteryId: lottery id
* @param _amount: amount to inject in ARCHIENEKO token
* @dev Callable by owner or injector address
*/
function injectFunds(uint256 _lotteryId, uint256 _amount) external override onlyOwnerOrInjector {
require(_lotteries[_lotteryId].status == Status.Open, "Lottery not open");
archienekoToken.safeTransferFrom(address(msg.sender), address(this), _amount);
_lotteries[_lotteryId].amountCollectedInArchieneko += _amount;
emit LotteryInjection(_lotteryId, _amount);
}
/**
* @notice Start the lottery
* @dev Callable by operator
* @param _endTime: endTime of the lottery
* @param _priceTicketInArchieneko: price of a ticket in ARCHIENEKO
* @param _discountDivisor: the divisor to calculate the discount magnitude for bulks
* @param _rewardsBreakdown: breakdown of rewards per bracket (must sum to 10,000)
* @param _treasuryFee: treasury fee (10,000 = 100%, 100 = 1%)
*/
function startLottery(
uint256 _endTime,
uint256 _priceTicketInArchieneko,
uint256 _discountDivisor,
uint256[6] calldata _rewardsBreakdown,
uint256 _treasuryFee
) external override onlyOperator {
require(
(currentLotteryId == 0) || (_lotteries[currentLotteryId].status == Status.Claimable),
"Not time to start lottery"
);
require(
((_endTime - block.timestamp) > MIN_LENGTH_LOTTERY) && ((_endTime - block.timestamp) < MAX_LENGTH_LOTTERY),
"Lottery length outside of range"
);
require(
(_priceTicketInArchieneko >= minPriceTicketInArchieneko) && (_priceTicketInArchieneko <= maxPriceTicketInArchieneko),
"Outside of limits"
);
require(_discountDivisor >= MIN_DISCOUNT_DIVISOR, "Discount divisor too low");
require(_treasuryFee <= MAX_TREASURY_FEE, "Treasury fee too high");
require(
(_rewardsBreakdown[0] +
_rewardsBreakdown[1] +
_rewardsBreakdown[2] +
_rewardsBreakdown[3] +
_rewardsBreakdown[4] +
_rewardsBreakdown[5]) == 10000,
"Rewards must equal 10000"
);
currentLotteryId++;
_lotteries[currentLotteryId] = Lottery({
status: Status.Open,
startTime: block.timestamp,
endTime: _endTime,
priceTicketInArchieneko: _priceTicketInArchieneko,
discountDivisor: _discountDivisor,
rewardsBreakdown: _rewardsBreakdown,
treasuryFee: _treasuryFee,
ArchienekoPerBracket: [uint256(0), uint256(0), uint256(0), uint256(0), uint256(0), uint256(0)],
countWinnersPerBracket: [uint256(0), uint256(0), uint256(0), uint256(0), uint256(0), uint256(0)],
firstTicketId: currentTicketId,
firstTicketIdNextLottery: currentTicketId,
amountCollectedInArchieneko: pendingInjectionNextLottery,
finalNumber: 0
});
emit LotteryOpen(
currentLotteryId,
block.timestamp,
_endTime,
_priceTicketInArchieneko,
currentTicketId,
pendingInjectionNextLottery
);
pendingInjectionNextLottery = 0;
}
/**
* @notice It allows the admin to recover wrong tokens sent to the contract
* @param _tokenAddress: the address of the token to withdraw
* @param _tokenAmount: the number of token amount to withdraw
* @dev Only callable by owner.
*/
function recoverWrongTokens(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(archienekoToken), "Cannot be Archieneko token");
IERC20(_tokenAddress).safeTransfer(address(msg.sender), _tokenAmount);
emit AdminTokenRecovery(_tokenAddress, _tokenAmount);
}
/**
* @notice Set ARCHIENEKO price ticket upper/lower limit
* @dev Only callable by owner
* @param _minPriceTicketInArchieneko: minimum price of a ticket in ARCHIENEKO
* @param _maxPriceTicketInArchieneko: maximum price of a ticket in ARCHIENEKO
*/
function setMinAndMaxTicketPriceInArchieneko(uint256 _minPriceTicketInArchieneko, uint256 _maxPriceTicketInArchieneko)
external
onlyOwner
{
require(_minPriceTicketInArchieneko <= _maxPriceTicketInArchieneko, "minPrice must be < maxPrice");
minPriceTicketInArchieneko = _minPriceTicketInArchieneko;
maxPriceTicketInArchieneko = _maxPriceTicketInArchieneko;
}
/**
* @notice Set max number of tickets
* @dev Only callable by owner
*/
function setMaxNumberTicketsPerBuy(uint256 _maxNumberTicketsPerBuy) external onlyOwner {
require(_maxNumberTicketsPerBuy != 0, "Must be > 0");
maxNumberTicketsPerBuyOrClaim = _maxNumberTicketsPerBuy;
}
/**
* @notice Set operator, treasury, and injector addresses
* @dev Only callable by owner
* @param _operatorAddress: address of the operator
* @param _treasuryAddress: address of the treasury
* @param _injectorAddress: address of the injector
*/
function setOperatorAndTreasuryAndInjectorAddresses(
address _operatorAddress,
address _treasuryAddress,
address _injectorAddress
) external onlyOwner {
require(_operatorAddress != address(0), "Cannot be zero address");
require(_treasuryAddress != address(0), "Cannot be zero address");
require(_injectorAddress != address(0), "Cannot be zero address");
operatorAddress = _operatorAddress;
treasuryAddress = _treasuryAddress;
injectorAddress = _injectorAddress;
emit NewOperatorAndTreasuryAndInjectorAddresses(_operatorAddress, _treasuryAddress, _injectorAddress);
}
/**
* @notice Calculate price of a set of tickets
* @param _discountDivisor: divisor for the discount
* @param _priceTicket price of a ticket (in ARCHIENEKO)
* @param _numberTickets number of tickets to buy
*/
function calculateTotalPriceForBulkTickets(
uint256 _discountDivisor,
uint256 _priceTicket,
uint256 _numberTickets
) external pure returns (uint256) {
require(_discountDivisor >= MIN_DISCOUNT_DIVISOR, "Must be >= MIN_DISCOUNT_DIVISOR");
require(_numberTickets != 0, "Number of tickets must be > 0");
return _calculateTotalPriceForBulkTickets(_discountDivisor, _priceTicket, _numberTickets);
}
/**
* @notice View current lottery id
*/
function viewCurrentLotteryId() external view override returns (uint256) {
return currentLotteryId;
}
/**
* @notice View lottery information
* @param _lotteryId: lottery id
*/
function viewLottery(uint256 _lotteryId) external view returns (Lottery memory) {
return _lotteries[_lotteryId];
}
/**
* @notice View ticker statuses and numbers for an array of ticket ids
* @param _ticketIds: array of _ticketId
*/
function viewNumbersAndStatusesForTicketIds(uint256[] calldata _ticketIds)
external
view
returns (uint32[] memory, bool[] memory)
{
uint256 length = _ticketIds.length;
uint32[] memory ticketNumbers = new uint32[](length);
bool[] memory ticketStatuses = new bool[](length);
for (uint256 i = 0; i < length; i++) {
ticketNumbers[i] = _tickets[_ticketIds[i]].number;
if (_tickets[_ticketIds[i]].owner == address(0)) {
ticketStatuses[i] = true;
} else {
ticketStatuses[i] = false;
}
}
return (ticketNumbers, ticketStatuses);
}
/**
* @notice View rewards for a given ticket, providing a bracket, and lottery id
* @dev Computations are mostly offchain. This is used to verify a ticket!
* @param _lotteryId: lottery id
* @param _ticketId: ticket id
* @param _bracket: bracket for the ticketId to verify the claim and calculate rewards
*/
function viewRewardsForTicketId(
uint256 _lotteryId,
uint256 _ticketId,
uint32 _bracket
) external view returns (uint256) {
// Check lottery is in claimable status
if (_lotteries[_lotteryId].status != Status.Claimable) {
return 0;
}
// Check ticketId is within range
if (
(_lotteries[_lotteryId].firstTicketIdNextLottery < _ticketId) &&
(_lotteries[_lotteryId].firstTicketId >= _ticketId)
) {
return 0;
}
return _calculateRewardsForTicketId(_lotteryId, _ticketId, _bracket);
}
/**
* @notice View user ticket ids, numbers, and statuses of user for a given lottery
* @param _user: user address
* @param _lotteryId: lottery id
* @param _cursor: cursor to start where to retrieve the tickets
* @param _size: the number of tickets to retrieve
*/
function viewUserInfoForLotteryId(
address _user,
uint256 _lotteryId,
uint256 _cursor,
uint256 _size
)
external
view
returns (
uint256[] memory,
uint32[] memory,
bool[] memory,
uint256
)
{
uint256 length = _size;
uint256 numberTicketsBoughtAtLotteryId = _userTicketIdsPerLotteryId[_user][_lotteryId].length;
if (length > (numberTicketsBoughtAtLotteryId - _cursor)) {
length = numberTicketsBoughtAtLotteryId - _cursor;
}
uint256[] memory lotteryTicketIds = new uint256[](length);
uint32[] memory ticketNumbers = new uint32[](length);
bool[] memory ticketStatuses = new bool[](length);
for (uint256 i = 0; i < length; i++) {
lotteryTicketIds[i] = _userTicketIdsPerLotteryId[_user][_lotteryId][i + _cursor];
ticketNumbers[i] = _tickets[lotteryTicketIds[i]].number;
// True = ticket claimed
if (_tickets[lotteryTicketIds[i]].owner == address(0)) {
ticketStatuses[i] = true;
} else {
// ticket not claimed (includes the ones that cannot be claimed)
ticketStatuses[i] = false;
}
}
return (lotteryTicketIds, ticketNumbers, ticketStatuses, _cursor + length);
}
/**
* @notice Calculate rewards for a given ticket
* @param _lotteryId: lottery id
* @param _ticketId: ticket id
* @param _bracket: bracket for the ticketId to verify the claim and calculate rewards
*/
function _calculateRewardsForTicketId(
uint256 _lotteryId,
uint256 _ticketId,
uint32 _bracket
) internal view returns (uint256) {
// Retrieve the winning number combination
uint32 userNumber = _lotteries[_lotteryId].finalNumber;
// Retrieve the user number combination from the ticketId
uint32 winningTicketNumber = _tickets[_ticketId].number;
// Apply transformation to verify the claim provided by the user is true
uint32 transformedWinningNumber = _bracketCalculator[_bracket] +
(winningTicketNumber % (uint32(10)**(_bracket + 1)));
uint32 transformedUserNumber = _bracketCalculator[_bracket] + (userNumber % (uint32(10)**(_bracket + 1)));
// Confirm that the two transformed numbers are the same, if not throw
if (transformedWinningNumber == transformedUserNumber) {
return _lotteries[_lotteryId].ArchienekoPerBracket[_bracket];
} else {
return 0;
}
}
/**
* @notice Calculate final price for bulk of tickets
* @param _discountDivisor: divisor for the discount (the smaller it is, the greater the discount is)
* @param _priceTicket: price of a ticket
* @param _numberTickets: number of tickets purchased
*/
function _calculateTotalPriceForBulkTickets(
uint256 _discountDivisor,
uint256 _priceTicket,
uint256 _numberTickets
) internal pure returns (uint256) {
return (_priceTicket * _numberTickets * (_discountDivisor + 1 - _numberTickets)) / _discountDivisor;
}
/**
* @notice Check if an address is a contract
*/
function _isContract(address _addr) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(_addr)
}
return size > 0;
}
}
|
Close lottery _lotteryId: lottery id Callable by operator/ Request a random number from the generator based on a seed
|
function closeLottery(uint256 _lotteryId) external override onlyOperator nonReentrant {
require(_lotteries[_lotteryId].status == Status.Open, "Lottery not open");
require(block.timestamp > _lotteries[_lotteryId].endTime, "Lottery not over");
_lotteries[_lotteryId].firstTicketIdNextLottery = currentTicketId;
randomGenerator.getRandomNumber(uint256(keccak256(abi.encodePacked(_lotteryId, currentTicketId))));
_lotteries[_lotteryId].status = Status.Close;
emit LotteryClose(_lotteryId, currentTicketId);
}
| 133,114
|
pragma solidity >=0.8.0 <0.9.0;
import "../openzeppelin/Safemath.sol";
import "./FriendRegistry.sol";
import "../utility/StakePool.sol";
import "hardhat/console.sol";
contract Freelancer {
using SafeMath for uint256;
using SafeMath for uint32;
// Use MAX_UINT to signify null uint value
uint256 constant MAX_UINT = 2**256 - 1;
//Default stake allocation = 5% of earned amount
uint256 constant DEFAULT_STAKE_ALLOCATION = 5;
// Null bytes32 values
bytes32 constant NULL = "";
/**
* @dev freelancer properties
**/
struct FreelancerMetadata {
uint16 jobsWorked;
bool isAvailable;
bool isInitialized;
}
/**
* @dev freelancer financials
**/
struct FreelancerFinancials {
uint256 totalEarned;
uint256 forgoneEarnings;
uint256 stakeAllocation;
uint256 totalUnpaid;
}
address[] freelancers;
mapping(address => FreelancerMetadata) public freelancerToMetadata;
mapping(address => FreelancerFinancials) public freelancerToFinancials;
mapping(address => StakePool) public freelancerToStakePool;
event FreelancerInit(FreelancerMetadata freelancerMetadata);
event Slashed(address freelancer, address to, uint256 amount);
FriendRegistry friendRegistry;
address tokenAddress;
constructor(address _friendRegistry, address _tokenAddress) {
friendRegistry = FriendRegistry(_friendRegistry);
tokenAddress = _tokenAddress;
}
modifier ifAvailable(address freelancer) {
require(
freelancerToMetadata[freelancer].isAvailable == true,
"freelancer is not available"
);
_;
}
modifier onlyFriend(address contractAddress) {
require(
friendRegistry.isFriend(contractAddress) == true,
"Contract is not a friend contract"
);
_;
}
modifier onlyIfFreelancerExists(address freelancerAddress) {
require(
freelancerToMetadata[freelancerAddress].isInitialized == true,
"Freelancer doesnt exist"
);
_;
}
/**
* @dev Sets a freelancer's stake allocation called by freelancer.
**/
function setMyAllocation(uint256 allocation) external {
freelancerToFinancials[msg.sender].stakeAllocation = allocation;
}
/**
* @dev Sets a freelancer's stake allocation called by a friend contract.
**/
function setFreelancerAllocation(address freelancer, uint256 allocation)
external
onlyIfFreelancerExists(freelancer)
onlyFriend(msg.sender)
{
freelancerToFinancials[freelancer].stakeAllocation = allocation;
}
/**
* @dev Sets a freelancer's total number of jobs worked.
* - Must be called by logic contracts upon completion of a job and can only be set if logic contract has access to set it
* @param freelancer The address of the freelancer whose rating needs to be updated
**/
function incrementJobsWorked(address freelancer)
external
onlyFriend(msg.sender)
{
freelancerToMetadata[freelancer].jobsWorked++;
}
/**
* @dev Sets a freelancer's availability.
* - Must be called by logic contracts upon completion or beginning of a job and can only be set if logic contract has access to set it
* @param freelancer The address of the freelancer whose rating needs to be updated
* @param isAvailable Availability set to true or false
**/
function setAvailability(address freelancer, bool isAvailable)
external
onlyFriend(msg.sender)
{
freelancerToMetadata[freelancer].isAvailable = isAvailable;
}
/**
* @dev Adds to a freelancer's stake pool called by freelancer.
**/
function addToMyStake(uint256 amount)
external
onlyIfFreelancerExists(msg.sender)
{
freelancerToStakePool[msg.sender].stake(amount);
}
/**
* @dev Adds to a freelancer's stake pool called by freelancer.
**/
function addToFreelancerStake(address freelancer, uint256 amount)
external
onlyIfFreelancerExists(freelancer)
onlyFriend(msg.sender)
{
freelancerToStakePool[freelancer].stake(amount);
}
/**
* @dev Reduce a freelancer's stake pool called by freelancer.
**/
function reduceMyStake(uint256 amount)
external
onlyIfFreelancerExists(msg.sender)
{
freelancerToStakePool[msg.sender].unstake(amount);
}
/**
* @dev Adds to a freelancer's stake pool called by freelancer.
**/
function lockFreelancerStake(address freelancer, uint256 amount)
external
onlyIfFreelancerExists(freelancer)
onlyFriend(msg.sender)
{
freelancerToStakePool[freelancer].lock(amount);
}
/**
* @dev Adds to a freelancer's stake pool called by freelancer.
**/
function unlockFreelancerStake(address freelancer, uint256 amount)
external
onlyIfFreelancerExists(freelancer)
onlyFriend(msg.sender)
{
freelancerToStakePool[freelancer].unlock(amount);
}
/**
* @dev Sets a freelancer's stake allocation called by freelancer.
**/
function addToFreelancerEarned(address freelancer, uint256 amount)
external
onlyIfFreelancerExists(freelancer)
onlyFriend(msg.sender)
{
freelancerToFinancials[freelancer].totalEarned = amount;
}
/**
* @dev Sets a freelancer's stake allocation called by freelancer.
**/
function addToFreelancerForgoneEarnings(address freelancer, uint256 amount)
external
onlyIfFreelancerExists(freelancer)
onlyFriend(msg.sender)
{
freelancerToFinancials[freelancer].forgoneEarnings = amount;
}
/**
* @dev Initialize a freelancer's metadata.
* - Called by createfreelancerIfFirstTime when a freelancer picks up his first job or stakes his tokens for the first time
* @param freelancer The address of the new freelancer
**/
function initializeFreelancerMetadataIfFirstTime(address freelancer)
external
onlyFriend(msg.sender)
{
if (freelancerToMetadata[freelancer].isInitialized == false) {
freelancerToMetadata[freelancer] = FreelancerMetadata(
0,
true,
true
);
freelancerToFinancials[freelancer]
.stakeAllocation = DEFAULT_STAKE_ALLOCATION;
freelancerToStakePool[freelancer] = new StakePool(
freelancer,
tokenAddress
);
freelancers.push(freelancer);
emit FreelancerInit(freelancerToMetadata[freelancer]);
}
}
/**
* @dev Slash a freelancer's locked stake
**/
function slashLockedStake(
address freelancer,
address to,
uint256 amount
) external onlyFriend(msg.sender) {
freelancerToStakePool[freelancer].unlock(amount);
freelancerToStakePool[freelancer].unstake(amount);
freelancerToStakePool[freelancer].slash(amount, to);
emit Slashed(freelancer, to, amount);
}
/**
* @dev Gets a freelancer's total earnings called by freelancer.
**/
function getFreelancerEarned(address freelancer)
external
view
returns (uint256)
{
return freelancerToFinancials[freelancer].totalEarned;
}
/**
* @dev Gets a freelancer's total earnings called by freelancer.
**/
function getFreelancerForgoneEarnings(address freelancer)
external
view
returns (uint256)
{
return freelancerToFinancials[freelancer].forgoneEarnings;
}
/**
* @dev Gets a freelancer by address.
**/
function getFreelancerMetadata(address freelancer)
external
view
returns (FreelancerMetadata memory)
{
return freelancerToMetadata[freelancer];
}
/**
* @dev Gets a freelancer by address.
**/
function getFreelancerAllocation(address freelancer)
external
view
returns (uint256)
{
return freelancerToFinancials[freelancer].stakeAllocation;
}
/**
* @dev Gets a freelancer by address.
**/
function getFreelancerStake(address freelancer)
external
view
returns (uint256)
{
return freelancerToStakePool[freelancer].getOwnerStake();
}
/**
* @dev Gets a freelancer by address.
**/
function getFreelancerLockedStake(address freelancer)
external
view
returns (uint256)
{
return freelancerToStakePool[freelancer].getLockedStake();
}
function selfInitializeFreelancerMetadata() external {
if (freelancerToMetadata[msg.sender].isInitialized == false) {
freelancerToMetadata[msg.sender] = FreelancerMetadata(
0,
true,
true
);
freelancerToFinancials[msg.sender]
.stakeAllocation = DEFAULT_STAKE_ALLOCATION;
freelancerToStakePool[msg.sender] = new StakePool(
msg.sender,
tokenAddress
);
freelancers.push(msg.sender);
emit FreelancerInit(freelancerToMetadata[msg.sender]);
}
}
}
|
Sets a freelancer's stake allocation called by freelancer./
|
function addToFreelancerEarned(address freelancer, uint256 amount)
external
onlyIfFreelancerExists(freelancer)
onlyFriend(msg.sender)
{
freelancerToFinancials[freelancer].totalEarned = amount;
}
| 7,320,113
|
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
import "./ERC9981155Extension.sol";
import "./ERC998ERC20Extension.sol";
import "../utils/ContractKeys.sol";
import "../interfaces/IBundleBuilder.sol";
import "../interfaces/INftfiBundler.sol";
import "../interfaces/INftfiHub.sol";
import "../interfaces/IPermittedNFTs.sol";
import "../interfaces/IPermittedERC20s.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
/**
* @title NftfiBundler
* @author NFTfi
* @dev ERC998 Top-Down Composable Non-Fungible Token that supports permitted ERC721, ERC1155 and ERC20 children.
*/
contract NftfiBundler is IBundleBuilder, ERC9981155Extension, ERC998ERC20Extension {
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableSet for EnumerableSet.AddressSet;
INftfiHub public immutable hub;
event NewBundle(uint256 bundleId, address indexed sender, address indexed receiver);
/**
* @dev Stores the NftfiHub, name and symbol
*
* @param _nftfiHub Address of the NftfiHub contract
* @param _name name of the token contract
* @param _symbol symbol of the token contract
*/
constructor(
address _nftfiHub,
string memory _name,
string memory _symbol
) ERC721(_name, _symbol) {
hub = INftfiHub(_nftfiHub);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 _interfaceId)
public
view
virtual
override(ERC9981155Extension, ERC998ERC20Extension)
returns (bool)
{
return
_interfaceId == type(IERC721Receiver).interfaceId ||
_interfaceId == type(INftfiBundler).interfaceId ||
super.supportsInterface(_interfaceId);
}
/**
* @notice Tells if an asset is permitted or not
* @param _asset address of the asset
* @return true if permitted, false otherwise
*/
function permittedAsset(address _asset) public view returns (bool) {
IPermittedNFTs permittedNFTs = IPermittedNFTs(hub.getContract(ContractKeys.PERMITTED_NFTS));
return permittedNFTs.getNFTPermit(_asset) > 0;
}
/**
* @notice Tells if the erc20 is permitted or not
* @param _erc20Contract address of the erc20
* @return true if permitted, false otherwise
*/
function permittedErc20Asset(address _erc20Contract) public view returns (bool) {
IPermittedERC20s permittedERC20s = IPermittedERC20s(hub.getContract(ContractKeys.PERMITTED_BUNDLE_ERC20S));
return permittedERC20s.getERC20Permit(_erc20Contract);
}
/**
* @dev used by the loan contract to build a bundle from the BundleElements struct at the beginning of a loan,
* returns the id of the created bundle
*
* @param _bundleElements - the lists of erc721-20-1155 tokens that are to be bundled
* @param _sender sender of the tokens in the bundle - the borrower
* @param _receiver receiver of the created bundle, normally the loan contract
*/
function buildBundle(
BundleElements memory _bundleElements,
address _sender,
address _receiver
) external override returns (uint256) {
uint256 bundleId = _safeMint(_receiver);
require(
_bundleElements.erc721s.length > 0 ||
_bundleElements.erc20s.length > 0 ||
_bundleElements.erc1155s.length > 0,
"bundle is empty"
);
for (uint256 i = 0; i < _bundleElements.erc721s.length; i++) {
if (_bundleElements.erc721s[i].safeTransferable) {
IERC721(_bundleElements.erc721s[i].tokenContract).safeTransferFrom(
_sender,
address(this),
_bundleElements.erc721s[i].id,
abi.encodePacked(bundleId)
);
} else {
_getChild(_sender, bundleId, _bundleElements.erc721s[i].tokenContract, _bundleElements.erc721s[i].id);
}
}
for (uint256 i = 0; i < _bundleElements.erc20s.length; i++) {
_getERC20(_sender, bundleId, _bundleElements.erc20s[i].tokenContract, _bundleElements.erc20s[i].amount);
}
for (uint256 i = 0; i < _bundleElements.erc1155s.length; i++) {
IERC1155(_bundleElements.erc1155s[i].tokenContract).safeBatchTransferFrom(
_sender,
address(this),
_bundleElements.erc1155s[i].ids,
_bundleElements.erc1155s[i].amounts,
abi.encodePacked(bundleId)
);
}
emit NewBundle(bundleId, _sender, _receiver);
return bundleId;
}
/**
* @notice Remove all the children from the bundle
* @dev This method may run out of gas if the list of children is too big. In that case, children can be removed
* individually.
* @param _tokenId the id of the bundle
* @param _receiver address of the receiver of the children
*/
function decomposeBundle(uint256 _tokenId, address _receiver) external override nonReentrant {
require(ownerOf(_tokenId) == msg.sender, "caller is not owner");
_validateReceiver(_receiver);
// In each iteration all contracts children are removed, so eventually all contracts are removed
while (childContracts[_tokenId].length() > 0) {
address childContract = childContracts[_tokenId].at(0);
// In each iteration a child is removed, so eventually all contracts children are removed
while (childTokens[_tokenId][childContract].length() > 0) {
uint256 childId = childTokens[_tokenId][childContract].at(0);
uint256 balance = balances[_tokenId][childContract][childId];
if (balance > 0) {
_remove1155Child(_tokenId, childContract, childId, balance);
IERC1155(childContract).safeTransferFrom(address(this), _receiver, childId, balance, "");
emit Transfer1155Child(_tokenId, _receiver, childContract, childId, balance);
} else {
_removeChild(_tokenId, childContract, childId);
try IERC721(childContract).safeTransferFrom(address(this), _receiver, childId) {
// solhint-disable-previous-line no-empty-blocks
} catch {
_oldNFTsTransfer(_receiver, childContract, childId);
}
emit TransferChild(_tokenId, _receiver, childContract, childId);
}
}
}
// In each iteration all contracts children are removed, so eventually all contracts are removed
while (erc20ChildContracts[_tokenId].length() > 0) {
address erc20Contract = erc20ChildContracts[_tokenId].at(0);
uint256 balance = erc20Balances[_tokenId][erc20Contract];
_removeERC20(_tokenId, erc20Contract, balance);
IERC20(erc20Contract).safeTransfer(_receiver, balance);
emit TransferERC20(_tokenId, _receiver, erc20Contract, balance);
}
}
/**
* @dev Update the state to receive a ERC721 child
* Overrides the implementation to check if the asset is permitted
* @param _from The owner of the child token
* @param _tokenId The token receiving the child
* @param _childContract The ERC721 contract of the child token
* @param _childTokenId The token that is being transferred to the parent
*/
function _receiveChild(
address _from,
uint256 _tokenId,
address _childContract,
uint256 _childTokenId
) internal virtual override {
require(permittedAsset(_childContract), "erc721 not permitted");
super._receiveChild(_from, _tokenId, _childContract, _childTokenId);
}
/**
* @dev Updates the state to receive a ERC1155 child
* Overrides the implementation to check if the asset is permitted
* @param _tokenId The token receiving the child
* @param _childContract The ERC1155 contract of the child token
* @param _childTokenId The token id that is being transferred to the parent
* @param _amount The amount of the token that is being transferred
*/
function _receive1155Child(
uint256 _tokenId,
address _childContract,
uint256 _childTokenId,
uint256 _amount
) internal virtual override {
require(permittedAsset(_childContract), "erc1155 not permitted");
super._receive1155Child(_tokenId, _childContract, _childTokenId, _amount);
}
/**
* @notice Store data for the received ERC20
* @param _from The current owner address of the ERC20 tokens that are being transferred.
* @param _tokenId The token to transfer the ERC20 tokens to.
* @param _erc20Contract The ERC20 token contract
* @param _value The number of ERC20 tokens to transfer
*/
function _receiveErc20Child(
address _from,
uint256 _tokenId,
address _erc20Contract,
uint256 _value
) internal virtual override {
require(permittedErc20Asset(_erc20Contract), "erc20 not permitted");
super._receiveErc20Child(_from, _tokenId, _erc20Contract, _value);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "./ERC998TopDown.sol";
import "../interfaces/IERC998ERC1155TopDown.sol";
/**
* @title ERC9981155Extension
* @author NFTfi
* @dev ERC998TopDown extension to support ERC1155 children
*/
abstract contract ERC9981155Extension is ERC998TopDown, IERC998ERC1155TopDown, IERC1155Receiver {
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableSet for EnumerableSet.AddressSet;
// tokenId => (child address => (child tokenId => balance))
mapping(uint256 => mapping(address => mapping(uint256 => uint256))) internal balances;
/**
* @dev Gives child balance for a specific child contract and child id
* @param _childContract The ERC1155 contract of the child token
* @param _childTokenId The tokenId of the child token
*/
function childBalance(
uint256 _tokenId,
address _childContract,
uint256 _childTokenId
) external view override returns (uint256) {
return balances[_tokenId][_childContract][_childTokenId];
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 _interfaceId)
public
view
virtual
override(ERC998TopDown, IERC165)
returns (bool)
{
return
_interfaceId == type(IERC998ERC1155TopDown).interfaceId ||
_interfaceId == type(IERC1155Receiver).interfaceId ||
super.supportsInterface(_interfaceId);
}
/**
* @notice Transfer a ERC1155 child token from top-down composable to address or other top-down composable
* @param _tokenId The owning token to transfer from
* @param _to The address that receives the child token
* @param _childContract The ERC1155 contract of the child token
* @param _childTokenId The tokenId of the token that is being transferred
* @param _amount The amount of the token that is being transferred
* @param _data Additional data with no specified format
*/
function safeTransferChild(
uint256 _tokenId,
address _to,
address _childContract,
uint256 _childTokenId,
uint256 _amount,
bytes memory _data
) external override nonReentrant {
_validateReceiver(_to);
_validate1155ChildTransfer(_tokenId);
_remove1155Child(_tokenId, _childContract, _childTokenId, _amount);
if (_to == address(this)) {
_validateAndReceive1155Child(msg.sender, _childContract, _childTokenId, _amount, _data);
} else {
IERC1155(_childContract).safeTransferFrom(address(this), _to, _childTokenId, _amount, _data);
emit Transfer1155Child(_tokenId, _to, _childContract, _childTokenId, _amount);
}
}
/**
* @notice Transfer batch of ERC1155 child token from top-down composable to address or other top-down composable
* @param _tokenId The owning token to transfer from
* @param _to The address that receives the child token
* @param _childContract The ERC1155 contract of the child token
* @param _childTokenIds The list of tokenId of the token that is being transferred
* @param _amounts The list of amount of the token that is being transferred
* @param _data Additional data with no specified format
*/
function safeBatchTransferChild(
uint256 _tokenId,
address _to,
address _childContract,
uint256[] memory _childTokenIds,
uint256[] memory _amounts,
bytes memory _data
) external override nonReentrant {
require(_childTokenIds.length == _amounts.length, "ids and amounts length mismatch");
_validateReceiver(_to);
_validate1155ChildTransfer(_tokenId);
for (uint256 i = 0; i < _childTokenIds.length; ++i) {
uint256 childTokenId = _childTokenIds[i];
uint256 amount = _amounts[i];
_remove1155Child(_tokenId, _childContract, childTokenId, amount);
if (_to == address(this)) {
_validateAndReceive1155Child(msg.sender, _childContract, childTokenId, amount, _data);
}
}
if (_to != address(this)) {
IERC1155(_childContract).safeBatchTransferFrom(address(this), _to, _childTokenIds, _amounts, _data);
emit Transfer1155BatchChild(_tokenId, _to, _childContract, _childTokenIds, _amounts);
}
}
/**
* @notice A token receives a child token
*/
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes memory
) external virtual override returns (bytes4) {
revert("external calls restricted");
}
/**
* @notice A token receives a batch of child tokens
* param The address that caused the transfer
* @param _from The owner of the child token
* @param _ids The list of token id that is being transferred to the parent
* @param _values The list of amounts of the tokens that is being transferred
* @param _data Up to the first 32 bytes contains an integer which is the receiving parent tokenId
* @return the selector of this method
*/
function onERC1155BatchReceived(
address,
address _from,
uint256[] memory _ids,
uint256[] memory _values,
bytes memory _data
) external virtual override nonReentrant returns (bytes4) {
require(_data.length == 32, "data must contain tokenId to transfer the child token to");
uint256 _receiverTokenId = _parseTokenId(_data);
for (uint256 i = 0; i < _ids.length; i++) {
_receive1155Child(_receiverTokenId, msg.sender, _ids[i], _values[i]);
emit Received1155Child(_from, _receiverTokenId, msg.sender, _ids[i], _values[i]);
}
return this.onERC1155BatchReceived.selector;
}
/**
* @dev Validates the data of the child token and receives it
* @param _from The owner of the child token
* @param _childContract The ERC1155 contract of the child token
* @param _id The token id that is being transferred to the parent
* @param _amount The amount of the token that is being transferred
* @param _data Up to the first 32 bytes contains an integer which is the receiving parent tokenId
*/
function _validateAndReceive1155Child(
address _from,
address _childContract,
uint256 _id,
uint256 _amount,
bytes memory _data
) internal virtual {
require(_data.length == 32, "data must contain tokenId to transfer the child token to");
uint256 _receiverTokenId = _parseTokenId(_data);
_receive1155Child(_receiverTokenId, _childContract, _id, _amount);
emit Received1155Child(_from, _receiverTokenId, _childContract, _id, _amount);
}
/**
* @dev Updates the state to receive a child
* @param _tokenId The token receiving the child
* @param _childContract The ERC1155 contract of the child token
* @param _childTokenId The token id that is being transferred to the parent
* @param _amount The amount of the token that is being transferred
*/
function _receive1155Child(
uint256 _tokenId,
address _childContract,
uint256 _childTokenId,
uint256 _amount
) internal virtual {
require(_exists(_tokenId), "bundle tokenId does not exist");
uint256 childTokensLength = childTokens[_tokenId][_childContract].length();
if (childTokensLength == 0) {
childContracts[_tokenId].add(_childContract);
}
childTokens[_tokenId][_childContract].add(_childTokenId);
balances[_tokenId][_childContract][_childTokenId] += _amount;
}
/**
* @notice Validates the transfer of a 1155 child
* @param _fromTokenId The owning token to transfer from
*/
function _validate1155ChildTransfer(uint256 _fromTokenId) internal virtual {
_validateTransferSender(_fromTokenId);
}
/**
* @notice Updates the state to remove a ERC1155 child
* @param _tokenId The owning token to transfer from
* @param _childContract The ERC1155 contract of the child token
* @param _childTokenId The tokenId of the token that is being transferred
* @param _amount The amount of the token that is being transferred
*/
function _remove1155Child(
uint256 _tokenId,
address _childContract,
uint256 _childTokenId,
uint256 _amount
) internal virtual {
require(
_amount != 0 && balances[_tokenId][_childContract][_childTokenId] >= _amount,
"insufficient child balance for transfer"
);
balances[_tokenId][_childContract][_childTokenId] -= _amount;
if (balances[_tokenId][_childContract][_childTokenId] == 0) {
// remove child token
childTokens[_tokenId][_childContract].remove(_childTokenId);
// remove contract
if (childTokens[_tokenId][_childContract].length() == 0) {
childContracts[_tokenId].remove(_childContract);
}
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
import "./ERC998TopDown.sol";
import "../interfaces/IERC998ERC20TopDown.sol";
import "../interfaces/IERC998ERC20TopDownEnumerable.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";
/**
* @title ERC998ERC20Extension
* @author NFTfi
* @dev ERC998TopDown extension to support ERC20 children
*/
abstract contract ERC998ERC20Extension is ERC998TopDown, IERC998ERC20TopDown, IERC998ERC20TopDownEnumerable {
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
// tokenId => ERC20 child contract
mapping(uint256 => EnumerableSet.AddressSet) internal erc20ChildContracts;
// tokenId => (token contract => balance)
mapping(uint256 => mapping(address => uint256)) internal erc20Balances;
/**
* @dev Look up the balance of ERC20 tokens for a specific token and ERC20 contract
* @param _tokenId The token that owns the ERC20 tokens
* @param _erc20Contract The ERC20 contract
* @return The number of ERC20 tokens owned by a token
*/
function balanceOfERC20(uint256 _tokenId, address _erc20Contract) external view virtual override returns (uint256) {
return erc20Balances[_tokenId][_erc20Contract];
}
/**
* @notice Get ERC20 contract by tokenId and index
* @param _tokenId The parent token of ERC20 tokens
* @param _index The index position of the child contract
* @return childContract The contract found at the tokenId and index
*/
function erc20ContractByIndex(uint256 _tokenId, uint256 _index) external view virtual override returns (address) {
return erc20ChildContracts[_tokenId].at(_index);
}
/**
* @notice Get the total number of ERC20 tokens owned by tokenId
* @param _tokenId The parent token of ERC20 tokens
* @return uint256 The total number of ERC20 tokens
*/
function totalERC20Contracts(uint256 _tokenId) external view virtual override returns (uint256) {
return erc20ChildContracts[_tokenId].length();
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 _interfaceId) public view virtual override(ERC998TopDown) returns (bool) {
return
_interfaceId == type(IERC998ERC20TopDown).interfaceId ||
_interfaceId == type(IERC998ERC20TopDownEnumerable).interfaceId ||
super.supportsInterface(_interfaceId);
}
/**
* @notice Transfer ERC20 tokens to address
* @param _tokenId The token to transfer from
* @param _to The address to send the ERC20 tokens to
* @param _erc20Contract The ERC20 contract
* @param _value The number of ERC20 tokens to transfer
*/
function transferERC20(
uint256 _tokenId,
address _to,
address _erc20Contract,
uint256 _value
) external virtual override {
_validateERC20Value(_value);
_validateReceiver(_to);
_validateERC20Transfer(_tokenId);
_removeERC20(_tokenId, _erc20Contract, _value);
IERC20(_erc20Contract).safeTransfer(_to, _value);
emit TransferERC20(_tokenId, _to, _erc20Contract, _value);
}
/**
* @notice Get ERC20 tokens from ERC20 contract.
* @dev This contract has to be approved first by _erc20Contract
*/
function getERC20(
address,
uint256,
address,
uint256
) external pure override {
revert("external calls restricted");
}
/**
* @notice NOT SUPPORTED
* Intended to transfer ERC223 tokens. ERC223 tokens can be transferred as regular ERC20
*/
function transferERC223(
uint256,
address,
address,
uint256,
bytes calldata
) external virtual override {
revert("TRANSFER_ERC223_NOT_SUPPORTED");
}
/**
* @notice NOT SUPPORTED
* Intended to receive ERC223 tokens. ERC223 tokens can be deposited as regular ERC20
*/
function tokenFallback(
address,
uint256,
bytes calldata
) external virtual override {
revert("TOKEN_FALLBACK_ERC223_NOT_SUPPORTED");
}
/**
* @notice Get ERC20 tokens from ERC20 contract.
* @dev This contract has to be approved first by _erc20Contract
* @param _from The current owner address of the ERC20 tokens that are being transferred.
* @param _tokenId The token to transfer the ERC20 tokens to.
* @param _erc20Contract The ERC20 token contract
* @param _value The number of ERC20 tokens to transfer
*/
function _getERC20(
address _from,
uint256 _tokenId,
address _erc20Contract,
uint256 _value
) internal {
_validateERC20Value(_value);
_receiveErc20Child(_from, _tokenId, _erc20Contract, _value);
IERC20(_erc20Contract).safeTransferFrom(_from, address(this), _value);
}
/**
* @notice Validates the value of a ERC20 transfer
* @param _value The number of ERC20 tokens to transfer
*/
function _validateERC20Value(uint256 _value) internal virtual {
require(_value > 0, "zero amount");
}
/**
* @notice Validates the transfer of a ERC20
* @param _fromTokenId The owning token to transfer from
*/
function _validateERC20Transfer(uint256 _fromTokenId) internal virtual {
_validateTransferSender(_fromTokenId);
}
/**
* @notice Store data for the received ERC20
* @param _from The current owner address of the ERC20 tokens that are being transferred.
* @param _tokenId The token to transfer the ERC20 tokens to.
* @param _erc20Contract The ERC20 token contract
* @param _value The number of ERC20 tokens to transfer
*/
function _receiveErc20Child(
address _from,
uint256 _tokenId,
address _erc20Contract,
uint256 _value
) internal virtual {
require(_exists(_tokenId), "bundle tokenId does not exist");
uint256 erc20Balance = erc20Balances[_tokenId][_erc20Contract];
if (erc20Balance == 0) {
erc20ChildContracts[_tokenId].add(_erc20Contract);
}
erc20Balances[_tokenId][_erc20Contract] += _value;
emit ReceivedERC20(_from, _tokenId, _erc20Contract, _value);
}
/**
* @notice Updates the state to remove ERC20 tokens
* @param _tokenId The token to transfer from
* @param _erc20Contract The ERC20 contract
* @param _value The number of ERC20 tokens to transfer
*/
function _removeERC20(
uint256 _tokenId,
address _erc20Contract,
uint256 _value
) internal virtual {
uint256 erc20Balance = erc20Balances[_tokenId][_erc20Contract];
require(erc20Balance >= _value, "not enough token available to transfer");
uint256 newERC20Balance = erc20Balance - _value;
erc20Balances[_tokenId][_erc20Contract] = newERC20Balance;
if (newERC20Balance == 0) {
erc20ChildContracts[_tokenId].remove(_erc20Contract);
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
/**
* @title ContractKeys
* @author NFTfi
* @dev Common library for contract keys
*/
library ContractKeys {
bytes32 public constant PERMITTED_ERC20S = bytes32("PERMITTED_ERC20S");
bytes32 public constant PERMITTED_NFTS = bytes32("PERMITTED_NFTS");
bytes32 public constant PERMITTED_PARTNERS = bytes32("PERMITTED_PARTNERS");
bytes32 public constant NFT_TYPE_REGISTRY = bytes32("NFT_TYPE_REGISTRY");
bytes32 public constant LOAN_REGISTRY = bytes32("LOAN_REGISTRY");
bytes32 public constant PERMITTED_SNFT_RECEIVER = bytes32("PERMITTED_SNFT_RECEIVER");
bytes32 public constant PERMITTED_BUNDLE_ERC20S = bytes32("PERMITTED_BUNDLE_ERC20S");
bytes32 public constant PERMITTED_AIRDROPS = bytes32("PERMITTED_AIRDROPS");
bytes32 public constant AIRDROP_RECEIVER = bytes32("AIRDROP_RECEIVER");
bytes32 public constant AIRDROP_FACTORY = bytes32("AIRDROP_FACTORY");
bytes32 public constant AIRDROP_FLASH_LOAN = bytes32("AIRDROP_FLASH_LOAN");
bytes32 public constant NFTFI_BUNDLER = bytes32("NFTFI_BUNDLER");
string public constant AIRDROP_WRAPPER_STRING = "AirdropWrapper";
/**
* @notice Returns the bytes32 representation of a string
* @param _key the string key
* @return id bytes32 representation
*/
function getIdFromStringKey(string memory _key) external pure returns (bytes32 id) {
require(bytes(_key).length <= 32, "invalid key");
// solhint-disable-next-line no-inline-assembly
assembly {
id := mload(add(_key, 32))
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
interface IBundleBuilder {
/**
* @notice data of a erc721 bundle element
*
* @param tokenContract - address of the token contract
* @param id - id of the token
* @param safeTransferable - wether the implementing token contract has a safeTransfer function or not
*/
struct BundleElementERC721 {
address tokenContract;
uint256 id;
bool safeTransferable;
}
/**
* @notice data of a erc20 bundle element
*
* @param tokenContract - address of the token contract
* @param amount - amount of the token
*/
struct BundleElementERC20 {
address tokenContract;
uint256 amount;
}
/**
* @notice data of a erc20 bundle element
*
* @param tokenContract - address of the token contract
* @param ids - list of ids of the tokens
* @param amounts - list amounts of the tokens
*/
struct BundleElementERC1155 {
address tokenContract;
uint256[] ids;
uint256[] amounts;
}
/**
* @notice the lists of erc721-20-1155 tokens that are to be bundled
*
* @param erc721s list of erc721 tokens
* @param erc20s list of erc20 tokens
* @param erc1155s list of erc1155 tokens
*/
struct BundleElements {
BundleElementERC721[] erc721s;
BundleElementERC20[] erc20s;
BundleElementERC1155[] erc1155s;
}
/**
* @notice used by the loan contract to build a bundle from the BundleElements struct at the beginning of a loan,
* returns the id of the created bundle
*
* @param _bundleElements - the lists of erc721-20-1155 tokens that are to be bundled
* @param _sender sender of the tokens in the bundle - the borrower
* @param _receiver receiver of the created bundle, normally the loan contract
*/
function buildBundle(
BundleElements memory _bundleElements,
address _sender,
address _receiver
) external returns (uint256);
/**
* @notice Remove all the children from the bundle
* @dev This method may run out of gas if the list of children is too big. In that case, children can be removed
* individually.
* @param _tokenId the id of the bundle
* @param _receiver address of the receiver of the children
*/
function decomposeBundle(uint256 _tokenId, address _receiver) external;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "./IERC998ERC721TopDown.sol";
interface INftfiBundler is IERC721 {
function safeMint(address _to) external returns (uint256);
function decomposeBundle(uint256 _tokenId, address _receiver) external;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
/**
* @title INftfiHub
* @author NFTfi
* @dev NftfiHub interface
*/
interface INftfiHub {
function setContract(string calldata _contractKey, address _contractAddress) external;
function getContract(bytes32 _contractKey) external view returns (address);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
interface IPermittedNFTs {
function setNFTPermit(address _nftContract, string memory _nftType) external;
function getNFTPermit(address _nftContract) external view returns (bytes32);
function getNFTWrapper(address _nftContract) external view returns (address);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
interface IPermittedERC20s {
function getERC20Permit(address _erc20) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
* @dev Handles the receipt of a single ERC1155 token type. This function is
* called at the end of a `safeTransferFrom` after the balance has been updated.
*
* NOTE: To accept the transfer, this must return
* `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* (i.e. 0xf23a6e61, or its own function selector).
*
* @param operator The address which initiated the transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param id The ID of the token being transferred
* @param value The amount of tokens being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
* @dev Handles the receipt of a multiple ERC1155 token types. This function
* is called at the end of a `safeBatchTransferFrom` after the balances have
* been updated.
*
* NOTE: To accept the transfer(s), this must return
* `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* (i.e. 0xbc197c81, or its own function selector).
*
* @param operator The address which initiated the batch transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param ids An array containing ids of each token being transferred (order and length must match values array)
* @param values An array containing amounts of each token being transferred (order and length must match ids array)
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "../interfaces/IERC998ERC721TopDown.sol";
import "../interfaces/IERC998ERC721TopDownEnumerable.sol";
/**
* @title ERC998TopDown
* @author NFTfi
* @dev ERC998ERC721 Top-Down Composable Non-Fungible Token.
* See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-998.md
* This implementation does not support children to be nested bundles, erc20 nor bottom-up
*/
abstract contract ERC998TopDown is
ERC721Enumerable,
IERC998ERC721TopDown,
IERC998ERC721TopDownEnumerable,
ReentrancyGuard
{
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableSet for EnumerableSet.AddressSet;
// return this.rootOwnerOf.selector ^ this.rootOwnerOfChild.selector ^
// this.tokenOwnerOf.selector ^ this.ownerOfChild.selector;
bytes32 public constant ERC998_MAGIC_VALUE = 0xcd740db500000000000000000000000000000000000000000000000000000000;
bytes32 internal constant ERC998_MAGIC_MASK = 0xffffffff00000000000000000000000000000000000000000000000000000000;
uint256 public tokenCount = 0;
// tokenId => child contract
mapping(uint256 => EnumerableSet.AddressSet) internal childContracts;
// tokenId => (child address => array of child tokens)
mapping(uint256 => mapping(address => EnumerableSet.UintSet)) internal childTokens;
// child address => childId => tokenId
// this is used for ERC721 type tokens
mapping(address => mapping(uint256 => uint256)) internal childTokenOwner;
/**
* @notice Tells whether the ERC721 type child exists or not
* @param _childContract The contract address of the child token
* @param _childTokenId The tokenId of the child
* @return True if the child exists, false otherwise
*/
function childExists(address _childContract, uint256 _childTokenId) external view virtual returns (bool) {
uint256 tokenId = childTokenOwner[_childContract][_childTokenId];
return tokenId != 0;
}
/**
* @notice Get the total number of child contracts with tokens that are owned by _tokenId
* @param _tokenId The parent token of child tokens in child contracts
* @return uint256 The total number of child contracts with tokens owned by _tokenId
*/
function totalChildContracts(uint256 _tokenId) external view virtual override returns (uint256) {
return childContracts[_tokenId].length();
}
/**
* @notice Get child contract by tokenId and index
* @param _tokenId The parent token of child tokens in child contract
* @param _index The index position of the child contract
* @return childContract The contract found at the _tokenId and index
*/
function childContractByIndex(uint256 _tokenId, uint256 _index)
external
view
virtual
override
returns (address childContract)
{
return childContracts[_tokenId].at(_index);
}
/**
* @notice Get the total number of child tokens owned by tokenId that exist in a child contract
* @param _tokenId The parent token of child tokens
* @param _childContract The child contract containing the child tokens
* @return uint256 The total number of child tokens found in child contract that are owned by _tokenId
*/
function totalChildTokens(uint256 _tokenId, address _childContract) external view override returns (uint256) {
return childTokens[_tokenId][_childContract].length();
}
/**
* @notice Get child token owned by _tokenId, in child contract, at index position
* @param _tokenId The parent token of the child token
* @param _childContract The child contract of the child token
* @param _index The index position of the child token
* @return childTokenId The child tokenId for the parent token, child token and index
*/
function childTokenByIndex(
uint256 _tokenId,
address _childContract,
uint256 _index
) external view virtual override returns (uint256 childTokenId) {
return childTokens[_tokenId][_childContract].at(_index);
}
/**
* @notice Get the parent tokenId and its owner of a ERC721 child token
* @param _childContract The contract address of the child token
* @param _childTokenId The tokenId of the child
* @return parentTokenOwner The parent address of the parent token and ERC998 magic value
* @return parentTokenId The parent tokenId of _childTokenId
*/
function ownerOfChild(address _childContract, uint256 _childTokenId)
external
view
virtual
override
returns (bytes32 parentTokenOwner, uint256 parentTokenId)
{
parentTokenId = childTokenOwner[_childContract][_childTokenId];
require(parentTokenId != 0, "owner of child not found");
address parentTokenOwnerAddress = ownerOf(parentTokenId);
// solhint-disable-next-line no-inline-assembly
assembly {
parentTokenOwner := or(ERC998_MAGIC_VALUE, parentTokenOwnerAddress)
}
}
/**
* @notice Get the root owner of tokenId
* @param _tokenId The token to query for a root owner address
* @return rootOwner The root owner at the top of tree of tokens and ERC998 magic value.
*/
function rootOwnerOf(uint256 _tokenId) public view virtual override returns (bytes32 rootOwner) {
return rootOwnerOfChild(address(0), _tokenId);
}
/**
* @notice Get the root owner of a child token
* @dev Returns the owner at the top of the tree of composables
* Use Cases handled:
* - Case 1: Token owner is this contract and token.
* - Case 2: Token owner is other external top-down composable
* - Case 3: Token owner is other contract
* - Case 4: Token owner is user
* @param _childContract The contract address of the child token
* @param _childTokenId The tokenId of the child
* @return rootOwner The root owner at the top of tree of tokens and ERC998 magic value
*/
function rootOwnerOfChild(address _childContract, uint256 _childTokenId)
public
view
virtual
override
returns (bytes32 rootOwner)
{
address rootOwnerAddress;
if (_childContract != address(0)) {
(rootOwnerAddress, _childTokenId) = _ownerOfChild(_childContract, _childTokenId);
} else {
rootOwnerAddress = ownerOf(_childTokenId);
}
if (rootOwnerAddress.isContract()) {
try IERC998ERC721TopDown(rootOwnerAddress).rootOwnerOfChild(address(this), _childTokenId) returns (
bytes32 returnedRootOwner
) {
// Case 2: Token owner is other external top-down composable
if (returnedRootOwner & ERC998_MAGIC_MASK == ERC998_MAGIC_VALUE) {
return returnedRootOwner;
}
} catch {
// solhint-disable-previous-line no-empty-blocks
}
}
// Case 3: Token owner is other contract
// Or
// Case 4: Token owner is user
// solhint-disable-next-line no-inline-assembly
assembly {
rootOwner := or(ERC998_MAGIC_VALUE, rootOwnerAddress)
}
return rootOwner;
}
/**
* @dev See {IERC165-supportsInterface}.
* The interface id 0x1efdf36a is added. The spec claims it to be the interface id of IERC998ERC721TopDown.
* But it is not.
* It is added anyway in case some contract checks it being compliant with the spec.
*/
function supportsInterface(bytes4 _interfaceId) public view virtual override(ERC721Enumerable) returns (bool) {
return
_interfaceId == type(IERC998ERC721TopDown).interfaceId ||
_interfaceId == type(IERC998ERC721TopDownEnumerable).interfaceId ||
_interfaceId == 0x1efdf36a ||
super.supportsInterface(_interfaceId);
}
/**
* @notice Mints a new bundle
* @param _to The address that owns the new bundle
* @return The id of the new bundle
*/
function _safeMint(address _to) internal returns (uint256) {
uint256 id = ++tokenCount;
_safeMint(_to, id);
return id;
}
/**
* @notice Transfer child token from top-down composable to address
* @param _fromTokenId The owning token to transfer from
* @param _to The address that receives the child token
* @param _childContract The ERC721 contract of the child token
* @param _childTokenId The tokenId of the token that is being transferred
*/
function safeTransferChild(
uint256 _fromTokenId,
address _to,
address _childContract,
uint256 _childTokenId
) external virtual override nonReentrant {
_transferChild(_fromTokenId, _to, _childContract, _childTokenId);
IERC721(_childContract).safeTransferFrom(address(this), _to, _childTokenId);
emit TransferChild(_fromTokenId, _to, _childContract, _childTokenId);
}
/**
* @notice Transfer child token from top-down composable to address or other top-down composable
* @param _fromTokenId The owning token to transfer from
* @param _to The address that receives the child token
* @param _childContract The ERC721 contract of the child token
* @param _childTokenId The tokenId of the token that is being transferred
* @param _data Additional data with no specified format
*/
function safeTransferChild(
uint256 _fromTokenId,
address _to,
address _childContract,
uint256 _childTokenId,
bytes memory _data
) external virtual override nonReentrant {
_transferChild(_fromTokenId, _to, _childContract, _childTokenId);
if (_to == address(this)) {
_validateAndReceiveChild(msg.sender, _childContract, _childTokenId, _data);
} else {
IERC721(_childContract).safeTransferFrom(address(this), _to, _childTokenId, _data);
emit TransferChild(_fromTokenId, _to, _childContract, _childTokenId);
}
}
/**
* @dev Transfer child token from top-down composable to address
* @param _fromTokenId The owning token to transfer from
* @param _to The address that receives the child token
* @param _childContract The ERC721 contract of the child token
* @param _childTokenId The tokenId of the token that is being transferred
*/
function transferChild(
uint256 _fromTokenId,
address _to,
address _childContract,
uint256 _childTokenId
) external virtual override nonReentrant {
_transferChild(_fromTokenId, _to, _childContract, _childTokenId);
_oldNFTsTransfer(_to, _childContract, _childTokenId);
emit TransferChild(_fromTokenId, _to, _childContract, _childTokenId);
}
/**
* @notice NOT SUPPORTED
* Intended to transfer bottom-up composable child token from top-down composable to other ERC721 token.
*/
function transferChildToParent(
uint256,
address,
uint256,
address,
uint256,
bytes memory
) external pure override {
revert("BOTTOM_UP_CHILD_NOT_SUPPORTED");
}
/**
* @notice Transfer a child token from an ERC721 contract to a composable. Used for old tokens that does not
* have a safeTransferFrom method like cryptokitties
*/
function getChild(
address,
uint256,
address,
uint256
) external pure override {
revert("external calls restricted");
}
/**
* @notice Transfer a child token from an ERC721 contract to a composable. Used for old tokens that does not
* have a safeTransferFrom method like cryptokitties
* @dev This contract has to be approved first in _childContract
* @param _from The address that owns the child token.
* @param _tokenId The token that becomes the parent owner
* @param _childContract The ERC721 contract of the child token
* @param _childTokenId The tokenId of the child token
*/
function _getChild(
address _from,
uint256 _tokenId,
address _childContract,
uint256 _childTokenId
) internal virtual nonReentrant {
_receiveChild(_from, _tokenId, _childContract, _childTokenId);
IERC721(_childContract).transferFrom(_from, address(this), _childTokenId);
}
/**
* @notice A token receives a child token
* param The address that caused the transfer
* @param _from The owner of the child token
* @param _childTokenId The token that is being transferred to the parent
* @param _data Up to the first 32 bytes contains an integer which is the receiving parent tokenId
* @return the selector of this method
*/
function onERC721Received(
address,
address _from,
uint256 _childTokenId,
bytes calldata _data
) external virtual override nonReentrant returns (bytes4) {
_validateAndReceiveChild(_from, msg.sender, _childTokenId, _data);
return this.onERC721Received.selector;
}
/**
* @dev ERC721 implementation hook that is called before any token transfer. Prevents nested bundles
* @param _from address of the current owner of the token
* @param _to destination address
* @param _tokenId id of the token to transfer
*/
function _beforeTokenTransfer(
address _from,
address _to,
uint256 _tokenId
) internal virtual override {
require(_to != address(this), "nested bundles not allowed");
super._beforeTokenTransfer(_from, _to, _tokenId);
}
/**
* @dev Validates the child transfer parameters and remove the child from the bundle
* @param _fromTokenId The owning token to transfer from
* @param _to The address that receives the child token
* @param _childContract The ERC721 contract of the child token
* @param _childTokenId The tokenId of the token that is being transferred
*/
function _transferChild(
uint256 _fromTokenId,
address _to,
address _childContract,
uint256 _childTokenId
) internal virtual {
_validateReceiver(_to);
_validateChildTransfer(_fromTokenId, _childContract, _childTokenId);
_removeChild(_fromTokenId, _childContract, _childTokenId);
}
/**
* @dev Validates the child transfer parameters
* @param _fromTokenId The owning token to transfer from
* @param _childContract The ERC721 contract of the child token
* @param _childTokenId The tokenId of the token that is being transferred
*/
function _validateChildTransfer(
uint256 _fromTokenId,
address _childContract,
uint256 _childTokenId
) internal virtual {
uint256 tokenId = childTokenOwner[_childContract][_childTokenId];
require(tokenId != 0, "_transferChild _childContract _childTokenId not found");
require(tokenId == _fromTokenId, "ComposableTopDown: _transferChild wrong tokenId found");
_validateTransferSender(tokenId);
}
/**
* @dev Validates the receiver of a child transfer
* @param _to The address that receives the child token
*/
function _validateReceiver(address _to) internal virtual {
require(_to != address(0), "child transfer to zero address");
}
/**
* @dev Updates the state to remove a child
* @param _tokenId The owning token to transfer from
* @param _childContract The ERC721 contract of the child token
* @param _childTokenId The tokenId of the token that is being transferred
*/
function _removeChild(
uint256 _tokenId,
address _childContract,
uint256 _childTokenId
) internal virtual {
// remove child token
childTokens[_tokenId][_childContract].remove(_childTokenId);
delete childTokenOwner[_childContract][_childTokenId];
// remove contract
if (childTokens[_tokenId][_childContract].length() == 0) {
childContracts[_tokenId].remove(_childContract);
}
}
/**
* @dev Validates the data from a child transfer and receives it
* @param _from The owner of the child token
* @param _childContract The ERC721 contract of the child token
* @param _childTokenId The token that is being transferred to the parent
* @param _data Up to the first 32 bytes contains an integer which is the receiving parent tokenId
*/
function _validateAndReceiveChild(
address _from,
address _childContract,
uint256 _childTokenId,
bytes memory _data
) internal virtual {
require(_data.length > 0, "data must contain tokenId to transfer the child token to");
// convert up to 32 bytes of _data to uint256, owner nft tokenId passed as uint in bytes
uint256 tokenId = _parseTokenId(_data);
_receiveChild(_from, tokenId, _childContract, _childTokenId);
}
/**
* @dev Update the state to receive a child
* @param _from The owner of the child token
* @param _tokenId The token receiving the child
* @param _childContract The ERC721 contract of the child token
* @param _childTokenId The token that is being transferred to the parent
*/
function _receiveChild(
address _from,
uint256 _tokenId,
address _childContract,
uint256 _childTokenId
) internal virtual {
require(_exists(_tokenId), "bundle tokenId does not exist");
uint256 childTokensLength = childTokens[_tokenId][_childContract].length();
if (childTokensLength == 0) {
childContracts[_tokenId].add(_childContract);
}
childTokens[_tokenId][_childContract].add(_childTokenId);
childTokenOwner[_childContract][_childTokenId] = _tokenId;
emit ReceivedChild(_from, _tokenId, _childContract, _childTokenId);
}
/**
* @dev Returns the owner of a child
* @param _childContract The contract address of the child token
* @param _childTokenId The tokenId of the child
* @return parentTokenOwner The parent address of the parent token and ERC998 magic value
* @return parentTokenId The parent tokenId of _childTokenId
*/
function _ownerOfChild(address _childContract, uint256 _childTokenId)
internal
view
virtual
returns (address parentTokenOwner, uint256 parentTokenId)
{
parentTokenId = childTokenOwner[_childContract][_childTokenId];
require(parentTokenId != 0, "owner of child not found");
return (ownerOf(parentTokenId), parentTokenId);
}
/**
* @dev Convert up to 32 bytes of_data to uint256, owner nft tokenId passed as uint in bytes
* @param _data Up to the first 32 bytes contains an integer which is the receiving parent tokenId
* @return tokenId the token Id encoded in the data
*/
function _parseTokenId(bytes memory _data) internal pure virtual returns (uint256 tokenId) {
// solhint-disable-next-line no-inline-assembly
assembly {
tokenId := mload(add(_data, 0x20))
}
}
/**
* @dev Transfers the NFT using method compatible with old token contracts
* @param _to address of the receiver of the children
* @param _childContract The contract address of the child token
* @param _childTokenId The tokenId of the child
*/
function _oldNFTsTransfer(
address _to,
address _childContract,
uint256 _childTokenId
) internal {
// This is here to be compatible with cryptokitties and other old contracts that require being owner and
// approved before transferring.
// Does not work with current standard which does not allow approving self, so we must let it fail in that case.
try IERC721(_childContract).approve(address(this), _childTokenId) {
// solhint-disable-previous-line no-empty-blocks
} catch {
// solhint-disable-previous-line no-empty-blocks
}
IERC721(_childContract).transferFrom(address(this), _to, _childTokenId);
}
/**
* @notice Validates that the sender is authorized to perform a child transfer
* @param _fromTokenId The owning token to transfer from
*/
function _validateTransferSender(uint256 _fromTokenId) internal virtual {
address rootOwner = address(uint160(uint256(rootOwnerOf(_fromTokenId))));
require(
rootOwner == msg.sender ||
getApproved(_fromTokenId) == msg.sender ||
isApprovedForAll(rootOwner, msg.sender),
"transferChild msg.sender not eligible"
);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
interface IERC998ERC1155TopDown {
event Received1155Child(
address indexed from,
uint256 indexed toTokenId,
address indexed childContract,
uint256 childTokenId,
uint256 amount
);
event Transfer1155Child(
uint256 indexed fromTokenId,
address indexed to,
address indexed childContract,
uint256 childTokenId,
uint256 amount
);
event Transfer1155BatchChild(
uint256 indexed fromTokenId,
address indexed to,
address indexed childContract,
uint256[] childTokenIds,
uint256[] amounts
);
function safeTransferChild(
uint256 fromTokenId,
address to,
address childContract,
uint256 childTokenId,
uint256 amount,
bytes calldata data
) external;
function safeBatchTransferChild(
uint256 fromTokenId,
address to,
address childContract,
uint256[] calldata childTokenIds,
uint256[] calldata amounts,
bytes calldata data
) external;
function childBalance(
uint256 tokenId,
address childContract,
uint256 childTokenId
) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
// 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 (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
interface IERC998ERC721TopDown {
event ReceivedChild(
address indexed _from,
uint256 indexed _tokenId,
address indexed _childContract,
uint256 _childTokenId
);
event TransferChild(
uint256 indexed tokenId,
address indexed _to,
address indexed _childContract,
uint256 _childTokenId
);
function onERC721Received(
address _operator,
address _from,
uint256 _childTokenId,
bytes calldata _data
) external returns (bytes4);
function transferChild(
uint256 _fromTokenId,
address _to,
address _childContract,
uint256 _childTokenId
) external;
function safeTransferChild(
uint256 _fromTokenId,
address _to,
address _childContract,
uint256 _childTokenId
) external;
function safeTransferChild(
uint256 _fromTokenId,
address _to,
address _childContract,
uint256 _childTokenId,
bytes memory _data
) external;
function transferChildToParent(
uint256 _fromTokenId,
address _toContract,
uint256 _toTokenId,
address _childContract,
uint256 _childTokenId,
bytes memory _data
) external;
// getChild function enables older contracts like cryptokitties to be transferred into a composable
// The _childContract must approve this contract. Then getChild can be called.
function getChild(
address _from,
uint256 _tokenId,
address _childContract,
uint256 _childTokenId
) external;
function rootOwnerOf(uint256 _tokenId) external view returns (bytes32 rootOwner);
function rootOwnerOfChild(address _childContract, uint256 _childTokenId) external view returns (bytes32 rootOwner);
function ownerOfChild(address _childContract, uint256 _childTokenId)
external
view
returns (bytes32 parentTokenOwner, uint256 parentTokenId);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
interface IERC998ERC721TopDownEnumerable {
function totalChildContracts(uint256 _tokenId) external view returns (uint256);
function childContractByIndex(uint256 _tokenId, uint256 _index) external view returns (address childContract);
function totalChildTokens(uint256 _tokenId, address _childContract) external view returns (uint256);
function childTokenByIndex(
uint256 _tokenId,
address _childContract,
uint256 _index
) external view returns (uint256 childTokenId);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts 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 (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: BUSL-1.1
pragma solidity 0.8.4;
interface IERC998ERC20TopDown {
event ReceivedERC20(
address indexed _from,
uint256 indexed _tokenId,
address indexed _erc20Contract,
uint256 _value
);
event TransferERC20(uint256 indexed _tokenId, address indexed _to, address indexed _erc20Contract, uint256 _value);
function balanceOfERC20(uint256 _tokenId, address __erc20Contract) external view returns (uint256);
function tokenFallback(
address _from,
uint256 _value,
bytes calldata _data
) external;
function transferERC20(
uint256 _tokenId,
address _to,
address _erc20Contract,
uint256 _value
) external;
function transferERC223(
uint256 _tokenId,
address _to,
address _erc223Contract,
uint256 _value,
bytes calldata _data
) external;
function getERC20(
address _from,
uint256 _tokenId,
address _erc20Contract,
uint256 _value
) external;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
interface IERC998ERC20TopDownEnumerable {
function totalERC20Contracts(uint256 _tokenId) external view returns (uint256);
function erc20ContractByIndex(uint256 _tokenId, uint256 _index) external view returns (address);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
|
Store data for the received ERC20 _from The current owner address of the ERC20 tokens that are being transferred. _tokenId The token to transfer the ERC20 tokens to. _erc20Contract The ERC20 token contract _value The number of ERC20 tokens to transfer/
|
function _receiveErc20Child(
address _from,
uint256 _tokenId,
address _erc20Contract,
uint256 _value
) internal virtual {
require(_exists(_tokenId), "bundle tokenId does not exist");
uint256 erc20Balance = erc20Balances[_tokenId][_erc20Contract];
if (erc20Balance == 0) {
erc20ChildContracts[_tokenId].add(_erc20Contract);
}
erc20Balances[_tokenId][_erc20Contract] += _value;
emit ReceivedERC20(_from, _tokenId, _erc20Contract, _value);
}
| 1,483,184
|
./full_match/5/0x02946E4Bc3f7A809CeEAAB30b68B91c4Cf1eF3B5/sources/Rent.sol
|
function to get the amount per minutes
|
function getAmountPerMinute(uint256 _tokenId) public view returns (uint256) {
return rentables[_tokenId].amountPerMinute;
}
| 1,953,216
|
pragma solidity ^0.4.19;
/**
* @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) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title EjectableOwnable
* @dev The EjectableOwnable contract provides the function to remove the ownership of the contract.
*/
contract EjectableOwnable is Ownable {
/**
* @dev Remove the ownership by setting the owner address to null,
* after calling this function, all onlyOwner function will be be able to be called by anyone anymore,
* the contract will achieve truly decentralisation.
*/
function removeOwnership() onlyOwner public {
owner = 0x0;
}
}
/**
* @title JointOwnable
* @dev Extension for the Ownable contract, where the owner can assign at most 2 other addresses
* to manage some functions of the contract, using the eitherOwner modifier.
* Note that onlyOwner modifier would still be accessible only for the original owner.
*/
contract JointOwnable is Ownable {
event AnotherOwnerAssigned(address indexed anotherOwner);
address public anotherOwner1;
address public anotherOwner2;
/**
* @dev Throws if called by any account other than the owner or anotherOwner.
*/
modifier eitherOwner() {
require(msg.sender == owner || msg.sender == anotherOwner1 || msg.sender == anotherOwner2);
_;
}
/**
* @dev Allows the current owner to assign another owner.
* @param _anotherOwner The address to another owner.
*/
function assignAnotherOwner1(address _anotherOwner) onlyOwner public {
require(_anotherOwner != 0);
AnotherOwnerAssigned(_anotherOwner);
anotherOwner1 = _anotherOwner;
}
/**
* @dev Allows the current owner to assign another owner.
* @param _anotherOwner The address to another owner.
*/
function assignAnotherOwner2(address _anotherOwner) onlyOwner public {
require(_anotherOwner != 0);
AnotherOwnerAssigned(_anotherOwner);
anotherOwner2 = _anotherOwner;
}
}
/**
* @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();
}
}
/**
* @title Destructible
* @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner.
*/
contract Destructible is Ownable {
function Destructible() public payable { }
/**
* @dev Transfers the current balance to the owner and terminates the contract.
*/
function destroy() onlyOwner public {
selfdestruct(owner);
}
function destroyAndSend(address _recipient) onlyOwner public {
selfdestruct(_recipient);
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title PullPayment
* @dev Base contract supporting async send for pull payments. Inherit from this
* contract and use asyncSend instead of send.
*/
contract PullPayment {
using SafeMath for uint256;
mapping(address => uint256) public payments;
uint256 public totalPayments;
/**
* @dev withdraw accumulated balance, called by payee.
*/
function withdrawPayments() public {
address payee = msg.sender;
uint256 payment = payments[payee];
require(payment != 0);
require(this.balance >= payment);
totalPayments = totalPayments.sub(payment);
payments[payee] = 0;
assert(payee.send(payment));
}
/**
* @dev Called by the payer to store the sent amount as credit to be pulled.
* @param dest The destination address of the funds.
* @param amount The amount to transfer.
*/
function asyncSend(address dest, uint256 amount) internal {
payments[dest] = payments[dest].add(amount);
totalPayments = totalPayments.add(amount);
}
}
/**
* @title A simplified interface of ERC-721, but without approval functions
*/
contract ERC721 {
// Events
event Transfer(address indexed from, address indexed to, uint tokenId);
// ERC20 compatible functions
// function name() public view returns (string);
// function symbol() public view returns (string);
function totalSupply() public view returns (uint);
function balanceOf(address _owner) public view returns (uint);
// Functions that define ownership
function ownerOf(uint _tokenId) external view returns (address);
function transfer(address _to, uint _tokenId) external;
}
contract DungeonStructs {
/**
* @dev The main Dungeon struct. Every dungeon in the game is represented by this structure.
* A dungeon is consists of an unlimited number of floors for your heroes to challenge,
* the power level of a dungeon is encoded in the floorGenes. Some dungeons are in fact more "challenging" than others,
* the secret formula for that is left for user to find out.
*
* Each dungeon also has a "training area", heroes can perform trainings and upgrade their stat,
* and some dungeons are more effective in the training, which is also a secret formula!
*
* When player challenge or do training in a dungeon, the fee will be collected as the dungeon rewards,
* which will be rewarded to the player who successfully challenged the current floor.
*
* Each dungeon fits in fits into three 256-bit words.
*/
struct Dungeon {
// Each dungeon has an ID which is the index in the storage array.
// The timestamp of the block when this dungeon is created.
uint32 creationTime;
// The status of the dungeon, each dungeon can have 5 status, namely:
// 0: Active | 1: Transport Only | 2: Challenge Only | 3: Train Only | 4: InActive
uint8 status;
// The dungeon's difficulty, the higher the difficulty,
// normally, the "rarer" the seedGenes, the higher the diffculty,
// and the higher the contribution fee it is to challenge, train, and transport to the dungeon,
// the formula for the contribution fee is in DungeonChallenge and DungeonTraining contracts.
// A dungeon's difficulty never change.
uint8 difficulty;
// The dungeon's capacity, maximum number of players allowed to stay on this dungeon.
// The capacity of the newbie dungeon (Holyland) is set at 0 (which is infinity).
// Using 16-bit unsigned integers can have a maximum of 65535 in capacity.
// A dungeon's capacity never change.
uint16 capacity;
// The current floor number, a dungeon is consists of an umlimited number of floors,
// when there is heroes successfully challenged a floor, the next floor will be
// automatically generated. Using 32-bit unsigned integer can have a maximum of 4 billion floors.
uint32 floorNumber;
// The timestamp of the block when the current floor is generated.
uint32 floorCreationTime;
// Current accumulated rewards, successful challenger will get a large proportion of it.
uint128 rewards;
// The seed genes of the dungeon, it is used as the base gene for first floor,
// some dungeons are rarer and some are more common, the exact details are,
// of course, top secret of the game!
// A dungeon's seedGenes never change.
uint seedGenes;
// The genes for current floor, it encodes the difficulty level of the current floor.
// We considered whether to store the entire array of genes for all floors, but
// in order to save some precious gas we're willing to sacrifice some functionalities with that.
uint floorGenes;
}
/**
* @dev The main Hero struct. Every hero in the game is represented by this structure.
*/
struct Hero {
// Each hero has an ID which is the index in the storage array.
// The timestamp of the block when this dungeon is created.
uint64 creationTime;
// The timestamp of the block where a challenge is performed, used to calculate when a hero is allowed to engage in another challenge.
uint64 cooldownStartTime;
// Every time a hero challenge a dungeon, its cooldown index will be incremented by one.
uint32 cooldownIndex;
// The seed of the hero, the gene encodes the power level of the hero.
// This is another top secret of the game! Hero's gene can be upgraded via
// training in a dungeon.
uint genes;
}
}
/**
* @title The ERC-721 compliance token contract for the Dungeon tokens.
* @dev See the DungeonStructs contract to see the details of the Dungeon token data structure.
*/
contract DungeonToken is ERC721, DungeonStructs, Pausable, JointOwnable {
/**
* @notice Limits the number of dungeons the contract owner can ever create.
*/
uint public constant DUNGEON_CREATION_LIMIT = 1024;
/**
* @dev The Mint event is fired whenever a new dungeon is created.
*/
event Mint(address indexed owner, uint newTokenId, uint difficulty, uint capacity, uint seedGenes);
/**
* @dev The NewDungeonFloor event is fired whenever a new dungeon floor is added.
*/
event NewDungeonFloor(uint timestamp, uint indexed dungeonId, uint32 newFloorNumber, uint128 newRewards , uint newFloorGenes);
/**
* @dev Transfer event as defined in current draft of ERC721. Emitted every time a token
* ownership (Dungeon Master) is assigned, including token creation.
*/
event Transfer(address indexed from, address indexed to, uint tokenId);
/**
* @dev Name of token.
*/
string public constant name = "Dungeon";
/**
* @dev Symbol of token.
*/
string public constant symbol = "DUNG";
/**
* @dev An array containing the Dungeon struct, which contains all the dungeons in existance.
* The ID for each dungeon is the index of this array.
*/
Dungeon[] public dungeons;
/**
* @dev A mapping from token IDs to the address that owns them.
*/
mapping(uint => address) tokenIndexToOwner;
/**
* @dev A mapping from owner address to count of tokens that address owns.
*/
mapping(address => uint) ownershipTokenCount;
/**
* Each non-fungible token owner can own more than one token at one time.
* Because each token is referenced by its unique ID, however,
* it can get difficult to keep track of the individual tokens that a user may own.
* To do this, the contract keeps a record of the IDs of each token that each user owns.
*/
mapping(address => uint[]) public ownerTokens;
/**
* @dev Returns the total number of tokens currently in existence.
*/
function totalSupply() public view returns (uint) {
return dungeons.length;
}
/**
* @dev Returns the number of tokens owned by a specific address.
* @param _owner The owner address to check.
*/
function balanceOf(address _owner) public view returns (uint) {
return ownershipTokenCount[_owner];
}
/**
* @dev Checks if a given address is the current owner of a particular token.
* @param _claimant The address we are validating against.
* @param _tokenId Token ID
*/
function _owns(address _claimant, uint _tokenId) internal view returns (bool) {
return tokenIndexToOwner[_tokenId] == _claimant;
}
/**
* @dev Returns the address currently assigned ownership of a given token.
*/
function ownerOf(uint _tokenId) external view returns (address) {
require(tokenIndexToOwner[_tokenId] != address(0));
return tokenIndexToOwner[_tokenId];
}
/**
* @dev Assigns ownership of a specific token to an address.
*/
function _transfer(address _from, address _to, uint _tokenId) internal {
// Increment the ownershipTokenCount.
ownershipTokenCount[_to]++;
// Transfer ownership.
tokenIndexToOwner[_tokenId] = _to;
// Add the _tokenId to ownerTokens[_to]
ownerTokens[_to].push(_tokenId);
// When creating new token, _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// Remove the _tokenId from ownerTokens[_from]
uint[] storage fromTokens = ownerTokens[_from];
bool iFound = false;
for (uint i = 0; i < fromTokens.length - 1; i++) {
if (iFound) {
fromTokens[i] = fromTokens[i + 1];
} else if (fromTokens[i] == _tokenId) {
iFound = true;
fromTokens[i] = fromTokens[i + 1];
}
}
fromTokens.length--;
}
// Emit the Transfer event.
Transfer(_from, _to, _tokenId);
}
/**
* @dev External function to transfers a token to another address.
* @param _to The address of the recipient, can be a user or contract.
* @param _tokenId The ID of the token to transfer.
*/
function transfer(address _to, uint _tokenId) whenNotPaused external {
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
require(_to != address(this));
// You can only send your own token.
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
/**
* @dev Get an array of IDs of each token that an user owns.
*/
function getOwnerTokens(address _owner) external view returns(uint[]) {
return ownerTokens[_owner];
}
/**
* @dev The external function that creates a new dungeon and stores it, only contract owners
* can create new token, and will be restricted by the DUNGEON_CREATION_LIMIT.
* Will generate a Mint event, a NewDungeonFloor event, and a Transfer event.
* @param _difficulty The difficulty of the new dungeon.
* @param _capacity The capacity of the new dungeon.
* @param _seedGenes The seed genes of the new dungeon.
* @param _firstFloorGenes The genes of the first dungeon floor.
* @return The dungeon ID of the new dungeon.
*/
function createDungeon(uint _difficulty, uint _capacity, uint _seedGenes, uint _firstFloorGenes, address _owner) eitherOwner external returns (uint) {
// Ensure the total supply is within the fixed limit.
require(totalSupply() < DUNGEON_CREATION_LIMIT);
// UPDATE STORAGE
// Create a new dungeon.
dungeons.push(Dungeon(uint32(now), 0, uint8(_difficulty), uint16(_capacity), 0, 0, 0, _seedGenes, 0));
// Token id is the index in the storage array.
uint newTokenId = dungeons.length - 1;
// Emit the token mint event.
Mint(_owner, newTokenId, _difficulty, _capacity, _seedGenes);
// Initialize the fist floor, this will emit the NewDungeonFloor event.
addDungeonNewFloor(newTokenId, 0, _firstFloorGenes);
// This will assign ownership, and also emit the Transfer event.
_transfer(0, _owner, newTokenId);
return newTokenId;
}
/**
* @dev The external function to set dungeon status by its ID,
* refer to DungeonStructs for more information about dungeon status.
* Only contract owners can alter dungeon state.
*/
function setDungeonStatus(uint _id, uint _newStatus) eitherOwner tokenExists(_id) external {
dungeons[_id].status = uint8(_newStatus);
}
/**
* @dev The external function to add additional dungeon rewards by its ID,
* only contract owners can alter dungeon state.
*/
function addDungeonRewards(uint _id, uint _additinalRewards) eitherOwner tokenExists(_id) external {
dungeons[_id].rewards += uint128(_additinalRewards);
}
/**
* @dev The external function to add another dungeon floor by its ID,
* only contract owners can alter dungeon state.
* Will generate both a NewDungeonFloor event.
*/
function addDungeonNewFloor(uint _id, uint _newRewards, uint _newFloorGenes) eitherOwner tokenExists(_id) public {
Dungeon storage dungeon = dungeons[_id];
dungeon.floorNumber++;
dungeon.floorCreationTime = uint32(now);
dungeon.rewards = uint128(_newRewards);
dungeon.floorGenes = _newFloorGenes;
// Emit the NewDungeonFloor event.
NewDungeonFloor(now, _id, dungeon.floorNumber, dungeon.rewards, dungeon.floorGenes);
}
/* ======== MODIFIERS ======== */
/**
* @dev Throws if _dungeonId is not created yet.
*/
modifier tokenExists(uint _tokenId) {
require(_tokenId < totalSupply());
_;
}
}
/**
* @title The ERC-721 compliance token contract for the Hero tokens.
* @dev See the DungeonStructs contract to see the details of the Hero token data structure.
*/
contract HeroToken is ERC721, DungeonStructs, Pausable, JointOwnable {
/**
* @dev The Mint event is fired whenever a new hero is created.
*/
event Mint(address indexed owner, uint newTokenId, uint _genes);
/**
* @dev Transfer event as defined in current draft of ERC721. Emitted every time a token
* ownership is assigned, including token creation.
*/
event Transfer(address indexed from, address indexed to, uint tokenId);
/**
* @dev Name of token.
*/
string public constant name = "Hero";
/**
* @dev Symbol of token.
*/
string public constant symbol = "HERO";
/**
* @dev An array containing the Hero struct, which contains all the heroes in existance.
* The ID for each hero is the index of this array.
*/
Hero[] public heroes;
/**
* @dev A mapping from token IDs to the address that owns them.
*/
mapping(uint => address) tokenIndexToOwner;
/**
* @dev A mapping from owner address to count of tokens that address owns.
*/
mapping(address => uint) ownershipTokenCount;
/**
* Each non-fungible token owner can own more than one token at one time.
* Because each token is referenced by its unique ID, however,
* it can get difficult to keep track of the individual tokens that a user may own.
* To do this, the contract keeps a record of the IDs of each token that each user owns.
*/
mapping(address => uint[]) public ownerTokens;
/**
* @dev Returns the total number of tokens currently in existence.
*/
function totalSupply() public view returns (uint) {
return heroes.length;
}
/**
* @dev Returns the number of tokens owned by a specific address.
* @param _owner The owner address to check.
*/
function balanceOf(address _owner) public view returns (uint) {
return ownershipTokenCount[_owner];
}
/**
* @dev Checks if a given address is the current owner of a particular token.
* @param _claimant The address we are validating against.
* @param _tokenId Token ID
*/
function _owns(address _claimant, uint _tokenId) internal view returns (bool) {
return tokenIndexToOwner[_tokenId] == _claimant;
}
/**
* @dev Returns the address currently assigned ownership of a given token.
*/
function ownerOf(uint _tokenId) external view returns (address) {
require(tokenIndexToOwner[_tokenId] != address(0));
return tokenIndexToOwner[_tokenId];
}
/**
* @dev Assigns ownership of a specific token to an address.
*/
function _transfer(address _from, address _to, uint _tokenId) internal {
// Increment the ownershipTokenCount.
ownershipTokenCount[_to]++;
// Transfer ownership.
tokenIndexToOwner[_tokenId] = _to;
// Add the _tokenId to ownerTokens[_to]
ownerTokens[_to].push(_tokenId);
// When creating new token, _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// Remove the _tokenId from ownerTokens[_from]
uint[] storage fromTokens = ownerTokens[_from];
bool iFound = false;
for (uint i = 0; i < fromTokens.length - 1; i++) {
if (iFound) {
fromTokens[i] = fromTokens[i + 1];
} else if (fromTokens[i] == _tokenId) {
iFound = true;
fromTokens[i] = fromTokens[i + 1];
}
}
fromTokens.length--;
}
// Emit the Transfer event.
Transfer(_from, _to, _tokenId);
}
/**
* @dev External function to transfers a token to another address.
* @param _to The address of the recipient, can be a user or contract.
* @param _tokenId The ID of the token to transfer.
*/
function transfer(address _to, uint _tokenId) whenNotPaused external {
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
require(_to != address(this));
// You can only send your own token.
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
/**
* @dev Get an array of IDs of each token that an user owns.
*/
function getOwnerTokens(address _owner) external view returns(uint[]) {
return ownerTokens[_owner];
}
/**
* @dev An external function that creates a new hero and stores it,
* only contract owners can create new token.
* method doesn't do any checking and should only be called when the
* input data is known to be valid.
* @param _genes The gene of the new hero.
* @param _owner The inital owner of this hero.
* @return The hero ID of the new hero.
*/
function createHero(uint _genes, address _owner) eitherOwner external returns (uint) {
// UPDATE STORAGE
// Create a new hero.
heroes.push(Hero(uint64(now), 0, 0, _genes));
// Token id is the index in the storage array.
uint newTokenId = heroes.length - 1;
// Emit the token mint event.
Mint(_owner, newTokenId, _genes);
// This will assign ownership, and also emit the Transfer event.
_transfer(0, _owner, newTokenId);
return newTokenId;
}
/**
* @dev The external function to set the hero genes by its ID,
* only contract owners can alter hero state.
*/
function setHeroGenes(uint _id, uint _newGenes) eitherOwner tokenExists(_id) external {
heroes[_id].genes = _newGenes;
}
/**
* @dev Set the cooldownStartTime for the given hero. Also increments the cooldownIndex.
*/
function triggerCooldown(uint _id) eitherOwner tokenExists(_id) external {
Hero storage hero = heroes[_id];
hero.cooldownStartTime = uint64(now);
hero.cooldownIndex++;
}
/* ======== MODIFIERS ======== */
/**
* @dev Throws if _dungeonId is not created yet.
*/
modifier tokenExists(uint _tokenId) {
require(_tokenId < totalSupply());
_;
}
}
/**
* SECRET
*/
contract ChallengeScienceInterface {
/**
* @dev given genes of current floor and dungeon seed, return a genetic combination - may have a random factor.
* @param _floorGenes Genes of floor.
* @param _seedGenes Seed genes of dungeon.
* @return The resulting genes.
*/
function mixGenes(uint _floorGenes, uint _seedGenes) external returns (uint);
}
/**
* SECRET
*/
contract TrainingScienceInterface {
/**
* @dev given genes of hero and current floor, return a genetic combination - may have a random factor.
* @param _heroGenes Genes of hero.
* @param _floorGenes Genes of current floor.
* @param _equipmentId Equipment index to train for, 0 is train all attributes.
* @return The resulting genes.
*/
function mixGenes(uint _heroGenes, uint _floorGenes, uint _equipmentId) external returns (uint);
}
/**
* @title DungeonBase
* @dev Base contract for Ether Dungeon. It implements all necessary sub-classes,
* holds all the base storage variables, and some commonly used functions.
*/
contract DungeonBase is EjectableOwnable, Pausable, PullPayment, DungeonStructs {
/* ======== TOKEN CONTRACTS ======== */
/**
* @dev The address of the ERC721 token contract managing all Dungeon tokens.
*/
DungeonToken public dungeonTokenContract;
/**
* @dev The address of the ERC721 token contract managing all Hero tokens.
*/
HeroToken public heroTokenContract;
/* ======== CLOSED SOURCE CONTRACTS ======== */
/**
* @dev The address of the ChallengeScience contract that handles the floor generation mechanics after challenge success.
*/
ChallengeScienceInterface challengeScienceContract;
/**
* @dev The address of the TrainingScience contract that handles the hero training mechanics.
*/
TrainingScienceInterface trainingScienceContract;
/* ======== CONSTANTS ======== */
uint16[32] EQUIPMENT_POWERS = [
1, 2, 4, 5, 16, 17, 18, 19, 0, 0, 0, 0, 0, 0, 0, 0,
4, 16, 32, 33, 0, 0, 0, 0, 32, 64, 0, 0, 128, 0, 0, 0
];
uint SUPER_HERO_MULTIPLIER = 32;
/* ======== SETTER FUNCTIONS ======== */
/**
* @dev Set the address of the dungeon token contract.
* @param _newDungeonTokenContract An address of a DungeonToken contract.
*/
function setDungeonTokenContract(address _newDungeonTokenContract) onlyOwner external {
dungeonTokenContract = DungeonToken(_newDungeonTokenContract);
}
/**
* @dev Set the address of the hero token contract.
* @param _newHeroTokenContract An address of a HeroToken contract.
*/
function setHeroTokenContract(address _newHeroTokenContract) onlyOwner external {
heroTokenContract = HeroToken(_newHeroTokenContract);
}
/**
* @dev Set the address of the secret dungeon challenge formula contract.
* @param _newChallengeScienceAddress An address of a ChallengeScience contract.
*/
function setChallengeScienceContract(address _newChallengeScienceAddress) onlyOwner external {
challengeScienceContract = ChallengeScienceInterface(_newChallengeScienceAddress);
}
/**
* @dev Set the address of the secret hero training formula contract.
* @param _newTrainingScienceAddress An address of a TrainingScience contract.
*/
function setTrainingScienceContract(address _newTrainingScienceAddress) onlyOwner external {
trainingScienceContract = TrainingScienceInterface(_newTrainingScienceAddress);
}
/* ======== MODIFIERS ======== */
/**
* @dev Throws if _dungeonId is not created yet.
*/
modifier dungeonExists(uint _dungeonId) {
require(_dungeonId < dungeonTokenContract.totalSupply());
_;
}
/* ======== HELPER FUNCTIONS ======== */
/**
* @dev An internal function to calculate the top 5 heroes power of a player.
*/
function _getTop5HeroesPower(address _address, uint _dungeonId) internal view returns (uint) {
uint heroCount = heroTokenContract.balanceOf(_address);
if (heroCount == 0) {
return 0;
}
// Compute all hero powers for further calculation.
uint[] memory heroPowers = new uint[](heroCount);
for (uint i = 0; i < heroCount; i++) {
uint heroId = heroTokenContract.ownerTokens(_address, i);
uint genes;
(,,, genes) = heroTokenContract.heroes(heroId);
// Power of dungeonId = 0 (no super hero boost).
heroPowers[i] = _getHeroPower(genes, _dungeonId);
}
// Calculate the top 5 heroes power.
uint result;
uint curMax;
uint curMaxIndex;
for (uint j; j < 5; j++){
for (uint k = 0; k < heroPowers.length; k++) {
if (heroPowers[k] > curMax) {
curMax = heroPowers[k];
curMaxIndex = k;
}
}
result += curMax;
heroPowers[curMaxIndex] = 0;
curMax = 0;
curMaxIndex = 0;
}
return result;
}
/**
* @dev An internal function to calculate the power of a hero,
* it calculates the base equipment power, stats power, and "Super" multiplier.
*/
function _getHeroPower(uint _genes, uint _dungeonId) internal view returns (uint) {
uint difficulty;
(,, difficulty,,,,,,) = dungeonTokenContract.dungeons(_dungeonId);
// Calculate total stats power.
uint statsPower;
for (uint i = 0; i < 4; i++) {
statsPower += _genes % 32 + 1;
_genes /= 32 ** 4;
}
// Calculate total equipment power.
uint equipmentPower;
uint superRank = _genes % 32;
for (uint j = 4; j < 12; j++) {
uint curGene = _genes % 32;
equipmentPower += EQUIPMENT_POWERS[curGene];
_genes /= 32 ** 4;
if (superRank != curGene) {
superRank = 0;
}
}
// Calculate super power boost.
bool isSuper = superRank >= 16;
uint superBoost;
if (isSuper) {
superBoost = (difficulty - 1) * SUPER_HERO_MULTIPLIER;
}
return statsPower + equipmentPower + superBoost;
}
/**
* @dev An internal function to calculate the difficulty of a dungeon floor.
*/
function _getDungeonPower(uint _genes) internal view returns (uint) {
// Calculate total dungeon power.
uint dungeonPower;
for (uint j = 0; j < 12; j++) {
dungeonPower += EQUIPMENT_POWERS[_genes % 32];
_genes /= 32 ** 4;
}
return dungeonPower;
}
}
contract DungeonTransportation is DungeonBase {
/**
* @dev The PlayerTransported event is fired when user transported to another dungeon.
*/
event PlayerTransported(uint timestamp, address indexed playerAddress, uint indexed originDungeonId, uint indexed destinationDungeonId);
/* ======== GAME SETTINGS ======== */
/**
* @notice The actual fee contribution required to call transport() is calculated by this feeMultiplier,
* times the dungeon difficulty of destination dungeon. The payment is accumulated to the rewards of the origin dungeon,
* and a large proportion will be claimed by whoever successfully challenged the floor.
* 1000 szabo = 0.001 ether
*/
uint public transportationFeeMultiplier = 500 szabo;
/* ======== STORAGE ======== */
/**
* @dev A mapping from token IDs to the address that owns them.
*/
mapping(address => uint) public playerToDungeonID;
/**
* @dev A mapping from owner address to count of tokens that address owns.
*/
mapping(uint => uint) public dungeonPlayerCount;
/**
* @dev The main external function to call when a player transport to another dungeon.
* Will generate a PlayerTransported event.
*/
function transport(uint _destinationDungeonId) whenNotPaused dungeonCanTransport(_destinationDungeonId) external payable {
uint originDungeonId = playerToDungeonID[msg.sender];
// Disallow transport to the same dungeon.
require(_destinationDungeonId != originDungeonId);
// Get the dungeon details from the token contract.
uint difficulty;
uint capacity;
(,, difficulty, capacity,,,,,) = dungeonTokenContract.dungeons(_destinationDungeonId);
// Disallow weaker user to transport to "difficult" dungeon.
uint top5HeroesPower = _getTop5HeroesPower(msg.sender, _destinationDungeonId);
require(top5HeroesPower >= difficulty * 12);
// Checks for payment, any exceeding funds will be transferred back to the player.
uint baseFee = difficulty * transportationFeeMultiplier;
uint additionalFee = top5HeroesPower / 48 * transportationFeeMultiplier;
uint requiredFee = baseFee + additionalFee;
require(msg.value >= requiredFee);
// ** STORAGE UPDATE **
// Increment the accumulated rewards for the dungeon.
dungeonTokenContract.addDungeonRewards(originDungeonId, requiredFee);
// Calculate any excess funds and make it available to be withdrawed by the player.
asyncSend(msg.sender, msg.value - requiredFee);
_transport(originDungeonId, _destinationDungeonId);
}
/**
* Private function to assigns location of a player
*/
function _transport(uint _originDungeonId, uint _destinationDungeonId) private {
// If a player do not have any hero, claim first hero.
if (heroTokenContract.balanceOf(msg.sender) == 0) {
claimHero();
}
// ** STORAGE UPDATE **
// Update the ownershipTokenCount.
dungeonPlayerCount[_originDungeonId]--;
dungeonPlayerCount[_destinationDungeonId]++;
// ** STORAGE UPDATE **
// Update player location.
playerToDungeonID[msg.sender] = _destinationDungeonId;
// Emit the DungeonChallenged event.
PlayerTransported(now, msg.sender, _originDungeonId, _destinationDungeonId);
}
/* ======== OWNERSHIP FUNCTIONS ======== */
/**
* @notice Used in transport, challenge and train, to get the genes of a specific hero,
* a claim a hero if didn't have any.
*/
function _getHeroGenesOrClaimFirstHero(uint _heroId) internal returns (uint heroId, uint heroGenes) {
heroId = _heroId;
// If a player do not have any hero, claim first hero first.
if (heroTokenContract.balanceOf(msg.sender) == 0) {
heroId = claimHero();
}
(,,,heroGenes) = heroTokenContract.heroes(heroId);
}
/**
* @dev Claim a new hero with empty genes.
*/
function claimHero() public returns (uint) {
// If a player do not tranport to any dungeon yet, and it is the first time claiming the hero,
// set the dungeon location, increment the #0 Holyland player count by 1.
if (playerToDungeonID[msg.sender] == 0 && heroTokenContract.balanceOf(msg.sender) == 0) {
dungeonPlayerCount[0]++;
}
return heroTokenContract.createHero(0, msg.sender);
}
/* ======== SETTER FUNCTIONS ======== */
/**
* @dev Updates the fee contribution multiplier required for calling transport().
*/
function setTransportationFeeMultiplier(uint _newTransportationFeeMultiplier) onlyOwner external {
transportationFeeMultiplier = _newTransportationFeeMultiplier;
}
/* ======== MODIFIERS ======== */
/**
* @dev Throws if dungeon status do not allow transportation, also check for dungeon existence.
* Also check if the capacity of the destination dungeon is reached.
*/
modifier dungeonCanTransport(uint _destinationDungeonId) {
require(_destinationDungeonId < dungeonTokenContract.totalSupply());
uint status;
uint capacity;
(,status,,capacity,,,,,) = dungeonTokenContract.dungeons(_destinationDungeonId);
require(status == 0 || status == 1);
// Check if the capacity of the destination dungeon is reached.
// Capacity 0 = Infinity
require(capacity == 0 || dungeonPlayerCount[_destinationDungeonId] < capacity);
_;
}
}
contract DungeonChallenge is DungeonTransportation {
/**
* @dev The DungeonChallenged event is fired when user finished a dungeon challenge.
*/
event DungeonChallenged(uint timestamp, address indexed playerAddress, uint indexed dungeonId, uint indexed heroId, uint heroGenes, uint floorNumber, uint floorGenes, bool success, uint newFloorGenes, uint successRewards, uint masterRewards);
/* ======== GAME SETTINGS ======== */
/**
* @notice The actual fee contribution required to call challenge() is calculated by this feeMultiplier,
* times the dungeon difficulty. The payment is accumulated to the dungeon rewards,
* and a large proportion will be claimed by whoever successfully challenged the floor.
* 1 finney = 0.001 ether
*/
uint public challengeFeeMultiplier = 1 finney;
/**
* @dev The percentage for which successful challenger be rewarded of the dungeons' accumulated rewards.
* The remaining rewards subtract dungeon master rewards will be used as the base rewards for new floor.
*/
uint public challengeRewardsPercent = 64;
/**
* @dev The developer fee for owner
* Note that when Ether Dungeon becomes truly decentralised, contract ownership will be ejected,
* and the master rewards will be rewarded to the dungeon owner (Dungeon Masters).
*/
uint public masterRewardsPercent = 8;
/**
* @dev The cooldown time period where a hero can engage in challenge again.
* This settings will likely be changed to 20 minutes when multiple heroes system is launched in Version 1.
*/
uint public challengeCooldownTime = 3 minutes;
/**
* @dev The preparation time period where a new dungeon is created, before it can be challenged.
* This settings will likely be changed to a smaller period (e.g. 20-30 minutes) .
*/
uint public dungeonPreparationTime = 60 minutes;
/**
* @dev The challenge rewards percentage used right after the preparation period.
*/
uint public rushTimeChallengeRewardsPercent = 30;
/**
* @dev The number of floor in which the rushTimeChallengeRewardsPercent be applied.
*/
uint public rushTimeFloorCount = 30;
/**
* @dev The main external function to call when a player challenge a dungeon,
* it determines whether if the player successfully challenged the current floor.
* Will generate a DungeonChallenged event.
*/
function challenge(uint _dungeonId, uint _heroId) whenNotPaused dungeonCanChallenge(_dungeonId) heroAllowedToChallenge(_heroId) external payable {
// Get the dungeon details from the token contract.
uint difficulty;
uint seedGenes;
(,, difficulty,,,,, seedGenes,) = dungeonTokenContract.dungeons(_dungeonId);
// Checks for payment, any exceeding funds will be transferred back to the player.
uint requiredFee = difficulty * challengeFeeMultiplier;
require(msg.value >= requiredFee);
// ** STORAGE UPDATE **
// Increment the accumulated rewards for the dungeon.
dungeonTokenContract.addDungeonRewards(_dungeonId, requiredFee);
// Calculate any excess funds and make it available to be withdrawed by the player.
asyncSend(msg.sender, msg.value - requiredFee);
// Split the challenge function into multiple parts because of stack too deep error.
_challengePart2(_dungeonId, _heroId);
}
/**
* Split the challenge function into multiple parts because of stack too deep error.
*/
function _challengePart2(uint _dungeonId, uint _heroId) private {
uint floorNumber;
uint rewards;
uint floorGenes;
(,,,, floorNumber,, rewards,, floorGenes) = dungeonTokenContract.dungeons(_dungeonId);
// Get the hero gene, or claim first hero.
uint heroGenes;
(_heroId, heroGenes) = _getHeroGenesOrClaimFirstHero(_heroId);
bool success = _getChallengeSuccess(heroGenes, _dungeonId, floorGenes);
uint newFloorGenes;
uint masterRewards;
uint successRewards;
uint newRewards;
// Whether a challenge is success or not is determined by a simple comparison between hero power and floor power.
if (success) {
newFloorGenes = _getNewFloorGene(_dungeonId);
masterRewards = rewards * masterRewardsPercent / 100;
if (floorNumber < rushTimeFloorCount) { // rush time right after prepration period
successRewards = rewards * rushTimeChallengeRewardsPercent / 100;
// The dungeon rewards for new floor as total rewards - challenge rewards - devleoper fee.
newRewards = rewards * (100 - rushTimeChallengeRewardsPercent - masterRewardsPercent) / 100;
} else {
successRewards = rewards * challengeRewardsPercent / 100;
newRewards = rewards * (100 - challengeRewardsPercent - masterRewardsPercent) / 100;
}
// TRIPLE CONFIRM sanity check.
require(successRewards + masterRewards + newRewards <= rewards);
// ** STORAGE UPDATE **
// Add new floor with the new floor genes and new rewards.
dungeonTokenContract.addDungeonNewFloor(_dungeonId, newRewards, newFloorGenes);
// Mark the challenge rewards available to be withdrawed by the player.
asyncSend(msg.sender, successRewards);
// Mark the master rewards available to be withdrawed by the dungeon master.
asyncSend(dungeonTokenContract.ownerOf(_dungeonId), masterRewards);
}
// ** STORAGE UPDATE **
// Trigger the cooldown for the hero.
heroTokenContract.triggerCooldown(_heroId);
// Emit the DungeonChallenged event.
DungeonChallenged(now, msg.sender, _dungeonId, _heroId, heroGenes, floorNumber, floorGenes, success, newFloorGenes, successRewards, masterRewards);
}
/**
* Split the challenge function into multiple parts because of stack too deep error.
*/
function _getChallengeSuccess(uint _heroGenes, uint _dungeonId, uint _floorGenes) private view returns (bool) {
// Determine if the player challenge successfuly the dungeon or not.
uint heroPower = _getHeroPower(_heroGenes, _dungeonId);
uint floorPower = _getDungeonPower(_floorGenes);
return heroPower > floorPower;
}
/**
* Split the challenge function into multiple parts because of stack too deep error.
*/
function _getNewFloorGene(uint _dungeonId) private returns (uint) {
uint seedGenes;
uint floorGenes;
(,,,,,, seedGenes, floorGenes) = dungeonTokenContract.dungeons(_dungeonId);
// Calculate the new floor gene.
uint floorPower = _getDungeonPower(floorGenes);
// Call the external closed source secret function that determines the resulting floor "genes".
uint newFloorGenes = challengeScienceContract.mixGenes(floorGenes, seedGenes);
uint newFloorPower = _getDungeonPower(newFloorGenes);
// If the power decreased, rollback to the current floor genes.
if (newFloorPower < floorPower) {
newFloorGenes = floorGenes;
}
return newFloorGenes;
}
/* ======== SETTER FUNCTIONS ======== */
/**
* @dev Updates the fee contribution multiplier required for calling challenge().
*/
function setChallengeFeeMultiplier(uint _newChallengeFeeMultiplier) onlyOwner external {
challengeFeeMultiplier = _newChallengeFeeMultiplier;
}
/**
* @dev Updates the challenge rewards pecentage.
*/
function setChallengeRewardsPercent(uint _newChallengeRewardsPercent) onlyOwner external {
challengeRewardsPercent = _newChallengeRewardsPercent;
}
/**
* @dev Updates the master rewards percentage.
*/
function setMasterRewardsPercent(uint _newMasterRewardsPercent) onlyOwner external {
masterRewardsPercent = _newMasterRewardsPercent;
}
/**
* @dev Updates the challenge cooldown time.
*/
function setChallengeCooldownTime(uint _newChallengeCooldownTime) onlyOwner external {
challengeCooldownTime = _newChallengeCooldownTime;
}
/**
* @dev Updates the challenge cooldown time.
*/
function setDungeonPreparationTime(uint _newDungeonPreparationTime) onlyOwner external {
dungeonPreparationTime = _newDungeonPreparationTime;
}
/**
* @dev Updates the rush time challenge rewards percentage.
*/
function setRushTimeChallengeRewardsPercent(uint _newRushTimeChallengeRewardsPercent) onlyOwner external {
rushTimeChallengeRewardsPercent = _newRushTimeChallengeRewardsPercent;
}
/**
* @dev Updates the rush time floor count.
*/
function setRushTimeFloorCount(uint _newRushTimeFloorCount) onlyOwner external {
rushTimeFloorCount = _newRushTimeFloorCount;
}
/* ======== MODIFIERS ======== */
/**
* @dev Throws if dungeon status do not allow challenge, also check for dungeon existence.
* Also check if the user is in the dungeon.
* Also check if the dungeon is not in preparation period.
*/
modifier dungeonCanChallenge(uint _dungeonId) {
require(_dungeonId < dungeonTokenContract.totalSupply());
uint creationTime;
uint status;
(creationTime, status,,,,,,,) = dungeonTokenContract.dungeons(_dungeonId);
require(status == 0 || status == 2);
// Check if the user is in the dungeon.
require(playerToDungeonID[msg.sender] == _dungeonId);
// Check if the dungeon is not in preparation period.
require(creationTime + dungeonPreparationTime <= now);
_;
}
/**
* @dev Throws if player does not own the hero, or it is still in cooldown.
* Unless the player does not have any hero yet, which will auto claim one during first challenge / train.
*/
modifier heroAllowedToChallenge(uint _heroId) {
if (heroTokenContract.balanceOf(msg.sender) > 0) {
// You can only challenge with your own hero.
require(heroTokenContract.ownerOf(_heroId) == msg.sender);
uint cooldownStartTime;
(, cooldownStartTime,,) = heroTokenContract.heroes(_heroId);
require(cooldownStartTime + challengeCooldownTime <= now);
}
_;
}
}
contract DungeonTraining is DungeonChallenge {
/**
* @dev The HeroTrained event is fired when user finished a training.
*/
event HeroTrained(uint timestamp, address indexed playerAddress, uint indexed dungeonId, uint indexed heroId, uint heroGenes, uint floorNumber, uint floorGenes, bool success, uint newHeroGenes);
/* ======== GAME SETTINGS ======== */
/**
* @dev The actual fee contribution required to call trainX() is calculated by this feeMultiplier,
* times the dungeon difficulty, times X. The payment is accumulated to the dungeon rewards,
* and a large proportion will be claimed by whoever successfully challenged the floor.
* 1 finney = 0.001 ether
*/
uint public trainingFeeMultiplier = 2 finney;
/**
* @dev The discounted training fee multiplier to be used in the preparation period.
* 1000 szabo = 0.001 ether
*/
uint public preparationPeriodTrainingFeeMultiplier = 1800 szabo;
/**
* @dev The actual fee contribution required to call trainEquipment() is calculated by this feeMultiplier,
* times the dungeon difficulty, times X. The payment is accumulated to the dungeon rewards,
* and a large proportion will be claimed by whoever successfully challenged the floor.
* (No preparation period discount on equipment training.)
* 1000 szabo = 0.001 ether
*/
uint public equipmentTrainingFeeMultiplier = 500 szabo;
/**
* @dev The external function to call when a hero train with a dungeon,
* it determines whether whether a training is successfully, and the resulting genes.
* Will generate a DungeonChallenged event.
*/
function train1(uint _dungeonId, uint _heroId) whenNotPaused dungeonCanTrain(_dungeonId) heroAllowedToTrain(_heroId) external payable {
_train(_dungeonId, _heroId, 0, 1);
}
function train2(uint _dungeonId, uint _heroId) whenNotPaused dungeonCanTrain(_dungeonId) heroAllowedToTrain(_heroId) external payable {
_train(_dungeonId, _heroId, 0, 2);
}
function train3(uint _dungeonId, uint _heroId) whenNotPaused dungeonCanTrain(_dungeonId) heroAllowedToTrain(_heroId) external payable {
_train(_dungeonId, _heroId, 0, 3);
}
/**
* @dev The external function to call when a hero train a particular equipment with a dungeon,
* it determines whether whether a training is successfully, and the resulting genes.
* Will generate a DungeonChallenged event.
* _equipmentIndex is the index of equipment: 0 is train all attributes, including equipments and stats.
* 1: weapon | 2: shield | 3: armor | 4: shoe | 5: helmet | 6: gloves | 7: belt | 8: shawl
*/
function trainEquipment(uint _dungeonId, uint _heroId, uint _equipmentIndex) whenNotPaused dungeonCanTrain(_dungeonId) heroAllowedToTrain(_heroId) external payable {
require(_equipmentIndex <= 8);
_train(_dungeonId, _heroId, _equipmentIndex, 1);
}
/**
* @dev An internal function of a hero train with dungeon,
* it determines whether whether a training is successfully, and the resulting genes.
* Will generate a DungeonChallenged event.
*/
function _train(uint _dungeonId, uint _heroId, uint _equipmentIndex, uint _trainingTimes) private {
// Get the dungeon details from the token contract.
uint creationTime;
uint difficulty;
uint floorNumber;
uint rewards;
uint seedGenes;
uint floorGenes;
(creationTime,,difficulty,,floorNumber,,rewards,seedGenes,floorGenes) = dungeonTokenContract.dungeons(_dungeonId);
// Check for _trainingTimes abnormality, we probably won't have any feature that train a hero 10 times with a single call.
require(_trainingTimes < 10);
// Checks for payment, any exceeding funds will be transferred back to the player.
uint requiredFee;
if (_equipmentIndex > 0) { // train specific equipments
requiredFee = difficulty * equipmentTrainingFeeMultiplier * _trainingTimes;
} else if (now < creationTime + dungeonPreparationTime) { // train all attributes, preparation period
requiredFee = difficulty * preparationPeriodTrainingFeeMultiplier * _trainingTimes;
} else { // train all attributes, normal period
requiredFee = difficulty * trainingFeeMultiplier * _trainingTimes;
}
require(msg.value >= requiredFee);
// Get the hero gene, or claim first hero.
uint heroGenes;
(_heroId, heroGenes) = _getHeroGenesOrClaimFirstHero(_heroId);
// ** STORAGE UPDATE **
// Increment the accumulated rewards for the dungeon.
dungeonTokenContract.addDungeonRewards(_dungeonId, requiredFee);
// Calculate any excess funds and make it available to be withdrawed by the player.
asyncSend(msg.sender, msg.value - requiredFee);
// Split the _train function into multiple parts because of stack too deep error.
_trainPart2(_dungeonId, _heroId, heroGenes, _equipmentIndex, _trainingTimes);
}
/**
* Split the _train function into multiple parts because of Stack Too Deep error.
*/
function _trainPart2(uint _dungeonId, uint _heroId, uint _heroGenes, uint _equipmentIndex, uint _trainingTimes) private {
// Get the dungeon details from the token contract.
uint floorNumber;
uint floorGenes;
(,,,, floorNumber,,,, floorGenes) = dungeonTokenContract.dungeons(_dungeonId);
// Determine if the hero training is successful or not, and the resulting genes.
uint heroPower = _getHeroPower(_heroGenes, _dungeonId);
uint newHeroGenes = _heroGenes;
uint newHeroPower = heroPower;
// Train the hero multiple times according to _trainingTimes,
// each time if the resulting power is larger, update new hero power.
for (uint i = 0; i < _trainingTimes; i++) {
// Call the external closed source secret function that determines the resulting hero "genes".
uint tmpHeroGenes = trainingScienceContract.mixGenes(newHeroGenes, floorGenes, _equipmentIndex);
uint tmpHeroPower = _getHeroPower(tmpHeroGenes, _dungeonId);
if (tmpHeroPower > newHeroPower) {
newHeroGenes = tmpHeroGenes;
newHeroPower = tmpHeroPower;
}
}
// Prevent reduced power.
if (newHeroPower > heroPower) {
// ** STORAGE UPDATE **
// Set the upgraded hero genes.
heroTokenContract.setHeroGenes(_heroId, newHeroGenes);
}
// Emit the HeroTrained event.
HeroTrained(now, msg.sender, _dungeonId, _heroId, _heroGenes, floorNumber, floorGenes, newHeroPower > heroPower, newHeroGenes);
}
/* ======== SETTER FUNCTIONS ======== */
/// @dev Updates the fee contribution multiplier required for calling trainX().
function setTrainingFeeMultiplier(uint _newTrainingFeeMultiplier) onlyOwner external {
trainingFeeMultiplier = _newTrainingFeeMultiplier;
}
/// @dev Updates the fee contribution multiplier for preparation period required for calling trainX().
function setPreparationPeriodTrainingFeeMultiplier(uint _newPreparationPeriodTrainingFeeMultiplier) onlyOwner external {
preparationPeriodTrainingFeeMultiplier = _newPreparationPeriodTrainingFeeMultiplier;
}
/// @dev Updates the fee contribution multiplier required for calling trainEquipment().
function setEquipmentTrainingFeeMultiplier(uint _newEquipmentTrainingFeeMultiplier) onlyOwner external {
equipmentTrainingFeeMultiplier = _newEquipmentTrainingFeeMultiplier;
}
/* ======== MODIFIERS ======== */
/**
* @dev Throws if dungeon status do not allow training, also check for dungeon existence.
* Also check if the user is in the dungeon.
*/
modifier dungeonCanTrain(uint _dungeonId) {
require(_dungeonId < dungeonTokenContract.totalSupply());
uint status;
(,status,,,,,,,) = dungeonTokenContract.dungeons(_dungeonId);
require(status == 0 || status == 3);
// Also check if the user is in the dungeon.
require(playerToDungeonID[msg.sender] == _dungeonId);
_;
}
/**
* @dev Throws if player does not own the hero.
* Unless the player does not have any hero yet, which will auto claim one during first challenge / train.
*/
modifier heroAllowedToTrain(uint _heroId) {
if (heroTokenContract.balanceOf(msg.sender) > 0) {
// You can only train with your own hero.
require(heroTokenContract.ownerOf(_heroId) == msg.sender);
}
_;
}
}
/**
* @title DungeonCoreBeta
* @dev Core Contract of Ether Dungeon.
* When Version 1 launches, DungeonCoreVersion1 contract will be deployed and DungeonCoreBeta will be destroyed.
* Since all dungeons and heroes are stored as tokens in external contracts, they remains immutable.
*/
contract DungeonCoreBeta is Destructible, DungeonTraining {
/**
* Initialize the DungeonCore contract with all the required contract addresses.
*/
function DungeonCoreBeta(
address _dungeonTokenAddress,
address _heroTokenAddress,
address _challengeScienceAddress,
address _trainingScienceAddress
) public {
dungeonTokenContract = DungeonToken(_dungeonTokenAddress);
heroTokenContract = HeroToken(_heroTokenAddress);
challengeScienceContract = ChallengeScienceInterface(_challengeScienceAddress);
trainingScienceContract = TrainingScienceInterface(_trainingScienceAddress);
}
/**
* @dev The external function to get all the relevant information about a specific dungeon by its ID.
* @param _id The ID of the dungeon.
*/
function getDungeonDetails(uint _id) external view returns (uint creationTime, uint status, uint difficulty, uint capacity, bool isReady, uint playerCount) {
require(_id < dungeonTokenContract.totalSupply());
// Didn't get the "floorCreationTime" because of Stack Too Deep error.
(creationTime, status, difficulty, capacity,,,,,) = dungeonTokenContract.dungeons(_id);
// Dungeon is ready to be challenged (not in preparation mode).
isReady = creationTime + dungeonPreparationTime <= now;
playerCount = dungeonPlayerCount[_id];
}
/**
* @dev Split floor related details out of getDungeonDetails, just to avoid Stack Too Deep error.
* @param _id The ID of the dungeon.
*/
function getDungeonFloorDetails(uint _id) external view returns (uint floorNumber, uint floorCreationTime, uint rewards, uint seedGenes, uint floorGenes) {
require(_id < dungeonTokenContract.totalSupply());
// Didn't get the "floorCreationTime" because of Stack Too Deep error.
(,,,, floorNumber, floorCreationTime, rewards, seedGenes, floorGenes) = dungeonTokenContract.dungeons(_id);
}
/**
* @dev The external function to get all the relevant information about a specific hero by its ID.
* @param _id The ID of the hero.
*/
function getHeroDetails(uint _id) external view returns (uint creationTime, uint cooldownStartTime, uint cooldownIndex, uint genes, bool isReady) {
require(_id < heroTokenContract.totalSupply());
(creationTime, cooldownStartTime, cooldownIndex, genes) = heroTokenContract.heroes(_id);
// Hero is ready to challenge (not in cooldown mode).
isReady = cooldownStartTime + challengeCooldownTime <= now;
}
/**
* @dev The external function to get all the relevant information about a specific player by its address.
* @param _address The address of the player.
*/
function getPlayerDetails(address _address) external view returns (uint dungeonId, uint payment) {
dungeonId = playerToDungeonID[_address];
payment = payments[_address];
}
}
|
Updates the challenge cooldown time./
|
function setChallengeCooldownTime(uint _newChallengeCooldownTime) onlyOwner external {
challengeCooldownTime = _newChallengeCooldownTime;
}
| 12,714,673
|
./full_match/1/0x4D91AaD0Deb494C71d538039c8C5d689fAFfa5Fc/sources/src/Registry.sol
|
Sets the enable/disable state of an Entity. _entity The entity whose active state is to be updated. _isActive True if the entity should be active, false otherwise./
|
function setEntityStatus(Entity _entity, bool _isActive) external requiresAuth {
isActiveEntity[_entity] = _isActive;
emit EntityStatusSet(address(_entity), _isActive);
}
| 17,094,362
|
./full_match/100/0x0675f76b8342e311108170fC97db70e27F53a85c/sources/contracts/official/SB06/SB06Token.sol
|
Gets current percent based in period Retorna a porcentagem de interesse gerada até a data especificada/ loop all dates if after the payment date, all interest is already generated calculate the day difference
|
function getPercentByTime(uint256 _nPaymentDate)
public
view
returns (uint256)
{
if (_nPaymentDate < DATE_INTEREST_START) {
return 0;
}
uint256 nInterest = 0;
for (uint8 i = 0; i < PERIOD_DATES.length; i++) {
uint256 nPeriodInterest = arrInterests[i];
uint256 nPeriodDate = PERIOD_DATES[i];
if (_nPaymentDate >= nPeriodDate) {
nInterest += nPeriodInterest;
uint256 nTotalDays = nPeriodDate.sub(DATE_INTEREST_START);
uint256 nCurrentDays = nTotalDays.sub(nPeriodDate.sub(_nPaymentDate));
uint256 nDifInterest = LiqiMathLib.mulDiv(
nCurrentDays.mul(1 ether),
nPeriodInterest.mul(1 ether),
nTotalDays.mul(1 ether)
);
nInterest += nDifInterest.div(1 ether);
}
}
return nInterest;
}
| 14,269,674
|
// SPDX-License-Identifier: AGPL-3.0-only
/*
Bounty.sol - SKALE Manager
Copyright (C) 2020-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "./delegation/DelegationController.sol";
import "./delegation/PartialDifferences.sol";
import "./delegation/TimeHelpers.sol";
import "./delegation/ValidatorService.sol";
import "./ConstantsHolder.sol";
import "./Nodes.sol";
import "./Permissions.sol";
contract BountyV2 is Permissions {
using PartialDifferences for PartialDifferences.Value;
using PartialDifferences for PartialDifferences.Sequence;
struct BountyHistory {
uint month;
uint bountyPaid;
}
uint public constant YEAR1_BOUNTY = 3850e5 * 1e18;
uint public constant YEAR2_BOUNTY = 3465e5 * 1e18;
uint public constant YEAR3_BOUNTY = 3080e5 * 1e18;
uint public constant YEAR4_BOUNTY = 2695e5 * 1e18;
uint public constant YEAR5_BOUNTY = 2310e5 * 1e18;
uint public constant YEAR6_BOUNTY = 1925e5 * 1e18;
uint public constant EPOCHS_PER_YEAR = 12;
uint public constant SECONDS_PER_DAY = 24 * 60 * 60;
uint public constant BOUNTY_WINDOW_SECONDS = 3 * SECONDS_PER_DAY;
uint private _nextEpoch;
uint private _epochPool;
uint private _bountyWasPaidInCurrentEpoch;
bool public bountyReduction;
uint public nodeCreationWindowSeconds;
PartialDifferences.Value private _effectiveDelegatedSum;
// validatorId amount of nodes
mapping (uint => uint) public nodesByValidator; // deprecated
// validatorId => BountyHistory
mapping (uint => BountyHistory) private _bountyHistory;
function calculateBounty(uint nodeIndex)
external
allow("SkaleManager")
returns (uint)
{
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
require(
_getNextRewardTimestamp(nodeIndex, nodes, timeHelpers) <= now,
"Transaction is sent too early"
);
uint validatorId = nodes.getValidatorId(nodeIndex);
if (nodesByValidator[validatorId] > 0) {
delete nodesByValidator[validatorId];
}
uint currentMonth = timeHelpers.getCurrentMonth();
_refillEpochPool(currentMonth, timeHelpers, constantsHolder);
_prepareBountyHistory(validatorId, currentMonth);
uint bounty = _calculateMaximumBountyAmount(
_epochPool,
_effectiveDelegatedSum.getAndUpdateValue(currentMonth),
_bountyWasPaidInCurrentEpoch,
nodeIndex,
_bountyHistory[validatorId].bountyPaid,
delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, currentMonth),
delegationController.getAndUpdateDelegatedToValidatorNow(validatorId),
constantsHolder,
nodes
);
_bountyHistory[validatorId].bountyPaid = _bountyHistory[validatorId].bountyPaid.add(bounty);
bounty = _reduceBounty(
bounty,
nodeIndex,
nodes,
constantsHolder
);
_epochPool = _epochPool.sub(bounty);
_bountyWasPaidInCurrentEpoch = _bountyWasPaidInCurrentEpoch.add(bounty);
return bounty;
}
function enableBountyReduction() external onlyOwner {
bountyReduction = true;
}
function disableBountyReduction() external onlyOwner {
bountyReduction = false;
}
function setNodeCreationWindowSeconds(uint window) external allow("Nodes") {
nodeCreationWindowSeconds = window;
}
function handleDelegationAdd(
uint amount,
uint month
)
external
allow("DelegationController")
{
_effectiveDelegatedSum.addToValue(amount, month);
}
function handleDelegationRemoving(
uint amount,
uint month
)
external
allow("DelegationController")
{
_effectiveDelegatedSum.subtractFromValue(amount, month);
}
function populate() external onlyOwner {
ValidatorService validatorService = ValidatorService(contractManager.getValidatorService());
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
TimeHelpers timeHelpers = TimeHelpers(contractManager.getTimeHelpers());
uint currentMonth = timeHelpers.getCurrentMonth();
// clean existing data
for (
uint i = _effectiveDelegatedSum.firstUnprocessedMonth;
i < _effectiveDelegatedSum.lastChangedMonth.add(1);
++i
)
{
delete _effectiveDelegatedSum.addDiff[i];
delete _effectiveDelegatedSum.subtractDiff[i];
}
delete _effectiveDelegatedSum.value;
delete _effectiveDelegatedSum.lastChangedMonth;
_effectiveDelegatedSum.firstUnprocessedMonth = currentMonth;
uint[] memory validators = validatorService.getTrustedValidators();
for (uint i = 0; i < validators.length; ++i) {
uint validatorId = validators[i];
uint currentEffectiveDelegated =
delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, currentMonth);
uint[] memory effectiveDelegated = delegationController.getEffectiveDelegatedValuesByValidator(validatorId);
if (effectiveDelegated.length > 0) {
assert(currentEffectiveDelegated == effectiveDelegated[0]);
}
uint added = 0;
for (uint j = 0; j < effectiveDelegated.length; ++j) {
if (effectiveDelegated[j] != added) {
if (effectiveDelegated[j] > added) {
_effectiveDelegatedSum.addToValue(effectiveDelegated[j].sub(added), currentMonth + j);
} else {
_effectiveDelegatedSum.subtractFromValue(added.sub(effectiveDelegated[j]), currentMonth + j);
}
added = effectiveDelegated[j];
}
}
delete effectiveDelegated;
}
}
function estimateBounty(uint nodeIndex) external view returns (uint) {
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
uint currentMonth = timeHelpers.getCurrentMonth();
uint validatorId = nodes.getValidatorId(nodeIndex);
uint stagePoolSize;
(stagePoolSize, ) = _getEpochPool(currentMonth, timeHelpers, constantsHolder);
return _calculateMaximumBountyAmount(
stagePoolSize,
_effectiveDelegatedSum.getValue(currentMonth),
_nextEpoch == currentMonth.add(1) ? _bountyWasPaidInCurrentEpoch : 0,
nodeIndex,
_getBountyPaid(validatorId, currentMonth),
delegationController.getEffectiveDelegatedToValidator(validatorId, currentMonth),
delegationController.getDelegatedToValidator(validatorId, currentMonth),
constantsHolder,
nodes
);
}
function getNextRewardTimestamp(uint nodeIndex) external view returns (uint) {
return _getNextRewardTimestamp(
nodeIndex,
Nodes(contractManager.getContract("Nodes")),
TimeHelpers(contractManager.getContract("TimeHelpers"))
);
}
function getEffectiveDelegatedSum() external view returns (uint[] memory) {
return _effectiveDelegatedSum.getValues();
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
_nextEpoch = 0;
_epochPool = 0;
_bountyWasPaidInCurrentEpoch = 0;
bountyReduction = false;
nodeCreationWindowSeconds = 3 * SECONDS_PER_DAY;
}
// private
function _calculateMaximumBountyAmount(
uint epochPoolSize,
uint effectiveDelegatedSum,
uint bountyWasPaidInCurrentEpoch,
uint nodeIndex,
uint bountyPaidToTheValidator,
uint effectiveDelegated,
uint delegated,
ConstantsHolder constantsHolder,
Nodes nodes
)
private
view
returns (uint)
{
if (nodes.isNodeLeft(nodeIndex)) {
return 0;
}
if (now < constantsHolder.launchTimestamp()) {
// network is not launched
// bounty is turned off
return 0;
}
if (effectiveDelegatedSum == 0) {
// no delegations in the system
return 0;
}
if (constantsHolder.msr() == 0) {
return 0;
}
uint bounty = _calculateBountyShare(
epochPoolSize.add(bountyWasPaidInCurrentEpoch),
effectiveDelegated,
effectiveDelegatedSum,
delegated.div(constantsHolder.msr()),
bountyPaidToTheValidator
);
return bounty;
}
function _calculateBountyShare(
uint monthBounty,
uint effectiveDelegated,
uint effectiveDelegatedSum,
uint maxNodesAmount,
uint paidToValidator
)
private
pure
returns (uint)
{
if (maxNodesAmount > 0) {
uint totalBountyShare = monthBounty
.mul(effectiveDelegated)
.div(effectiveDelegatedSum);
return _min(
totalBountyShare.div(maxNodesAmount),
totalBountyShare.sub(paidToValidator)
);
} else {
return 0;
}
}
function _getFirstEpoch(TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private view returns (uint) {
return timeHelpers.timestampToMonth(constantsHolder.launchTimestamp());
}
function _getEpochPool(
uint currentMonth,
TimeHelpers timeHelpers,
ConstantsHolder constantsHolder
)
private
view
returns (uint epochPool, uint nextEpoch)
{
epochPool = _epochPool;
for (nextEpoch = _nextEpoch; nextEpoch <= currentMonth; ++nextEpoch) {
epochPool = epochPool.add(_getEpochReward(nextEpoch, timeHelpers, constantsHolder));
}
}
function _refillEpochPool(uint currentMonth, TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private {
uint epochPool;
uint nextEpoch;
(epochPool, nextEpoch) = _getEpochPool(currentMonth, timeHelpers, constantsHolder);
if (_nextEpoch < nextEpoch) {
(_epochPool, _nextEpoch) = (epochPool, nextEpoch);
_bountyWasPaidInCurrentEpoch = 0;
}
}
function _getEpochReward(
uint epoch,
TimeHelpers timeHelpers,
ConstantsHolder constantsHolder
)
private
view
returns (uint)
{
uint firstEpoch = _getFirstEpoch(timeHelpers, constantsHolder);
if (epoch < firstEpoch) {
return 0;
}
uint epochIndex = epoch.sub(firstEpoch);
uint year = epochIndex.div(EPOCHS_PER_YEAR);
if (year >= 6) {
uint power = year.sub(6).div(3).add(1);
if (power < 256) {
return YEAR6_BOUNTY.div(2 ** power).div(EPOCHS_PER_YEAR);
} else {
return 0;
}
} else {
uint[6] memory customBounties = [
YEAR1_BOUNTY,
YEAR2_BOUNTY,
YEAR3_BOUNTY,
YEAR4_BOUNTY,
YEAR5_BOUNTY,
YEAR6_BOUNTY
];
return customBounties[year].div(EPOCHS_PER_YEAR);
}
}
function _reduceBounty(
uint bounty,
uint nodeIndex,
Nodes nodes,
ConstantsHolder constants
)
private
returns (uint reducedBounty)
{
if (!bountyReduction) {
return bounty;
}
reducedBounty = bounty;
if (!nodes.checkPossibilityToMaintainNode(nodes.getValidatorId(nodeIndex), nodeIndex)) {
reducedBounty = reducedBounty.div(constants.MSR_REDUCING_COEFFICIENT());
}
}
function _prepareBountyHistory(uint validatorId, uint currentMonth) private {
if (_bountyHistory[validatorId].month < currentMonth) {
_bountyHistory[validatorId].month = currentMonth;
delete _bountyHistory[validatorId].bountyPaid;
}
}
function _getBountyPaid(uint validatorId, uint month) private view returns (uint) {
require(_bountyHistory[validatorId].month <= month, "Can't get bounty paid");
if (_bountyHistory[validatorId].month == month) {
return _bountyHistory[validatorId].bountyPaid;
} else {
return 0;
}
}
function _getNextRewardTimestamp(uint nodeIndex, Nodes nodes, TimeHelpers timeHelpers) private view returns (uint) {
uint lastRewardTimestamp = nodes.getNodeLastRewardDate(nodeIndex);
uint lastRewardMonth = timeHelpers.timestampToMonth(lastRewardTimestamp);
uint lastRewardMonthStart = timeHelpers.monthToTimestamp(lastRewardMonth);
uint timePassedAfterMonthStart = lastRewardTimestamp.sub(lastRewardMonthStart);
uint currentMonth = timeHelpers.getCurrentMonth();
assert(lastRewardMonth <= currentMonth);
if (lastRewardMonth == currentMonth) {
uint nextMonthStart = timeHelpers.monthToTimestamp(currentMonth.add(1));
uint nextMonthFinish = timeHelpers.monthToTimestamp(lastRewardMonth.add(2));
if (lastRewardTimestamp < lastRewardMonthStart.add(nodeCreationWindowSeconds)) {
return nextMonthStart.sub(BOUNTY_WINDOW_SECONDS);
} else {
return _min(nextMonthStart.add(timePassedAfterMonthStart), nextMonthFinish.sub(BOUNTY_WINDOW_SECONDS));
}
} else if (lastRewardMonth.add(1) == currentMonth) {
uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth);
uint currentMonthFinish = timeHelpers.monthToTimestamp(currentMonth.add(1));
return _min(
currentMonthStart.add(_max(timePassedAfterMonthStart, nodeCreationWindowSeconds)),
currentMonthFinish.sub(BOUNTY_WINDOW_SECONDS)
);
} else {
uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth);
return currentMonthStart.add(nodeCreationWindowSeconds);
}
}
function _min(uint a, uint b) private pure returns (uint) {
if (a < b) {
return a;
} else {
return b;
}
}
function _max(uint a, uint b) private pure returns (uint) {
if (a < b) {
return b;
} else {
return a;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ConstantsHolder.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "./Permissions.sol";
/**
* @title ConstantsHolder
* @dev Contract contains constants and common variables for the SKALE Network.
*/
contract ConstantsHolder is Permissions {
// initial price for creating Node (100 SKL)
uint public constant NODE_DEPOSIT = 100 * 1e18;
uint8 public constant TOTAL_SPACE_ON_NODE = 128;
// part of Node for Small Skale-chain (1/128 of Node)
uint8 public constant SMALL_DIVISOR = 128;
// part of Node for Medium Skale-chain (1/32 of Node)
uint8 public constant MEDIUM_DIVISOR = 32;
// part of Node for Large Skale-chain (full Node)
uint8 public constant LARGE_DIVISOR = 1;
// part of Node for Medium Test Skale-chain (1/4 of Node)
uint8 public constant MEDIUM_TEST_DIVISOR = 4;
// typically number of Nodes for Skale-chain (16 Nodes)
uint public constant NUMBER_OF_NODES_FOR_SCHAIN = 16;
// number of Nodes for Test Skale-chain (2 Nodes)
uint public constant NUMBER_OF_NODES_FOR_TEST_SCHAIN = 2;
// number of Nodes for Test Skale-chain (4 Nodes)
uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4;
// number of seconds in one year
uint32 public constant SECONDS_TO_YEAR = 31622400;
// initial number of monitors
uint public constant NUMBER_OF_MONITORS = 24;
uint public constant OPTIMAL_LOAD_PERCENTAGE = 80;
uint public constant ADJUSTMENT_SPEED = 1000;
uint public constant COOLDOWN_TIME = 60;
uint public constant MIN_PRICE = 10**6;
uint public constant MSR_REDUCING_COEFFICIENT = 2;
uint public constant DOWNTIME_THRESHOLD_PART = 30;
uint public constant BOUNTY_LOCKUP_MONTHS = 2;
// MSR - Minimum staking requirement
uint public msr;
// Reward period - 30 days (each 30 days Node would be granted for bounty)
uint32 public rewardPeriod;
// Allowable latency - 150000 ms by default
uint32 public allowableLatency;
/**
* Delta period - 1 hour (1 hour before Reward period became Monitors need
* to send Verdicts and 1 hour after Reward period became Node need to come
* and get Bounty)
*/
uint32 public deltaPeriod;
/**
* Check time - 2 minutes (every 2 minutes monitors should check metrics
* from checked nodes)
*/
uint public checkTime;
//Need to add minimal allowed parameters for verdicts
uint public launchTimestamp;
uint public rotationDelay;
uint public proofOfUseLockUpPeriodDays;
uint public proofOfUseDelegationPercentage;
uint public limitValidatorsPerDelegator;
uint256 public firstDelegationsMonth; // deprecated
// date when schains will be allowed for creation
uint public schainCreationTimeStamp;
uint public minimalSchainLifetime;
uint public complaintTimelimit;
/**
* @dev Allows the Owner to set new reward and delta periods
* This function is only for tests.
*/
function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external onlyOwner {
require(
newRewardPeriod >= newDeltaPeriod && newRewardPeriod - newDeltaPeriod >= checkTime,
"Incorrect Periods"
);
rewardPeriod = newRewardPeriod;
deltaPeriod = newDeltaPeriod;
}
/**
* @dev Allows the Owner to set the new check time.
* This function is only for tests.
*/
function setCheckTime(uint newCheckTime) external onlyOwner {
require(rewardPeriod - deltaPeriod >= checkTime, "Incorrect check time");
checkTime = newCheckTime;
}
/**
* @dev Allows the Owner to set the allowable latency in milliseconds.
* This function is only for testing purposes.
*/
function setLatency(uint32 newAllowableLatency) external onlyOwner {
allowableLatency = newAllowableLatency;
}
/**
* @dev Allows the Owner to set the minimum stake requirement.
*/
function setMSR(uint newMSR) external onlyOwner {
msr = newMSR;
}
/**
* @dev Allows the Owner to set the launch timestamp.
*/
function setLaunchTimestamp(uint timestamp) external onlyOwner {
require(now < launchTimestamp, "Cannot set network launch timestamp because network is already launched");
launchTimestamp = timestamp;
}
/**
* @dev Allows the Owner to set the node rotation delay.
*/
function setRotationDelay(uint newDelay) external onlyOwner {
rotationDelay = newDelay;
}
/**
* @dev Allows the Owner to set the proof-of-use lockup period.
*/
function setProofOfUseLockUpPeriod(uint periodDays) external onlyOwner {
proofOfUseLockUpPeriodDays = periodDays;
}
/**
* @dev Allows the Owner to set the proof-of-use delegation percentage
* requirement.
*/
function setProofOfUseDelegationPercentage(uint percentage) external onlyOwner {
require(percentage <= 100, "Percentage value is incorrect");
proofOfUseDelegationPercentage = percentage;
}
/**
* @dev Allows the Owner to set the maximum number of validators that a
* single delegator can delegate to.
*/
function setLimitValidatorsPerDelegator(uint newLimit) external onlyOwner {
limitValidatorsPerDelegator = newLimit;
}
function setSchainCreationTimeStamp(uint timestamp) external onlyOwner {
schainCreationTimeStamp = timestamp;
}
function setMinimalSchainLifetime(uint lifetime) external onlyOwner {
minimalSchainLifetime = lifetime;
}
function setComplaintTimelimit(uint timelimit) external onlyOwner {
complaintTimelimit = timelimit;
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
msr = 0;
rewardPeriod = 2592000;
allowableLatency = 150000;
deltaPeriod = 3600;
checkTime = 300;
launchTimestamp = uint(-1);
rotationDelay = 12 hours;
proofOfUseLockUpPeriodDays = 90;
proofOfUseDelegationPercentage = 50;
limitValidatorsPerDelegator = 20;
firstDelegationsMonth = 0;
complaintTimelimit = 1800;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ContractManager.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol";
import "./utils/StringUtils.sol";
/**
* @title ContractManager
* @dev Contract contains the actual current mapping from contract IDs
* (in the form of human-readable strings) to addresses.
*/
contract ContractManager is OwnableUpgradeSafe {
using StringUtils for string;
using Address for address;
string public constant BOUNTY = "Bounty";
string public constant CONSTANTS_HOLDER = "ConstantsHolder";
string public constant DELEGATION_PERIOD_MANAGER = "DelegationPeriodManager";
string public constant PUNISHER = "Punisher";
string public constant SKALE_TOKEN = "SkaleToken";
string public constant TIME_HELPERS = "TimeHelpers";
string public constant TOKEN_LAUNCH_LOCKER = "TokenLaunchLocker";
string public constant TOKEN_STATE = "TokenState";
string public constant VALIDATOR_SERVICE = "ValidatorService";
// mapping of actual smart contracts addresses
mapping (bytes32 => address) public contracts;
/**
* @dev Emitted when contract is upgraded.
*/
event ContractUpgraded(string contractsName, address contractsAddress);
function initialize() external initializer {
OwnableUpgradeSafe.__Ownable_init();
}
/**
* @dev Allows the Owner to add contract to mapping of contract addresses.
*
* Emits a {ContractUpgraded} event.
*
* Requirements:
*
* - New address is non-zero.
* - Contract is not already added.
* - Contract address contains code.
*/
function setContractsAddress(string calldata contractsName, address newContractsAddress) external onlyOwner {
// check newContractsAddress is not equal to zero
require(newContractsAddress != address(0), "New address is equal zero");
// create hash of contractsName
bytes32 contractId = keccak256(abi.encodePacked(contractsName));
// check newContractsAddress is not equal the previous contract's address
require(contracts[contractId] != newContractsAddress, "Contract is already added");
require(newContractsAddress.isContract(), "Given contract address does not contain code");
// add newContractsAddress to mapping of actual contract addresses
contracts[contractId] = newContractsAddress;
emit ContractUpgraded(contractsName, newContractsAddress);
}
/**
* @dev Returns contract address.
*
* Requirements:
*
* - Contract must exist.
*/
function getDelegationPeriodManager() external view returns (address) {
return getContract(DELEGATION_PERIOD_MANAGER);
}
function getBounty() external view returns (address) {
return getContract(BOUNTY);
}
function getValidatorService() external view returns (address) {
return getContract(VALIDATOR_SERVICE);
}
function getTimeHelpers() external view returns (address) {
return getContract(TIME_HELPERS);
}
function getTokenLaunchLocker() external view returns (address) {
return getContract(TOKEN_LAUNCH_LOCKER);
}
function getConstantsHolder() external view returns (address) {
return getContract(CONSTANTS_HOLDER);
}
function getSkaleToken() external view returns (address) {
return getContract(SKALE_TOKEN);
}
function getTokenState() external view returns (address) {
return getContract(TOKEN_STATE);
}
function getPunisher() external view returns (address) {
return getContract(PUNISHER);
}
function getContract(string memory name) public view returns (address contractAddress) {
contractAddress = contracts[keccak256(abi.encodePacked(name))];
if (contractAddress == address(0)) {
revert(name.strConcat(" contract has not been found"));
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Decryption.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
/**
* @title Decryption
* @dev This contract performs encryption and decryption functions.
* Decrypt is used by SkaleDKG contract to decrypt secret key contribution to
* validate complaints during the DKG procedure.
*/
contract Decryption {
/**
* @dev Returns an encrypted text given a secret and a key.
*/
function encrypt(uint256 secretNumber, bytes32 key) external pure returns (bytes32 ciphertext) {
return bytes32(secretNumber) ^ key;
}
/**
* @dev Returns a secret given an encrypted text and a key.
*/
function decrypt(bytes32 ciphertext, bytes32 key) external pure returns (uint256 secretNumber) {
return uint256(ciphertext ^ key);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
KeyStorage.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "./Decryption.sol";
import "./Permissions.sol";
import "./SchainsInternal.sol";
import "./thirdparty/ECDH.sol";
import "./utils/Precompiled.sol";
import "./utils/FieldOperations.sol";
contract KeyStorage is Permissions {
using Fp2Operations for Fp2Operations.Fp2Point;
using G2Operations for G2Operations.G2Point;
struct BroadcastedData {
KeyShare[] secretKeyContribution;
G2Operations.G2Point[] verificationVector;
}
struct KeyShare {
bytes32[2] publicKey;
bytes32 share;
}
// Unused variable!!
mapping(bytes32 => mapping(uint => BroadcastedData)) private _data;
//
mapping(bytes32 => G2Operations.G2Point) private _publicKeysInProgress;
mapping(bytes32 => G2Operations.G2Point) private _schainsPublicKeys;
// Unused variable
mapping(bytes32 => G2Operations.G2Point[]) private _schainsNodesPublicKeys;
//
mapping(bytes32 => G2Operations.G2Point[]) private _previousSchainsPublicKeys;
function deleteKey(bytes32 schainId) external allow("SkaleDKG") {
_previousSchainsPublicKeys[schainId].push(_schainsPublicKeys[schainId]);
delete _schainsPublicKeys[schainId];
}
function initPublicKeyInProgress(bytes32 schainId) external allow("SkaleDKG") {
_publicKeysInProgress[schainId] = G2Operations.getG2Zero();
}
function adding(bytes32 schainId, G2Operations.G2Point memory value) external allow("SkaleDKG") {
require(value.isG2(), "Incorrect g2 point");
_publicKeysInProgress[schainId] = value.addG2(_publicKeysInProgress[schainId]);
}
function finalizePublicKey(bytes32 schainId) external allow("SkaleDKG") {
if (!_isSchainsPublicKeyZero(schainId)) {
_previousSchainsPublicKeys[schainId].push(_schainsPublicKeys[schainId]);
}
_schainsPublicKeys[schainId] = _publicKeysInProgress[schainId];
delete _publicKeysInProgress[schainId];
}
function getCommonPublicKey(bytes32 schainId) external view returns (G2Operations.G2Point memory) {
return _schainsPublicKeys[schainId];
}
function getPreviousPublicKey(bytes32 schainId) external view returns (G2Operations.G2Point memory) {
uint length = _previousSchainsPublicKeys[schainId].length;
if (length == 0) {
return G2Operations.getG2Zero();
}
return _previousSchainsPublicKeys[schainId][length - 1];
}
function getAllPreviousPublicKeys(bytes32 schainId) external view returns (G2Operations.G2Point[] memory) {
return _previousSchainsPublicKeys[schainId];
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
}
function _isSchainsPublicKeyZero(bytes32 schainId) private view returns (bool) {
return _schainsPublicKeys[schainId].x.a == 0 &&
_schainsPublicKeys[schainId].x.b == 0 &&
_schainsPublicKeys[schainId].y.a == 0 &&
_schainsPublicKeys[schainId].y.b == 0;
}
function _getData() private view returns (BroadcastedData memory) {
return _data[keccak256(abi.encodePacked("UnusedFunction"))][0];
}
function _getNodesPublicKey() private view returns (G2Operations.G2Point memory) {
return _schainsNodesPublicKeys[keccak256(abi.encodePacked("UnusedFunction"))][0];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
NodeRotation.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/utils/Strings.sol";
import "./Permissions.sol";
import "./ConstantsHolder.sol";
import "./SchainsInternal.sol";
import "./Schains.sol";
import "./Nodes.sol";
import "./interfaces/ISkaleDKG.sol";
/**
* @title NodeRotation
* @dev This contract handles all node rotation functionality.
*/
contract NodeRotation is Permissions {
using StringUtils for string;
using StringUtils for uint;
using Strings for uint;
/**
* nodeIndex - index of Node which is in process of rotation (left from schain)
* newNodeIndex - index of Node which is rotated(added to schain)
* freezeUntil - time till which Node should be turned on
* rotationCounter - how many rotations were on this schain
*/
struct Rotation {
uint nodeIndex;
uint newNodeIndex;
uint freezeUntil;
uint rotationCounter;
}
struct LeavingHistory {
bytes32 schainIndex;
uint finishedRotation;
}
mapping (bytes32 => Rotation) public rotations;
mapping (uint => LeavingHistory[]) public leavingHistory;
mapping (bytes32 => bool) public waitForNewNode;
/**
* @dev Allows SkaleManager to remove, find new node, and rotate node from
* schain.
*
* Requirements:
*
* - A free node must exist.
*/
function exitFromSchain(uint nodeIndex) external allow("SkaleManager") returns (bool) {
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
bytes32 schainId = schainsInternal.getActiveSchain(nodeIndex);
require(_checkRotation(schainId), "No free Nodes available for rotating");
rotateNode(nodeIndex, schainId, true);
return schainsInternal.getActiveSchain(nodeIndex) == bytes32(0) ? true : false;
}
/**
* @dev Allows SkaleManager contract to freeze all schains on a given node.
*/
function freezeSchains(uint nodeIndex) external allow("SkaleManager") {
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
bytes32[] memory schains = schainsInternal.getActiveSchains(nodeIndex);
for (uint i = 0; i < schains.length; i++) {
Rotation memory rotation = rotations[schains[i]];
if (rotation.nodeIndex == nodeIndex && now < rotation.freezeUntil) {
continue;
}
string memory schainName = schainsInternal.getSchainName(schains[i]);
string memory revertMessage = "Node cannot rotate on Schain ";
revertMessage = revertMessage.strConcat(schainName);
revertMessage = revertMessage.strConcat(", occupied by Node ");
revertMessage = revertMessage.strConcat(rotation.nodeIndex.toString());
string memory dkgRevert = "DKG process did not finish on schain ";
ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG"));
require(
skaleDKG.isLastDKGSuccessful(keccak256(abi.encodePacked(schainName))),
dkgRevert.strConcat(schainName));
require(rotation.freezeUntil < now, revertMessage);
_startRotation(schains[i], nodeIndex);
}
}
/**
* @dev Allows Schains contract to remove a rotation from an schain.
*/
function removeRotation(bytes32 schainIndex) external allow("Schains") {
delete rotations[schainIndex];
}
/**
* @dev Allows Owner to immediately rotate an schain.
*/
function skipRotationDelay(bytes32 schainIndex) external onlyOwner {
rotations[schainIndex].freezeUntil = now;
}
/**
* @dev Returns rotation details for a given schain.
*/
function getRotation(bytes32 schainIndex) external view returns (Rotation memory) {
return rotations[schainIndex];
}
/**
* @dev Returns leaving history for a given node.
*/
function getLeavingHistory(uint nodeIndex) external view returns (LeavingHistory[] memory) {
return leavingHistory[nodeIndex];
}
function isRotationInProgress(bytes32 schainIndex) external view returns (bool) {
return rotations[schainIndex].freezeUntil >= now && !waitForNewNode[schainIndex];
}
function initialize(address newContractsAddress) public override initializer {
Permissions.initialize(newContractsAddress);
}
/**
* @dev Allows SkaleDKG and SkaleManager contracts to rotate a node from an
* schain.
*/
function rotateNode(
uint nodeIndex,
bytes32 schainId,
bool shouldDelay
)
public
allowTwo("SkaleDKG", "SkaleManager")
returns (uint newNode)
{
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
Schains schains = Schains(contractManager.getContract("Schains"));
schainsInternal.removeNodeFromSchain(nodeIndex, schainId);
newNode = selectNodeToGroup(schainId);
uint8 space = schainsInternal.getSchainsPartOfNode(schainId);
schains.addSpace(nodeIndex, space);
_finishRotation(schainId, nodeIndex, newNode, shouldDelay);
}
/**
* @dev Allows SkaleManager, Schains, and SkaleDKG contracts to
* pseudo-randomly select a new Node for an Schain.
*
* Requirements:
*
* - Schain is active.
* - A free node already exists.
* - Free space can be allocated from the node.
*/
function selectNodeToGroup(bytes32 schainId)
public
allowThree("SkaleManager", "Schains", "SkaleDKG")
returns (uint)
{
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
require(schainsInternal.isSchainActive(schainId), "Group is not active");
uint8 space = schainsInternal.getSchainsPartOfNode(schainId);
uint[] memory possibleNodes = schainsInternal.isEnoughNodes(schainId);
require(possibleNodes.length > 0, "No free Nodes available for rotation");
uint nodeIndex;
uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number - 1)), schainId)));
do {
uint index = random % possibleNodes.length;
nodeIndex = possibleNodes[index];
random = uint(keccak256(abi.encodePacked(random, nodeIndex)));
} while (schainsInternal.checkException(schainId, nodeIndex));
require(nodes.removeSpaceFromNode(nodeIndex, space), "Could not remove space from nodeIndex");
schainsInternal.addSchainForNode(nodeIndex, schainId);
schainsInternal.setException(schainId, nodeIndex);
schainsInternal.setNodeInGroup(schainId, nodeIndex);
return nodeIndex;
}
/**
* @dev Initiates rotation of a node from an schain.
*/
function _startRotation(bytes32 schainIndex, uint nodeIndex) private {
ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
rotations[schainIndex].nodeIndex = nodeIndex;
rotations[schainIndex].newNodeIndex = nodeIndex;
rotations[schainIndex].freezeUntil = now.add(constants.rotationDelay());
waitForNewNode[schainIndex] = true;
}
/**
* @dev Completes rotation of a node from an schain.
*/
function _finishRotation(
bytes32 schainIndex,
uint nodeIndex,
uint newNodeIndex,
bool shouldDelay)
private
{
ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
leavingHistory[nodeIndex].push(
LeavingHistory(schainIndex, shouldDelay ? now.add(constants.rotationDelay()) : now)
);
rotations[schainIndex].newNodeIndex = newNodeIndex;
rotations[schainIndex].rotationCounter++;
delete waitForNewNode[schainIndex];
ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainIndex);
}
/**
* @dev Checks whether a rotation can be performed.
*
* Requirements:
*
* - Schain must exist.
*/
function _checkRotation(bytes32 schainId ) private view returns (bool) {
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
require(schainsInternal.isSchainExist(schainId), "Schain does not exist for rotation");
return schainsInternal.isAnyFreeNode(schainId);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Nodes.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
@author Dmytro Stebaiev
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/utils/SafeCast.sol";
import "./delegation/DelegationController.sol";
import "./delegation/ValidatorService.sol";
import "./BountyV2.sol";
import "./ConstantsHolder.sol";
import "./Permissions.sol";
/**
* @title Nodes
* @dev This contract contains all logic to manage SKALE Network nodes states,
* space availability, stake requirement checks, and exit functions.
*
* Nodes may be in one of several states:
*
* - Active: Node is registered and is in network operation.
* - Leaving: Node has begun exiting from the network.
* - Left: Node has left the network.
* - In_Maintenance: Node is temporarily offline or undergoing infrastructure
* maintenance
*
* Note: Online nodes contain both Active and Leaving states.
*/
contract Nodes is Permissions {
using SafeCast for uint;
// All Nodes states
enum NodeStatus {Active, Leaving, Left, In_Maintenance}
struct Node {
string name;
bytes4 ip;
bytes4 publicIP;
uint16 port;
bytes32[2] publicKey;
uint startBlock;
uint lastRewardDate;
uint finishTime;
NodeStatus status;
uint validatorId;
string domainName;
}
// struct to note which Nodes and which number of Nodes owned by user
struct CreatedNodes {
mapping (uint => bool) isNodeExist;
uint numberOfNodes;
}
struct SpaceManaging {
uint8 freeSpace;
uint indexInSpaceMap;
}
// TODO: move outside the contract
struct NodeCreationParams {
string name;
bytes4 ip;
bytes4 publicIp;
uint16 port;
bytes32[2] publicKey;
uint16 nonce;
string domainName;
}
// array which contain all Nodes
Node[] public nodes;
SpaceManaging[] public spaceOfNodes;
// mapping for checking which Nodes and which number of Nodes owned by user
mapping (address => CreatedNodes) public nodeIndexes;
// mapping for checking is IP address busy
mapping (bytes4 => bool) public nodesIPCheck;
// mapping for checking is Name busy
mapping (bytes32 => bool) public nodesNameCheck;
// mapping for indication from Name to Index
mapping (bytes32 => uint) public nodesNameToIndex;
// mapping for indication from space to Nodes
mapping (uint8 => uint[]) public spaceToNodes;
mapping (uint => uint[]) public validatorToNodeIndexes;
uint public numberOfActiveNodes;
uint public numberOfLeavingNodes;
uint public numberOfLeftNodes;
/**
* @dev Emitted when a node is created.
*/
event NodeCreated(
uint nodeIndex,
address owner,
string name,
bytes4 ip,
bytes4 publicIP,
uint16 port,
uint16 nonce,
string domainName,
uint time,
uint gasSpend
);
/**
* @dev Emitted when a node completes a network exit.
*/
event ExitCompleted(
uint nodeIndex,
uint time,
uint gasSpend
);
/**
* @dev Emitted when a node begins to exit from the network.
*/
event ExitInitialized(
uint nodeIndex,
uint startLeavingPeriod,
uint time,
uint gasSpend
);
modifier checkNodeExists(uint nodeIndex) {
require(nodeIndex < nodes.length, "Node with such index does not exist");
_;
}
modifier onlyNodeOrAdmin(uint nodeIndex) {
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
require(
isNodeExist(msg.sender, nodeIndex) ||
_isAdmin(msg.sender) ||
getValidatorId(nodeIndex) == validatorService.getValidatorId(msg.sender),
"Sender is not permitted to call this function"
);
_;
}
/**
* @dev Allows Schains and SchainsInternal contracts to occupy available
* space on a node.
*
* Returns whether operation is successful.
*/
function removeSpaceFromNode(uint nodeIndex, uint8 space)
external
checkNodeExists(nodeIndex)
allowTwo("NodeRotation", "SchainsInternal")
returns (bool)
{
if (spaceOfNodes[nodeIndex].freeSpace < space) {
return false;
}
if (space > 0) {
_moveNodeToNewSpaceMap(
nodeIndex,
uint(spaceOfNodes[nodeIndex].freeSpace).sub(space).toUint8()
);
}
return true;
}
/**
* @dev Allows Schains contract to occupy free space on a node.
*
* Returns whether operation is successful.
*/
function addSpaceToNode(uint nodeIndex, uint8 space)
external
checkNodeExists(nodeIndex)
allow("Schains")
{
if (space > 0) {
_moveNodeToNewSpaceMap(
nodeIndex,
uint(spaceOfNodes[nodeIndex].freeSpace).add(space).toUint8()
);
}
}
/**
* @dev Allows SkaleManager to change a node's last reward date.
*/
function changeNodeLastRewardDate(uint nodeIndex)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
{
nodes[nodeIndex].lastRewardDate = block.timestamp;
}
/**
* @dev Allows SkaleManager to change a node's finish time.
*/
function changeNodeFinishTime(uint nodeIndex, uint time)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
{
nodes[nodeIndex].finishTime = time;
}
/**
* @dev Allows SkaleManager contract to create new node and add it to the
* Nodes contract.
*
* Emits a {NodeCreated} event.
*
* Requirements:
*
* - Node IP must be non-zero.
* - Node IP must be available.
* - Node name must not already be registered.
* - Node port must be greater than zero.
*/
function createNode(address from, NodeCreationParams calldata params)
external
allow("SkaleManager")
// returns (uint nodeIndex)
{
// checks that Node has correct data
require(params.ip != 0x0 && !nodesIPCheck[params.ip], "IP address is zero or is not available");
require(!nodesNameCheck[keccak256(abi.encodePacked(params.name))], "Name is already registered");
require(params.port > 0, "Port is zero");
require(from == _publicKeyToAddress(params.publicKey), "Public Key is incorrect");
uint validatorId = ValidatorService(
contractManager.getContract("ValidatorService")).getValidatorIdByNodeAddress(from);
// adds Node to Nodes contract
uint nodeIndex = _addNode(
from,
params.name,
params.ip,
params.publicIp,
params.port,
params.publicKey,
params.domainName,
validatorId);
emit NodeCreated(
nodeIndex,
from,
params.name,
params.ip,
params.publicIp,
params.port,
params.nonce,
params.domainName,
block.timestamp,
gasleft());
}
/**
* @dev Allows SkaleManager contract to initiate a node exit procedure.
*
* Returns whether the operation is successful.
*
* Emits an {ExitInitialized} event.
*/
function initExit(uint nodeIndex)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
returns (bool)
{
require(isNodeActive(nodeIndex), "Node should be Active");
_setNodeLeaving(nodeIndex);
emit ExitInitialized(
nodeIndex,
block.timestamp,
block.timestamp,
gasleft());
return true;
}
/**
* @dev Allows SkaleManager contract to complete a node exit procedure.
*
* Returns whether the operation is successful.
*
* Emits an {ExitCompleted} event.
*
* Requirements:
*
* - Node must have already initialized a node exit procedure.
*/
function completeExit(uint nodeIndex)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
returns (bool)
{
require(isNodeLeaving(nodeIndex), "Node is not Leaving");
_setNodeLeft(nodeIndex);
_deleteNode(nodeIndex);
emit ExitCompleted(
nodeIndex,
block.timestamp,
gasleft());
return true;
}
/**
* @dev Allows SkaleManager contract to delete a validator's node.
*
* Requirements:
*
* - Validator ID must exist.
*/
function deleteNodeForValidator(uint validatorId, uint nodeIndex)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
{
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
require(validatorService.validatorExists(validatorId), "Validator ID does not exist");
uint[] memory validatorNodes = validatorToNodeIndexes[validatorId];
uint position = _findNode(validatorNodes, nodeIndex);
if (position < validatorNodes.length) {
validatorToNodeIndexes[validatorId][position] =
validatorToNodeIndexes[validatorId][validatorNodes.length.sub(1)];
}
validatorToNodeIndexes[validatorId].pop();
address nodeOwner = _publicKeyToAddress(nodes[nodeIndex].publicKey);
if (validatorService.getValidatorIdByNodeAddress(nodeOwner) == validatorId) {
if (nodeIndexes[nodeOwner].numberOfNodes == 1 && !validatorService.validatorAddressExists(nodeOwner)) {
validatorService.removeNodeAddress(validatorId, nodeOwner);
}
nodeIndexes[nodeOwner].isNodeExist[nodeIndex] = false;
nodeIndexes[nodeOwner].numberOfNodes--;
}
}
/**
* @dev Allows SkaleManager contract to check whether a validator has
* sufficient stake to create another node.
*
* Requirements:
*
* - Validator must be included on trusted list if trusted list is enabled.
* - Validator must have sufficient stake to operate an additional node.
*/
function checkPossibilityCreatingNode(address nodeAddress) external allow("SkaleManager") {
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
uint validatorId = validatorService.getValidatorIdByNodeAddress(nodeAddress);
require(validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to create a node");
uint[] memory validatorNodes = validatorToNodeIndexes[validatorId];
uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId);
uint msr = ConstantsHolder(contractManager.getContract("ConstantsHolder")).msr();
require(
validatorNodes.length.add(1).mul(msr) <= delegationsTotal,
"Validator must meet the Minimum Staking Requirement");
}
/**
* @dev Allows SkaleManager contract to check whether a validator has
* sufficient stake to maintain a node.
*
* Returns whether validator can maintain node with current stake.
*
* Requirements:
*
* - Validator ID and nodeIndex must both exist.
*/
function checkPossibilityToMaintainNode(
uint validatorId,
uint nodeIndex
)
external
checkNodeExists(nodeIndex)
allow("Bounty")
returns (bool)
{
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
require(validatorService.validatorExists(validatorId), "Validator ID does not exist");
uint[] memory validatorNodes = validatorToNodeIndexes[validatorId];
uint position = _findNode(validatorNodes, nodeIndex);
require(position < validatorNodes.length, "Node does not exist for this Validator");
uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId);
uint msr = ConstantsHolder(contractManager.getContract("ConstantsHolder")).msr();
return position.add(1).mul(msr) <= delegationsTotal;
}
/**
* @dev Allows Node to set In_Maintenance status.
*
* Requirements:
*
* - Node must already be Active.
* - `msg.sender` must be owner of Node, validator, or SkaleManager.
*/
function setNodeInMaintenance(uint nodeIndex) external onlyNodeOrAdmin(nodeIndex) {
require(nodes[nodeIndex].status == NodeStatus.Active, "Node is not Active");
_setNodeInMaintenance(nodeIndex);
}
/**
* @dev Allows Node to remove In_Maintenance status.
*
* Requirements:
*
* - Node must already be In Maintenance.
* - `msg.sender` must be owner of Node, validator, or SkaleManager.
*/
function removeNodeFromInMaintenance(uint nodeIndex) external onlyNodeOrAdmin(nodeIndex) {
require(nodes[nodeIndex].status == NodeStatus.In_Maintenance, "Node is not In Maintenance");
_setNodeActive(nodeIndex);
}
function setDomainName(uint nodeIndex, string memory domainName)
external
onlyNodeOrAdmin(nodeIndex)
{
nodes[nodeIndex].domainName = domainName;
}
/**
* @dev Returns nodes with space availability.
*/
function getNodesWithFreeSpace(uint8 freeSpace) external view returns (uint[] memory) {
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
uint[] memory nodesWithFreeSpace = new uint[](countNodesWithFreeSpace(freeSpace));
uint cursor = 0;
uint totalSpace = constantsHolder.TOTAL_SPACE_ON_NODE();
for (uint8 i = freeSpace; i <= totalSpace; ++i) {
for (uint j = 0; j < spaceToNodes[i].length; j++) {
nodesWithFreeSpace[cursor] = spaceToNodes[i][j];
++cursor;
}
}
return nodesWithFreeSpace;
}
/**
* @dev Checks whether it is time for a node's reward.
*/
function isTimeForReward(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bool)
{
return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex) <= now;
}
/**
* @dev Returns IP address of a given node.
*
* Requirements:
*
* - Node must exist.
*/
function getNodeIP(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bytes4)
{
require(nodeIndex < nodes.length, "Node does not exist");
return nodes[nodeIndex].ip;
}
/**
* @dev Returns domain name of a given node.
*
* Requirements:
*
* - Node must exist.
*/
function getNodeDomainName(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (string memory)
{
return nodes[nodeIndex].domainName;
}
/**
* @dev Returns the port of a given node.
*
* Requirements:
*
* - Node must exist.
*/
function getNodePort(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (uint16)
{
return nodes[nodeIndex].port;
}
/**
* @dev Returns the public key of a given node.
*/
function getNodePublicKey(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bytes32[2] memory)
{
return nodes[nodeIndex].publicKey;
}
/**
* @dev Returns an address of a given node.
*/
function getNodeAddress(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (address)
{
return _publicKeyToAddress(nodes[nodeIndex].publicKey);
}
/**
* @dev Returns the finish exit time of a given node.
*/
function getNodeFinishTime(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (uint)
{
return nodes[nodeIndex].finishTime;
}
/**
* @dev Checks whether a node has left the network.
*/
function isNodeLeft(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.Left;
}
function isNodeInMaintenance(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.In_Maintenance;
}
/**
* @dev Returns a given node's last reward date.
*/
function getNodeLastRewardDate(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (uint)
{
return nodes[nodeIndex].lastRewardDate;
}
/**
* @dev Returns a given node's next reward date.
*/
function getNodeNextRewardDate(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (uint)
{
return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex);
}
/**
* @dev Returns the total number of registered nodes.
*/
function getNumberOfNodes() external view returns (uint) {
return nodes.length;
}
/**
* @dev Returns the total number of online nodes.
*
* Note: Online nodes are equal to the number of active plus leaving nodes.
*/
function getNumberOnlineNodes() external view returns (uint) {
return numberOfActiveNodes.add(numberOfLeavingNodes);
}
/**
* @dev Returns IPs of active nodes.
*/
function getActiveNodeIPs() external view returns (bytes4[] memory activeNodeIPs) {
activeNodeIPs = new bytes4[](numberOfActiveNodes);
uint indexOfActiveNodeIPs = 0;
for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) {
if (isNodeActive(indexOfNodes)) {
activeNodeIPs[indexOfActiveNodeIPs] = nodes[indexOfNodes].ip;
indexOfActiveNodeIPs++;
}
}
}
/**
* @dev Returns active nodes linked to the `msg.sender` (validator address).
*/
function getActiveNodesByAddress() external view returns (uint[] memory activeNodesByAddress) {
activeNodesByAddress = new uint[](nodeIndexes[msg.sender].numberOfNodes);
uint indexOfActiveNodesByAddress = 0;
for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) {
if (isNodeExist(msg.sender, indexOfNodes) && isNodeActive(indexOfNodes)) {
activeNodesByAddress[indexOfActiveNodesByAddress] = indexOfNodes;
indexOfActiveNodesByAddress++;
}
}
}
/**
* @dev Return active node IDs.
*/
function getActiveNodeIds() external view returns (uint[] memory activeNodeIds) {
activeNodeIds = new uint[](numberOfActiveNodes);
uint indexOfActiveNodeIds = 0;
for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) {
if (isNodeActive(indexOfNodes)) {
activeNodeIds[indexOfActiveNodeIds] = indexOfNodes;
indexOfActiveNodeIds++;
}
}
}
/**
* @dev Return a given node's current status.
*/
function getNodeStatus(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (NodeStatus)
{
return nodes[nodeIndex].status;
}
/**
* @dev Return a validator's linked nodes.
*
* Requirements:
*
* - Validator ID must exist.
*/
function getValidatorNodeIndexes(uint validatorId) external view returns (uint[] memory) {
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
require(validatorService.validatorExists(validatorId), "Validator ID does not exist");
return validatorToNodeIndexes[validatorId];
}
/**
* @dev constructor in Permissions approach.
*/
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
numberOfActiveNodes = 0;
numberOfLeavingNodes = 0;
numberOfLeftNodes = 0;
}
/**
* @dev Returns the Validator ID for a given node.
*/
function getValidatorId(uint nodeIndex)
public
view
checkNodeExists(nodeIndex)
returns (uint)
{
return nodes[nodeIndex].validatorId;
}
/**
* @dev Checks whether a node exists for a given address.
*/
function isNodeExist(address from, uint nodeIndex)
public
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodeIndexes[from].isNodeExist[nodeIndex];
}
/**
* @dev Checks whether a node's status is Active.
*/
function isNodeActive(uint nodeIndex)
public
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.Active;
}
/**
* @dev Checks whether a node's status is Leaving.
*/
function isNodeLeaving(uint nodeIndex)
public
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.Leaving;
}
/**
* @dev Returns number of nodes with available space.
*/
function countNodesWithFreeSpace(uint8 freeSpace) public view returns (uint count) {
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
count = 0;
uint totalSpace = constantsHolder.TOTAL_SPACE_ON_NODE();
for (uint8 i = freeSpace; i <= totalSpace; ++i) {
count = count.add(spaceToNodes[i].length);
}
}
/**
* @dev Returns the index of a given node within the validator's node index.
*/
function _findNode(uint[] memory validatorNodeIndexes, uint nodeIndex) private pure returns (uint) {
uint i;
for (i = 0; i < validatorNodeIndexes.length; i++) {
if (validatorNodeIndexes[i] == nodeIndex) {
return i;
}
}
return validatorNodeIndexes.length;
}
/**
* @dev Moves a node to a new space mapping.
*/
function _moveNodeToNewSpaceMap(uint nodeIndex, uint8 newSpace) private {
uint8 previousSpace = spaceOfNodes[nodeIndex].freeSpace;
uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap;
if (indexInArray < spaceToNodes[previousSpace].length.sub(1)) {
uint shiftedIndex = spaceToNodes[previousSpace][spaceToNodes[previousSpace].length.sub(1)];
spaceToNodes[previousSpace][indexInArray] = shiftedIndex;
spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray;
spaceToNodes[previousSpace].pop();
} else {
spaceToNodes[previousSpace].pop();
}
spaceToNodes[newSpace].push(nodeIndex);
spaceOfNodes[nodeIndex].freeSpace = newSpace;
spaceOfNodes[nodeIndex].indexInSpaceMap = spaceToNodes[newSpace].length.sub(1);
}
/**
* @dev Changes a node's status to Active.
*/
function _setNodeActive(uint nodeIndex) private {
nodes[nodeIndex].status = NodeStatus.Active;
numberOfActiveNodes = numberOfActiveNodes.add(1);
}
/**
* @dev Changes a node's status to In_Maintenance.
*/
function _setNodeInMaintenance(uint nodeIndex) private {
nodes[nodeIndex].status = NodeStatus.In_Maintenance;
numberOfActiveNodes = numberOfActiveNodes.sub(1);
}
/**
* @dev Changes a node's status to Left.
*/
function _setNodeLeft(uint nodeIndex) private {
nodesIPCheck[nodes[nodeIndex].ip] = false;
nodesNameCheck[keccak256(abi.encodePacked(nodes[nodeIndex].name))] = false;
delete nodesNameToIndex[keccak256(abi.encodePacked(nodes[nodeIndex].name))];
if (nodes[nodeIndex].status == NodeStatus.Active) {
numberOfActiveNodes--;
} else {
numberOfLeavingNodes--;
}
nodes[nodeIndex].status = NodeStatus.Left;
numberOfLeftNodes++;
}
/**
* @dev Changes a node's status to Leaving.
*/
function _setNodeLeaving(uint nodeIndex) private {
nodes[nodeIndex].status = NodeStatus.Leaving;
numberOfActiveNodes--;
numberOfLeavingNodes++;
}
/**
* @dev Adds node to array.
*/
function _addNode(
address from,
string memory name,
bytes4 ip,
bytes4 publicIP,
uint16 port,
bytes32[2] memory publicKey,
string memory domainName,
uint validatorId
)
private
returns (uint nodeIndex)
{
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
nodes.push(Node({
name: name,
ip: ip,
publicIP: publicIP,
port: port,
//owner: from,
publicKey: publicKey,
startBlock: block.number,
lastRewardDate: block.timestamp,
finishTime: 0,
status: NodeStatus.Active,
validatorId: validatorId,
domainName: domainName
}));
nodeIndex = nodes.length.sub(1);
validatorToNodeIndexes[validatorId].push(nodeIndex);
bytes32 nodeId = keccak256(abi.encodePacked(name));
nodesIPCheck[ip] = true;
nodesNameCheck[nodeId] = true;
nodesNameToIndex[nodeId] = nodeIndex;
nodeIndexes[from].isNodeExist[nodeIndex] = true;
nodeIndexes[from].numberOfNodes++;
spaceOfNodes.push(SpaceManaging({
freeSpace: constantsHolder.TOTAL_SPACE_ON_NODE(),
indexInSpaceMap: spaceToNodes[constantsHolder.TOTAL_SPACE_ON_NODE()].length
}));
spaceToNodes[constantsHolder.TOTAL_SPACE_ON_NODE()].push(nodeIndex);
numberOfActiveNodes++;
}
/**
* @dev Deletes node from array.
*/
function _deleteNode(uint nodeIndex) private {
uint8 space = spaceOfNodes[nodeIndex].freeSpace;
uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap;
if (indexInArray < spaceToNodes[space].length.sub(1)) {
uint shiftedIndex = spaceToNodes[space][spaceToNodes[space].length.sub(1)];
spaceToNodes[space][indexInArray] = shiftedIndex;
spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray;
spaceToNodes[space].pop();
} else {
spaceToNodes[space].pop();
}
delete spaceOfNodes[nodeIndex].freeSpace;
delete spaceOfNodes[nodeIndex].indexInSpaceMap;
}
function _publicKeyToAddress(bytes32[2] memory pubKey) private pure returns (address) {
bytes32 hash = keccak256(abi.encodePacked(pubKey[0], pubKey[1]));
bytes20 addr;
for (uint8 i = 12; i < 32; i++) {
addr |= bytes20(hash[i] & 0xFF) >> ((i - 12) * 8);
}
return address(addr);
}
function _min(uint a, uint b) private pure returns (uint) {
if (a < b) {
return a;
} else {
return b;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Permissions.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol";
import "./ContractManager.sol";
/**
* @title Permissions
* @dev Contract is connected module for Upgradeable approach, knows ContractManager
*/
contract Permissions is AccessControlUpgradeSafe {
using SafeMath for uint;
using Address for address;
ContractManager public contractManager;
/**
* @dev Modifier to make a function callable only when caller is the Owner.
*
* Requirements:
*
* - The caller must be the owner.
*/
modifier onlyOwner() {
require(_isOwner(), "Caller is not the owner");
_;
}
/**
* @dev Modifier to make a function callable only when caller is an Admin.
*
* Requirements:
*
* - The caller must be an admin.
*/
modifier onlyAdmin() {
require(_isAdmin(msg.sender), "Caller is not an admin");
_;
}
/**
* @dev Modifier to make a function callable only when caller is the Owner
* or `contractName` contract.
*
* Requirements:
*
* - The caller must be the owner or `contractName`.
*/
modifier allow(string memory contractName) {
require(
contractManager.getContract(contractName) == msg.sender || _isOwner(),
"Message sender is invalid");
_;
}
/**
* @dev Modifier to make a function callable only when caller is the Owner
* or `contractName1` or `contractName2` contract.
*
* Requirements:
*
* - The caller must be the owner, `contractName1`, or `contractName2`.
*/
modifier allowTwo(string memory contractName1, string memory contractName2) {
require(
contractManager.getContract(contractName1) == msg.sender ||
contractManager.getContract(contractName2) == msg.sender ||
_isOwner(),
"Message sender is invalid");
_;
}
/**
* @dev Modifier to make a function callable only when caller is the Owner
* or `contractName1`, `contractName2`, or `contractName3` contract.
*
* Requirements:
*
* - The caller must be the owner, `contractName1`, `contractName2`, or
* `contractName3`.
*/
modifier allowThree(string memory contractName1, string memory contractName2, string memory contractName3) {
require(
contractManager.getContract(contractName1) == msg.sender ||
contractManager.getContract(contractName2) == msg.sender ||
contractManager.getContract(contractName3) == msg.sender ||
_isOwner(),
"Message sender is invalid");
_;
}
function initialize(address contractManagerAddress) public virtual initializer {
AccessControlUpgradeSafe.__AccessControl_init();
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setContractManager(contractManagerAddress);
}
function _isOwner() internal view returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
function _isAdmin(address account) internal view returns (bool) {
address skaleManagerAddress = contractManager.contracts(keccak256(abi.encodePacked("SkaleManager")));
if (skaleManagerAddress != address(0)) {
AccessControlUpgradeSafe skaleManager = AccessControlUpgradeSafe(skaleManagerAddress);
return skaleManager.hasRole(keccak256("ADMIN_ROLE"), account) || _isOwner();
} else {
return _isOwner();
}
}
function _setContractManager(address contractManagerAddress) private {
require(contractManagerAddress != address(0), "ContractManager address is not set");
require(contractManagerAddress.isContract(), "Address is not contract");
contractManager = ContractManager(contractManagerAddress);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Schains.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "./Permissions.sol";
import "./SchainsInternal.sol";
import "./ConstantsHolder.sol";
import "./KeyStorage.sol";
import "./SkaleVerifier.sol";
import "./utils/FieldOperations.sol";
import "./NodeRotation.sol";
import "./interfaces/ISkaleDKG.sol";
/**
* @title Schains
* @dev Contains functions to manage Schains such as Schain creation,
* deletion, and rotation.
*/
contract Schains is Permissions {
using StringUtils for string;
using StringUtils for uint;
struct SchainParameters {
uint lifetime;
uint8 typeOfSchain;
uint16 nonce;
string name;
}
/**
* @dev Emitted when an schain is created.
*/
event SchainCreated(
string name,
address owner,
uint partOfNode,
uint lifetime,
uint numberOfNodes,
uint deposit,
uint16 nonce,
bytes32 schainId,
uint time,
uint gasSpend
);
/**
* @dev Emitted when an schain is deleted.
*/
event SchainDeleted(
address owner,
string name,
bytes32 indexed schainId
);
/**
* @dev Emitted when a node in an schain is rotated.
*/
event NodeRotated(
bytes32 schainId,
uint oldNode,
uint newNode
);
/**
* @dev Emitted when a node is added to an schain.
*/
event NodeAdded(
bytes32 schainId,
uint newNode
);
/**
* @dev Emitted when a group of nodes is created for an schain.
*/
event SchainNodes(
string name,
bytes32 schainId,
uint[] nodesInGroup,
uint time,
uint gasSpend
);
bytes32 public constant SCHAIN_CREATOR_ROLE = keccak256("SCHAIN_CREATOR_ROLE");
/**
* @dev Allows SkaleManager contract to create an Schain.
*
* Emits an {SchainCreated} event.
*
* Requirements:
*
* - Schain type is valid.
* - There is sufficient deposit to create type of schain.
*/
function addSchain(address from, uint deposit, bytes calldata data) external allow("SkaleManager") {
SchainParameters memory schainParameters = _fallbackSchainParametersDataConverter(data);
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
uint schainCreationTimeStamp = constantsHolder.schainCreationTimeStamp();
uint minSchainLifetime = constantsHolder.minimalSchainLifetime();
require(now >= schainCreationTimeStamp, "It is not a time for creating Schain");
require(
schainParameters.lifetime >= minSchainLifetime,
"Minimal schain lifetime should be satisfied"
);
require(
getSchainPrice(schainParameters.typeOfSchain, schainParameters.lifetime) <= deposit,
"Not enough money to create Schain");
_addSchain(from, deposit, schainParameters);
}
function addSchainByFoundation(
uint lifetime,
uint8 typeOfSchain,
uint16 nonce,
string calldata name
)
external
{
require(hasRole(SCHAIN_CREATOR_ROLE, msg.sender), "Sender is not authorized to create schain");
SchainParameters memory schainParameters = SchainParameters({
lifetime: lifetime,
typeOfSchain: typeOfSchain,
nonce: nonce,
name: name
});
_addSchain(msg.sender, 0, schainParameters);
}
/**
* @dev Allows SkaleManager to remove an schain from the network.
* Upon removal, the space availability of each node is updated.
*
* Emits an {SchainDeleted} event.
*
* Requirements:
*
* - Executed by schain owner.
*/
function deleteSchain(address from, string calldata name) external allow("SkaleManager") {
NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation"));
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
bytes32 schainId = keccak256(abi.encodePacked(name));
require(
schainsInternal.isOwnerAddress(from, schainId),
"Message sender is not the owner of the Schain"
);
address nodesAddress = contractManager.getContract("Nodes");
// removes Schain from Nodes
uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainId);
uint8 partOfNode = schainsInternal.getSchainsPartOfNode(schainId);
for (uint i = 0; i < nodesInGroup.length; i++) {
uint schainIndex = schainsInternal.findSchainAtSchainsForNode(
nodesInGroup[i],
schainId
);
if (schainsInternal.checkHoleForSchain(schainId, i)) {
continue;
}
require(
schainIndex < schainsInternal.getLengthOfSchainsForNode(nodesInGroup[i]),
"Some Node does not contain given Schain");
schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainId);
schainsInternal.removeNodeFromExceptions(schainId, nodesInGroup[i]);
if (!Nodes(nodesAddress).isNodeLeft(nodesInGroup[i])) {
this.addSpace(nodesInGroup[i], partOfNode);
}
}
schainsInternal.deleteGroup(schainId);
schainsInternal.removeSchain(schainId, from);
schainsInternal.removeHolesForSchain(schainId);
nodeRotation.removeRotation(schainId);
emit SchainDeleted(from, name, schainId);
}
/**
* @dev Allows SkaleManager to delete any Schain.
* Upon removal, the space availability of each node is updated.
*
* Emits an {SchainDeleted} event.
*
* Requirements:
*
* - Schain exists.
*/
function deleteSchainByRoot(string calldata name) external allow("SkaleManager") {
NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation"));
bytes32 schainId = keccak256(abi.encodePacked(name));
SchainsInternal schainsInternal = SchainsInternal(
contractManager.getContract("SchainsInternal"));
require(schainsInternal.isSchainExist(schainId), "Schain does not exist");
// removes Schain from Nodes
uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainId);
uint8 partOfNode = schainsInternal.getSchainsPartOfNode(schainId);
for (uint i = 0; i < nodesInGroup.length; i++) {
uint schainIndex = schainsInternal.findSchainAtSchainsForNode(
nodesInGroup[i],
schainId
);
if (schainsInternal.checkHoleForSchain(schainId, i)) {
continue;
}
require(
schainIndex < schainsInternal.getLengthOfSchainsForNode(nodesInGroup[i]),
"Some Node does not contain given Schain");
schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainId);
schainsInternal.removeNodeFromExceptions(schainId, nodesInGroup[i]);
this.addSpace(nodesInGroup[i], partOfNode);
}
schainsInternal.deleteGroup(schainId);
address from = schainsInternal.getSchainOwner(schainId);
schainsInternal.removeSchain(schainId, from);
schainsInternal.removeHolesForSchain(schainId);
nodeRotation.removeRotation(schainId);
emit SchainDeleted(from, name, schainId);
}
/**
* @dev Allows SkaleManager contract to restart schain creation by forming a
* new schain group. Executed when DKG procedure fails and becomes stuck.
*
* Emits a {NodeAdded} event.
*
* Requirements:
*
* - Previous DKG procedure must have failed.
* - DKG failure got stuck because there were no free nodes to rotate in.
* - A free node must be released in the network.
*/
function restartSchainCreation(string calldata name) external allow("SkaleManager") {
NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation"));
bytes32 schainId = keccak256(abi.encodePacked(name));
ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG"));
require(!skaleDKG.isLastDKGSuccessful(schainId), "DKG success");
SchainsInternal schainsInternal = SchainsInternal(
contractManager.getContract("SchainsInternal"));
require(schainsInternal.isAnyFreeNode(schainId), "No free Nodes for new group formation");
uint newNodeIndex = nodeRotation.selectNodeToGroup(schainId);
skaleDKG.openChannel(schainId);
emit NodeAdded(schainId, newNodeIndex);
}
/**
* @dev addSpace - return occupied space to Node
* @param nodeIndex - index of Node at common array of Nodes
* @param partOfNode - divisor of given type of Schain
*/
function addSpace(uint nodeIndex, uint8 partOfNode) external allowTwo("Schains", "NodeRotation") {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
nodes.addSpaceToNode(nodeIndex, partOfNode);
}
/**
* @dev Checks whether schain group signature is valid.
*/
function verifySchainSignature(
uint signatureA,
uint signatureB,
bytes32 hash,
uint counter,
uint hashA,
uint hashB,
string calldata schainName
)
external
view
returns (bool)
{
SkaleVerifier skaleVerifier = SkaleVerifier(contractManager.getContract("SkaleVerifier"));
G2Operations.G2Point memory publicKey = KeyStorage(
contractManager.getContract("KeyStorage")
).getCommonPublicKey(
keccak256(abi.encodePacked(schainName))
);
return skaleVerifier.verify(
Fp2Operations.Fp2Point({
a: signatureA,
b: signatureB
}),
hash, counter,
hashA, hashB,
publicKey
);
}
function initialize(address newContractsAddress) public override initializer {
Permissions.initialize(newContractsAddress);
}
/**
* @dev Returns the current price in SKL tokens for given Schain type and lifetime.
*/
function getSchainPrice(uint typeOfSchain, uint lifetime) public view returns (uint) {
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
uint nodeDeposit = constantsHolder.NODE_DEPOSIT();
uint numberOfNodes;
uint8 divisor;
(numberOfNodes, divisor) = getNodesDataFromTypeOfSchain(typeOfSchain);
if (divisor == 0) {
return 1e18;
} else {
uint up = nodeDeposit.mul(numberOfNodes.mul(lifetime.mul(2)));
uint down = uint(
uint(constantsHolder.SMALL_DIVISOR())
.mul(uint(constantsHolder.SECONDS_TO_YEAR()))
.div(divisor)
);
return up.div(down);
}
}
/**
* @dev Returns the number of Nodes and resource divisor that is needed for a
* given Schain type.
*/
function getNodesDataFromTypeOfSchain(uint typeOfSchain)
public
view
returns (uint numberOfNodes, uint8 partOfNode)
{
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_SCHAIN();
if (typeOfSchain == 1) {
partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.SMALL_DIVISOR();
} else if (typeOfSchain == 2) {
partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.MEDIUM_DIVISOR();
} else if (typeOfSchain == 3) {
partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.LARGE_DIVISOR();
} else if (typeOfSchain == 4) {
partOfNode = 0;
numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_TEST_SCHAIN();
} else if (typeOfSchain == 5) {
partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.MEDIUM_TEST_DIVISOR();
numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN();
} else {
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
(partOfNode, numberOfNodes) = schainsInternal.schainTypes(typeOfSchain);
if (numberOfNodes == 0) {
revert("Bad schain type");
}
}
}
/**
* @dev Initializes an schain in the SchainsInternal contract.
*
* Requirements:
*
* - Schain name is not already in use.
*/
function _initializeSchainInSchainsInternal(
string memory name,
address from,
uint deposit,
uint lifetime) private
{
address dataAddress = contractManager.getContract("SchainsInternal");
require(SchainsInternal(dataAddress).isSchainNameAvailable(name), "Schain name is not available");
// initialize Schain
SchainsInternal(dataAddress).initializeSchain(
name,
from,
lifetime,
deposit);
SchainsInternal(dataAddress).setSchainIndex(keccak256(abi.encodePacked(name)), from);
}
/**
* @dev Converts data from bytes to normal schain parameters of lifetime,
* type, nonce, and name.
*/
function _fallbackSchainParametersDataConverter(bytes memory data)
private
pure
returns (SchainParameters memory schainParameters)
{
(schainParameters.lifetime,
schainParameters.typeOfSchain,
schainParameters.nonce,
schainParameters.name) = abi.decode(data, (uint, uint8, uint16, string));
}
/**
* @dev Allows creation of node group for Schain.
*
* Emits an {SchainNodes} event.
*/
function _createGroupForSchain(
string memory schainName,
bytes32 schainId,
uint numberOfNodes,
uint8 partOfNode
)
private
{
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
uint[] memory nodesInGroup = schainsInternal.createGroupForSchain(schainId, numberOfNodes, partOfNode);
ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainId);
emit SchainNodes(
schainName,
schainId,
nodesInGroup,
block.timestamp,
gasleft());
}
/**
* @dev Creates an schain.
*
* Emits an {SchainCreated} event.
*
* Requirements:
*
* - Schain type must be valid.
*/
function _addSchain(address from, uint deposit, SchainParameters memory schainParameters) private {
uint numberOfNodes;
uint8 partOfNode;
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
require(schainParameters.typeOfSchain <= schainsInternal.numberOfSchainTypes(), "Invalid type of Schain");
//initialize Schain
_initializeSchainInSchainsInternal(
schainParameters.name,
from,
deposit,
schainParameters.lifetime);
// create a group for Schain
(numberOfNodes, partOfNode) = getNodesDataFromTypeOfSchain(schainParameters.typeOfSchain);
_createGroupForSchain(
schainParameters.name,
keccak256(abi.encodePacked(schainParameters.name)),
numberOfNodes,
partOfNode
);
emit SchainCreated(
schainParameters.name,
from,
partOfNode,
schainParameters.lifetime,
numberOfNodes,
deposit,
schainParameters.nonce,
keccak256(abi.encodePacked(schainParameters.name)),
block.timestamp,
gasleft());
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SchainsInternal.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "./ConstantsHolder.sol";
import "./Nodes.sol";
import "./interfaces/ISkaleDKG.sol";
/**
* @title SchainsInternal
* @dev Contract contains all functionality logic to internally manage Schains.
*/
contract SchainsInternal is Permissions {
struct Schain {
string name;
address owner;
uint indexInOwnerList;
uint8 partOfNode;
uint lifetime;
uint startDate;
uint startBlock;
uint deposit;
uint64 index;
}
struct SchainType {
uint8 partOfNode;
uint numberOfNodes;
}
// mapping which contain all schains
mapping (bytes32 => Schain) public schains;
mapping (bytes32 => bool) public isSchainActive;
mapping (bytes32 => uint[]) public schainsGroups;
mapping (bytes32 => mapping (uint => bool)) private _exceptionsForGroups;
// mapping shows schains by owner's address
mapping (address => bytes32[]) public schainIndexes;
// mapping shows schains which Node composed in
mapping (uint => bytes32[]) public schainsForNodes;
mapping (uint => uint[]) public holesForNodes;
mapping (bytes32 => uint[]) public holesForSchains;
// array which contain all schains
bytes32[] public schainsAtSystem;
uint64 public numberOfSchains;
// total resources that schains occupied
uint public sumOfSchainsResources;
mapping (bytes32 => bool) public usedSchainNames;
mapping (uint => SchainType) public schainTypes;
uint public numberOfSchainTypes;
// schain hash => node index => index of place
// index of place is a number from 1 to max number of slots on node(128)
mapping (bytes32 => mapping (uint => uint)) public placeOfSchainOnNode;
/**
* @dev Allows Schain contract to initialize an schain.
*/
function initializeSchain(
string calldata name,
address from,
uint lifetime,
uint deposit) external allow("Schains")
{
bytes32 schainId = keccak256(abi.encodePacked(name));
schains[schainId].name = name;
schains[schainId].owner = from;
schains[schainId].startDate = block.timestamp;
schains[schainId].startBlock = block.number;
schains[schainId].lifetime = lifetime;
schains[schainId].deposit = deposit;
schains[schainId].index = numberOfSchains;
isSchainActive[schainId] = true;
numberOfSchains++;
schainsAtSystem.push(schainId);
usedSchainNames[schainId] = true;
}
/**
* @dev Allows Schain contract to create a node group for an schain.
*/
function createGroupForSchain(
bytes32 schainId,
uint numberOfNodes,
uint8 partOfNode
)
external
allow("Schains")
returns (uint[] memory)
{
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
schains[schainId].partOfNode = partOfNode;
if (partOfNode > 0) {
sumOfSchainsResources = sumOfSchainsResources.add(
numberOfNodes.mul(constantsHolder.TOTAL_SPACE_ON_NODE()).div(partOfNode)
);
}
return _generateGroup(schainId, numberOfNodes);
}
/**
* @dev Allows Schains contract to set index in owner list.
*/
function setSchainIndex(bytes32 schainId, address from) external allow("Schains") {
schains[schainId].indexInOwnerList = schainIndexes[from].length;
schainIndexes[from].push(schainId);
}
/**
* @dev Allows Schains contract to change the Schain lifetime through
* an additional SKL token deposit.
*/
function changeLifetime(bytes32 schainId, uint lifetime, uint deposit) external allow("Schains") {
schains[schainId].deposit = schains[schainId].deposit.add(deposit);
schains[schainId].lifetime = schains[schainId].lifetime.add(lifetime);
}
/**
* @dev Allows Schains contract to remove an schain from the network.
* Generally schains are not removed from the system; instead they are
* simply allowed to expire.
*/
function removeSchain(bytes32 schainId, address from) external allow("Schains") {
isSchainActive[schainId] = false;
uint length = schainIndexes[from].length;
uint index = schains[schainId].indexInOwnerList;
if (index != length.sub(1)) {
bytes32 lastSchainId = schainIndexes[from][length.sub(1)];
schains[lastSchainId].indexInOwnerList = index;
schainIndexes[from][index] = lastSchainId;
}
schainIndexes[from].pop();
// TODO:
// optimize
for (uint i = 0; i + 1 < schainsAtSystem.length; i++) {
if (schainsAtSystem[i] == schainId) {
schainsAtSystem[i] = schainsAtSystem[schainsAtSystem.length.sub(1)];
break;
}
}
schainsAtSystem.pop();
delete schains[schainId];
numberOfSchains--;
}
/**
* @dev Allows Schains and SkaleDKG contracts to remove a node from an
* schain for node rotation or DKG failure.
*/
function removeNodeFromSchain(
uint nodeIndex,
bytes32 schainHash
)
external
allowThree("NodeRotation", "SkaleDKG", "Schains")
{
uint indexOfNode = _findNode(schainHash, nodeIndex);
uint indexOfLastNode = schainsGroups[schainHash].length.sub(1);
if (indexOfNode == indexOfLastNode) {
schainsGroups[schainHash].pop();
} else {
delete schainsGroups[schainHash][indexOfNode];
if (holesForSchains[schainHash].length > 0 && holesForSchains[schainHash][0] > indexOfNode) {
uint hole = holesForSchains[schainHash][0];
holesForSchains[schainHash][0] = indexOfNode;
holesForSchains[schainHash].push(hole);
} else {
holesForSchains[schainHash].push(indexOfNode);
}
}
uint schainIndexOnNode = findSchainAtSchainsForNode(nodeIndex, schainHash);
removeSchainForNode(nodeIndex, schainIndexOnNode);
delete placeOfSchainOnNode[schainHash][nodeIndex];
}
/**
* @dev Allows Schains contract to remove node from exceptions
*/
function removeNodeFromExceptions(bytes32 schainHash, uint nodeIndex) external allow("Schains") {
_exceptionsForGroups[schainHash][nodeIndex] = false;
}
/**
* @dev Allows Schains contract to delete a group of schains
*/
function deleteGroup(bytes32 schainId) external allow("Schains") {
// delete channel
ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG"));
delete schainsGroups[schainId];
skaleDKG.deleteChannel(schainId);
}
/**
* @dev Allows Schain and NodeRotation contracts to set a Node like
* exception for a given schain and nodeIndex.
*/
function setException(bytes32 schainId, uint nodeIndex) external allowTwo("Schains", "NodeRotation") {
_exceptionsForGroups[schainId][nodeIndex] = true;
}
/**
* @dev Allows Schains and NodeRotation contracts to add node to an schain
* group.
*/
function setNodeInGroup(bytes32 schainId, uint nodeIndex) external allowTwo("Schains", "NodeRotation") {
if (holesForSchains[schainId].length == 0) {
schainsGroups[schainId].push(nodeIndex);
} else {
schainsGroups[schainId][holesForSchains[schainId][0]] = nodeIndex;
uint min = uint(-1);
uint index = 0;
for (uint i = 1; i < holesForSchains[schainId].length; i++) {
if (min > holesForSchains[schainId][i]) {
min = holesForSchains[schainId][i];
index = i;
}
}
if (min == uint(-1)) {
delete holesForSchains[schainId];
} else {
holesForSchains[schainId][0] = min;
holesForSchains[schainId][index] =
holesForSchains[schainId][holesForSchains[schainId].length - 1];
holesForSchains[schainId].pop();
}
}
}
/**
* @dev Allows Schains contract to remove holes for schains
*/
function removeHolesForSchain(bytes32 schainHash) external allow("Schains") {
delete holesForSchains[schainHash];
}
/**
* @dev Allows Admin to add schain type
*/
function addSchainType(uint8 partOfNode, uint numberOfNodes) external onlyAdmin {
schainTypes[numberOfSchainTypes + 1].partOfNode = partOfNode;
schainTypes[numberOfSchainTypes + 1].numberOfNodes = numberOfNodes;
numberOfSchainTypes++;
}
/**
* @dev Allows Admin to remove schain type
*/
function removeSchainType(uint typeOfSchain) external onlyAdmin {
delete schainTypes[typeOfSchain].partOfNode;
delete schainTypes[typeOfSchain].numberOfNodes;
}
/**
* @dev Allows Admin to set number of schain types
*/
function setNumberOfSchainTypes(uint newNumberOfSchainTypes) external onlyAdmin {
numberOfSchainTypes = newNumberOfSchainTypes;
}
/**
* @dev Allows Admin to move schain to placeOfSchainOnNode map
*/
function moveToPlaceOfSchainOnNode(bytes32 schainHash) external onlyAdmin {
for (uint i = 0; i < schainsGroups[schainHash].length; i++) {
uint nodeIndex = schainsGroups[schainHash][i];
for (uint j = 0; j < schainsForNodes[nodeIndex].length; j++) {
if (schainsForNodes[nodeIndex][j] == schainHash) {
placeOfSchainOnNode[schainHash][nodeIndex] = j + 1;
}
}
}
}
/**
* @dev Returns all Schains in the network.
*/
function getSchains() external view returns (bytes32[] memory) {
return schainsAtSystem;
}
/**
* @dev Returns all occupied resources on one node for an Schain.
*/
function getSchainsPartOfNode(bytes32 schainId) external view returns (uint8) {
return schains[schainId].partOfNode;
}
/**
* @dev Returns number of schains by schain owner.
*/
function getSchainListSize(address from) external view returns (uint) {
return schainIndexes[from].length;
}
/**
* @dev Returns hashes of schain names by schain owner.
*/
function getSchainIdsByAddress(address from) external view returns (bytes32[] memory) {
return schainIndexes[from];
}
/**
* @dev Returns hashes of schain names running on a node.
*/
function getSchainIdsForNode(uint nodeIndex) external view returns (bytes32[] memory) {
return schainsForNodes[nodeIndex];
}
/**
* @dev Returns the owner of an schain.
*/
function getSchainOwner(bytes32 schainId) external view returns (address) {
return schains[schainId].owner;
}
/**
* @dev Checks whether schain name is available.
* TODO Need to delete - copy of web3.utils.soliditySha3
*/
function isSchainNameAvailable(string calldata name) external view returns (bool) {
bytes32 schainId = keccak256(abi.encodePacked(name));
return schains[schainId].owner == address(0) &&
!usedSchainNames[schainId] &&
keccak256(abi.encodePacked(name)) != keccak256(abi.encodePacked("Mainnet"));
}
/**
* @dev Checks whether schain lifetime has expired.
*/
function isTimeExpired(bytes32 schainId) external view returns (bool) {
return uint(schains[schainId].startDate).add(schains[schainId].lifetime) < block.timestamp;
}
/**
* @dev Checks whether address is owner of schain.
*/
function isOwnerAddress(address from, bytes32 schainId) external view returns (bool) {
return schains[schainId].owner == from;
}
/**
* @dev Checks whether schain exists.
*/
function isSchainExist(bytes32 schainId) external view returns (bool) {
return keccak256(abi.encodePacked(schains[schainId].name)) != keccak256(abi.encodePacked(""));
}
/**
* @dev Returns schain name.
*/
function getSchainName(bytes32 schainId) external view returns (string memory) {
return schains[schainId].name;
}
/**
* @dev Returns last active schain of a node.
*/
function getActiveSchain(uint nodeIndex) external view returns (bytes32) {
for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) {
if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) {
return schainsForNodes[nodeIndex][i - 1];
}
}
return bytes32(0);
}
/**
* @dev Returns active schains of a node.
*/
function getActiveSchains(uint nodeIndex) external view returns (bytes32[] memory activeSchains) {
uint activeAmount = 0;
for (uint i = 0; i < schainsForNodes[nodeIndex].length; i++) {
if (schainsForNodes[nodeIndex][i] != bytes32(0)) {
activeAmount++;
}
}
uint cursor = 0;
activeSchains = new bytes32[](activeAmount);
for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) {
if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) {
activeSchains[cursor++] = schainsForNodes[nodeIndex][i - 1];
}
}
}
/**
* @dev Returns number of nodes in an schain group.
*/
function getNumberOfNodesInGroup(bytes32 schainId) external view returns (uint) {
return schainsGroups[schainId].length;
}
/**
* @dev Returns nodes in an schain group.
*/
function getNodesInGroup(bytes32 schainId) external view returns (uint[] memory) {
return schainsGroups[schainId];
}
/**
* @dev Checks whether sender is a node address from a given schain group.
*/
function isNodeAddressesInGroup(bytes32 schainId, address sender) external view returns (bool) {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
for (uint i = 0; i < schainsGroups[schainId].length; i++) {
if (nodes.getNodeAddress(schainsGroups[schainId][i]) == sender) {
return true;
}
}
return false;
}
/**
* @dev Returns node index in schain group.
*/
function getNodeIndexInGroup(bytes32 schainId, uint nodeId) external view returns (uint) {
for (uint index = 0; index < schainsGroups[schainId].length; index++) {
if (schainsGroups[schainId][index] == nodeId) {
return index;
}
}
return schainsGroups[schainId].length;
}
/**
* @dev Checks whether there are any nodes with free resources for given
* schain.
*/
function isAnyFreeNode(bytes32 schainId) external view returns (bool) {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
uint8 space = schains[schainId].partOfNode;
uint[] memory nodesWithFreeSpace = nodes.getNodesWithFreeSpace(space);
for (uint i = 0; i < nodesWithFreeSpace.length; i++) {
if (_isCorrespond(schainId, nodesWithFreeSpace[i])) {
return true;
}
}
return false;
}
/**
* @dev Returns whether any exceptions exist for node in a schain group.
*/
function checkException(bytes32 schainId, uint nodeIndex) external view returns (bool) {
return _exceptionsForGroups[schainId][nodeIndex];
}
function checkHoleForSchain(bytes32 schainHash, uint indexOfNode) external view returns (bool) {
for (uint i = 0; i < holesForSchains[schainHash].length; i++) {
if (holesForSchains[schainHash][i] == indexOfNode) {
return true;
}
}
return false;
}
/**
* @dev Returns number of Schains on a node.
*/
function getLengthOfSchainsForNode(uint nodeIndex) external view returns (uint) {
return schainsForNodes[nodeIndex].length;
}
function initialize(address newContractsAddress) public override initializer {
Permissions.initialize(newContractsAddress);
numberOfSchains = 0;
sumOfSchainsResources = 0;
numberOfSchainTypes = 5;
}
/**
* @dev Allows Schains and NodeRotation contracts to add schain to node.
*/
function addSchainForNode(uint nodeIndex, bytes32 schainId) public allowTwo("Schains", "NodeRotation") {
if (holesForNodes[nodeIndex].length == 0) {
schainsForNodes[nodeIndex].push(schainId);
placeOfSchainOnNode[schainId][nodeIndex] = schainsForNodes[nodeIndex].length;
} else {
uint lastHoleOfNode = holesForNodes[nodeIndex][holesForNodes[nodeIndex].length - 1];
schainsForNodes[nodeIndex][lastHoleOfNode] = schainId;
placeOfSchainOnNode[schainId][nodeIndex] = lastHoleOfNode + 1;
holesForNodes[nodeIndex].pop();
}
}
/**
* @dev Allows Schains, NodeRotation, and SkaleDKG contracts to remove an
* schain from a node.
*/
function removeSchainForNode(uint nodeIndex, uint schainIndex)
public
allowThree("NodeRotation", "SkaleDKG", "Schains")
{
uint length = schainsForNodes[nodeIndex].length;
if (schainIndex == length.sub(1)) {
schainsForNodes[nodeIndex].pop();
} else {
schainsForNodes[nodeIndex][schainIndex] = bytes32(0);
if (holesForNodes[nodeIndex].length > 0 && holesForNodes[nodeIndex][0] > schainIndex) {
uint hole = holesForNodes[nodeIndex][0];
holesForNodes[nodeIndex][0] = schainIndex;
holesForNodes[nodeIndex].push(hole);
} else {
holesForNodes[nodeIndex].push(schainIndex);
}
}
}
/**
* @dev Returns index of Schain in list of schains for a given node.
*/
function findSchainAtSchainsForNode(uint nodeIndex, bytes32 schainId) public view returns (uint) {
if (placeOfSchainOnNode[schainId][nodeIndex] == 0)
return schainsForNodes[nodeIndex].length;
return placeOfSchainOnNode[schainId][nodeIndex] - 1;
}
function isEnoughNodes(bytes32 schainId) public view returns (uint[] memory result) {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
uint8 space = schains[schainId].partOfNode;
uint[] memory nodesWithFreeSpace = nodes.getNodesWithFreeSpace(space);
uint counter = 0;
for (uint i = 0; i < nodesWithFreeSpace.length; i++) {
if (!_isCorrespond(schainId, nodesWithFreeSpace[i])) {
counter++;
}
}
if (counter < nodesWithFreeSpace.length) {
result = new uint[](nodesWithFreeSpace.length.sub(counter));
counter = 0;
for (uint i = 0; i < nodesWithFreeSpace.length; i++) {
if (_isCorrespond(schainId, nodesWithFreeSpace[i])) {
result[counter] = nodesWithFreeSpace[i];
counter++;
}
}
}
}
/**
* @dev Generates schain group using a pseudo-random generator.
*/
function _generateGroup(bytes32 schainId, uint numberOfNodes) private returns (uint[] memory nodesInGroup) {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
uint8 space = schains[schainId].partOfNode;
nodesInGroup = new uint[](numberOfNodes);
uint[] memory possibleNodes = isEnoughNodes(schainId);
require(possibleNodes.length >= nodesInGroup.length, "Not enough nodes to create Schain");
uint ignoringTail = 0;
uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number.sub(1))), schainId)));
for (uint i = 0; i < nodesInGroup.length; ++i) {
uint index = random % (possibleNodes.length.sub(ignoringTail));
uint node = possibleNodes[index];
nodesInGroup[i] = node;
_swap(possibleNodes, index, possibleNodes.length.sub(ignoringTail).sub(1));
++ignoringTail;
_exceptionsForGroups[schainId][node] = true;
addSchainForNode(node, schainId);
require(nodes.removeSpaceFromNode(node, space), "Could not remove space from Node");
}
// set generated group
schainsGroups[schainId] = nodesInGroup;
}
function _isCorrespond(bytes32 schainId, uint nodeIndex) private view returns (bool) {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
return !_exceptionsForGroups[schainId][nodeIndex] && nodes.isNodeActive(nodeIndex);
}
/**
* @dev Swaps one index for another in an array.
*/
function _swap(uint[] memory array, uint index1, uint index2) private pure {
uint buffer = array[index1];
array[index1] = array[index2];
array[index2] = buffer;
}
/**
* @dev Returns local index of node in schain group.
*/
function _findNode(bytes32 schainId, uint nodeIndex) private view returns (uint) {
uint[] memory nodesInGroup = schainsGroups[schainId];
uint index;
for (index = 0; index < nodesInGroup.length; index++) {
if (nodesInGroup[index] == nodeIndex) {
return index;
}
}
return index;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleVerifier.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "./Permissions.sol";
import "./SchainsInternal.sol";
import "./utils/Precompiled.sol";
import "./utils/FieldOperations.sol";
/**
* @title SkaleVerifier
* @dev Contains verify function to perform BLS signature verification.
*/
contract SkaleVerifier is Permissions {
using Fp2Operations for Fp2Operations.Fp2Point;
/**
* @dev Verifies a BLS signature.
*
* Requirements:
*
* - Signature is in G1.
* - Hash is in G1.
* - G2.one in G2.
* - Public Key in G2.
*/
function verify(
Fp2Operations.Fp2Point calldata signature,
bytes32 hash,
uint counter,
uint hashA,
uint hashB,
G2Operations.G2Point calldata publicKey
)
external
view
returns (bool)
{
require(G1Operations.checkRange(signature), "Signature is not valid");
if (!_checkHashToGroupWithHelper(
hash,
counter,
hashA,
hashB
)
)
{
return false;
}
uint newSignB = G1Operations.negate(signature.b);
require(G1Operations.isG1Point(signature.a, newSignB), "Sign not in G1");
require(G1Operations.isG1Point(hashA, hashB), "Hash not in G1");
G2Operations.G2Point memory g2 = G2Operations.getG2Generator();
require(
G2Operations.isG2(publicKey),
"Public Key not in G2"
);
return Precompiled.bn256Pairing(
signature.a, newSignB,
g2.x.b, g2.x.a, g2.y.b, g2.y.a,
hashA, hashB,
publicKey.x.b, publicKey.x.a, publicKey.y.b, publicKey.y.a
);
}
function initialize(address newContractsAddress) public override initializer {
Permissions.initialize(newContractsAddress);
}
function _checkHashToGroupWithHelper(
bytes32 hash,
uint counter,
uint hashA,
uint hashB
)
private
pure
returns (bool)
{
if (counter > 100) {
return false;
}
uint xCoord = uint(hash) % Fp2Operations.P;
xCoord = (xCoord.add(counter)) % Fp2Operations.P;
uint ySquared = addmod(
mulmod(mulmod(xCoord, xCoord, Fp2Operations.P), xCoord, Fp2Operations.P),
3,
Fp2Operations.P
);
if (hashB < Fp2Operations.P.div(2) || mulmod(hashB, hashB, Fp2Operations.P) != ySquared || xCoord != hashA) {
return false;
}
return true;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
DelegationController.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol";
import "../BountyV2.sol";
import "../Nodes.sol";
import "../Permissions.sol";
import "../utils/FractionUtils.sol";
import "../utils/MathUtils.sol";
import "./DelegationPeriodManager.sol";
import "./PartialDifferences.sol";
import "./Punisher.sol";
import "./TokenLaunchLocker.sol";
import "./TokenState.sol";
import "./ValidatorService.sol";
/**
* @title Delegation Controller
* @dev This contract performs all delegation functions including delegation
* requests, and undelegation, etc.
*
* Delegators and validators may both perform delegations. Validators who perform
* delegations to themselves are effectively self-delegating or self-bonding.
*
* IMPORTANT: Undelegation may be requested at any time, but undelegation is only
* performed at the completion of the current delegation period.
*
* Delegated tokens may be in one of several states:
*
* - PROPOSED: token holder proposes tokens to delegate to a validator.
* - ACCEPTED: token delegations are accepted by a validator and are locked-by-delegation.
* - CANCELED: token holder cancels delegation proposal. Only allowed before the proposal is accepted by the validator.
* - REJECTED: token proposal expires at the UTC start of the next month.
* - DELEGATED: accepted delegations are delegated at the UTC start of the month.
* - UNDELEGATION_REQUESTED: token holder requests delegations to undelegate from the validator.
* - COMPLETED: undelegation request is completed at the end of the delegation period.
*/
contract DelegationController is Permissions, ILocker {
using MathUtils for uint;
using PartialDifferences for PartialDifferences.Sequence;
using PartialDifferences for PartialDifferences.Value;
using FractionUtils for FractionUtils.Fraction;
uint public constant UNDELEGATION_PROHIBITION_WINDOW_SECONDS = 3 * 24 * 60 * 60;
enum State {
PROPOSED,
ACCEPTED,
CANCELED,
REJECTED,
DELEGATED,
UNDELEGATION_REQUESTED,
COMPLETED
}
struct Delegation {
address holder; // address of token owner
uint validatorId;
uint amount;
uint delegationPeriod;
uint created; // time of delegation creation
uint started; // month when a delegation becomes active
uint finished; // first month after a delegation ends
string info;
}
struct SlashingLogEvent {
FractionUtils.Fraction reducingCoefficient;
uint nextMonth;
}
struct SlashingLog {
// month => slashing event
mapping (uint => SlashingLogEvent) slashes;
uint firstMonth;
uint lastMonth;
}
struct DelegationExtras {
uint lastSlashingMonthBeforeDelegation;
}
struct SlashingEvent {
FractionUtils.Fraction reducingCoefficient;
uint validatorId;
uint month;
}
struct SlashingSignal {
address holder;
uint penalty;
}
struct LockedInPending {
uint amount;
uint month;
}
struct FirstDelegationMonth {
// month
uint value;
//validatorId => month
mapping (uint => uint) byValidator;
}
struct ValidatorsStatistics {
// number of validators
uint number;
//validatorId => bool - is Delegated or not
mapping (uint => uint) delegated;
}
/**
* @dev Emitted when a delegation is proposed to a validator.
*/
event DelegationProposed(
uint delegationId
);
/**
* @dev Emitted when a delegation is accepted by a validator.
*/
event DelegationAccepted(
uint delegationId
);
/**
* @dev Emitted when a delegation is cancelled by the delegator.
*/
event DelegationRequestCanceledByUser(
uint delegationId
);
/**
* @dev Emitted when a delegation is requested to undelegate.
*/
event UndelegationRequested(
uint delegationId
);
/// @dev delegations will never be deleted to index in this array may be used like delegation id
Delegation[] public delegations;
// validatorId => delegationId[]
mapping (uint => uint[]) public delegationsByValidator;
// holder => delegationId[]
mapping (address => uint[]) public delegationsByHolder;
// delegationId => extras
mapping(uint => DelegationExtras) private _delegationExtras;
// validatorId => sequence
mapping (uint => PartialDifferences.Value) private _delegatedToValidator;
// validatorId => sequence
mapping (uint => PartialDifferences.Sequence) private _effectiveDelegatedToValidator;
// validatorId => slashing log
mapping (uint => SlashingLog) private _slashesOfValidator;
// holder => sequence
mapping (address => PartialDifferences.Value) private _delegatedByHolder;
// holder => validatorId => sequence
mapping (address => mapping (uint => PartialDifferences.Value)) private _delegatedByHolderToValidator;
// holder => validatorId => sequence
mapping (address => mapping (uint => PartialDifferences.Sequence)) private _effectiveDelegatedByHolderToValidator;
SlashingEvent[] private _slashes;
// holder => index in _slashes;
mapping (address => uint) private _firstUnprocessedSlashByHolder;
// holder => validatorId => month
mapping (address => FirstDelegationMonth) private _firstDelegationMonth;
// holder => locked in pending
mapping (address => LockedInPending) private _lockedInPendingDelegations;
mapping (address => ValidatorsStatistics) private _numberOfValidatorsPerDelegator;
/**
* @dev Modifier to make a function callable only if delegation exists.
*/
modifier checkDelegationExists(uint delegationId) {
require(delegationId < delegations.length, "Delegation does not exist");
_;
}
/**
* @dev Update and return a validator's delegations.
*/
function getAndUpdateDelegatedToValidatorNow(uint validatorId) external returns (uint) {
return _getAndUpdateDelegatedToValidator(validatorId, _getCurrentMonth());
}
/**
* @dev Update and return the amount delegated.
*/
function getAndUpdateDelegatedAmount(address holder) external returns (uint) {
return _getAndUpdateDelegatedByHolder(holder);
}
/**
* @dev Update and return the effective amount delegated (minus slash) for
* the given month.
*/
function getAndUpdateEffectiveDelegatedByHolderToValidator(address holder, uint validatorId, uint month) external
allow("Distributor") returns (uint effectiveDelegated)
{
SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(holder);
effectiveDelegated = _effectiveDelegatedByHolderToValidator[holder][validatorId]
.getAndUpdateValueInSequence(month);
_sendSlashingSignals(slashingSignals);
}
/**
* @dev Allows a token holder to create a delegation proposal of an `amount`
* and `delegationPeriod` to a `validatorId`. Delegation must be accepted
* by the validator before the UTC start of the month, otherwise the
* delegation will be rejected.
*
* The token holder may add additional information in each proposal.
*
* Emits a {DelegationProposed} event.
*
* Requirements:
*
* - Holder must have sufficient delegatable tokens.
* - Delegation must be above the validator's minimum delegation amount.
* - Delegation period must be allowed.
* - Validator must be authorized if trusted list is enabled.
* - Validator must be accepting new delegation requests.
*/
function delegate(
uint validatorId,
uint amount,
uint delegationPeriod,
string calldata info
)
external
{
require(
_getDelegationPeriodManager().isDelegationPeriodAllowed(delegationPeriod),
"This delegation period is not allowed");
_getValidatorService().checkValidatorCanReceiveDelegation(validatorId, amount);
_checkIfDelegationIsAllowed(msg.sender, validatorId);
SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(msg.sender);
uint delegationId = _addDelegation(
msg.sender,
validatorId,
amount,
delegationPeriod,
info);
// check that there is enough money
uint holderBalance = IERC777(contractManager.getSkaleToken()).balanceOf(msg.sender);
uint forbiddenForDelegation = TokenState(contractManager.getTokenState())
.getAndUpdateForbiddenForDelegationAmount(msg.sender);
require(holderBalance >= forbiddenForDelegation, "Token holder does not have enough tokens to delegate");
emit DelegationProposed(delegationId);
_sendSlashingSignals(slashingSignals);
}
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function getAndUpdateLockedAmount(address wallet) external override returns (uint) {
return _getAndUpdateLockedAmount(wallet);
}
/**
* @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}.
*/
function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) {
return _getAndUpdateLockedAmount(wallet);
}
/**
* @dev Allows token holder to cancel a delegation proposal.
*
* Emits a {DelegationRequestCanceledByUser} event.
*
* Requirements:
*
* - `msg.sender` must be the token holder of the delegation proposal.
* - Delegation state must be PROPOSED.
*/
function cancelPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) {
require(msg.sender == delegations[delegationId].holder, "Only token holders can cancel delegation request");
require(getState(delegationId) == State.PROPOSED, "Token holders are only able to cancel PROPOSED delegations");
delegations[delegationId].finished = _getCurrentMonth();
_subtractFromLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount);
emit DelegationRequestCanceledByUser(delegationId);
}
/**
* @dev Allows a validator to accept a proposed delegation.
* Successful acceptance of delegations transition the tokens from a
* PROPOSED state to ACCEPTED, and tokens are locked for the remainder of the
* delegation period.
*
* Emits a {DelegationAccepted} event.
*
* Requirements:
*
* - Validator must be recipient of proposal.
* - Delegation state must be PROPOSED.
*/
function acceptPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) {
require(
_getValidatorService().checkValidatorAddressToId(msg.sender, delegations[delegationId].validatorId),
"No permissions to accept request");
_accept(delegationId);
}
/**
* @dev Allows delegator to undelegate a specific delegation.
*
* Emits UndelegationRequested event.
*
* Requirements:
*
* - `msg.sender` must be the delegator.
* - Delegation state must be DELEGATED.
*/
function requestUndelegation(uint delegationId) external checkDelegationExists(delegationId) {
require(getState(delegationId) == State.DELEGATED, "Cannot request undelegation");
ValidatorService validatorService = _getValidatorService();
require(
delegations[delegationId].holder == msg.sender ||
(validatorService.validatorAddressExists(msg.sender) &&
delegations[delegationId].validatorId == validatorService.getValidatorId(msg.sender)),
"Permission denied to request undelegation");
_removeValidatorFromValidatorsPerDelegators(
delegations[delegationId].holder,
delegations[delegationId].validatorId);
processAllSlashes(msg.sender);
delegations[delegationId].finished = _calculateDelegationEndMonth(delegationId);
require(
now.add(UNDELEGATION_PROHIBITION_WINDOW_SECONDS)
< _getTimeHelpers().monthToTimestamp(delegations[delegationId].finished),
"Undelegation requests must be sent 3 days before the end of delegation period"
);
_subtractFromAllStatistics(delegationId);
emit UndelegationRequested(delegationId);
}
/**
* @dev Allows Punisher contract to slash an `amount` of stake from
* a validator. This slashes an amount of delegations of the validator,
* which reduces the amount that the validator has staked. This consequence
* may force the SKALE Manager to reduce the number of nodes a validator is
* operating so the validator can meet the Minimum Staking Requirement.
*
* Emits a {SlashingEvent}.
*
* See {Punisher}.
*/
function confiscate(uint validatorId, uint amount) external allow("Punisher") {
uint currentMonth = _getCurrentMonth();
FractionUtils.Fraction memory coefficient =
_delegatedToValidator[validatorId].reduceValue(amount, currentMonth);
uint initialEffectiveDelegated =
_effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth);
uint[] memory initialSubtractions = new uint[](0);
if (currentMonth < _effectiveDelegatedToValidator[validatorId].lastChangedMonth) {
initialSubtractions = new uint[](
_effectiveDelegatedToValidator[validatorId].lastChangedMonth.sub(currentMonth)
);
for (uint i = 0; i < initialSubtractions.length; ++i) {
initialSubtractions[i] = _effectiveDelegatedToValidator[validatorId]
.subtractDiff[currentMonth.add(i).add(1)];
}
}
_effectiveDelegatedToValidator[validatorId].reduceSequence(coefficient, currentMonth);
_putToSlashingLog(_slashesOfValidator[validatorId], coefficient, currentMonth);
_slashes.push(SlashingEvent({reducingCoefficient: coefficient, validatorId: validatorId, month: currentMonth}));
BountyV2 bounty = _getBounty();
bounty.handleDelegationRemoving(
initialEffectiveDelegated.sub(
_effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth)
),
currentMonth
);
for (uint i = 0; i < initialSubtractions.length; ++i) {
bounty.handleDelegationAdd(
initialSubtractions[i].sub(
_effectiveDelegatedToValidator[validatorId].subtractDiff[currentMonth.add(i).add(1)]
),
currentMonth.add(i).add(1)
);
}
}
/**
* @dev Allows Distributor contract to return and update the effective
* amount delegated (minus slash) to a validator for a given month.
*/
function getAndUpdateEffectiveDelegatedToValidator(uint validatorId, uint month)
external allowTwo("Bounty", "Distributor") returns (uint)
{
return _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(month);
}
/**
* @dev Return and update the amount delegated to a validator for the
* current month.
*/
function getAndUpdateDelegatedByHolderToValidatorNow(address holder, uint validatorId) external returns (uint) {
return _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, _getCurrentMonth());
}
function getEffectiveDelegatedValuesByValidator(uint validatorId) external view returns (uint[] memory) {
return _effectiveDelegatedToValidator[validatorId].getValuesInSequence();
}
function getEffectiveDelegatedToValidator(uint validatorId, uint month) external view returns (uint) {
return _effectiveDelegatedToValidator[validatorId].getValueInSequence(month);
}
function getDelegatedToValidator(uint validatorId, uint month) external view returns (uint) {
return _delegatedToValidator[validatorId].getValue(month);
}
/**
* @dev Return Delegation struct.
*/
function getDelegation(uint delegationId)
external view checkDelegationExists(delegationId) returns (Delegation memory)
{
return delegations[delegationId];
}
/**
* @dev Returns the first delegation month.
*/
function getFirstDelegationMonth(address holder, uint validatorId) external view returns(uint) {
return _firstDelegationMonth[holder].byValidator[validatorId];
}
/**
* @dev Returns a validator's total number of delegations.
*/
function getDelegationsByValidatorLength(uint validatorId) external view returns (uint) {
return delegationsByValidator[validatorId].length;
}
/**
* @dev Returns a holder's total number of delegations.
*/
function getDelegationsByHolderLength(address holder) external view returns (uint) {
return delegationsByHolder[holder].length;
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
}
/**
* @dev Process slashes up to the given limit.
*/
function processSlashes(address holder, uint limit) public {
_sendSlashingSignals(_processSlashesWithoutSignals(holder, limit));
}
/**
* @dev Process all slashes.
*/
function processAllSlashes(address holder) public {
processSlashes(holder, 0);
}
/**
* @dev Returns the token state of a given delegation.
*/
function getState(uint delegationId) public view checkDelegationExists(delegationId) returns (State state) {
if (delegations[delegationId].started == 0) {
if (delegations[delegationId].finished == 0) {
if (_getCurrentMonth() == _getTimeHelpers().timestampToMonth(delegations[delegationId].created)) {
return State.PROPOSED;
} else {
return State.REJECTED;
}
} else {
return State.CANCELED;
}
} else {
if (_getCurrentMonth() < delegations[delegationId].started) {
return State.ACCEPTED;
} else {
if (delegations[delegationId].finished == 0) {
return State.DELEGATED;
} else {
if (_getCurrentMonth() < delegations[delegationId].finished) {
return State.UNDELEGATION_REQUESTED;
} else {
return State.COMPLETED;
}
}
}
}
}
/**
* @dev Returns the amount of tokens in PENDING delegation state.
*/
function getLockedInPendingDelegations(address holder) public view returns (uint) {
uint currentMonth = _getCurrentMonth();
if (_lockedInPendingDelegations[holder].month < currentMonth) {
return 0;
} else {
return _lockedInPendingDelegations[holder].amount;
}
}
/**
* @dev Checks whether there are any unprocessed slashes.
*/
function hasUnprocessedSlashes(address holder) public view returns (bool) {
return _everDelegated(holder) && _firstUnprocessedSlashByHolder[holder] < _slashes.length;
}
// private
/**
* @dev Allows Nodes contract to get and update the amount delegated
* to validator for a given month.
*/
function _getAndUpdateDelegatedToValidator(uint validatorId, uint month)
private returns (uint)
{
return _delegatedToValidator[validatorId].getAndUpdateValue(month);
}
/**
* @dev Adds a new delegation proposal.
*/
function _addDelegation(
address holder,
uint validatorId,
uint amount,
uint delegationPeriod,
string memory info
)
private
returns (uint delegationId)
{
delegationId = delegations.length;
delegations.push(Delegation(
holder,
validatorId,
amount,
delegationPeriod,
now,
0,
0,
info
));
delegationsByValidator[validatorId].push(delegationId);
delegationsByHolder[holder].push(delegationId);
_addToLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount);
}
/**
* @dev Returns the month when a delegation ends.
*/
function _calculateDelegationEndMonth(uint delegationId) private view returns (uint) {
uint currentMonth = _getCurrentMonth();
uint started = delegations[delegationId].started;
if (currentMonth < started) {
return started.add(delegations[delegationId].delegationPeriod);
} else {
uint completedPeriods = currentMonth.sub(started).div(delegations[delegationId].delegationPeriod);
return started.add(completedPeriods.add(1).mul(delegations[delegationId].delegationPeriod));
}
}
function _addToDelegatedToValidator(uint validatorId, uint amount, uint month) private {
_delegatedToValidator[validatorId].addToValue(amount, month);
}
function _addToEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private {
_effectiveDelegatedToValidator[validatorId].addToSequence(effectiveAmount, month);
}
function _addToDelegatedByHolder(address holder, uint amount, uint month) private {
_delegatedByHolder[holder].addToValue(amount, month);
}
function _addToDelegatedByHolderToValidator(
address holder, uint validatorId, uint amount, uint month) private
{
_delegatedByHolderToValidator[holder][validatorId].addToValue(amount, month);
}
function _addValidatorToValidatorsPerDelegators(address holder, uint validatorId) private {
if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0) {
_numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.add(1);
}
_numberOfValidatorsPerDelegator[holder].
delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].add(1);
}
function _removeFromDelegatedByHolder(address holder, uint amount, uint month) private {
_delegatedByHolder[holder].subtractFromValue(amount, month);
}
function _removeFromDelegatedByHolderToValidator(
address holder, uint validatorId, uint amount, uint month) private
{
_delegatedByHolderToValidator[holder][validatorId].subtractFromValue(amount, month);
}
function _removeValidatorFromValidatorsPerDelegators(address holder, uint validatorId) private {
if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 1) {
_numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.sub(1);
}
_numberOfValidatorsPerDelegator[holder].
delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].sub(1);
}
function _addToEffectiveDelegatedByHolderToValidator(
address holder,
uint validatorId,
uint effectiveAmount,
uint month)
private
{
_effectiveDelegatedByHolderToValidator[holder][validatorId].addToSequence(effectiveAmount, month);
}
function _removeFromEffectiveDelegatedByHolderToValidator(
address holder,
uint validatorId,
uint effectiveAmount,
uint month)
private
{
_effectiveDelegatedByHolderToValidator[holder][validatorId].subtractFromSequence(effectiveAmount, month);
}
function _getAndUpdateDelegatedByHolder(address holder) private returns (uint) {
uint currentMonth = _getCurrentMonth();
processAllSlashes(holder);
return _delegatedByHolder[holder].getAndUpdateValue(currentMonth);
}
function _getAndUpdateDelegatedByHolderToValidator(
address holder,
uint validatorId,
uint month)
private returns (uint)
{
return _delegatedByHolderToValidator[holder][validatorId].getAndUpdateValue(month);
}
function _addToLockedInPendingDelegations(address holder, uint amount) private returns (uint) {
uint currentMonth = _getCurrentMonth();
if (_lockedInPendingDelegations[holder].month < currentMonth) {
_lockedInPendingDelegations[holder].amount = amount;
_lockedInPendingDelegations[holder].month = currentMonth;
} else {
assert(_lockedInPendingDelegations[holder].month == currentMonth);
_lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.add(amount);
}
}
function _subtractFromLockedInPendingDelegations(address holder, uint amount) private returns (uint) {
uint currentMonth = _getCurrentMonth();
assert(_lockedInPendingDelegations[holder].month == currentMonth);
_lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.sub(amount);
}
function _getCurrentMonth() private view returns (uint) {
return _getTimeHelpers().getCurrentMonth();
}
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function _getAndUpdateLockedAmount(address wallet) private returns (uint) {
return _getAndUpdateDelegatedByHolder(wallet).add(getLockedInPendingDelegations(wallet));
}
function _updateFirstDelegationMonth(address holder, uint validatorId, uint month) private {
if (_firstDelegationMonth[holder].value == 0) {
_firstDelegationMonth[holder].value = month;
_firstUnprocessedSlashByHolder[holder] = _slashes.length;
}
if (_firstDelegationMonth[holder].byValidator[validatorId] == 0) {
_firstDelegationMonth[holder].byValidator[validatorId] = month;
}
}
/**
* @dev Checks whether the holder has performed a delegation.
*/
function _everDelegated(address holder) private view returns (bool) {
return _firstDelegationMonth[holder].value > 0;
}
function _removeFromDelegatedToValidator(uint validatorId, uint amount, uint month) private {
_delegatedToValidator[validatorId].subtractFromValue(amount, month);
}
function _removeFromEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private {
_effectiveDelegatedToValidator[validatorId].subtractFromSequence(effectiveAmount, month);
}
/**
* @dev Returns the delegated amount after a slashing event.
*/
function _calculateDelegationAmountAfterSlashing(uint delegationId) private view returns (uint) {
uint startMonth = _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation;
uint validatorId = delegations[delegationId].validatorId;
uint amount = delegations[delegationId].amount;
if (startMonth == 0) {
startMonth = _slashesOfValidator[validatorId].firstMonth;
if (startMonth == 0) {
return amount;
}
}
for (uint i = startMonth;
i > 0 && i < delegations[delegationId].finished;
i = _slashesOfValidator[validatorId].slashes[i].nextMonth) {
if (i >= delegations[delegationId].started) {
amount = amount
.mul(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.numerator)
.div(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.denominator);
}
}
return amount;
}
function _putToSlashingLog(
SlashingLog storage log,
FractionUtils.Fraction memory coefficient,
uint month)
private
{
if (log.firstMonth == 0) {
log.firstMonth = month;
log.lastMonth = month;
log.slashes[month].reducingCoefficient = coefficient;
log.slashes[month].nextMonth = 0;
} else {
require(log.lastMonth <= month, "Cannot put slashing event in the past");
if (log.lastMonth == month) {
log.slashes[month].reducingCoefficient =
log.slashes[month].reducingCoefficient.multiplyFraction(coefficient);
} else {
log.slashes[month].reducingCoefficient = coefficient;
log.slashes[month].nextMonth = 0;
log.slashes[log.lastMonth].nextMonth = month;
log.lastMonth = month;
}
}
}
function _processSlashesWithoutSignals(address holder, uint limit)
private returns (SlashingSignal[] memory slashingSignals)
{
if (hasUnprocessedSlashes(holder)) {
uint index = _firstUnprocessedSlashByHolder[holder];
uint end = _slashes.length;
if (limit > 0 && index.add(limit) < end) {
end = index.add(limit);
}
slashingSignals = new SlashingSignal[](end.sub(index));
uint begin = index;
for (; index < end; ++index) {
uint validatorId = _slashes[index].validatorId;
uint month = _slashes[index].month;
uint oldValue = _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month);
if (oldValue.muchGreater(0)) {
_delegatedByHolderToValidator[holder][validatorId].reduceValueByCoefficientAndUpdateSum(
_delegatedByHolder[holder],
_slashes[index].reducingCoefficient,
month);
_effectiveDelegatedByHolderToValidator[holder][validatorId].reduceSequence(
_slashes[index].reducingCoefficient,
month);
slashingSignals[index.sub(begin)].holder = holder;
slashingSignals[index.sub(begin)].penalty
= oldValue.boundedSub(_getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month));
}
}
_firstUnprocessedSlashByHolder[holder] = end;
}
}
function _processAllSlashesWithoutSignals(address holder)
private returns (SlashingSignal[] memory slashingSignals)
{
return _processSlashesWithoutSignals(holder, 0);
}
function _sendSlashingSignals(SlashingSignal[] memory slashingSignals) private {
Punisher punisher = Punisher(contractManager.getPunisher());
address previousHolder = address(0);
uint accumulatedPenalty = 0;
for (uint i = 0; i < slashingSignals.length; ++i) {
if (slashingSignals[i].holder != previousHolder) {
if (accumulatedPenalty > 0) {
punisher.handleSlash(previousHolder, accumulatedPenalty);
}
previousHolder = slashingSignals[i].holder;
accumulatedPenalty = slashingSignals[i].penalty;
} else {
accumulatedPenalty = accumulatedPenalty.add(slashingSignals[i].penalty);
}
}
if (accumulatedPenalty > 0) {
punisher.handleSlash(previousHolder, accumulatedPenalty);
}
}
function _addToAllStatistics(uint delegationId) private {
uint currentMonth = _getCurrentMonth();
delegations[delegationId].started = currentMonth.add(1);
if (_slashesOfValidator[delegations[delegationId].validatorId].lastMonth > 0) {
_delegationExtras[delegationId].lastSlashingMonthBeforeDelegation =
_slashesOfValidator[delegations[delegationId].validatorId].lastMonth;
}
_addToDelegatedToValidator(
delegations[delegationId].validatorId,
delegations[delegationId].amount,
currentMonth.add(1));
_addToDelegatedByHolder(
delegations[delegationId].holder,
delegations[delegationId].amount,
currentMonth.add(1));
_addToDelegatedByHolderToValidator(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
delegations[delegationId].amount,
currentMonth.add(1));
_updateFirstDelegationMonth(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
currentMonth.add(1));
uint effectiveAmount = delegations[delegationId].amount.mul(
_getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod));
_addToEffectiveDelegatedToValidator(
delegations[delegationId].validatorId,
effectiveAmount,
currentMonth.add(1));
_addToEffectiveDelegatedByHolderToValidator(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
effectiveAmount,
currentMonth.add(1));
_addValidatorToValidatorsPerDelegators(
delegations[delegationId].holder,
delegations[delegationId].validatorId
);
}
function _subtractFromAllStatistics(uint delegationId) private {
uint amountAfterSlashing = _calculateDelegationAmountAfterSlashing(delegationId);
_removeFromDelegatedToValidator(
delegations[delegationId].validatorId,
amountAfterSlashing,
delegations[delegationId].finished);
_removeFromDelegatedByHolder(
delegations[delegationId].holder,
amountAfterSlashing,
delegations[delegationId].finished);
_removeFromDelegatedByHolderToValidator(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
amountAfterSlashing,
delegations[delegationId].finished);
uint effectiveAmount = amountAfterSlashing.mul(
_getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod));
_removeFromEffectiveDelegatedToValidator(
delegations[delegationId].validatorId,
effectiveAmount,
delegations[delegationId].finished);
_removeFromEffectiveDelegatedByHolderToValidator(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
effectiveAmount,
delegations[delegationId].finished);
_getTokenLaunchLocker().handleDelegationRemoving(
delegations[delegationId].holder,
delegationId,
delegations[delegationId].finished);
_getBounty().handleDelegationRemoving(
effectiveAmount,
delegations[delegationId].finished);
}
/**
* @dev Checks whether delegation to a validator is allowed.
*
* Requirements:
*
* - Delegator must not have reached the validator limit.
* - Delegation must be made in or after the first delegation month.
*/
function _checkIfDelegationIsAllowed(address holder, uint validatorId) private view returns (bool) {
require(
_numberOfValidatorsPerDelegator[holder].delegated[validatorId] > 0 ||
(
_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0 &&
_numberOfValidatorsPerDelegator[holder].number < _getConstantsHolder().limitValidatorsPerDelegator()
),
"Limit of validators is reached"
);
}
function _getDelegationPeriodManager() private view returns (DelegationPeriodManager) {
return DelegationPeriodManager(contractManager.getDelegationPeriodManager());
}
function _getBounty() private view returns (BountyV2) {
return BountyV2(contractManager.getBounty());
}
function _getValidatorService() private view returns (ValidatorService) {
return ValidatorService(contractManager.getValidatorService());
}
function _getTimeHelpers() private view returns (TimeHelpers) {
return TimeHelpers(contractManager.getTimeHelpers());
}
function _getTokenLaunchLocker() private view returns (TokenLaunchLocker) {
return TokenLaunchLocker(contractManager.getTokenLaunchLocker());
}
function _getConstantsHolder() private view returns (ConstantsHolder) {
return ConstantsHolder(contractManager.getConstantsHolder());
}
function _accept(uint delegationId) private {
_checkIfDelegationIsAllowed(delegations[delegationId].holder, delegations[delegationId].validatorId);
State currentState = getState(delegationId);
if (currentState != State.PROPOSED) {
if (currentState == State.ACCEPTED ||
currentState == State.DELEGATED ||
currentState == State.UNDELEGATION_REQUESTED ||
currentState == State.COMPLETED)
{
revert("The delegation has been already accepted");
} else if (currentState == State.CANCELED) {
revert("The delegation has been cancelled by token holder");
} else if (currentState == State.REJECTED) {
revert("The delegation request is outdated");
}
}
require(currentState == State.PROPOSED, "Cannot set delegation state to accepted");
SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(delegations[delegationId].holder);
_addToAllStatistics(delegationId);
uint amount = delegations[delegationId].amount;
_getTokenLaunchLocker().handleDelegationAdd(
delegations[delegationId].holder,
delegationId,
amount,
delegations[delegationId].started
);
uint effectiveAmount = amount.mul(
_getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod)
);
_getBounty().handleDelegationAdd(
effectiveAmount,
delegations[delegationId].started
);
_sendSlashingSignals(slashingSignals);
emit DelegationAccepted(delegationId);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
DelegationPeriodManager.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../Permissions.sol";
/**
* @title Delegation Period Manager
* @dev This contract handles all delegation offerings. Delegations are held for
* a specified period (months), and different durations can have different
* returns or `stakeMultiplier`. Currently, only delegation periods can be added.
*/
contract DelegationPeriodManager is Permissions {
mapping (uint => uint) public stakeMultipliers;
/**
* @dev Emitted when a new delegation period is specified.
*/
event DelegationPeriodWasSet(
uint length,
uint stakeMultiplier
);
/**
* @dev Allows the Owner to create a new available delegation period and
* stake multiplier in the network.
*
* Emits a {DelegationPeriodWasSet} event.
*/
function setDelegationPeriod(uint monthsCount, uint stakeMultiplier) external onlyOwner {
require(stakeMultipliers[monthsCount] == 0, "Delegation perios is already set");
stakeMultipliers[monthsCount] = stakeMultiplier;
emit DelegationPeriodWasSet(monthsCount, stakeMultiplier);
}
/**
* @dev Checks whether given delegation period is allowed.
*/
function isDelegationPeriodAllowed(uint monthsCount) external view returns (bool) {
return stakeMultipliers[monthsCount] != 0;
}
/**
* @dev Initial delegation period and multiplier settings.
*/
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
stakeMultipliers[2] = 100; // 2 months at 100
// stakeMultipliers[6] = 150; // 6 months at 150
// stakeMultipliers[12] = 200; // 12 months at 200
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
PartialDifferences.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../utils/MathUtils.sol";
import "../utils/FractionUtils.sol";
/**
* @title Partial Differences Library
* @dev This library contains functions to manage Partial Differences data
* structure. Partial Differences is an array of value differences over time.
*
* For example: assuming an array [3, 6, 3, 1, 2], partial differences can
* represent this array as [_, 3, -3, -2, 1].
*
* This data structure allows adding values on an open interval with O(1)
* complexity.
*
* For example: add +5 to [3, 6, 3, 1, 2] starting from the second element (3),
* instead of performing [3, 6, 3+5, 1+5, 2+5] partial differences allows
* performing [_, 3, -3+5, -2, 1]. The original array can be restored by
* adding values from partial differences.
*/
library PartialDifferences {
using SafeMath for uint;
using MathUtils for uint;
struct Sequence {
// month => diff
mapping (uint => uint) addDiff;
// month => diff
mapping (uint => uint) subtractDiff;
// month => value
mapping (uint => uint) value;
uint firstUnprocessedMonth;
uint lastChangedMonth;
}
struct Value {
// month => diff
mapping (uint => uint) addDiff;
// month => diff
mapping (uint => uint) subtractDiff;
uint value;
uint firstUnprocessedMonth;
uint lastChangedMonth;
}
// functions for sequence
function addToSequence(Sequence storage sequence, uint diff, uint month) internal {
require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past");
if (sequence.firstUnprocessedMonth == 0) {
sequence.firstUnprocessedMonth = month;
}
sequence.addDiff[month] = sequence.addDiff[month].add(diff);
if (sequence.lastChangedMonth != month) {
sequence.lastChangedMonth = month;
}
}
function subtractFromSequence(Sequence storage sequence, uint diff, uint month) internal {
require(sequence.firstUnprocessedMonth <= month, "Cannot subtract from the past");
if (sequence.firstUnprocessedMonth == 0) {
sequence.firstUnprocessedMonth = month;
}
sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff);
if (sequence.lastChangedMonth != month) {
sequence.lastChangedMonth = month;
}
}
function getAndUpdateValueInSequence(Sequence storage sequence, uint month) internal returns (uint) {
if (sequence.firstUnprocessedMonth == 0) {
return 0;
}
if (sequence.firstUnprocessedMonth <= month) {
for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) {
uint nextValue = sequence.value[i.sub(1)].add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]);
if (sequence.value[i] != nextValue) {
sequence.value[i] = nextValue;
}
if (sequence.addDiff[i] > 0) {
delete sequence.addDiff[i];
}
if (sequence.subtractDiff[i] > 0) {
delete sequence.subtractDiff[i];
}
}
sequence.firstUnprocessedMonth = month.add(1);
}
return sequence.value[month];
}
function getValueInSequence(Sequence storage sequence, uint month) internal view returns (uint) {
if (sequence.firstUnprocessedMonth == 0) {
return 0;
}
if (sequence.firstUnprocessedMonth <= month) {
uint value = sequence.value[sequence.firstUnprocessedMonth.sub(1)];
for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) {
value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]);
}
return value;
} else {
return sequence.value[month];
}
}
function getValuesInSequence(Sequence storage sequence) internal view returns (uint[] memory values) {
if (sequence.firstUnprocessedMonth == 0) {
return values;
}
uint begin = sequence.firstUnprocessedMonth.sub(1);
uint end = sequence.lastChangedMonth.add(1);
if (end <= begin) {
end = begin.add(1);
}
values = new uint[](end.sub(begin));
values[0] = sequence.value[sequence.firstUnprocessedMonth.sub(1)];
for (uint i = 0; i.add(1) < values.length; ++i) {
uint month = sequence.firstUnprocessedMonth.add(i);
values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]);
}
}
function reduceSequence(
Sequence storage sequence,
FractionUtils.Fraction memory reducingCoefficient,
uint month) internal
{
require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past");
require(
reducingCoefficient.numerator <= reducingCoefficient.denominator,
"Increasing of values is not implemented");
if (sequence.firstUnprocessedMonth == 0) {
return;
}
uint value = getAndUpdateValueInSequence(sequence, month);
if (value.approximatelyEqual(0)) {
return;
}
sequence.value[month] = sequence.value[month]
.mul(reducingCoefficient.numerator)
.div(reducingCoefficient.denominator);
for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) {
sequence.subtractDiff[i] = sequence.subtractDiff[i]
.mul(reducingCoefficient.numerator)
.div(reducingCoefficient.denominator);
}
}
// functions for value
function addToValue(Value storage sequence, uint diff, uint month) internal {
require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past");
if (sequence.firstUnprocessedMonth == 0) {
sequence.firstUnprocessedMonth = month;
sequence.lastChangedMonth = month;
}
if (month > sequence.lastChangedMonth) {
sequence.lastChangedMonth = month;
}
if (month >= sequence.firstUnprocessedMonth) {
sequence.addDiff[month] = sequence.addDiff[month].add(diff);
} else {
sequence.value = sequence.value.add(diff);
}
}
function subtractFromValue(Value storage sequence, uint diff, uint month) internal {
require(sequence.firstUnprocessedMonth <= month.add(1), "Cannot subtract from the past");
if (sequence.firstUnprocessedMonth == 0) {
sequence.firstUnprocessedMonth = month;
sequence.lastChangedMonth = month;
}
if (month > sequence.lastChangedMonth) {
sequence.lastChangedMonth = month;
}
if (month >= sequence.firstUnprocessedMonth) {
sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff);
} else {
sequence.value = sequence.value.boundedSub(diff);
}
}
function getAndUpdateValue(Value storage sequence, uint month) internal returns (uint) {
require(
month.add(1) >= sequence.firstUnprocessedMonth,
"Cannot calculate value in the past");
if (sequence.firstUnprocessedMonth == 0) {
return 0;
}
if (sequence.firstUnprocessedMonth <= month) {
uint value = sequence.value;
for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) {
value = value.add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]);
if (sequence.addDiff[i] > 0) {
delete sequence.addDiff[i];
}
if (sequence.subtractDiff[i] > 0) {
delete sequence.subtractDiff[i];
}
}
if (sequence.value != value) {
sequence.value = value;
}
sequence.firstUnprocessedMonth = month.add(1);
}
return sequence.value;
}
function getValue(Value storage sequence, uint month) internal view returns (uint) {
require(
month.add(1) >= sequence.firstUnprocessedMonth,
"Cannot calculate value in the past");
if (sequence.firstUnprocessedMonth == 0) {
return 0;
}
if (sequence.firstUnprocessedMonth <= month) {
uint value = sequence.value;
for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) {
value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]);
}
return value;
} else {
return sequence.value;
}
}
function getValues(Value storage sequence) internal view returns (uint[] memory values) {
if (sequence.firstUnprocessedMonth == 0) {
return values;
}
uint begin = sequence.firstUnprocessedMonth.sub(1);
uint end = sequence.lastChangedMonth.add(1);
if (end <= begin) {
end = begin.add(1);
}
values = new uint[](end.sub(begin));
values[0] = sequence.value;
for (uint i = 0; i.add(1) < values.length; ++i) {
uint month = sequence.firstUnprocessedMonth.add(i);
values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]);
}
}
function reduceValue(
Value storage sequence,
uint amount,
uint month)
internal returns (FractionUtils.Fraction memory)
{
require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past");
if (sequence.firstUnprocessedMonth == 0) {
return FractionUtils.createFraction(0);
}
uint value = getAndUpdateValue(sequence, month);
if (value.approximatelyEqual(0)) {
return FractionUtils.createFraction(0);
}
uint _amount = amount;
if (value < amount) {
_amount = value;
}
FractionUtils.Fraction memory reducingCoefficient =
FractionUtils.createFraction(value.boundedSub(_amount), value);
reduceValueByCoefficient(sequence, reducingCoefficient, month);
return reducingCoefficient;
}
function reduceValueByCoefficient(
Value storage sequence,
FractionUtils.Fraction memory reducingCoefficient,
uint month)
internal
{
reduceValueByCoefficientAndUpdateSumIfNeeded(
sequence,
sequence,
reducingCoefficient,
month,
false);
}
function reduceValueByCoefficientAndUpdateSum(
Value storage sequence,
Value storage sumSequence,
FractionUtils.Fraction memory reducingCoefficient,
uint month) internal
{
reduceValueByCoefficientAndUpdateSumIfNeeded(
sequence,
sumSequence,
reducingCoefficient,
month,
true);
}
function reduceValueByCoefficientAndUpdateSumIfNeeded(
Value storage sequence,
Value storage sumSequence,
FractionUtils.Fraction memory reducingCoefficient,
uint month,
bool hasSumSequence) internal
{
require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past");
if (hasSumSequence) {
require(month.add(1) >= sumSequence.firstUnprocessedMonth, "Cannot reduce value in the past");
}
require(
reducingCoefficient.numerator <= reducingCoefficient.denominator,
"Increasing of values is not implemented");
if (sequence.firstUnprocessedMonth == 0) {
return;
}
uint value = getAndUpdateValue(sequence, month);
if (value.approximatelyEqual(0)) {
return;
}
uint newValue = sequence.value.mul(reducingCoefficient.numerator).div(reducingCoefficient.denominator);
if (hasSumSequence) {
subtractFromValue(sumSequence, sequence.value.boundedSub(newValue), month);
}
sequence.value = newValue;
for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) {
uint newDiff = sequence.subtractDiff[i]
.mul(reducingCoefficient.numerator)
.div(reducingCoefficient.denominator);
if (hasSumSequence) {
sumSequence.subtractDiff[i] = sumSequence.subtractDiff[i]
.boundedSub(sequence.subtractDiff[i].boundedSub(newDiff));
}
sequence.subtractDiff[i] = newDiff;
}
}
function clear(Value storage sequence) internal {
for (uint i = sequence.firstUnprocessedMonth; i <= sequence.lastChangedMonth; ++i) {
if (sequence.addDiff[i] > 0) {
delete sequence.addDiff[i];
}
if (sequence.subtractDiff[i] > 0) {
delete sequence.subtractDiff[i];
}
}
if (sequence.value > 0) {
delete sequence.value;
}
if (sequence.firstUnprocessedMonth > 0) {
delete sequence.firstUnprocessedMonth;
}
if (sequence.lastChangedMonth > 0) {
delete sequence.lastChangedMonth;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Punisher.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../Permissions.sol";
import "../interfaces/delegation/ILocker.sol";
import "./ValidatorService.sol";
import "./DelegationController.sol";
/**
* @title Punisher
* @dev This contract handles all slashing and forgiving operations.
*/
contract Punisher is Permissions, ILocker {
// holder => tokens
mapping (address => uint) private _locked;
/**
* @dev Emitted upon slashing condition.
*/
event Slash(
uint validatorId,
uint amount
);
/**
* @dev Emitted upon forgive condition.
*/
event Forgive(
address wallet,
uint amount
);
/**
* @dev Allows SkaleDKG contract to execute slashing on a validator and
* validator's delegations by an `amount` of tokens.
*
* Emits a {Slash} event.
*
* Requirements:
*
* - Validator must exist.
*/
function slash(uint validatorId, uint amount) external allow("SkaleDKG") {
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController"));
require(validatorService.validatorExists(validatorId), "Validator does not exist");
delegationController.confiscate(validatorId, amount);
emit Slash(validatorId, amount);
}
/**
* @dev Allows the Admin to forgive a slashing condition.
*
* Emits a {Forgive} event.
*
* Requirements:
*
* - All slashes must have been processed.
*/
function forgive(address holder, uint amount) external onlyAdmin {
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController"));
require(!delegationController.hasUnprocessedSlashes(holder), "Not all slashes were calculated");
if (amount > _locked[holder]) {
delete _locked[holder];
} else {
_locked[holder] = _locked[holder].sub(amount);
}
emit Forgive(holder, amount);
}
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function getAndUpdateLockedAmount(address wallet) external override returns (uint) {
return _getAndUpdateLockedAmount(wallet);
}
/**
* @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}.
*/
function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) {
return _getAndUpdateLockedAmount(wallet);
}
/**
* @dev Allows DelegationController contract to execute slashing of
* delegations.
*/
function handleSlash(address holder, uint amount) external allow("DelegationController") {
_locked[holder] = _locked[holder].add(amount);
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
}
// private
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function _getAndUpdateLockedAmount(address wallet) private returns (uint) {
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController"));
delegationController.processAllSlashes(wallet);
return _locked[wallet];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
TimeHelpers.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "../thirdparty/BokkyPooBahsDateTimeLibrary.sol";
/**
* @title TimeHelpers
* @dev The contract performs time operations.
*
* These functions are used to calculate monthly and Proof of Use epochs.
*/
contract TimeHelpers {
using SafeMath for uint;
uint constant private _ZERO_YEAR = 2020;
function calculateProofOfUseLockEndTime(uint month, uint lockUpPeriodDays) external view returns (uint timestamp) {
timestamp = BokkyPooBahsDateTimeLibrary.addDays(monthToTimestamp(month), lockUpPeriodDays);
}
function addDays(uint fromTimestamp, uint n) external pure returns (uint) {
return BokkyPooBahsDateTimeLibrary.addDays(fromTimestamp, n);
}
function addMonths(uint fromTimestamp, uint n) external pure returns (uint) {
return BokkyPooBahsDateTimeLibrary.addMonths(fromTimestamp, n);
}
function addYears(uint fromTimestamp, uint n) external pure returns (uint) {
return BokkyPooBahsDateTimeLibrary.addYears(fromTimestamp, n);
}
function getCurrentMonth() external view virtual returns (uint) {
return timestampToMonth(now);
}
function timestampToDay(uint timestamp) external view returns (uint) {
uint wholeDays = timestamp / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY;
uint zeroDay = BokkyPooBahsDateTimeLibrary.timestampFromDate(_ZERO_YEAR, 1, 1) /
BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY;
require(wholeDays >= zeroDay, "Timestamp is too far in the past");
return wholeDays - zeroDay;
}
function timestampToYear(uint timestamp) external view virtual returns (uint) {
uint year;
(year, , ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp);
require(year >= _ZERO_YEAR, "Timestamp is too far in the past");
return year - _ZERO_YEAR;
}
function timestampToMonth(uint timestamp) public view virtual returns (uint) {
uint year;
uint month;
(year, month, ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp);
require(year >= _ZERO_YEAR, "Timestamp is too far in the past");
month = month.sub(1).add(year.sub(_ZERO_YEAR).mul(12));
require(month > 0, "Timestamp is too far in the past");
return month;
}
function monthToTimestamp(uint month) public view virtual returns (uint timestamp) {
uint year = _ZERO_YEAR;
uint _month = month;
year = year.add(_month.div(12));
_month = _month.mod(12);
_month = _month.add(1);
return BokkyPooBahsDateTimeLibrary.timestampFromDate(year, _month, 1);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
TokenLaunchLocker.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../Permissions.sol";
import "../interfaces/delegation/ILocker.sol";
import "../ConstantsHolder.sol";
import "../utils/MathUtils.sol";
import "./DelegationController.sol";
import "./TimeHelpers.sol";
import "./PartialDifferences.sol";
/**
* @title TokenLaunchLocker
* @dev This contract manages lockers applied to the launch process.
*/
contract TokenLaunchLocker is Permissions, ILocker {
using MathUtils for uint;
using PartialDifferences for PartialDifferences.Value;
/**
* @dev Emitted when an `amount` is unlocked.
*/
event Unlocked(
address holder,
uint amount
);
/**
* @dev Emitted when an `amount` is locked.
*/
event Locked(
address holder,
uint amount
);
struct DelegatedAmountAndMonth {
uint delegated;
uint month;
}
// holder => tokens
mapping (address => uint) private _locked;
// holder => tokens
mapping (address => PartialDifferences.Value) private _delegatedAmount;
mapping (address => DelegatedAmountAndMonth) private _totalDelegatedAmount;
// delegationId => tokens
mapping (uint => uint) private _delegationAmount;
/**
* @dev Allows TokenLaunchManager contract to lock an amount of tokens in a
* holder wallet.
*
* Emits a {Locked} event.
*/
function lock(address holder, uint amount) external allow("TokenLaunchManager") {
_locked[holder] = _locked[holder].add(amount);
emit Locked(holder, amount);
}
/**
* @dev Allows DelegationController contract to notify TokenLaunchLocker
* about new delegations.
*/
function handleDelegationAdd(
address holder, uint delegationId, uint amount, uint month)
external allow("DelegationController")
{
if (_locked[holder] > 0) {
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
uint currentMonth = timeHelpers.getCurrentMonth();
uint fromLocked = amount;
uint locked = _locked[holder].boundedSub(_getAndUpdateDelegatedAmount(holder, currentMonth));
if (fromLocked > locked) {
fromLocked = locked;
}
if (fromLocked > 0) {
require(_delegationAmount[delegationId] == 0, "Delegation was already added");
_addToDelegatedAmount(holder, fromLocked, month);
_addToTotalDelegatedAmount(holder, fromLocked, month);
_delegationAmount[delegationId] = fromLocked;
}
}
}
/**
* @dev Allows DelegationController contract to notify TokenLaunchLocker
* about new undelegation requests.
*/
function handleDelegationRemoving(
address holder,
uint delegationId,
uint month)
external allow("DelegationController")
{
if (_delegationAmount[delegationId] > 0) {
if (_locked[holder] > 0) {
_removeFromDelegatedAmount(holder, _delegationAmount[delegationId], month);
}
delete _delegationAmount[delegationId];
}
}
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function getAndUpdateLockedAmount(address wallet) external override returns (uint) {
if (_locked[wallet] > 0) {
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController"));
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
uint currentMonth = timeHelpers.getCurrentMonth();
if (_totalDelegatedSatisfiesProofOfUseCondition(wallet) &&
timeHelpers.calculateProofOfUseLockEndTime(
_totalDelegatedAmount[wallet].month,
constantsHolder.proofOfUseLockUpPeriodDays()
) <= now) {
_unlock(wallet);
return 0;
} else {
uint lockedByDelegationController = _getAndUpdateDelegatedAmount(wallet, currentMonth)
.add(delegationController.getLockedInPendingDelegations(wallet));
if (_locked[wallet] > lockedByDelegationController) {
return _locked[wallet].boundedSub(lockedByDelegationController);
} else {
return 0;
}
}
} else {
return 0;
}
}
/**
* @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}.
*/
function getAndUpdateForbiddenForDelegationAmount(address) external override returns (uint) {
return 0;
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
}
// private
/**
* @dev Returns and updates the current delegated amount.
*/
function _getAndUpdateDelegatedAmount(address holder, uint currentMonth) private returns (uint) {
return _delegatedAmount[holder].getAndUpdateValue(currentMonth);
}
/**
* @dev Adds a delegated amount to the given month.
*/
function _addToDelegatedAmount(address holder, uint amount, uint month) private {
_delegatedAmount[holder].addToValue(amount, month);
}
/**
* @dev Removes a delegated amount from the given month.
*/
function _removeFromDelegatedAmount(address holder, uint amount, uint month) private {
_delegatedAmount[holder].subtractFromValue(amount, month);
}
/**
* @dev Adds the amount to the total delegated for the given month.
*/
function _addToTotalDelegatedAmount(address holder, uint amount, uint month) private {
require(
_totalDelegatedAmount[holder].month == 0 || _totalDelegatedAmount[holder].month <= month,
"Cannot add to total delegated in the past");
// do not update counter if it is big enough
// because it will override month value
if (!_totalDelegatedSatisfiesProofOfUseCondition(holder)) {
_totalDelegatedAmount[holder].delegated = _totalDelegatedAmount[holder].delegated.add(amount);
_totalDelegatedAmount[holder].month = month;
}
}
/**
* @dev Unlocks tokens.
*
* Emits an {Unlocked} event.
*/
function _unlock(address holder) private {
emit Unlocked(holder, _locked[holder]);
delete _locked[holder];
_deleteDelegatedAmount(holder);
_deleteTotalDelegatedAmount(holder);
}
/**
* @dev Deletes the delegated amount.
*/
function _deleteDelegatedAmount(address holder) private {
_delegatedAmount[holder].clear();
}
/**
* @dev Deletes the total delegated amount.
*/
function _deleteTotalDelegatedAmount(address holder) private {
delete _totalDelegatedAmount[holder].delegated;
delete _totalDelegatedAmount[holder].month;
}
/**
* @dev Checks whether total delegated satisfies Proof-of-Use.
*/
function _totalDelegatedSatisfiesProofOfUseCondition(address holder) private view returns (bool) {
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
return _totalDelegatedAmount[holder].delegated.mul(100) >=
_locked[holder].mul(constantsHolder.proofOfUseDelegationPercentage());
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
TokenState.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "../interfaces/delegation/ILocker.sol";
import "../Permissions.sol";
import "./DelegationController.sol";
import "./TimeHelpers.sol";
/**
* @title Token State
* @dev This contract manages lockers to control token transferability.
*
* The SKALE Network has three types of locked tokens:
*
* - Tokens that are transferrable but are currently locked into delegation with
* a validator.
*
* - Tokens that are not transferable from one address to another, but may be
* delegated to a validator `getAndUpdateLockedAmount`. This lock enforces
* Proof-of-Use requirements.
*
* - Tokens that are neither transferable nor delegatable
* `getAndUpdateForbiddenForDelegationAmount`. This lock enforces slashing.
*/
contract TokenState is Permissions, ILocker {
string[] private _lockers;
DelegationController private _delegationController;
/**
* @dev Emitted when a contract is added to the locker.
*/
event LockerWasAdded(
string locker
);
/**
* @dev Emitted when a contract is removed from the locker.
*/
event LockerWasRemoved(
string locker
);
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function getAndUpdateLockedAmount(address holder) external override returns (uint) {
if (address(_delegationController) == address(0)) {
_delegationController =
DelegationController(contractManager.getContract("DelegationController"));
}
uint locked = 0;
if (_delegationController.getDelegationsByHolderLength(holder) > 0) {
// the holder ever delegated
for (uint i = 0; i < _lockers.length; ++i) {
ILocker locker = ILocker(contractManager.getContract(_lockers[i]));
locked = locked.add(locker.getAndUpdateLockedAmount(holder));
}
}
return locked;
}
/**
* @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}.
*/
function getAndUpdateForbiddenForDelegationAmount(address holder) external override returns (uint amount) {
uint forbidden = 0;
for (uint i = 0; i < _lockers.length; ++i) {
ILocker locker = ILocker(contractManager.getContract(_lockers[i]));
forbidden = forbidden.add(locker.getAndUpdateForbiddenForDelegationAmount(holder));
}
return forbidden;
}
/**
* @dev Allows the Owner to remove a contract from the locker.
*
* Emits a {LockerWasRemoved} event.
*/
function removeLocker(string calldata locker) external onlyOwner {
uint index;
bytes32 hash = keccak256(abi.encodePacked(locker));
for (index = 0; index < _lockers.length; ++index) {
if (keccak256(abi.encodePacked(_lockers[index])) == hash) {
break;
}
}
if (index < _lockers.length) {
if (index < _lockers.length.sub(1)) {
_lockers[index] = _lockers[_lockers.length.sub(1)];
}
delete _lockers[_lockers.length.sub(1)];
_lockers.pop();
emit LockerWasRemoved(locker);
}
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
addLocker("DelegationController");
addLocker("Punisher");
addLocker("TokenLaunchLocker");
}
/**
* @dev Allows the Owner to add a contract to the Locker.
*
* Emits a {LockerWasAdded} event.
*/
function addLocker(string memory locker) public onlyOwner {
_lockers.push(locker);
emit LockerWasAdded(locker);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ValidatorService.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
@author Artem Payvin
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/cryptography/ECDSA.sol";
import "../Permissions.sol";
import "../ConstantsHolder.sol";
import "./DelegationController.sol";
import "./TimeHelpers.sol";
/**
* @title ValidatorService
* @dev This contract handles all validator operations including registration,
* node management, validator-specific delegation parameters, and more.
*
* TIP: For more information see our main instructions
* https://forum.skale.network/t/skale-mainnet-launch-faq/182[SKALE MainNet Launch FAQ].
*
* Validators register an address, and use this address to accept delegations and
* register nodes.
*/
contract ValidatorService is Permissions {
using ECDSA for bytes32;
struct Validator {
string name;
address validatorAddress;
address requestedAddress;
string description;
uint feeRate;
uint registrationTime;
uint minimumDelegationAmount;
bool acceptNewRequests;
}
/**
* @dev Emitted when a validator registers.
*/
event ValidatorRegistered(
uint validatorId
);
/**
* @dev Emitted when a validator address changes.
*/
event ValidatorAddressChanged(
uint validatorId,
address newAddress
);
/**
* @dev Emitted when a validator is enabled.
*/
event ValidatorWasEnabled(
uint validatorId
);
/**
* @dev Emitted when a validator is disabled.
*/
event ValidatorWasDisabled(
uint validatorId
);
/**
* @dev Emitted when a node address is linked to a validator.
*/
event NodeAddressWasAdded(
uint validatorId,
address nodeAddress
);
/**
* @dev Emitted when a node address is unlinked from a validator.
*/
event NodeAddressWasRemoved(
uint validatorId,
address nodeAddress
);
mapping (uint => Validator) public validators;
mapping (uint => bool) private _trustedValidators;
uint[] public trustedValidatorsList;
// address => validatorId
mapping (address => uint) private _validatorAddressToId;
// address => validatorId
mapping (address => uint) private _nodeAddressToValidatorId;
// validatorId => nodeAddress[]
mapping (uint => address[]) private _nodeAddresses;
uint public numberOfValidators;
bool public useWhitelist;
modifier checkValidatorExists(uint validatorId) {
require(validatorExists(validatorId), "Validator with such ID does not exist");
_;
}
/**
* @dev Creates a new validator ID that includes a validator name, description,
* commission or fee rate, and a minimum delegation amount accepted by the validator.
*
* Emits a {ValidatorRegistered} event.
*
* Requirements:
*
* - Sender must not already have registered a validator ID.
* - Fee rate must be between 0 - 1000‰. Note: in per mille.
*/
function registerValidator(
string calldata name,
string calldata description,
uint feeRate,
uint minimumDelegationAmount
)
external
returns (uint validatorId)
{
require(!validatorAddressExists(msg.sender), "Validator with such address already exists");
require(feeRate <= 1000, "Fee rate of validator should be lower than 100%");
validatorId = ++numberOfValidators;
validators[validatorId] = Validator(
name,
msg.sender,
address(0),
description,
feeRate,
now,
minimumDelegationAmount,
true
);
_setValidatorAddress(validatorId, msg.sender);
emit ValidatorRegistered(validatorId);
}
/**
* @dev Allows Admin to enable a validator by adding their ID to the
* trusted list.
*
* Emits a {ValidatorWasEnabled} event.
*
* Requirements:
*
* - Validator must not already be enabled.
*/
function enableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin {
require(!_trustedValidators[validatorId], "Validator is already enabled");
_trustedValidators[validatorId] = true;
trustedValidatorsList.push(validatorId);
emit ValidatorWasEnabled(validatorId);
}
/**
* @dev Allows Admin to disable a validator by removing their ID from
* the trusted list.
*
* Emits a {ValidatorWasDisabled} event.
*
* Requirements:
*
* - Validator must not already be disabled.
*/
function disableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin {
require(_trustedValidators[validatorId], "Validator is already disabled");
_trustedValidators[validatorId] = false;
uint position = _find(trustedValidatorsList, validatorId);
if (position < trustedValidatorsList.length) {
trustedValidatorsList[position] =
trustedValidatorsList[trustedValidatorsList.length.sub(1)];
}
trustedValidatorsList.pop();
emit ValidatorWasDisabled(validatorId);
}
/**
* @dev Owner can disable the trusted validator list. Once turned off, the
* trusted list cannot be re-enabled.
*/
function disableWhitelist() external onlyOwner {
useWhitelist = false;
}
/**
* @dev Allows `msg.sender` to request a new address.
*
* Requirements:
*
* - `msg.sender` must already be a validator.
* - New address must not be null.
* - New address must not be already registered as a validator.
*/
function requestForNewAddress(address newValidatorAddress) external {
require(newValidatorAddress != address(0), "New address cannot be null");
require(_validatorAddressToId[newValidatorAddress] == 0, "Address already registered");
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].requestedAddress = newValidatorAddress;
}
/**
* @dev Allows msg.sender to confirm an address change.
*
* Emits a {ValidatorAddressChanged} event.
*
* Requirements:
*
* - Must be owner of new address.
*/
function confirmNewAddress(uint validatorId)
external
checkValidatorExists(validatorId)
{
require(
getValidator(validatorId).requestedAddress == msg.sender,
"The validator address cannot be changed because it is not the actual owner"
);
delete validators[validatorId].requestedAddress;
_setValidatorAddress(validatorId, msg.sender);
emit ValidatorAddressChanged(validatorId, validators[validatorId].validatorAddress);
}
/**
* @dev Links a node address to validator ID. Validator must present
* the node signature of the validator ID.
*
* Requirements:
*
* - Signature must be valid.
* - Address must not be assigned to a validator.
*/
function linkNodeAddress(address nodeAddress, bytes calldata sig) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
require(
keccak256(abi.encodePacked(validatorId)).toEthSignedMessageHash().recover(sig) == nodeAddress,
"Signature is not pass"
);
require(_validatorAddressToId[nodeAddress] == 0, "Node address is a validator");
_addNodeAddress(validatorId, nodeAddress);
emit NodeAddressWasAdded(validatorId, nodeAddress);
}
/**
* @dev Unlinks a node address from a validator.
*
* Emits a {NodeAddressWasRemoved} event.
*/
function unlinkNodeAddress(address nodeAddress) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
this.removeNodeAddress(validatorId, nodeAddress);
emit NodeAddressWasRemoved(validatorId, nodeAddress);
}
/**
* @dev Allows a validator to set a minimum delegation amount.
*/
function setValidatorMDA(uint minimumDelegationAmount) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].minimumDelegationAmount = minimumDelegationAmount;
}
/**
* @dev Allows a validator to set a new validator name.
*/
function setValidatorName(string calldata newName) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].name = newName;
}
/**
* @dev Allows a validator to set a new validator description.
*/
function setValidatorDescription(string calldata newDescription) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].description = newDescription;
}
/**
* @dev Allows a validator to start accepting new delegation requests.
*
* Requirements:
*
* - Must not have already enabled accepting new requests.
*/
function startAcceptingNewRequests() external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
require(!isAcceptingNewRequests(validatorId), "Accepting request is already enabled");
validators[validatorId].acceptNewRequests = true;
}
/**
* @dev Allows a validator to stop accepting new delegation requests.
*
* Requirements:
*
* - Must not have already stopped accepting new requests.
*/
function stopAcceptingNewRequests() external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
require(isAcceptingNewRequests(validatorId), "Accepting request is already disabled");
validators[validatorId].acceptNewRequests = false;
}
function removeNodeAddress(uint validatorId, address nodeAddress) external allowTwo("ValidatorService", "Nodes") {
require(_nodeAddressToValidatorId[nodeAddress] == validatorId,
"Validator does not have permissions to unlink node");
delete _nodeAddressToValidatorId[nodeAddress];
for (uint i = 0; i < _nodeAddresses[validatorId].length; ++i) {
if (_nodeAddresses[validatorId][i] == nodeAddress) {
if (i + 1 < _nodeAddresses[validatorId].length) {
_nodeAddresses[validatorId][i] =
_nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)];
}
delete _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)];
_nodeAddresses[validatorId].pop();
break;
}
}
}
/**
* @dev Returns the amount of validator bond (self-delegation).
*/
function getAndUpdateBondAmount(uint validatorId)
external
returns (uint)
{
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
return delegationController.getAndUpdateDelegatedByHolderToValidatorNow(
getValidator(validatorId).validatorAddress,
validatorId
);
}
/**
* @dev Returns node addresses linked to the msg.sender.
*/
function getMyNodesAddresses() external view returns (address[] memory) {
return getNodeAddresses(getValidatorId(msg.sender));
}
/**
* @dev Returns the list of trusted validators.
*/
function getTrustedValidators() external view returns (uint[] memory) {
return trustedValidatorsList;
}
/**
* @dev Checks whether the validator ID is linked to the validator address.
*/
function checkValidatorAddressToId(address validatorAddress, uint validatorId)
external
view
returns (bool)
{
return getValidatorId(validatorAddress) == validatorId ? true : false;
}
/**
* @dev Returns the validator ID linked to a node address.
*
* Requirements:
*
* - Node address must be linked to a validator.
*/
function getValidatorIdByNodeAddress(address nodeAddress) external view returns (uint validatorId) {
validatorId = _nodeAddressToValidatorId[nodeAddress];
require(validatorId != 0, "Node address is not assigned to a validator");
}
function checkValidatorCanReceiveDelegation(uint validatorId, uint amount) external view {
require(isAuthorizedValidator(validatorId), "Validator is not authorized to accept delegation request");
require(isAcceptingNewRequests(validatorId), "The validator is not currently accepting new requests");
require(
validators[validatorId].minimumDelegationAmount <= amount,
"Amount does not meet the validator's minimum delegation amount"
);
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
useWhitelist = true;
}
/**
* @dev Returns a validator's node addresses.
*/
function getNodeAddresses(uint validatorId) public view returns (address[] memory) {
return _nodeAddresses[validatorId];
}
/**
* @dev Checks whether validator ID exists.
*/
function validatorExists(uint validatorId) public view returns (bool) {
return validatorId <= numberOfValidators && validatorId != 0;
}
/**
* @dev Checks whether validator address exists.
*/
function validatorAddressExists(address validatorAddress) public view returns (bool) {
return _validatorAddressToId[validatorAddress] != 0;
}
/**
* @dev Checks whether validator address exists.
*/
function checkIfValidatorAddressExists(address validatorAddress) public view {
require(validatorAddressExists(validatorAddress), "Validator address does not exist");
}
/**
* @dev Returns the Validator struct.
*/
function getValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (Validator memory) {
return validators[validatorId];
}
/**
* @dev Returns the validator ID for the given validator address.
*/
function getValidatorId(address validatorAddress) public view returns (uint) {
checkIfValidatorAddressExists(validatorAddress);
return _validatorAddressToId[validatorAddress];
}
/**
* @dev Checks whether the validator is currently accepting new delegation requests.
*/
function isAcceptingNewRequests(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) {
return validators[validatorId].acceptNewRequests;
}
function isAuthorizedValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) {
return _trustedValidators[validatorId] || !useWhitelist;
}
// private
/**
* @dev Links a validator address to a validator ID.
*
* Requirements:
*
* - Address is not already in use by another validator.
*/
function _setValidatorAddress(uint validatorId, address validatorAddress) private {
if (_validatorAddressToId[validatorAddress] == validatorId) {
return;
}
require(_validatorAddressToId[validatorAddress] == 0, "Address is in use by another validator");
address oldAddress = validators[validatorId].validatorAddress;
delete _validatorAddressToId[oldAddress];
_nodeAddressToValidatorId[validatorAddress] = validatorId;
validators[validatorId].validatorAddress = validatorAddress;
_validatorAddressToId[validatorAddress] = validatorId;
}
/**
* @dev Links a node address to a validator ID.
*
* Requirements:
*
* - Node address must not be already linked to a validator.
*/
function _addNodeAddress(uint validatorId, address nodeAddress) private {
if (_nodeAddressToValidatorId[nodeAddress] == validatorId) {
return;
}
require(_nodeAddressToValidatorId[nodeAddress] == 0, "Validator cannot override node address");
_nodeAddressToValidatorId[nodeAddress] = validatorId;
_nodeAddresses[validatorId].push(nodeAddress);
}
function _find(uint[] memory array, uint index) private pure returns (uint) {
uint i;
for (i = 0; i < array.length; i++) {
if (array[i] == index) {
return i;
}
}
return array.length;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ISkaleDKG.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
/**
* @dev Interface to {SkaleDKG}.
*/
interface ISkaleDKG {
/**
* @dev See {SkaleDKG-openChannel}.
*/
function openChannel(bytes32 schainId) external;
/**
* @dev See {SkaleDKG-deleteChannel}.
*/
function deleteChannel(bytes32 schainId) external;
/**
* @dev See {SkaleDKG-isLastDKGSuccessful}.
*/
function isLastDKGSuccessful(bytes32 groupIndex) external view returns (bool);
/**
* @dev See {SkaleDKG-isChannelOpened}.
*/
function isChannelOpened(bytes32 schainId) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ILocker.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
/**
* @dev Interface of the Locker functions.
*/
interface ILocker {
/**
* @dev Returns and updates the total amount of locked tokens of a given
* `holder`.
*/
function getAndUpdateLockedAmount(address wallet) external returns (uint);
/**
* @dev Returns and updates the total non-transferrable and un-delegatable
* amount of a given `holder`.
*/
function getAndUpdateForbiddenForDelegationAmount(address wallet) external returns (uint);
}
pragma solidity ^0.6.0;
// ----------------------------------------------------------------------------
// BokkyPooBah's DateTime Library v1.01
//
// A gas-efficient Solidity date and time library
//
// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary
//
// Tested date range 1970/01/01 to 2345/12/31
//
// Conventions:
// Unit | Range | Notes
// :-------- |:-------------:|:-----
// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC
// year | 1970 ... 2345 |
// month | 1 ... 12 |
// day | 1 ... 31 |
// hour | 0 ... 23 |
// minute | 0 ... 59 |
// second | 0 ... 59 |
// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday
//
//
// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.
// ----------------------------------------------------------------------------
library BokkyPooBahsDateTimeLibrary {
uint constant SECONDS_PER_DAY = 24 * 60 * 60;
uint constant SECONDS_PER_HOUR = 60 * 60;
uint constant SECONDS_PER_MINUTE = 60;
int constant OFFSET19700101 = 2440588;
uint constant DOW_MON = 1;
uint constant DOW_TUE = 2;
uint constant DOW_WED = 3;
uint constant DOW_THU = 4;
uint constant DOW_FRI = 5;
uint constant DOW_SAT = 6;
uint constant DOW_SUN = 7;
// ------------------------------------------------------------------------
// Calculate the number of days from 1970/01/01 to year/month/day using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and subtracting the offset 2440588 so that 1970/01/01 is day 0
//
// days = day
// - 32075
// + 1461 * (year + 4800 + (month - 14) / 12) / 4
// + 367 * (month - 2 - (month - 14) / 12 * 12) / 12
// - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4
// - offset
// ------------------------------------------------------------------------
function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) {
require(year >= 1970);
int _year = int(year);
int _month = int(month);
int _day = int(day);
int __days = _day
- 32075
+ 1461 * (_year + 4800 + (_month - 14) / 12) / 4
+ 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12
- 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4
- OFFSET19700101;
_days = uint(__days);
}
// ------------------------------------------------------------------------
// Calculate year/month/day from the number of days since 1970/01/01 using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and adding the offset 2440588 so that 1970/01/01 is day 0
//
// int L = days + 68569 + offset
// int N = 4 * L / 146097
// L = L - (146097 * N + 3) / 4
// year = 4000 * (L + 1) / 1461001
// L = L - 1461 * year / 4 + 31
// month = 80 * L / 2447
// dd = L - 2447 * month / 80
// L = month / 11
// month = month + 2 - 12 * L
// year = 100 * (N - 49) + year + L
// ------------------------------------------------------------------------
function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) {
int __days = int(_days);
int L = __days + 68569 + OFFSET19700101;
int N = 4 * L / 146097;
L = L - (146097 * N + 3) / 4;
int _year = 4000 * (L + 1) / 1461001;
L = L - 1461 * _year / 4 + 31;
int _month = 80 * L / 2447;
int _day = L - 2447 * _month / 80;
L = _month / 11;
_month = _month + 2 - 12 * L;
_year = 100 * (N - 49) + _year + L;
year = uint(_year);
month = uint(_month);
day = uint(_day);
}
function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) {
timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY;
}
function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) {
timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second;
}
function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) {
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) {
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
uint secs = timestamp % SECONDS_PER_DAY;
hour = secs / SECONDS_PER_HOUR;
secs = secs % SECONDS_PER_HOUR;
minute = secs / SECONDS_PER_MINUTE;
second = secs % SECONDS_PER_MINUTE;
}
function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) {
if (year >= 1970 && month > 0 && month <= 12) {
uint daysInMonth = _getDaysInMonth(year, month);
if (day > 0 && day <= daysInMonth) {
valid = true;
}
}
}
function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) {
if (isValidDate(year, month, day)) {
if (hour < 24 && minute < 60 && second < 60) {
valid = true;
}
}
}
function isLeapYear(uint timestamp) internal pure returns (bool leapYear) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
leapYear = _isLeapYear(year);
}
function _isLeapYear(uint year) internal pure returns (bool leapYear) {
leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
function isWeekDay(uint timestamp) internal pure returns (bool weekDay) {
weekDay = getDayOfWeek(timestamp) <= DOW_FRI;
}
function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) {
weekEnd = getDayOfWeek(timestamp) >= DOW_SAT;
}
function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
daysInMonth = _getDaysInMonth(year, month);
}
function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) {
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
daysInMonth = 31;
} else if (month != 2) {
daysInMonth = 30;
} else {
daysInMonth = _isLeapYear(year) ? 29 : 28;
}
}
// 1 = Monday, 7 = Sunday
function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) {
uint _days = timestamp / SECONDS_PER_DAY;
dayOfWeek = (_days + 3) % 7 + 1;
}
function getYear(uint timestamp) internal pure returns (uint year) {
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getMonth(uint timestamp) internal pure returns (uint month) {
uint year;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getDay(uint timestamp) internal pure returns (uint day) {
uint year;
uint month;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getHour(uint timestamp) internal pure returns (uint hour) {
uint secs = timestamp % SECONDS_PER_DAY;
hour = secs / SECONDS_PER_HOUR;
}
function getMinute(uint timestamp) internal pure returns (uint minute) {
uint secs = timestamp % SECONDS_PER_HOUR;
minute = secs / SECONDS_PER_MINUTE;
}
function getSecond(uint timestamp) internal pure returns (uint second) {
second = timestamp % SECONDS_PER_MINUTE;
}
function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
year += _years;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
month += _months;
year += (month - 1) / 12;
month = (month - 1) % 12 + 1;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _days * SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _hours * SECONDS_PER_HOUR;
require(newTimestamp >= timestamp);
}
function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE;
require(newTimestamp >= timestamp);
}
function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _seconds;
require(newTimestamp >= timestamp);
}
function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
year -= _years;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
uint yearMonth = year * 12 + (month - 1) - _months;
year = yearMonth / 12;
month = yearMonth % 12 + 1;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _days * SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _hours * SECONDS_PER_HOUR;
require(newTimestamp <= timestamp);
}
function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE;
require(newTimestamp <= timestamp);
}
function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _seconds;
require(newTimestamp <= timestamp);
}
function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) {
require(fromTimestamp <= toTimestamp);
uint fromYear;
uint fromMonth;
uint fromDay;
uint toYear;
uint toMonth;
uint toDay;
(fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY);
(toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY);
_years = toYear - fromYear;
}
function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) {
require(fromTimestamp <= toTimestamp);
uint fromYear;
uint fromMonth;
uint fromDay;
uint toYear;
uint toMonth;
uint toDay;
(fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY);
(toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY);
_months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;
}
function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) {
require(fromTimestamp <= toTimestamp);
_days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY;
}
function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) {
require(fromTimestamp <= toTimestamp);
_hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR;
}
function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) {
require(fromTimestamp <= toTimestamp);
_minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE;
}
function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) {
require(fromTimestamp <= toTimestamp);
_seconds = toTimestamp - fromTimestamp;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
/*
Modifications Copyright (C) 2018 SKALE Labs
ec.sol by @jbaylina under GPL-3.0 License
*/
/** @file ECDH.sol
* @author Jordi Baylina (@jbaylina)
* @date 2016
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
/**
* @title ECDH
* @dev This contract performs Elliptic-curve Diffie-Hellman key exchange to
* support the DKG process.
*/
contract ECDH {
using SafeMath for uint256;
uint256 constant private _GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798;
uint256 constant private _GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8;
uint256 constant private _N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;
uint256 constant private _A = 0;
function publicKey(uint256 privKey) external pure returns (uint256 qx, uint256 qy) {
uint256 x;
uint256 y;
uint256 z;
(x, y, z) = ecMul(
privKey,
_GX,
_GY,
1
);
z = inverse(z);
qx = mulmod(x, z, _N);
qy = mulmod(y, z, _N);
}
function deriveKey(
uint256 privKey,
uint256 pubX,
uint256 pubY
)
external
pure
returns (uint256 qx, uint256 qy)
{
uint256 x;
uint256 y;
uint256 z;
(x, y, z) = ecMul(
privKey,
pubX,
pubY,
1
);
z = inverse(z);
qx = mulmod(x, z, _N);
qy = mulmod(y, z, _N);
}
function jAdd(
uint256 x1,
uint256 z1,
uint256 x2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 z3)
{
(x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(x2, z1, _N), _N), mulmod(z1, z2, _N));
}
function jSub(
uint256 x1,
uint256 z1,
uint256 x2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 z3)
{
(x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(_N.sub(x2), z1, _N), _N), mulmod(z1, z2, _N));
}
function jMul(
uint256 x1,
uint256 z1,
uint256 x2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 z3)
{
(x3, z3) = (mulmod(x1, x2, _N), mulmod(z1, z2, _N));
}
function jDiv(
uint256 x1,
uint256 z1,
uint256 x2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 z3)
{
(x3, z3) = (mulmod(x1, z2, _N), mulmod(z1, x2, _N));
}
function inverse(uint256 a) public pure returns (uint256 invA) {
require(a > 0 && a < _N, "Input is incorrect");
uint256 t = 0;
uint256 newT = 1;
uint256 r = _N;
uint256 newR = a;
uint256 q;
while (newR != 0) {
q = r.div(newR);
(t, newT) = (newT, addmod(t, (_N.sub(mulmod(q, newT, _N))), _N));
(r, newR) = (newR, r % newR);
}
return t;
}
function ecAdd(
uint256 x1,
uint256 y1,
uint256 z1,
uint256 x2,
uint256 y2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 y3, uint256 z3)
{
uint256 ln;
uint256 lz;
uint256 da;
uint256 db;
// we use (0 0 1) as zero point, z always equal 1
if ((x1 == 0) && (y1 == 0)) {
return (x2, y2, z2);
}
// we use (0 0 1) as zero point, z always equal 1
if ((x2 == 0) && (y2 == 0)) {
return (x1, y1, z1);
}
if ((x1 == x2) && (y1 == y2)) {
(ln, lz) = jMul(x1, z1, x1, z1);
(ln, lz) = jMul(ln,lz,3,1);
(ln, lz) = jAdd(ln,lz,_A,1);
(da, db) = jMul(y1,z1,2,1);
} else {
(ln, lz) = jSub(y2,z2,y1,z1);
(da, db) = jSub(x2,z2,x1,z1);
}
(ln, lz) = jDiv(ln,lz,da,db);
(x3, da) = jMul(ln,lz,ln,lz);
(x3, da) = jSub(x3,da,x1,z1);
(x3, da) = jSub(x3,da,x2,z2);
(y3, db) = jSub(x1,z1,x3,da);
(y3, db) = jMul(y3,db,ln,lz);
(y3, db) = jSub(y3,db,y1,z1);
if (da != db) {
x3 = mulmod(x3, db, _N);
y3 = mulmod(y3, da, _N);
z3 = mulmod(da, db, _N);
} else {
z3 = da;
}
}
function ecDouble(
uint256 x1,
uint256 y1,
uint256 z1
)
public
pure
returns (uint256 x3, uint256 y3, uint256 z3)
{
(x3, y3, z3) = ecAdd(
x1,
y1,
z1,
x1,
y1,
z1
);
}
function ecMul(
uint256 d,
uint256 x1,
uint256 y1,
uint256 z1
)
public
pure
returns (uint256 x3, uint256 y3, uint256 z3)
{
uint256 remaining = d;
uint256 px = x1;
uint256 py = y1;
uint256 pz = z1;
uint256 acx = 0;
uint256 acy = 0;
uint256 acz = 1;
if (d == 0) {
return (0, 0, 1);
}
while (remaining != 0) {
if ((remaining & 1) != 0) {
(acx, acy, acz) = ecAdd(
acx,
acy,
acz,
px,
py,
pz
);
}
remaining = remaining.div(2);
(px, py, pz) = ecDouble(px, py, pz);
}
(x3, y3, z3) = (acx, acy, acz);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
FieldOperations.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "./Precompiled.sol";
library Fp2Operations {
using SafeMath for uint;
struct Fp2Point {
uint a;
uint b;
}
uint constant public P = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
function addFp2(Fp2Point memory value1, Fp2Point memory value2) internal pure returns (Fp2Point memory) {
return Fp2Point({ a: addmod(value1.a, value2.a, P), b: addmod(value1.b, value2.b, P) });
}
function scalarMulFp2(Fp2Point memory value, uint scalar) internal pure returns (Fp2Point memory) {
return Fp2Point({ a: mulmod(scalar, value.a, P), b: mulmod(scalar, value.b, P) });
}
function minusFp2(Fp2Point memory diminished, Fp2Point memory subtracted) internal pure
returns (Fp2Point memory difference)
{
uint p = P;
if (diminished.a >= subtracted.a) {
difference.a = addmod(diminished.a, p - subtracted.a, p);
} else {
difference.a = (p - addmod(subtracted.a, p - diminished.a, p)).mod(p);
}
if (diminished.b >= subtracted.b) {
difference.b = addmod(diminished.b, p - subtracted.b, p);
} else {
difference.b = (p - addmod(subtracted.b, p - diminished.b, p)).mod(p);
}
}
function mulFp2(
Fp2Point memory value1,
Fp2Point memory value2
)
internal
pure
returns (Fp2Point memory result)
{
uint p = P;
Fp2Point memory point = Fp2Point({
a: mulmod(value1.a, value2.a, p),
b: mulmod(value1.b, value2.b, p)});
result.a = addmod(
point.a,
mulmod(p - 1, point.b, p),
p);
result.b = addmod(
mulmod(
addmod(value1.a, value1.b, p),
addmod(value2.a, value2.b, p),
p),
p - addmod(point.a, point.b, p),
p);
}
function squaredFp2(Fp2Point memory value) internal pure returns (Fp2Point memory) {
uint p = P;
uint ab = mulmod(value.a, value.b, p);
uint mult = mulmod(addmod(value.a, value.b, p), addmod(value.a, mulmod(p - 1, value.b, p), p), p);
return Fp2Point({ a: mult, b: addmod(ab, ab, p) });
}
function inverseFp2(Fp2Point memory value) internal view returns (Fp2Point memory result) {
uint p = P;
uint t0 = mulmod(value.a, value.a, p);
uint t1 = mulmod(value.b, value.b, p);
uint t2 = mulmod(p - 1, t1, p);
if (t0 >= t2) {
t2 = addmod(t0, p - t2, p);
} else {
t2 = (p - addmod(t2, p - t0, p)).mod(p);
}
uint t3 = Precompiled.bigModExp(t2, p - 2, p);
result.a = mulmod(value.a, t3, p);
result.b = (p - mulmod(value.b, t3, p)).mod(p);
}
function isEqual(
Fp2Point memory value1,
Fp2Point memory value2
)
internal
pure
returns (bool)
{
return value1.a == value2.a && value1.b == value2.b;
}
}
library G1Operations {
using SafeMath for uint;
using Fp2Operations for Fp2Operations.Fp2Point;
function getG1Generator() internal pure returns (Fp2Operations.Fp2Point memory) {
// Current solidity version does not support Constants of non-value type
// so we implemented this function
return Fp2Operations.Fp2Point({
a: 1,
b: 2
});
}
function isG1Point(uint x, uint y) internal pure returns (bool) {
uint p = Fp2Operations.P;
return mulmod(y, y, p) ==
addmod(mulmod(mulmod(x, x, p), x, p), 3, p);
}
function isG1(Fp2Operations.Fp2Point memory point) internal pure returns (bool) {
return isG1Point(point.a, point.b);
}
function checkRange(Fp2Operations.Fp2Point memory point) internal pure returns (bool) {
return point.a < Fp2Operations.P && point.b < Fp2Operations.P;
}
function negate(uint y) internal pure returns (uint) {
return Fp2Operations.P.sub(y).mod(Fp2Operations.P);
}
}
library G2Operations {
using SafeMath for uint;
using Fp2Operations for Fp2Operations.Fp2Point;
struct G2Point {
Fp2Operations.Fp2Point x;
Fp2Operations.Fp2Point y;
}
function getTWISTB() internal pure returns (Fp2Operations.Fp2Point memory) {
// Current solidity version does not support Constants of non-value type
// so we implemented this function
return Fp2Operations.Fp2Point({
a: 19485874751759354771024239261021720505790618469301721065564631296452457478373,
b: 266929791119991161246907387137283842545076965332900288569378510910307636690
});
}
function getG2Generator() internal pure returns (G2Point memory) {
// Current solidity version does not support Constants of non-value type
// so we implemented this function
return G2Point({
x: Fp2Operations.Fp2Point({
a: 10857046999023057135944570762232829481370756359578518086990519993285655852781,
b: 11559732032986387107991004021392285783925812861821192530917403151452391805634
}),
y: Fp2Operations.Fp2Point({
a: 8495653923123431417604973247489272438418190587263600148770280649306958101930,
b: 4082367875863433681332203403145435568316851327593401208105741076214120093531
})
});
}
function getG2Zero() internal pure returns (G2Point memory) {
// Current solidity version does not support Constants of non-value type
// so we implemented this function
return G2Point({
x: Fp2Operations.Fp2Point({
a: 0,
b: 0
}),
y: Fp2Operations.Fp2Point({
a: 1,
b: 0
})
});
}
function isG2Point(Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y) internal pure returns (bool) {
if (isG2ZeroPoint(x, y)) {
return true;
}
Fp2Operations.Fp2Point memory squaredY = y.squaredFp2();
Fp2Operations.Fp2Point memory res = squaredY.minusFp2(
x.squaredFp2().mulFp2(x)
).minusFp2(getTWISTB());
return res.a == 0 && res.b == 0;
}
function isG2(G2Point memory value) internal pure returns (bool) {
return isG2Point(value.x, value.y);
}
function isG2ZeroPoint(
Fp2Operations.Fp2Point memory x,
Fp2Operations.Fp2Point memory y
)
internal
pure
returns (bool)
{
return x.a == 0 && x.b == 0 && y.a == 1 && y.b == 0;
}
function isG2Zero(G2Point memory value) internal pure returns (bool) {
return value.x.a == 0 && value.x.b == 0 && value.y.a == 1 && value.y.b == 0;
// return isG2ZeroPoint(value.x, value.y);
}
function addG2(
G2Point memory value1,
G2Point memory value2
)
internal
view
returns (G2Point memory sum)
{
if (isG2Zero(value1)) {
return value2;
}
if (isG2Zero(value2)) {
return value1;
}
if (isEqual(value1, value2)) {
return doubleG2(value1);
}
Fp2Operations.Fp2Point memory s = value2.y.minusFp2(value1.y).mulFp2(value2.x.minusFp2(value1.x).inverseFp2());
sum.x = s.squaredFp2().minusFp2(value1.x.addFp2(value2.x));
sum.y = value1.y.addFp2(s.mulFp2(sum.x.minusFp2(value1.x)));
uint p = Fp2Operations.P;
sum.y.a = (p - sum.y.a).mod(p);
sum.y.b = (p - sum.y.b).mod(p);
}
function isEqual(
G2Point memory value1,
G2Point memory value2
)
internal
pure
returns (bool)
{
return value1.x.isEqual(value2.x) && value1.y.isEqual(value2.y);
}
function doubleG2(G2Point memory value)
internal
view
returns (G2Point memory result)
{
if (isG2Zero(value)) {
return value;
} else {
Fp2Operations.Fp2Point memory s =
value.x.squaredFp2().scalarMulFp2(3).mulFp2(value.y.scalarMulFp2(2).inverseFp2());
result.x = s.squaredFp2().minusFp2(value.x.addFp2(value.x));
result.y = value.y.addFp2(s.mulFp2(result.x.minusFp2(value.x)));
uint p = Fp2Operations.P;
result.y.a = (p - result.y.a).mod(p);
result.y.b = (p - result.y.b).mod(p);
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
FractionUtils.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
library FractionUtils {
using SafeMath for uint;
struct Fraction {
uint numerator;
uint denominator;
}
function createFraction(uint numerator, uint denominator) internal pure returns (Fraction memory) {
require(denominator > 0, "Division by zero");
Fraction memory fraction = Fraction({numerator: numerator, denominator: denominator});
reduceFraction(fraction);
return fraction;
}
function createFraction(uint value) internal pure returns (Fraction memory) {
return createFraction(value, 1);
}
function reduceFraction(Fraction memory fraction) internal pure {
uint _gcd = gcd(fraction.numerator, fraction.denominator);
fraction.numerator = fraction.numerator.div(_gcd);
fraction.denominator = fraction.denominator.div(_gcd);
}
// numerator - is limited by 7*10^27, we could multiply it numerator * numerator - it would less than 2^256-1
function multiplyFraction(Fraction memory a, Fraction memory b) internal pure returns (Fraction memory) {
return createFraction(a.numerator.mul(b.numerator), a.denominator.mul(b.denominator));
}
function gcd(uint a, uint b) internal pure returns (uint) {
uint _a = a;
uint _b = b;
if (_b > _a) {
(_a, _b) = swap(_a, _b);
}
while (_b > 0) {
_a = _a.mod(_b);
(_a, _b) = swap (_a, _b);
}
return _a;
}
function swap(uint a, uint b) internal pure returns (uint, uint) {
return (b, a);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
StringUtils.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
library MathUtils {
uint constant private _EPS = 1e6;
event UnderflowError(
uint a,
uint b
);
function boundedSub(uint256 a, uint256 b) internal returns (uint256) {
if (a >= b) {
return a - b;
} else {
emit UnderflowError(a, b);
return 0;
}
}
function boundedSubWithoutEvent(uint256 a, uint256 b) internal pure returns (uint256) {
if (a >= b) {
return a - b;
} else {
return 0;
}
}
function muchGreater(uint256 a, uint256 b) internal pure returns (bool) {
assert(uint(-1) - _EPS > b);
return a > b + _EPS;
}
function approximatelyEqual(uint256 a, uint256 b) internal pure returns (bool) {
if (a > b) {
return a - b < _EPS;
} else {
return b - a < _EPS;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Precompiled.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
library Precompiled {
function bigModExp(uint base, uint power, uint modulus) internal view returns (uint) {
uint[6] memory inputToBigModExp;
inputToBigModExp[0] = 32;
inputToBigModExp[1] = 32;
inputToBigModExp[2] = 32;
inputToBigModExp[3] = base;
inputToBigModExp[4] = power;
inputToBigModExp[5] = modulus;
uint[1] memory out;
bool success;
// solhint-disable-next-line no-inline-assembly
assembly {
success := staticcall(not(0), 5, inputToBigModExp, mul(6, 0x20), out, 0x20)
}
require(success, "BigModExp failed");
return out[0];
}
function bn256ScalarMul(uint x, uint y, uint k) internal view returns (uint , uint ) {
uint[3] memory inputToMul;
uint[2] memory output;
inputToMul[0] = x;
inputToMul[1] = y;
inputToMul[2] = k;
bool success;
// solhint-disable-next-line no-inline-assembly
assembly {
success := staticcall(not(0), 7, inputToMul, 0x60, output, 0x40)
}
require(success, "Multiplication failed");
return (output[0], output[1]);
}
function bn256Pairing(
uint x1,
uint y1,
uint a1,
uint b1,
uint c1,
uint d1,
uint x2,
uint y2,
uint a2,
uint b2,
uint c2,
uint d2)
internal view returns (bool)
{
bool success;
uint[12] memory inputToPairing;
inputToPairing[0] = x1;
inputToPairing[1] = y1;
inputToPairing[2] = a1;
inputToPairing[3] = b1;
inputToPairing[4] = c1;
inputToPairing[5] = d1;
inputToPairing[6] = x2;
inputToPairing[7] = y2;
inputToPairing[8] = a2;
inputToPairing[9] = b2;
inputToPairing[10] = c2;
inputToPairing[11] = d2;
uint[1] memory out;
// solhint-disable-next-line no-inline-assembly
assembly {
success := staticcall(not(0), 8, inputToPairing, mul(12, 0x20), out, 0x20)
}
require(success, "Pairing check failed");
return out[0] != 0;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
StringUtils.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
library StringUtils {
using SafeMath for uint;
function strConcat(string memory a, string memory b) internal pure returns (string memory) {
bytes memory _ba = bytes(a);
bytes memory _bb = bytes(b);
string memory ab = new string(_ba.length.add(_bb.length));
bytes memory strBytes = bytes(ab);
uint k = 0;
uint i = 0;
for (i = 0; i < _ba.length; i++) {
strBytes[k++] = _ba[i];
}
for (i = 0; i < _bb.length; i++) {
strBytes[k++] = _bb[i];
}
return string(strBytes);
}
}
pragma solidity ^0.6.0;
import "../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.
*/
contract ContextUpgradeSafe is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __Context_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;
}
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
pragma solidity ^0.6.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../GSN/Context.sol";
import "../Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, _msgSender()));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*/
abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
pragma solidity ^0.6.0;
import "../GSN/Context.sol";
import "../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.
*/
contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe {
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;
}
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));
}
}
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC777Token standard as defined in the EIP.
*
* This contract uses the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let
* token holders and recipients react to token movements by using setting implementers
* for the associated interfaces in said registry. See {IERC1820Registry} and
* {ERC1820Implementer}.
*/
interface IERC777 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the smallest part of the token that is not divisible. This
* means all token operations (creation, movement and destruction) must have
* amounts that are a multiple of this number.
*
* For most token contracts, this value will equal 1.
*/
function granularity() external view returns (uint256);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by an account (`owner`).
*/
function balanceOf(address owner) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* If send or receive hooks are registered for the caller and `recipient`,
* the corresponding functions will be called with `data` and empty
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function send(address recipient, uint256 amount, bytes calldata data) external;
/**
* @dev Destroys `amount` tokens from the caller's account, reducing the
* total supply.
*
* If a send hook is registered for the caller, the corresponding function
* will be called with `data` and empty `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
*/
function burn(uint256 amount, bytes calldata data) external;
/**
* @dev Returns true if an account is an operator of `tokenHolder`.
* Operators can send and burn tokens on behalf of their owners. All
* accounts are their own operator.
*
* See {operatorSend} and {operatorBurn}.
*/
function isOperatorFor(address operator, address tokenHolder) external view returns (bool);
/**
* @dev Make an account an operator of the caller.
*
* See {isOperatorFor}.
*
* Emits an {AuthorizedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function authorizeOperator(address operator) external;
/**
* @dev Revoke an account's operator status for the caller.
*
* See {isOperatorFor} and {defaultOperators}.
*
* Emits a {RevokedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function revokeOperator(address operator) external;
/**
* @dev Returns the list of default operators. These accounts are operators
* for all token holders, even if {authorizeOperator} was never called on
* them.
*
* This list is immutable, but individual holders may revoke these via
* {revokeOperator}, in which case {isOperatorFor} will return false.
*/
function defaultOperators() external view returns (address[] memory);
/**
* @dev Moves `amount` tokens from `sender` to `recipient`. The caller must
* be an operator of `sender`.
*
* If send or receive hooks are registered for `sender` and `recipient`,
* the corresponding functions will be called with `data` and
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - `sender` cannot be the zero address.
* - `sender` must have at least `amount` tokens.
* - the caller must be an operator for `sender`.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
/**
* @dev Destroys `amount` tokens from `account`, reducing the total supply.
* The caller must be an operator of `account`.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `data` and `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
* - the caller must be an operator for `account`.
*/
function operatorBurn(
address account,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
event Sent(
address indexed operator,
address indexed from,
address indexed to,
uint256 amount,
bytes data,
bytes operatorData
);
event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData);
event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
}
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
pragma solidity ^0.6.0;
/**
* @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);
}
}
pragma solidity ^0.6.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = byte(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
|
Interface to {SkaleDKG}./
|
interface ISkaleDKG {
function openChannel(bytes32 schainId) external;
function deleteChannel(bytes32 schainId) external;
function isLastDKGSuccessful(bytes32 groupIndex) external view returns (bool);
function isChannelOpened(bytes32 schainId) external view returns (bool);
ISkaleDKG.sol - SKALE Manager
}
| 401,498
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import './ERC721Burnable.sol';
/**
* @title Puppy contract
* @dev Extends ERC721 Non-Fungible Token Standard basic implementation
*/
interface IDogePound {
function ownerOf(uint256 tokenId) external view returns (address);
}
contract Puppy is ERC721Burnable {
using SafeMath for uint256;
IDogePound public dogePound = IDogePound(0xF4ee95274741437636e748DdAc70818B4ED7d043);
uint256 public maxToMint;
string public PROVENANCE_HASH = "";
uint256 breedIndex = 10000;
bool public mintIsActive;
bool public breedByDoggoIsActive;
address public breedFeeWallet;
uint256 public breedFeePct;
mapping (bytes32 => bool) public digestUsed;
string public constant sname = "Puppy Contract";
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the breed struct used by the contract
bytes32 public constant BREED_TYPEHASH = keccak256("Breed(address doggoOwner,uint256 doggoId,address dogeOwner,uint256 dogeId,uint256 breedPrice,uint256 deadline)");
event Mint (uint256 indexed puppyId);
event ReserveByOwner (uint256 indexed puppyId);
event BreedByDoggo (uint256 indexed puppyId,
address indexed doggoOwner,
uint256 doggoId,
address indexed dogeOwner,
uint256 dogeId,
uint256 breedPrice,
uint256 breedTime);
event BreedByOwner (uint256 indexed puppyId,
address indexed doggoOwner,
uint256 doggoId,
address indexed dogeOwner,
uint256 dogeId,
uint256 breedPrice,
uint256 breedTime);
event BreedModeUpdated (bool breedByDoggoIsActive);
event BreedFeePctUpdated (uint256 breedFeePct);
constructor() ERC721("The Doge Pound Puppies", "PUPPY") {
maxToMint = 20;
mintIsActive = false;
breedByDoggoIsActive = false;
breedFeeWallet = 0xeE41417780eB5AD0533105A13C85Eae1991AA10E;
breedFeePct = 20;
}
/**
* Get the array of token for owner.
*/
function tokensOfOwner(address _owner) external view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
for (uint256 index; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
/**
* Check if certain token id is exists.
*/
function exists(uint256 _tokenId) public view returns (bool) {
return _exists(_tokenId);
}
/**
* Mint Puppy by Owner
*/
function breedPuppyByOwner (address doggoOwner,
uint256 doggoId,
address dogeOwner,
uint256 dogeId,
uint256 breedPrice) external onlyOwner {
require(mintIsActive, "Mint is not enable now.");
require(doggoOwner != address(0), "Invalid doggo address.");
require(dogeOwner != address(0), "Invalid doge address.");
_safeMint(doggoOwner, breedIndex);
emit BreedByOwner (breedIndex,
doggoOwner,
doggoId,
dogeOwner,
dogeId,
breedPrice,
block.timestamp);
breedIndex = breedIndex + 1;
}
/**
* Mint Puppy by Doggo
*/
function breedPuppyByDoggo (address doggoOwner,
uint256 doggoId,
address dogeOwner,
uint256 dogeId,
uint256 breedPrice,
uint256 deadline,
uint8 v, bytes32 r, bytes32 s) payable external {
require(mintIsActive, "Mint is not enable now.");
require(breedByDoggoIsActive, "Breed is not enable by doggo.");
require(doggoOwner != address(0) && msg.sender == doggoOwner, "Invalid doggo address.");
require(dogeOwner != address(0), "Invalid doge address.");
require(block.timestamp <= deadline, "Passed deadline.");
require(msg.value >= breedPrice, "Passed deadline.");
// check sign with signKey
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(sname)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(BREED_TYPEHASH, doggoOwner, doggoId, dogeOwner, dogeId, breedPrice, deadline));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(!digestUsed[digest], "This signature was already used to breed.");
require(signatory == owner(), "Puppy::breedPuppyByDoggo: invalid signature");
_safeMint(doggoOwner, breedIndex);
emit BreedByDoggo (breedIndex,
doggoOwner,
doggoId,
dogeOwner,
dogeId,
breedPrice,
block.timestamp);
breedIndex = breedIndex + 1;
digestUsed[digest] = true;
uint256 breedFee = breedPrice.mul(breedFeePct).div(100);
uint256 breedValueForDoge = breedPrice.sub(breedFee);
if(breedValueForDoge > 0)
payable(dogeOwner).transfer(breedValueForDoge);
}
/**
* Mint Puppy by OGDoge holders
*/
function mintPuppy(uint256[] memory ogDogeList) external {
require(mintIsActive, "Mint is not enable now.");
require(ogDogeList.length <= maxToMint, "Mint amount is bigger than max limit.");
for(uint256 i = 0; i < ogDogeList.length; i++) {
require(msg.sender == dogePound.ownerOf(ogDogeList[i]), "Invalid ogdoge id.");
require(!exists(ogDogeList[i]), "The puppy already minted.");
_safeMint(msg.sender, ogDogeList[i]);
emit Mint(ogDogeList[i]);
}
}
/**
* Mint Puppy by Owner
*/
function reservePuppyByOwner(address _to, uint256 _count) external onlyOwner {
require(mintIsActive, "Mint is not enable now.");
require(_count <= maxToMint, "Mint count is bigger than maxToMint.");
uint256 puppyId = breedIndex;
for(uint256 i = 0; i < _count; i++) {
_safeMint(_to, puppyId);
emit ReserveByOwner(puppyId);
puppyId = puppyId + 1;
}
breedIndex = puppyId;
}
function reserveBurnedPuppies(address _to, uint256 number) external onlyOwner {
require(mintIsActive, "Mint is not enable now.");
require(!exists(number), "The puppy already minted.");
_safeMint(_to, number);
emit Mint(number);
}
function getChainId() internal view returns (uint) {
uint chainId;
assembly { chainId := chainid() }
return chainId;
}
/**
* Set maximum count to mint per once.
*/
function setMaxToMint(uint256 _maxValue) external onlyOwner {
maxToMint = _maxValue;
}
/*
* Set provenance once it's calculated
*/
function setProvenanceHash(string memory _provenanceHash) external onlyOwner {
PROVENANCE_HASH = _provenanceHash;
}
function setBaseURI(string memory baseURI) external onlyOwner {
_setBaseURI(baseURI);
}
/*
* Pause mint if active, make active if paused
*/
function setMintState(bool _mintIsActive) external onlyOwner {
mintIsActive = _mintIsActive;
}
/*
* Set breed mode
*/
function setBreedMode(bool _breedByDoggoIsActive) external onlyOwner {
breedByDoggoIsActive = _breedByDoggoIsActive;
emit BreedModeUpdated(_breedByDoggoIsActive);
}
/*
* Set breed fee percentage
*/
function setBreedFeePct(uint256 _breedFeePct) external onlyOwner {
require(_breedFeePct <= 20, 'Breed fee percentage is too much');
breedFeePct = _breedFeePct;
emit BreedFeePctUpdated(_breedFeePct);
}
function setBreedFeeWallet(address _walletAddress) external onlyOwner {
breedFeeWallet = _walletAddress;
}
function setDogePoundAddr(address _dogePoundAddr) external onlyOwner {
dogePound = IDogePound(_dogePoundAddr);
}
function withdrawFee() external onlyOwner {
uint256 balance = address(this).balance;
payable(breedFeeWallet).transfer(balance);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC721.sol";
import "./Ownable.sol";
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721Burnable is Ownable, ERC721 {
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_msgSender() == owner() || _isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721Receiver.sol";
import "./IERC721Metadata.sol";
import "./IERC721Enumerable.sol";
import "./Address.sol";
import "./Strings.sol";
import "./EnumerableSet.sol";
import "./EnumerableMap.sol";
import "./SafeMath.sol";
import "./Context.sol";
import "./ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// 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] = valueIndex; // Replace lastvalue's index to valueIndex
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
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.8.0;
import "./EnumerableSet.sol";
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
using EnumerableSet for EnumerableSet.Bytes32Set;
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct Map {
// Storage of keys
EnumerableSet.Bytes32Set _keys;
mapping (bytes32 => bytes32) _values;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
map._values[key] = value;
return map._keys.add(key);
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
delete map._values[key];
return map._keys.remove(key);
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._keys.contains(key);
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._keys.length();
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
bytes32 key = map._keys.at(index);
return (key, map._values[key]);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
bytes32 value = map._values[key];
if (value == bytes32(0)) {
return (_contains(map, key), bytes32(0));
} else {
return (true, value);
}
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
bytes32 value = map._values[key];
require(value != 0 || _contains(map, key), "EnumerableMap: nonexistent key");
return value;
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
bytes32 value = map._values[key];
require(value != 0 || _contains(map, key), errorMessage);
return value;
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.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.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./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 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
|
Set breed fee percentage/
|
function setBreedFeePct(uint256 _breedFeePct) external onlyOwner {
require(_breedFeePct <= 20, 'Breed fee percentage is too much');
breedFeePct = _breedFeePct;
emit BreedFeePctUpdated(_breedFeePct);
}
| 10,268,982
|
./full_match/5/0xaf5969Ad7038b24f83Ae7A7A3290b5738b723dBC/sources/contractsv0.0.5/nnsregistrar/NNSRegistrarController.sol
|
ora:address owner,address resolver, address addr
|
function channelRegisterWithConfig(string calldata name, address[] calldata ora,string calldata channelId) external payable {
| 1,930,463
|
./full_match/5/0x2860549ca81Bccf5d3c70CfEb8AD29729cFDc1Cc/sources/contracts/MvM.sol
|
checking if an obyc token has been transformed to level two
|
function isAlreadyMintedMvML2(uint256 _mvmTokenId)
internal
view
returns (bool)
{
for (
uint256 index = 0;
index < mvmL2Tokens.length;
index++
) {
if (
transformInfoLevelTwoByTokenId[mvmL2Tokens[index]].mvmLevelOneTokenId ==
_mvmTokenId
) {
return true;
}
}
return false;
}
| 1,958,311
|
./full_match/1/0x84fE05f541cee93d0B02e03cD4319c29BA0030A2/sources/src/libraries/DoubleLogicUUPSUpgradeable.sol
|
Upgrade the secondary implementation of the proxy to `newImplementation`, and subsequently execute the function call encoded in `data`. Calls {_authorizeSecondaryUpgrade}. Emits an {UpgradedSecondary} event./
|
function upgradeSecondaryToAndCall(address newImplementation, bytes memory data)
external
payable
onlyProxy
{
_authorizeSecondaryUpgrade(newImplementation);
_upgradeSecondaryToAndCallUUPS(newImplementation, data, true);
}
| 3,877,610
|
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "hardhat/console.sol";
import "./LibUintToString.sol";
contract TestUintToString {
using LibUintToString for uint256;
/// @dev Converts `n` to a string using LibUintToString and
/// measures the gas cost.
/// @param n The integer to convert.
/// @return str `n` as a decimal string.
/// @return gasCost The gas cost of the conversion.
function testToString(uint256 n)
public
view
returns (string memory str, uint256 gasCost)
{
uint256 g0 = gasleft();
str = n.toString();
gasCost = g0 - gasleft();
}
/// @dev Converts `n` to a string using the baseline implementation
/// (`uint2str`) and measures the gas cost.
/// @param n The integer to convert.
/// @return str `n` as a decimal string.
/// @return gasCost The gas cost of the conversion.
function baselineToString(uint256 n)
public
view
returns (string memory str, uint256 gasCost)
{
uint256 g0 = gasleft();
str = toStringOZ(n);
gasCost = g0 - gasleft();
}
/// @dev Baseline uint256 to string implementation, from OpenZeppelin
/// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/788d338c9b53d57f7229f79815573dcb91ecede1/contracts/utils/Strings.sol#L14
/// @param value The integer to convert.
/// @return str The `value` as a decimal string.
function toStringOZ(uint256 value)
internal
pure
returns (string memory str)
{
// 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);
}
}
|
Baseline uint256 to string implementation, from OpenZeppelin https://github.com/OpenZeppelin/openzeppelin-contracts/blob/788d338c9b53d57f7229f79815573dcb91ecede1/contracts/utils/Strings.solL14 value The integer to convert. return str The `value` as a decimal string. Inspired by OraclizeAPI's implementation - MIT licence https:github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
|
function toStringOZ(uint256 value)
internal
pure
returns (string memory str)
{
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);
}
| 13,007,034
|
./partial_match/42/0x30090A4A525Fc866E6D38Dde0601E9475D1778fb/sources/AlpacaSquad.sol
|
Update the balance of a id for a given address _address Address to update id balance _id Id to update balance of _amount Amount to update the id balance _operation Which operation to conduct : Operations.Add: Add _amount to id balance Operations.Sub: Substract _amount from id balance/ Get bin and index of _id Update balance
|
function _updateIDBalance(address _address, uint256 _id, uint256 _amount, Operations _operation)
internal
{
uint256 bin;
uint256 index;
(bin, index) = getIDBinIndex(_id);
balances[_address][bin] = _viewUpdateBinValue(balances[_address][bin], index, _amount, _operation);
}
| 8,951,521
|
./partial_match/42/0xe456202B1D213D0a953C9bd7Ad15EA5cBca23cb0/sources/EPNToken.sol
|
Check if ensName is already linked with user or not ensName The ENS name that owner's own return Returns true if the specified ensName is not mapped with any tokenId/
|
function available(string memory ensName) override public view returns(bool) {
return ensMapping[ensName] == emptyTokenId;
}
| 8,913,286
|
// SPDX-License-Identifier: UNLICENSED
/*
* https://cannappscorp.com/ -- Global Cannabis Applications Corporation (GCAC)
*
* Address: Suite 830, 1100 Melville Street, Vancouver, British Columbia, V6E 4A6 Canada
* Email: [email protected]
*
* As at 31-March-2021, GCAC is a publicly traded company on the Canadian Stock Exchange.
*
* Official GCAC Listing
* https://www.thecse.com/en/listings/technology/global-cannabis-applications-corp
*
* Official GCAC Regulatory Filings
* https://www.sedar.com/DisplayCompanyDocuments.do?lang=EN&issuerNo=00036309
*
* This is an ERC-20 smart contract for the GCAC token that will be used as one side
* of a Uniswap liquidity pool trading pair. This GCAC token has the following properties:
*
* 1. The number of GCAC tokens from this contract that will be initially added to the
* Uniswap liquidity pool shall be 100,000. The amount of WETH added to the other side of
* the initial Uniswap liquidity pool shall be 5.
* 2. GCAC hereby commits to swap an amount of WETH currency with the Uniswap GCAC<>WETH
* trading pair every 3 months for no fewer than 8 quarters, i.e., 2 years, commencing
* for the quarterly report as filed by GCAC for the quarter ending 31-March-2021.
* 3. The value of the WETH currency swapped by GCAC shall be equal to 1% of GCAC's official
* 'revenue', as disclosed in each of its quarterly regulatory filings. Each WETH
* swap shall be performed no later than 10 working days after the regulatory filing is
* available on the System for Electronic Document Analysis and Retrieval (SEDAR). SEDAR
* is a mandatory document filing system for Canadian public companies.
* 4. GCAC tokens returned by Uniswap from the quarterly swap of WETH shall be burned
* by this smart contract, thereby reducing GCAC token circulating supply over time.
* 5. This contract shall not be allowed mint any new GCAC tokens, i.e., no dilution.
* 6. GCAC, the company, shall initially hold 100,000 GCAC tokens on its corporate
* balance sheet, i.e., the GCAC treasury tokens.
* 7. GCAC's treasury tokens may only ever be swapped for WETH in Uniswap and are prevented
* from being transferred out of this contract to another exchange or wallet, i.e., no rug-pull.
* 8. GCAC hereby commits to notify the DeFi community of its intent to withdraw liquidity from
* Uniswap at least 3 months in advance. This contact enforces the liquidity-time-lock.
* 9. GCAC hereby commits to notify the DeFi community of its intent to swap GCAC treasury tokens
* on Uniswap at least 3 months in advance. This contact enforces the treasury-time-lock.
*
*
* https://abbey.ch/ -- Abbey Technology GmbH, Zug, Switzerland
*
* ABBEY DEFI
* ==========
* 1. Decentralized Finance 'DeFi' is designed to be globally inclusive.
* 2. Centralized finance is based around national stock markets that have high barriers to entry.
* 3. The Abbey DeFi methodology offers companies listed on national stock exchanges exposure to DeFi.
*
* Abbey is a Uniswap-based DeFi service provider that allows public companies to offer people a novel
* way to speculate on the success of their business in a decentralized manner.
*
* The premise is both elegant and simple, the public company commits to a marketing spend equal to 1%
* of its quarterly sales revenue. And, since it’s a public company, the exact value of this 1% is
* published in their public accounts, as filed quarterly with a national securities regulator.
*
* Using Abbey as a Uniswap DeFi marketing agency, the public company spends 1% of its quarterly cash
* sales revenue on one side of a bespoke Uniswap trading contract. The other side of the Uniswap trade
* is the public company’s proprietary token that’s representing 1% of its future sales revenue.
*
* DeFi traders wishing to speculate on the revenue growth of the public company deposit crypto-USD
* in return for “PUBCO-1%” Uniswap tokens. The Uniswap Automated Market Maker ensures DeFi market
* liquidity and legitimate price discovery. The more USD that the company deposits over time, the
* higher the value of the PUBCO-1% token, as held by DeFi speculators.
*
*/
pragma solidity 0.7.6;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/**
* @title Global Cannabis Applications Corporation (GCAC) contract for Uniswap.
* @author Abbey Technology GmbH
* @notice Token contract for use with Uniswap. Enforces restrictions outlined in the prospectus.
*/
contract GCACToken is ERC20 {
enum TokenType { Unknown, GCAC, LiquidityPool }
/**
* @notice The details of a future company cashout.
*/
struct Notice {
// The maximum number of tokens proposed for sale.
uint256 amount;
// The date after which company tokens can be swapped.
uint256 releaseDate;
// Whether the notice given is for this contract's tokens (GCAC) or the
// liquidity pool tokens created by Uniswap where fees are periodically
// cashed in.
TokenType tokenType;
}
// Event fired when a restricted wallet gives notice of a potential future trade.
event NoticeGiven(address indexed who, uint256 amount, uint256 releaseDate, TokenType tokenType);
/**
* @notice Notice must be given to the public before treasury tokens can be swapped.
*/
Notice public noticeTreasury;
/**
* @notice Notice must be given to the public before Liquidity Tokens can be removed from the pool.
*/
Notice public noticeLiquidity;
/**
* @notice The account that created this contract, also functions as the liquidity provider.
*/
address public owner;
/**
* @notice Holder of the company's 50% share of all Uniswap tokens. Can only interact with the
* Uniswap pair/router, is forbidden from trading tokens elsewhere.
*/
address public treasury;
/**
* @notice The account that performs the 1% of sales buyback of tokens, all bought tokens are burned.
* @dev They cannot be autoburned during transfer as the Uniswap client prevents the transaction.
*/
address public buyback;
/**
* @notice The address of the Uniswap router, the liquidity provider and treasury can only interact with this
* address. This prevents trading outside of Uniswap for these accounts.
*/
address public router;
/**
* @notice The address of the Uniswap Pair/ERC20 contract holding the Liquidity Pool tokens.
*/
address public pairAddress;
/**
* @notice Restrict functionaly to the contract owner.
*/
modifier onlyOwner {
require(_msgSender() == owner, "You are not Owner.");
_;
}
/**
* @notice Restrict functionaly to the buyback account.
*/
modifier onlyBuyback {
require(_msgSender() == buyback, "You are not Buyback.");
_;
}
constructor(uint256 initialSupply, string memory name, string memory symbol) ERC20(name, symbol) {
owner = _msgSender();
_mint(_msgSender(), initialSupply);
}
/**
* Set the account that burns GCAC tokens periodically.
*/
function setBuyback(address who) public onlyOwner {
require(buyback == address(0), "The Buyback address can only be set once.");
buyback = who;
}
/**
* Set the address of the account holding GCAC tokens on behalf of the company.
*/
function setTreasury(address who) public onlyOwner {
require(treasury == address(0), "The Treasury address can only be set once.");
treasury = who;
}
/**
* Set the address of the Uniswap router, only this address is allowed to move Treasury tokens.
*/
function setRouter(address who) public onlyOwner {
require(router == address(0), "The Router address can only be set once.");
router = who;
}
/**
* Set the address of the Uniswap Pair/Pool contract.
*/
function setPairAddress(address who) public onlyOwner {
require(pairAddress == address(0), "The Pair address can only be set once.");
pairAddress = who;
}
/**
* @notice Treasury and Liquidity tokens must give advanced notice to the public before they can
* be used. The token type is determined by the address giving notice.
*
* @param who The address giving notice of a sale in the future.
* @param amount The maximum number of tokens (in wei).
* @param numSeconds The number of seconds the tokens cannot be sold for.
*/
function giveNotice(address who, uint256 amount, uint256 numSeconds) public onlyOwner {
require(pairAddress != address(0), "The Uniswap Pair contract address must be set.");
require(who == treasury || who == address(this), "Only Treasury and Liquidity must give notice.");
uint256 when = block.timestamp + (numSeconds * 1 seconds);
TokenType tokenType;
if(who == treasury) {
require(noticeTreasury.releaseDate == 0 || block.timestamp >= noticeTreasury.releaseDate, "Cannot overwrite an active existing notice.");
require(amount <= balanceOf(who), "Can't give notice for more GCAC tokens than owned.");
tokenType = TokenType.GCAC;
noticeTreasury = Notice(amount, when, tokenType);
}
else {
require(noticeLiquidity.releaseDate == 0 || block.timestamp >= noticeLiquidity.releaseDate, "Cannot overwrite an active existing notice.");
ERC20 pair = ERC20(pairAddress);
require(amount <= pair.balanceOf(who), "Can't give notice for more Liquidity Tokens than owned.");
tokenType = TokenType.LiquidityPool;
noticeLiquidity = Notice(amount, when, tokenType);
}
emit NoticeGiven(who, amount, when, tokenType);
}
/**
* @notice Enforce rules around the company accounts:
* - Liquidity Pool Creator (owner) can never receive tokens back from Uniswap.
* - Treasury can only send tokens to Uniswap.
* - Tokens bought back by the company are immediateley burned.
*/
function _transfer(address sender, address recipient, uint256 amount) internal override {
require(recipient != owner, "Liquidity Pool Creator cannot receive tokens.");
require(sender != buyback, "Buyback cannot transfer tokens, it can only burn.");
if(sender == treasury) {
require(_msgSender() == router, "Treasury account tokens can only be moved by the Uniswap Router.");
require(noticeTreasury.releaseDate != 0 && block.timestamp >= noticeTreasury.releaseDate, "Notice period has not been set or has not expired.");
require(amount <= noticeTreasury.amount, "Treasury can't transfer more tokens than given notice for.");
require(noticeTreasury.tokenType == TokenType.GCAC, "The notice given for this user is the wrong token type.");
// Clear the remaining notice balance, this prevents giving notice on all tokens and
// trickling them out.
noticeTreasury = Notice(0, 0, TokenType.Unknown);
}
super._transfer(sender, recipient, amount);
}
/**
* @notice Periodically draw down any fee entitlement from the Liquidity Pool after giving notice.
* @param to The account to send the tokens to.
* @param amount The number of tokens, in wei.
*/
function transferLiquidityTokens(address to, uint256 amount) public onlyOwner {
require(pairAddress != address(0), "The Uniswap Pair contract address must be set.");
require(noticeLiquidity.releaseDate != 0 && block.timestamp >= noticeLiquidity.releaseDate, "Notice period has not been set or has not expired.");
require(amount <= noticeLiquidity.amount, "Insufficient Liquidity Token balance.");
require(noticeLiquidity.tokenType == TokenType.LiquidityPool, "The notice given for this user is the wrong token type.");
ERC20 pair = ERC20(pairAddress);
pair.transfer(to, amount);
// Clear the notice even if only partially used.
noticeLiquidity = Notice(0, 0, TokenType.Unknown);
}
/**
* @notice The buyback account periodically buys tokens and then burns them to reduce the
* total supply pushing up the price of the remaining tokens.
*/
function burn() public onlyBuyback {
_burn(buyback, balanceOf(buyback));
}
}
// 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 Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.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;
}
}
|
Enforce rules around the company accounts: - Liquidity Pool Creator (owner) can never receive tokens back from Uniswap. - Treasury can only send tokens to Uniswap. - Tokens bought back by the company are immediateley burned./ Clear the remaining notice balance, this prevents giving notice on all tokens and trickling them out.
|
function _transfer(address sender, address recipient, uint256 amount) internal override {
require(recipient != owner, "Liquidity Pool Creator cannot receive tokens.");
require(sender != buyback, "Buyback cannot transfer tokens, it can only burn.");
if(sender == treasury) {
require(_msgSender() == router, "Treasury account tokens can only be moved by the Uniswap Router.");
require(noticeTreasury.releaseDate != 0 && block.timestamp >= noticeTreasury.releaseDate, "Notice period has not been set or has not expired.");
require(amount <= noticeTreasury.amount, "Treasury can't transfer more tokens than given notice for.");
require(noticeTreasury.tokenType == TokenType.GCAC, "The notice given for this user is the wrong token type.");
noticeTreasury = Notice(0, 0, TokenType.Unknown);
}
super._transfer(sender, recipient, amount);
}
| 5,949,104
|
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./Uniswap.sol";
import "./IUniMexFactory.sol";
import "hardhat/console.sol";
interface IUniMexStaking {
function distribute(uint256 _amount) external;
}
interface IUniMexPool {
function borrow(uint256 _amount) external;
function distribute(uint256 _amount) external;
function repay(uint256 _amount) external returns (bool);
}
contract UniMexMargin is Ownable, AccessControl, ReentrancyGuard {
using SafeMath for uint256;
using SafeMath for uint32;
using SafeERC20 for IERC20;
bytes32 public constant LIQUIDATOR_ROLE = keccak256("LIQUIDATOR_ROLE");
address private WETH_ADDRESS;
IERC20 public WETH;
uint256 public constant MAG = 1e18;
uint256 public constant LIQUIDATION_MARGIN = 1.1e18; //11%
uint256 public thresholdGasPrice = 3e8; //gas price in wei used to calculate bonuses for liquidation, sl, tp
uint32 public borrowInterestPercentScaled = 100; //10%
uint256 public constant YEAR = 31536000;
uint256 public positionNonce = 0;
bool public paused = false;
uint256 public amountThresholds;
struct Position {
uint256 owed;
uint256 input;
uint256 commitment;
address token;
bool isShort;
uint32 startTimestamp;
uint32 borrowInterest;
address owner;
uint32 stopLossPercent;
uint32 takeProfitPercent;
}
struct Limit {
uint256 amount;
uint256 minimalSwapAmount;
address token;
bool isShort;
uint32 validBefore;
uint32 leverageScaled;
address owner;
uint32 takeProfitPercent;
uint32 stopLossPercent;
uint256 escrowAmount;
}
mapping(bytes32 => Position) public positionInfo;
mapping(bytes32 => Limit) public limitOrders;
mapping(address => uint256) public balanceOf;
mapping(address => uint256) public escrow;
IUniMexStaking public staking;
IUniMexFactory public unimex_factory;
IUniswapV2Factory public uniswap_factory;
IUniswapV2Router02 public uniswap_router;
event OnClosePosition(
bytes32 indexed positionId,
address token,
address indexed owner,
uint256 owed,
uint256 input,
uint256 commitment,
uint32 startTimestamp,
bool isShort,
uint256 borrowInterest,
uint256 liquidationBonus, //amount that went to liquidator when position was liquidated. 0 if position was closed
uint256 scaledCloseRate // weth/token multiplied by 1e18
);
event OnOpenPosition(
address indexed sender,
bytes32 positionId,
bool isShort,
address indexed token,
uint256 scaledLeverage
);
event OnAddCommitment(
bytes32 indexed positionId,
uint256 amount
);
event OnLimitOrder(
bytes32 indexed limitOrderId,
address indexed owner,
address token,
uint256 amount,
uint256 minimalSwapAmount,
uint256 leverageScaled,
uint256 validBefore,
uint256 escrowAmount,
uint32 takeProfitPercent,
uint32 stopLossPercent,
bool isShort
);
event OnLimitOrderCancelled(
bytes32 indexed limitOrderId
);
event OnLimitOrderCompleted(
bytes32 indexed limitOrderId,
bytes32 positionId
);
event OnTakeProfit(
bytes32 indexed positionId,
uint256 positionInput,
uint256 swapAmount,
address token,
bool isShort
);
event OnStopLoss(
bytes32 indexed positionId,
uint256 positionInput,
uint256 swapAmount,
address token,
bool isShort
);
//to prevent flashloans
modifier isHuman() {
require(msg.sender == tx.origin);
_;
}
constructor(
address _staking,
address _factory,
address _weth,
address _uniswap_factory,
address _uniswap_router
) public {
staking = IUniMexStaking(_staking);
unimex_factory = IUniMexFactory(_factory);
WETH_ADDRESS = _weth;
WETH = IERC20(_weth);
uniswap_factory = IUniswapV2Factory(_uniswap_factory);
uniswap_router = IUniswapV2Router02(_uniswap_router);
// Grant the contract deployer the default admin role: it will be able
// to grant and revoke any roles
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
amountThresholds = 275;
}
function deposit(uint256 _amount) public {
WETH.safeTransferFrom(msg.sender, address(this), _amount);
balanceOf[msg.sender] = balanceOf[msg.sender].add(_amount);
}
function withdraw(uint256 _amount) public {
require(balanceOf[msg.sender] >= _amount);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_amount);
WETH.safeTransfer(msg.sender, _amount);
}
function calculateBorrowInterest(bytes32 positionId) public view returns (uint256) {
Position storage position = positionInfo[positionId];
uint256 loanTime = block.timestamp.sub(position.startTimestamp);
return position.owed.mul(loanTime).mul(position.borrowInterest).div(1000).div(YEAR);
}
function openShortPosition(address token, uint256 amount, uint256 scaledLeverage, uint256 minimalSwapAmount) public isHuman {
uint256[5] memory values = [amount, scaledLeverage, minimalSwapAmount, 0, 0];
_openPosition(msg.sender, token, true, values);
}
function openLongPosition(address token, uint256 amount, uint256 scaledLeverage, uint256 minimalSwapAmount) public isHuman {
uint256[5] memory values = [amount, scaledLeverage, minimalSwapAmount, 0, 0];
_openPosition(msg.sender, token, false, values);
}
function openShortPositionWithSlTp(address token, uint256 amount, uint256 scaledLeverage, uint256 minimalSwapAmount,
uint256 takeProfitPercent, uint256 stopLossPercent) public isHuman {
uint256[5] memory values = [amount, scaledLeverage, minimalSwapAmount, takeProfitPercent, stopLossPercent];
_openPosition(msg.sender, token, true, values);
}
function openLongPositionWithSlTp(address token, uint256 amount, uint256 scaledLeverage, uint256 minimalSwapAmount,
uint256 takeProfitPercent, uint256 stopLossPercent) public isHuman {
uint256[5] memory values = [amount, scaledLeverage, minimalSwapAmount, takeProfitPercent, stopLossPercent];
_openPosition(msg.sender, token, false, values);
}
/**
* values[0] amount
* values[1] scaledLeverage
* values[2] minimalSwapAmount
* values[3] takeProfitPercent
* values[4] stopLossPercent
*/
function _openPosition(address owner, address token, bool isShort, uint256[5] memory values)
private nonReentrant returns (bytes32) {
require(!paused, "PAUSED");
require(values[0] > 0, "AMOUNT_ZERO");
require(values[4] < 1e6, "STOPLOSS EXCEEDS MAX");
address pool = unimex_factory.getPool(address(isShort ? IERC20(token) : WETH));
require(pool != address(0), "POOL_DOES_NOT_EXIST");
require(values[1] <= unimex_factory.getMaxLeverage(token).mul(MAG), "LEVERAGE_EXCEEDS_MAX");
require(checkPositionAmount(token, values[0], values[1]), "NOT_ENOUGH_UNISWAP_LIQUIDITY");
uint256 amountInWeth = isShort ? calculateConvertedValue(token, WETH_ADDRESS, values[0]) : values[0];
uint256 commitment = getCommitment(amountInWeth, values[1]);
uint256 commitmentWithLb = commitment.add(calculateAutoCloseBonus());
require(balanceOf[owner] >= commitmentWithLb, "NO_BALANCE");
IUniMexPool(pool).borrow(values[0]);
uint256 swap;
{
(address baseToken, address quoteToken) = isShort ? (token, WETH_ADDRESS) : (WETH_ADDRESS, token);
swap = swapTokens(baseToken, quoteToken, values[0]);
require(swap >= values[2], "INSUFFICIENT_SWAP");
}
uint256 fees = (swap.mul(4)).div(1000);
swap = swap.sub(fees);
if(!isShort) {
fees = swapTokens(token, WETH_ADDRESS, fees); // convert fees to ETH
}
transferFees(fees, pool);
transferUserToEscrow(owner, owner, commitmentWithLb);
positionNonce = positionNonce + 1; //possible overflow is ok
bytes32 positionId = getPositionId(
owner,
token,
values[0],
values[1],
positionNonce
);
Position memory position = Position({
owed: values[0],
input: swap,
commitment: commitmentWithLb,
token: token,
isShort: isShort,
startTimestamp: uint32(block.timestamp),
owner: owner,
borrowInterest: borrowInterestPercentScaled,
takeProfitPercent: uint32(values[3]),
stopLossPercent: uint32(values[4])
});
positionInfo[positionId] = position;
emit OnOpenPosition(owner, positionId, isShort, token, values[1]);
if(position.takeProfitPercent > 0) {
emit OnTakeProfit(positionId, swap, position.takeProfitPercent, token, isShort);
}
if(position.stopLossPercent > 0) {
emit OnStopLoss(positionId, swap, position.stopLossPercent, token, isShort);
}
return positionId;
}
/**
* @dev add additional commitment to an opened position. The amount
* must be initially approved
* @param positionId id of the position to add commitment
* @param amount the amount to add to commitment
*/
function addCommitmentToPosition(bytes32 positionId, uint256 amount) public {
Position storage position = positionInfo[positionId];
_checkPositionIsOpen(position);
position.commitment = position.commitment.add(amount);
WETH.safeTransferFrom(msg.sender, address(this), amount);
escrow[position.owner] = escrow[position.owner].add(amount);
emit OnAddCommitment(positionId, amount);
}
/**
* @dev allows anyone to close position if it's loss exceeds threshold
*/
function setStopLoss(bytes32 positionId, uint32 percentAmount) public {
require(percentAmount < 1e6, "STOPLOSS EXCEEDS MAX");
Position storage position = positionInfo[positionId];
_checkPositionIsOpen(position);
require(msg.sender == position.owner, "NOT_OWNER");
position.stopLossPercent = percentAmount;
emit OnStopLoss(positionId, position.input, percentAmount, position.token, position.isShort);
}
/**
* @dev allows anyone to close position if it's profit exceeds threshold
*/
function setTakeProfit(bytes32 positionId, uint32 percentAmount) public {
Position storage position = positionInfo[positionId];
_checkPositionIsOpen(position);
require(msg.sender == position.owner, "NOT_OWNER");
position.takeProfitPercent = percentAmount;
emit OnTakeProfit(positionId, position.input, percentAmount, position.token, position.isShort);
}
function autoClose(bytes32 positionId) public isHuman {
Position storage position = positionInfo[positionId];
_checkPositionIsOpen(position);
//check constraints
(address baseToken, address quoteToken) = position.isShort ? (WETH_ADDRESS, position.token) : (position.token, WETH_ADDRESS);
uint256 swapAmount = calculateConvertedValue(baseToken, quoteToken, position.input);
uint256 hundredPercent = 1e6;
require((position.takeProfitPercent != 0 && position.owed.mul(hundredPercent.add(position.takeProfitPercent)).div(hundredPercent) <= swapAmount) ||
(position.stopLossPercent != 0 && position.owed.mul(hundredPercent.sub(position.stopLossPercent)).div(hundredPercent) >= swapAmount), "SL_OR_TP_UNAVAILABLE");
//withdraw bonus from position commitment
uint256 closeBonus = calculateAutoCloseBonus();
position.commitment = position.commitment.sub(closeBonus);
WETH.safeTransfer(msg.sender, closeBonus);
transferEscrowToUser(position.owner, address(0), closeBonus);
_closePosition(positionId, position, 0);
}
function calculateAutoOpenBonus() public view returns(uint256) {
return thresholdGasPrice.mul(510000);
}
function calculateAutoCloseBonus() public view returns(uint256) {
return thresholdGasPrice.mul(270000);
}
/**
* @dev opens position that can be opened at a specific price
*/
function openLimitOrder(address token, bool isShort, uint256 amount, uint256 minimalSwapAmount,
uint256 leverageScaled, uint32 validBefore, uint32 takeProfitPercent, uint32 stopLossPercent) public {
require(!paused, "PAUSED");
require(stopLossPercent < 1e6, "STOPLOSS EXCEEDS MAX");
require(validBefore > block.timestamp, "INCORRECT_EXP_DATE");
uint256[3] memory values256 = [amount, minimalSwapAmount, leverageScaled];
uint32[3] memory values32 = [validBefore, takeProfitPercent, stopLossPercent];
_openLimitOrder(token, isShort, values256, values32);
}
/**
* @dev values256[0] - amount
* values256[1] - minimal swap amount
* values256[2] - scaled leverage
* values32[0] - valid before
* values32[1] - take profit percent
* values32[2] - stop loss percent
*/
function _openLimitOrder(address token, bool isShort, uint256[3] memory values256, uint32[3] memory values) private {
uint256 escrowAmount; //stack depth optimization
{
uint256 commitment = isShort ? getCommitment(values256[1], values256[2]) : getCommitment(values256[0], values256[2]);
escrowAmount = commitment.add(calculateAutoOpenBonus()).add(calculateAutoCloseBonus());
require(balanceOf[msg.sender] >= escrowAmount, "INSUFFICIENT_BALANCE");
transferUserToEscrow(msg.sender, msg.sender, escrowAmount);
}
bytes32 limitOrderId = _getLimitOrderId(token, values256[0], values256[1], values256[2],
values[0], msg.sender, isShort);
Limit memory limitOrder = Limit({
token: token,
amount: values256[0],
minimalSwapAmount: values256[1],
leverageScaled: uint32(values256[2].div(1e14)),
validBefore: values[0],
owner: msg.sender,
escrowAmount: escrowAmount,
isShort: isShort,
takeProfitPercent: values[1],
stopLossPercent: values[2]
});
limitOrders[limitOrderId] = limitOrder;
emitLimitOrderEvent(limitOrderId, token, values256, values, escrowAmount, isShort);
}
function emitLimitOrderEvent(bytes32 limitOrderId, address token, uint256[3] memory values256,
uint32[3] memory values, uint256 escrowAmount, bool isShort) private {
emit OnLimitOrder(limitOrderId, msg.sender, token, values256[0], values[1], values256[2], values[0], escrowAmount,
values[1], values[2], isShort);
}
function cancelLimitOrder(bytes32 limitOrderId) public {
Limit storage limitOrder = limitOrders[limitOrderId];
require(limitOrder.owner == msg.sender, "NOT_OWNER");
transferEscrowToUser(limitOrder.owner, limitOrder.owner, limitOrder.escrowAmount);
delete limitOrders[limitOrderId];
emit OnLimitOrderCancelled(limitOrderId);
}
function autoOpen(bytes32 limitOrderId) public isHuman {
//get limit order
Limit storage limitOrder = limitOrders[limitOrderId];
require(limitOrder.owner != address(0), "NO_ORDER");
require(limitOrder.validBefore >= uint32(block.timestamp), "EXPIRED");
//check open rate
(address baseToken, address quoteToken) = limitOrder.isShort ? (limitOrder.token, WETH_ADDRESS) : (WETH_ADDRESS, limitOrder.token);
uint256 swapAmount = calculateConvertedValue(baseToken, quoteToken, limitOrder.amount);
require(swapAmount >= limitOrder.minimalSwapAmount, "LIMIT_NOT_SATISFIED");
uint256 openBonus = calculateAutoOpenBonus();
//transfer bonus from escrow to caller
WETH.transfer(msg.sender, openBonus);
transferEscrowToUser(limitOrder.owner, limitOrder.owner, limitOrder.escrowAmount.sub(openBonus));
transferEscrowToUser(limitOrder.owner, address(0), openBonus);
//open position for user
uint256[5] memory values = [limitOrder.amount, uint256(limitOrder.leverageScaled.mul(1e14)),
limitOrder.minimalSwapAmount, uint256(limitOrder.takeProfitPercent), uint256(limitOrder.stopLossPercent)];
bytes32 positionId = _openPosition(limitOrder.owner, limitOrder.token, limitOrder.isShort, values);
//delete order id
delete limitOrders[limitOrderId];
emit OnLimitOrderCompleted(limitOrderId, positionId);
}
function _getLimitOrderId(address token, uint256 amount, uint256 minSwapAmount,
uint256 scaledLeverage, uint256 validBefore, address owner, bool isShort) private pure returns (bytes32) {
return keccak256(abi.encodePacked(token, amount, minSwapAmount, scaledLeverage, validBefore,
owner, isShort));
}
function _checkPositionIsOpen(Position storage position) private view {
require(position.owner != address(0), "NO_OPEN_POSITION");
}
function closePosition(bytes32 positionId, uint256 minimalSwapAmount) external isHuman {
Position storage position = positionInfo[positionId];
_checkPositionIsOpen(position);
require(msg.sender == position.owner, "BORROWER_ONLY");
_closePosition(positionId, position, minimalSwapAmount);
}
function _closePosition(bytes32 positionId, Position storage position, uint256 minimalSwapAmount) private nonReentrant{
uint256 scaledRate;
if(position.isShort) {
scaledRate = _closeShort(positionId, position, minimalSwapAmount);
}else{
scaledRate = _closeLong(positionId, position, minimalSwapAmount);
}
deletePosition(positionId, position, 0, scaledRate);
}
function _closeShort(bytes32 positionId, Position storage position, uint256 minimalSwapAmount) private returns (uint256){
uint256 input = position.input;
uint256 owed = position.owed;
uint256 commitment = position.commitment;
address pool = unimex_factory.getPool(position.token);
uint256 poolInterestInTokens = calculateBorrowInterest(positionId);
uint256 swap = swapTokens(WETH_ADDRESS, position.token, input);
require(swap >= minimalSwapAmount, "INSUFFICIENT_SWAP");
uint256 scaledRate = calculateScaledRate(input, swap);
require(swap >= owed.add(poolInterestInTokens).mul(input).div(input.add(commitment)), "LIQUIDATE_ONLY");
bool isProfit = owed < swap;
uint256 amount;
uint256 fees = poolInterestInTokens > 0 ? calculateConvertedValue(position.token, address(WETH), poolInterestInTokens) : 0;
if(isProfit) {
uint256 profitInTokens = swap.sub(owed);
amount = swapTokens(position.token, WETH_ADDRESS, profitInTokens); //profit in eth
} else {
uint256 commitmentInTokens = swapTokens(WETH_ADDRESS, position.token, commitment);
uint256 remainder = owed.sub(swap);
require(commitmentInTokens >= remainder, "LIQUIDATE_ONLY");
amount = swapTokens(position.token, WETH_ADDRESS, commitmentInTokens.sub(remainder)); //return to user's balance
}
if(isProfit) {
if(amount >= fees) {
transferEscrowToUser(position.owner, position.owner, commitment);
transferToUser(position.owner, amount.sub(fees));
} else {
uint256 remainder = fees.sub(amount);
transferEscrowToUser(position.owner, position.owner, commitment.sub(remainder));
transferEscrowToUser(position.owner, address(0), remainder);
}
} else {
require(amount >= fees, "LIQUIDATE_ONLY"); //safety check
transferEscrowToUser(position.owner, address(0x0), commitment);
transferToUser(position.owner, amount.sub(fees));
}
transferFees(fees, pool);
transferToPool(pool, position.token, owed);
return scaledRate;
}
function _closeLong(bytes32 positionId, Position storage position, uint256 minimalSwapAmount) private returns (uint256){
uint256 input = position.input;
uint256 owed = position.owed;
address pool = unimex_factory.getPool(WETH_ADDRESS);
uint256 fees = calculateBorrowInterest(positionId);
uint256 swap = swapTokens(position.token, WETH_ADDRESS, input);
require(swap >= minimalSwapAmount, "INSUFFICIENT_SWAP");
uint256 scaledRate = calculateScaledRate(swap, input);
require(swap.add(position.commitment) >= owed.add(fees), "LIQUIDATE_ONLY");
uint256 commitment = position.commitment;
bool isProfit = swap >= owed;
uint256 amount = isProfit ? swap.sub(owed) : commitment.sub(owed.sub(swap));
transferToPool(pool, WETH_ADDRESS, owed);
transferFees(fees, pool);
transferEscrowToUser(position.owner, isProfit ? position.owner : address(0x0), commitment);
transferToUser(position.owner, amount.sub(fees));
return scaledRate;
}
/**
* @dev helper function, indicates when a position can be liquidated.
* Liquidation threshold is when position input plus commitment can be converted to 110% of owed tokens
*/
function canLiquidate(bytes32 positionId) public view returns(bool) {
Position storage position = positionInfo[positionId];
uint256 liquidationBonus = calculateAutoCloseBonus();
uint256 canReturn;
if(position.isShort) {
uint256 positionBalance = position.input.add(position.commitment);
uint256 valueToConvert = positionBalance < liquidationBonus ? 0 : positionBalance.sub(liquidationBonus);
canReturn = calculateConvertedValue(WETH_ADDRESS, position.token, valueToConvert);
} else {
uint256 canReturnOverall = calculateConvertedValue(position.token, WETH_ADDRESS, position.input)
.add(position.commitment);
canReturn = canReturnOverall < liquidationBonus ? 0 : canReturnOverall.sub(liquidationBonus);
}
uint256 poolInterest = calculateBorrowInterest(positionId);
return canReturn < position.owed.add(poolInterest).mul(LIQUIDATION_MARGIN).div(MAG);
}
/**
* @dev Liquidates position and sends a liquidation bonus from user's commitment to a caller.
* can only be called from account that has the LIQUIDATOR role
*/
function liquidatePosition(bytes32 positionId, uint256 minimalSwapAmount) external isHuman nonReentrant {
Position storage position = positionInfo[positionId];
_checkPositionIsOpen(position);
uint256 canReturn;
uint256 poolInterest = calculateBorrowInterest(positionId);
uint256 liquidationBonus = calculateAutoCloseBonus();
uint256 liquidatorBonus;
uint256 scaledRate;
if(position.isShort) {
uint256 positionBalance = position.input.add(position.commitment);
uint256 valueToConvert;
(valueToConvert, liquidatorBonus) = _safeSubtract(positionBalance, liquidationBonus);
canReturn = swapTokens(WETH_ADDRESS, position.token, valueToConvert);
require(canReturn >= minimalSwapAmount, "INSUFFICIENT_SWAP");
scaledRate = calculateScaledRate(valueToConvert, canReturn);
} else {
uint256 swap = swapTokens(position.token, WETH_ADDRESS, position.input);
require(swap >= minimalSwapAmount, "INSUFFICIENT_SWAP");
scaledRate = calculateScaledRate(swap, position.input);
uint256 canReturnOverall = swap.add(position.commitment);
(canReturn, liquidatorBonus) = _safeSubtract(canReturnOverall, liquidationBonus);
}
require(canReturn < position.owed.add(poolInterest).mul(LIQUIDATION_MARGIN).div(MAG), "CANNOT_LIQUIDATE");
_liquidate(position, canReturn, poolInterest);
transferEscrowToUser(position.owner, address(0x0), position.commitment);
WETH.safeTransfer(msg.sender, liquidatorBonus);
deletePosition(positionId, position, liquidatorBonus, scaledRate);
}
function _liquidate(Position memory position, uint256 canReturn, uint256 fees) private {
address baseToken = position.isShort ? position.token : WETH_ADDRESS;
address pool = unimex_factory.getPool(baseToken);
if(canReturn > position.owed) {
transferToPool(pool, baseToken, position.owed);
uint256 remainder = canReturn.sub(position.owed);
if(remainder > fees) { //can pay fees completely
if(position.isShort) {
remainder = swapTokens(position.token, WETH_ADDRESS, remainder);
if(fees > 0) { //with fees == 0 calculation is reverted with "UV2: insufficient input amount"
fees = calculateConvertedValue(position.token, WETH_ADDRESS, fees);
if(fees > remainder) { //safety check
fees = remainder;
}
}
}
transferFees(fees, pool);
transferToUser(position.owner, remainder.sub(fees));
} else { //all is left is for fees
if(position.isShort) {
//convert remainder to weth
remainder = swapTokens(position.token, WETH_ADDRESS, canReturn.sub(position.owed));
}
transferFees(remainder, pool);
}
} else {
//return to pool all that's left
transferToPool(pool, baseToken, canReturn);
}
}
function setStaking(address _staking) external onlyOwner {
require(_staking != address(0));
staking = IUniMexStaking(_staking);
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner public {
paused = true;
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner public {
paused = false;
}
function setThresholdGasPrice(uint256 gasPrice) public {
require(hasRole(LIQUIDATOR_ROLE, msg.sender), "NOT_LIQUIDATOR");
thresholdGasPrice = gasPrice;
}
/**
* @dev set interest rate for tokens owed from pools. Scaled to 10 (e.g. 150 is 15%)
*/
function setBorrowPercent(uint32 _newPercentScaled) external onlyOwner {
borrowInterestPercentScaled = _newPercentScaled;
}
function calculateScaledRate(uint256 wethAmount, uint256 tokenAmount) private pure returns (uint256 scaledRate) {
if(tokenAmount == 0) {
return 0;
}
return wethAmount.mul(MAG).div(tokenAmount);
}
function transferUserToEscrow(address from, address to, uint256 amount) private {
require(balanceOf[from] >= amount);
balanceOf[from] = balanceOf[from].sub(amount);
escrow[to] = escrow[to].add(amount);
}
function transferEscrowToUser(address from, address to, uint256 amount) private {
require(escrow[from] >= amount);
escrow[from] = escrow[from].sub(amount);
balanceOf[to] = balanceOf[to].add(amount);
}
function transferToUser(address to, uint256 amount) private {
balanceOf[to] = balanceOf[to].add(amount);
}
function getPositionId(
address maker,
address token,
uint256 amount,
uint256 leverage,
uint256 nonce
) private pure returns (bytes32 positionId) {
//date acts as a nonce
positionId = keccak256(
abi.encodePacked(maker, token, amount, leverage, nonce)
);
}
function calculateConvertedValue(address baseToken, address quoteToken, uint256 amount) private view returns (uint256) {
address token0;
address token1;
(token0, token1) = UniswapV2Library.sortTokens(baseToken, quoteToken);
IUniswapV2Pair pair = IUniswapV2Pair(uniswap_factory.getPair(token0, token1));
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 value;
if (token1 == baseToken) {
value = UniswapV2Library.getAmountOut(amount, reserve1, reserve0);
} else {
value = UniswapV2Library.getAmountOut(amount, reserve0, reserve1);
}
return value;
}
function swapTokens(address baseToken, address quoteToken, uint256 input) private returns (uint256 swap) {
if(input == 0) {
return 0;
}
IERC20(baseToken).approve(address(uniswap_router), input);
address[] memory path = new address[](2);
path[0] = baseToken;
path[1] = quoteToken;
uint256 balanceBefore = IERC20(quoteToken).balanceOf(address(this));
IUniswapV2Router02(uniswap_router).swapExactTokensForTokensSupportingFeeOnTransferTokens(
input,
0, //checks are done after swap in caller functions
path,
address(this),
block.timestamp
);
uint256 balanceAfter = IERC20(quoteToken).balanceOf(address(this));
swap = balanceAfter.sub(balanceBefore);
}
function getCommitment(uint256 _amount, uint256 scaledLeverage) private pure returns (uint256 commitment) {
commitment = (_amount.mul(MAG)).div(scaledLeverage);
}
function transferFees(uint256 fees, address pool) private {
uint256 halfFees = fees.div(2);
// Pool fees
WETH.approve(pool, halfFees);
IUniMexPool(pool).distribute(halfFees);
// Staking Fees
WETH.approve(address(staking), fees.sub(halfFees));
staking.distribute(fees.sub(halfFees));
}
function transferToPool(address pool, address token, uint256 amount) private {
IERC20(token).approve(pool, amount);
IUniMexPool(pool).repay(amount);
}
function _safeSubtract(uint256 from, uint256 amount) private pure returns (uint256 remainder, uint256 subtractedAmount) {
if(from < amount) {
remainder = 0;
subtractedAmount = from;
} else {
remainder = from.sub(amount);
subtractedAmount = amount;
}
}
function setAmountThresholds(uint32 leverage5) public onlyOwner {
amountThresholds = leverage5;
}
function checkPositionAmount(address token, uint256 amount, uint256 leverageScaled) public view returns (bool) {
if(leverageScaled <= 1e18) {
return true;
}
address token0;
address token1;
(token0, token1) = UniswapV2Library.sortTokens(token, WETH_ADDRESS);
IUniswapV2Pair pair = IUniswapV2Pair(uniswap_factory.getPair(token0, token1));
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 tokenLiquidity = token0 == token ? reserve0 : reserve1;
if (leverageScaled <= 2e18) {
return amount < tokenLiquidity.mul(amountThresholds).mul(1109).div(1000).div(1e4);
} else {
return amount < tokenLiquidity.mul(amountThresholds).div(1e4);
}
}
function deletePosition(bytes32 positionId, Position storage position, uint256 liquidatedAmount, uint256 scaledRate) private {
emit OnClosePosition(
positionId,
position.token,
position.owner,
position.owed,
position.input,
position.commitment,
position.startTimestamp,
position.isShort,
position.borrowInterest,
liquidatedAmount,
scaledRate
);
delete positionInfo[positionId];
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @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 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: UNLICENSED
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
interface IUniswapV2Pair {
function getReserves() external view returns (uint112 r0, uint112 r1, uint32 blockTimestampLast);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
}
interface IUniswapV2Factory {
function getPair(address a, address b) external view returns (address p);
}
interface IUniswapV2Router02 {
function WETH() external returns (address);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
library UniswapV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UV2: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UV2: ZERO_ADDRESS');
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UV2: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UV2: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.6.12;
interface IUniMexFactory {
function getPool(address) external returns(address);
function getMaxLeverage(address) external returns(uint256);
function allowedMargins(address) external returns (bool);
function utilizationScaled(address token) external pure returns(uint256);
}
// 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;
/**
* @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.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev 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;
}
}
|
Liquidates position and sends a liquidation bonus from user's commitment to a caller. can only be called from account that has the LIQUIDATOR role/
|
function liquidatePosition(bytes32 positionId, uint256 minimalSwapAmount) external isHuman nonReentrant {
Position storage position = positionInfo[positionId];
_checkPositionIsOpen(position);
uint256 canReturn;
uint256 poolInterest = calculateBorrowInterest(positionId);
uint256 liquidationBonus = calculateAutoCloseBonus();
uint256 liquidatorBonus;
uint256 scaledRate;
if(position.isShort) {
uint256 positionBalance = position.input.add(position.commitment);
uint256 valueToConvert;
(valueToConvert, liquidatorBonus) = _safeSubtract(positionBalance, liquidationBonus);
canReturn = swapTokens(WETH_ADDRESS, position.token, valueToConvert);
require(canReturn >= minimalSwapAmount, "INSUFFICIENT_SWAP");
scaledRate = calculateScaledRate(valueToConvert, canReturn);
uint256 swap = swapTokens(position.token, WETH_ADDRESS, position.input);
require(swap >= minimalSwapAmount, "INSUFFICIENT_SWAP");
scaledRate = calculateScaledRate(swap, position.input);
uint256 canReturnOverall = swap.add(position.commitment);
(canReturn, liquidatorBonus) = _safeSubtract(canReturnOverall, liquidationBonus);
}
require(canReturn < position.owed.add(poolInterest).mul(LIQUIDATION_MARGIN).div(MAG), "CANNOT_LIQUIDATE");
_liquidate(position, canReturn, poolInterest);
transferEscrowToUser(position.owner, address(0x0), position.commitment);
WETH.safeTransfer(msg.sender, liquidatorBonus);
deletePosition(positionId, position, liquidatorBonus, scaledRate);
}
| 13,657,256
|
./full_match/1/0x556d9E146CC7Fe7DF93fBdd90347Af8930acb104/sources/browser/Contract_Code_Min.sol
|
Interface of the ERC20 standard as defined in the EIP. Does not include the optional functions; to access them see {ERC20Detailed}./
|
interface ITokenERC20 {
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
}
}
| 3,090,249
|
./partial_match/3/0x7F38c33d47e2103f79E775CcCb5EfF265a8a3C31/sources/Arbitrage.sol
|
Uniswap srcToken => dstTokenUniswap srcToken => dstToken
|
function runTokenUniswapTransferThisAddressintransfer(uint amount, address srcTokenAddress, address dstTokenAddress) onlyOwner() external {
IERC20 srcToken = IERC20(srcTokenAddress);
IERC20 dstToken = IERC20(dstTokenAddress);
srcToken.transfer(address(this), amount);
IUniswap uniswap = IUniswap(uniswapAddress);
srcToken.approve(address(uniswap), amount);
address[] memory path = new address[](2);
path[0] = address(srcToken);
path[1] = address(dstToken);
uint[] memory minOuts = uniswap.getAmountsOut(amount, path);
uniswap.swapExactTokensForTokens(amount, minOuts[0], path, address(this), now);
}
| 5,082,642
|
./full_match/5/0x43B2249764BF6D797D4A320996bCe882238a2cce/sources/contracts/interfaces/v0.8.x/IFilteredMinterMerkleV0.sol
|
This interface extends the IFilteredMinterV1 interface in order to add support for including Merkle proofs when purchasing. Art Blocks Inc./ Triggers a purchase of a token from the desired project, to the TX-sending address. Requires Merkle proof. Triggers a purchase of a token from the desired project, to the specified receiving address. Requires Merkle proof.
|
interface IFilteredMinterMerkleV0 is IFilteredMinterV1 {
event DefaultMaxInvocationsPerAddress(
uint256 defaultMaxInvocationsPerAddress
);
function purchase(
uint256 _projectId,
bytes32[] memory _proof
) external payable returns (uint256 tokenId);
function purchaseTo(
address _to,
uint256 _projectId,
bytes32[] memory _proof
) external payable returns (uint256 tokenId);
}
| 1,959,730
|
./partial_match/42/0x7Cb5CBcFCDc169f81e1c20A78ACAEb60d01CfD8A/sources/ExampleTokenCrowdsale.sol
|
low level token purchase DO NOT OVERRIDE _beneficiary Address performing the token purchase/ calculate token amount to be created update state _processPurchase(_beneficiary, tokens); _updatePurchasingState(_beneficiary, weiAmount); _postValidatePurchase(_beneficiary, weiAmount);
|
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
uint256 tokens = _getTokenAmount(weiAmount);
weiRaised = weiRaised.add(weiAmount);
emit TokenPurchase(
msg.sender,
_beneficiary,
weiAmount,
tokens
);
_forwardFunds();
}
| 9,094,692
|
./partial_match/3/0xd95209cBb12652C10e0B49a0CdfD8bDDc27848E9/sources/testcontract.sol
|
Uniswap srcToken => dstTokenIERC20 dstToken = IERC20(dstTokenAddress);IUniswapV2Router01 uniswap = IUniswapV2Router01(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); Approve Uniswap to spend tokens Setup transfer address[] memory path = new address[](2); path[0] = address(srcToken); path[1] = address(dstToken); uint[] memory minOuts = uniswap.getAmountsOut(amount, path); As you can see I changed the address to msg.sender and added time uniswap.swapExactTokensForTokens(amount, minOuts[1], path, msg.sender, block.timestamp);
|
function runTokenUniswapTransferonly(uint amount, address srcTokenAddress) onlyOwner() external {
IERC20 srcToken = IERC20(srcTokenAddress);
srcToken.approve(address(uniswapAddress), amount);
srcToken.transferFrom(msg.sender, address(this), amount);
}
| 5,062,489
|
./full_match/1/0x0bC24E61DAAd6293A1b3b53a7D01086BfF0Ea6e5/sources/contracts/WiseSecurity/WiseSecurityHelper.sol
|
Read function returning the full (private and public) collateral amount of a {_poolToken} from a {_nftId} updated to current values. Can be extrapolated linear within {_interval}./
|
function getUSDCollateralUpdated(
uint256 _nftId,
address _poolToken,
uint256 _interval
)
public
view
returns (uint256)
{
uint256 lendingShares = WISE_LENDING.getPositionLendingShares(
_nftId,
_poolToken
);
if (lendingShares == 0) {
return 0;
}
uint256 currentTotalLendingShares = WISE_LENDING.getTotalDepositShares(
_poolToken
);
uint256 updatedPseudo = _getUpdatedPseudoPool(
_poolToken,
_interval
);
uint256 updatedToken = lendingShares
* updatedPseudo
/ currentTotalLendingShares;
return WISE_ORACLE.getTokensInUSD(
_poolToken,
updatedToken
);
}
| 4,818,512
|
pragma solidity ^0.4.23;
/**
* @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;
}
}
/**
* @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 ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
require(token.transfer(to, value));
}
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 value
)
internal
{
require(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
require(token.approve(spender, value));
}
}
contract ARPLongTermHolding {
using SafeERC20 for ERC20;
using SafeMath for uint256;
using Math for uint256;
// During the first 31 days of deployment, this contract opens for deposit of ARP.
uint256 public constant DEPOSIT_PERIOD = 31 days; // = 1 months
// 16 months after deposit, user can withdrawal all his/her ARP.
uint256 public constant WITHDRAWAL_DELAY = 480 days; // = 16 months
// Ower can drain all remaining ARP after 3 years.
uint256 public constant DRAIN_DELAY = 1080 days; // = 3 years.
// 50% bonus ARP return
uint256 public constant BONUS_SCALE = 2;
// ERC20 basic token contract being held
ERC20 public arpToken;
address public owner;
uint256 public arpDeposited;
uint256 public depositStartTime;
uint256 public depositStopTime;
struct Record {
uint256 amount;
uint256 timestamp;
}
mapping (address => Record) records;
/*
* EVENTS
*/
/// Emitted when all ARP are drained.
event Drained(uint256 _amount);
/// Emitted for each sucuessful deposit.
uint256 public depositId = 0;
event Deposit(uint256 _depositId, address indexed _addr, uint256 _amount, uint256 _bonus);
/// Emitted for each sucuessful withdrawal.
uint256 public withdrawId = 0;
event Withdrawal(uint256 _withdrawId, address indexed _addr, uint256 _amount);
/// Initialize the contract
constructor(ERC20 _arpToken, uint256 _depositStartTime) public {
arpToken = _arpToken;
owner = msg.sender;
depositStartTime = _depositStartTime;
depositStopTime = _depositStartTime.add(DEPOSIT_PERIOD);
}
/*
* PUBLIC FUNCTIONS
*/
/// Drains ARP.
function drain() public {
require(msg.sender == owner);
// solium-disable-next-line security/no-block-members
require(now >= depositStartTime.add(DRAIN_DELAY));
uint256 balance = arpToken.balanceOf(address(this));
require(balance > 0);
arpToken.safeTransfer(owner, balance);
emit Drained(balance);
}
function() public {
// solium-disable-next-line security/no-block-members
if (now >= depositStartTime && now < depositStopTime) {
deposit();
// solium-disable-next-line security/no-block-members
} else if (now > depositStopTime){
withdraw();
} else {
revert();
}
}
/// Gets the balance of the specified address.
function balanceOf(address _owner) view public returns (uint256) {
return records[_owner].amount;
}
/// Gets the withdrawal timestamp of the specified address.
function withdrawalTimeOf(address _owner) view public returns (uint256) {
return records[_owner].timestamp.add(WITHDRAWAL_DELAY);
}
/// Deposits ARP.
function deposit() private {
uint256 amount = arpToken
.balanceOf(msg.sender)
.min256(arpToken.allowance(msg.sender, address(this)));
require(amount > 0);
uint256 bonus = amount.div(BONUS_SCALE);
Record storage record = records[msg.sender];
record.amount = record.amount.add(amount).add(bonus);
// solium-disable-next-line security/no-block-members
record.timestamp = now;
records[msg.sender] = record;
arpDeposited = arpDeposited.add(amount).add(bonus);
if (bonus > 0) {
arpToken.safeTransferFrom(owner, address(this), bonus);
}
arpToken.safeTransferFrom(msg.sender, address(this), amount);
emit Deposit(depositId++, msg.sender, amount, bonus);
}
/// Withdraws ARP.
function withdraw() private {
require(arpDeposited > 0);
Record storage record = records[msg.sender];
require(record.amount > 0);
// solium-disable-next-line security/no-block-members
require(now >= record.timestamp.add(WITHDRAWAL_DELAY));
uint256 amount = record.amount;
delete records[msg.sender];
arpDeposited = arpDeposited.sub(amount);
arpToken.safeTransfer(msg.sender, amount);
emit Withdrawal(withdrawId++, msg.sender, amount);
}
}
|
solium-disable-next-line security/no-block-members solium-disable-next-line security/no-block-members
|
function() public {
if (now >= depositStartTime && now < depositStopTime) {
deposit();
withdraw();
revert();
}
}
| 5,421,229
|
// to test issue with nodes breaking with large clients over WS
// fixed in web3 with fragmentationThreshold: 8192
pragma solidity ^0.4.17;
contract BigFreakingContract {
event Transfer(address indexed from, address indexed to, uint value);
event Approval( address indexed owner, address indexed spender, uint value);
mapping( address => uint ) _balances;
mapping( address => mapping( address => uint ) ) _approvals;
uint public _supply;
constructor( uint initial_balance ) public {
_balances[msg.sender] = initial_balance;
_supply = initial_balance;
}
function totalSupply() public constant returns (uint supply) {
return _supply;
}
function balanceOf( address who ) public constant returns (uint value) {
return _balances[who];
}
function transfer( address to, uint value) public returns (bool ok) {
if( _balances[msg.sender] < value ) {
revert();
}
if( !safeToAdd(_balances[to], value) ) {
revert();
}
_balances[msg.sender] -= value;
_balances[to] += value;
emit Transfer( msg.sender, to, value );
return true;
}
function transferFrom( address from, address to, uint value) public returns (bool ok) {
// if you don't have enough balance, throw
if( _balances[from] < value ) {
revert();
}
// if you don't have approval, throw
if( _approvals[from][msg.sender] < value ) {
revert();
}
if( !safeToAdd(_balances[to], value) ) {
revert();
}
// transfer and return true
_approvals[from][msg.sender] -= value;
_balances[from] -= value;
_balances[to] += value;
emit Transfer( from, to, value );
return true;
}
function approve(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function allowance(address owner, address spender) public constant returns (uint _allowance) {
return _approvals[owner][spender];
}
function safeToAdd(uint a, uint b) internal pure returns (bool) {
return (a + b >= a);
}
function isAvailable() public pure returns (bool) {
return false;
}
function approve_1(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_2(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_3(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_4(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_5(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_6(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_7(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_8(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_9(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_10(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_11(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_12(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_13(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_14(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_15(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_16(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_17(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_18(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_19(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_20(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_21(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_22(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_23(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_24(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_25(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_26(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_27(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_28(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_29(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_30(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_31(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_32(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_33(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_34(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_35(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_36(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_37(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_38(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_39(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_40(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_41(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_42(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_43(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_44(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_45(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_46(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_47(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_48(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_49(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_50(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_51(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_52(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_53(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_54(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_55(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_56(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_57(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_58(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_59(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_60(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_61(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_62(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_63(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_64(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_65(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_66(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_67(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_68(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_69(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_70(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_71(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_72(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_73(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_74(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_75(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_76(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_77(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_78(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_79(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_80(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_81(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_82(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_83(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_84(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_85(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_86(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_87(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_88(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_89(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_90(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_91(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_92(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_93(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_94(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_95(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_96(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_97(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_98(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_99(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_100(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_101(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_102(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_103(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_104(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_105(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_106(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_107(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_108(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_109(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_110(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_111(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_112(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_113(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_114(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_115(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_116(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_117(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_118(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_119(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_120(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_121(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_122(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_123(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_124(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_125(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_126(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_127(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_128(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_129(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_130(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_131(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_132(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_133(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_134(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_135(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_136(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_137(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_138(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_139(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_140(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_141(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_142(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_143(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_144(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_145(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_146(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_147(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_148(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_149(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_150(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_151(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_152(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_153(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_154(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_155(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_156(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_157(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_158(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_159(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_160(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_161(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_162(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_163(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_164(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_165(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_166(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_167(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_168(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_169(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_170(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_171(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_172(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_173(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_174(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_175(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_176(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_177(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_178(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_179(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_180(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_181(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_182(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_183(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_184(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_185(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_186(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_187(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_188(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_189(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_190(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_191(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_192(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_193(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_194(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_195(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_196(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_197(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_198(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_199(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_200(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_201(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_202(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_203(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_204(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_205(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_206(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_207(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_208(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_209(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_210(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_211(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_212(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_213(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_214(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_215(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_216(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_217(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_218(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_219(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_220(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_221(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_222(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_223(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_224(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_225(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_226(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_227(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_228(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_229(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_230(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_231(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_232(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_233(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_234(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_235(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_236(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_237(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_238(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_239(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_240(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_241(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_242(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_243(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_244(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_245(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_246(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_247(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_248(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_249(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_250(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_251(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_252(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_253(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_254(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_255(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_256(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_257(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_258(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_259(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_260(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_261(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_262(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_263(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_264(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_265(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_266(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_267(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_268(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_269(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_270(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_271(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_272(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_273(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_274(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_275(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_276(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_277(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_278(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_279(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_280(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_281(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_282(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_283(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_284(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_285(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_286(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_287(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_288(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_289(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_290(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_291(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_292(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_293(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_294(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_295(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_296(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_297(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_298(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_299(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_300(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_301(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_302(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_303(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_304(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_305(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_306(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_307(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_308(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_309(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_310(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_311(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_312(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_313(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_314(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_315(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_316(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_317(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_318(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_319(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_320(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_321(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_322(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_323(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_324(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_325(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_326(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_327(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_328(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_329(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_330(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_331(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_332(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_333(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_334(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_335(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_336(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_337(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_338(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_339(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_340(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_341(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_342(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_343(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_344(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_345(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_346(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_347(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_348(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_349(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_350(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_351(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_352(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_353(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_354(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_355(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_356(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_357(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_358(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_359(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_360(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_361(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_362(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_363(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_364(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_365(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_366(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_367(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_368(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_369(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_370(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_371(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_372(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_373(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_374(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_375(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_376(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_377(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_378(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_379(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_380(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_381(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_382(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_383(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_384(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_385(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_386(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_387(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_388(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_389(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_390(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_391(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_392(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_393(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_394(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_395(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_396(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_397(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_398(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_399(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_400(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_401(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_402(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_403(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_404(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_405(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_406(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_407(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_408(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_409(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_410(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_411(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_412(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_413(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_414(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_415(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_416(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_417(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_418(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_419(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_420(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_421(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_422(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_423(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_424(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_425(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_426(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_427(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_428(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_429(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_430(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_431(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_432(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_433(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_434(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_435(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_436(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_437(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_438(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_439(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_440(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_441(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_442(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_443(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_444(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_445(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_446(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_447(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_448(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_449(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_450(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_451(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_452(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_453(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_454(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_455(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_456(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_457(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_458(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_459(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_460(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_461(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_462(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_463(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_464(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_465(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_466(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_467(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_468(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_469(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_470(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_471(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_472(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_473(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_474(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_475(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_476(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_477(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_478(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_479(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_480(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_481(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_482(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_483(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_484(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_485(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_486(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_487(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_488(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_489(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_490(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_491(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_492(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_493(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_494(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_495(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_496(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_497(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_498(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_499(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_500(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_501(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_502(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_503(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_504(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_505(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_506(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_507(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_508(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_509(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_510(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_511(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_512(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_513(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_514(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_515(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_516(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_517(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_518(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_519(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_520(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_521(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_522(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_523(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_524(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_525(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_526(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_527(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_528(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_529(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_530(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_531(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_532(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_533(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_534(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_535(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_536(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_537(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_538(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_539(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_540(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_541(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_542(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_543(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_544(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_545(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_546(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_547(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_548(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_549(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_550(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_551(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_552(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_553(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_554(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_555(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_556(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_557(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_558(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_559(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_560(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_561(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_562(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_563(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_564(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_565(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_566(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_567(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_568(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_569(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_570(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_571(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_572(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_573(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_574(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_575(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_576(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_577(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_578(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_579(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_580(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_581(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_582(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_583(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_584(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_585(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_586(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_587(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_588(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_589(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_590(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_591(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_592(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_593(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_594(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_595(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_596(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_597(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_598(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_599(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_600(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_601(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_602(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_603(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_604(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_605(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_606(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_607(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_608(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_609(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_610(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_611(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_612(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_613(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_614(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_615(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_616(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_617(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_618(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_619(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_620(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_621(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_622(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_623(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_624(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_625(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_626(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_627(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_628(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_629(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_630(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_631(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_632(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_633(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_634(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_635(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_636(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_637(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_638(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_639(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_640(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_641(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_642(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_643(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_644(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_645(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_646(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_647(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_648(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_649(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_650(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_651(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_652(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_653(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_654(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_655(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_656(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_657(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_658(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_659(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_660(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_661(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_662(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_663(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_664(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_665(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_666(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_667(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_668(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_669(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_670(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_671(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_672(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_673(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_674(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_675(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_676(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_677(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_678(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_679(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_680(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_681(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_682(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_683(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_684(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_685(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_686(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_687(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_688(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_689(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_690(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_691(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_692(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_693(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_694(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_695(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_696(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_697(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_698(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_699(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_700(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_701(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_702(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_703(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_704(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_705(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_706(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_707(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_708(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_709(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_710(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_711(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_712(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_713(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_714(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_715(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_716(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_717(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_718(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_719(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_720(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_721(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_722(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_723(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_724(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_725(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_726(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_727(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_728(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_729(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_730(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_731(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_732(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_733(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_734(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_735(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_736(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_737(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_738(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_739(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_740(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_741(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_742(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_743(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_744(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_745(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_746(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_747(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_748(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_749(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_750(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_751(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_752(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_753(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_754(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_755(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_756(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_757(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_758(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_759(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_760(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_761(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_762(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_763(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_764(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_765(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_766(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_767(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_768(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_769(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_770(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_771(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_772(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_773(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_774(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_775(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_776(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_777(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_778(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_779(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_780(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_781(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_782(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_783(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_784(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_785(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_786(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_787(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_788(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_789(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_790(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_791(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_792(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_793(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_794(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_795(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_796(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_797(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_798(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_799(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_800(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_801(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_802(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_803(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_804(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_805(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_806(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_807(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_808(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_809(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_810(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_811(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_812(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_813(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_814(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_815(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_816(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_817(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_818(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_819(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_820(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_821(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_822(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_823(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_824(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_825(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_826(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_827(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_828(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_829(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_830(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_831(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_832(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_833(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_834(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_835(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_836(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_837(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_838(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_839(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_840(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_841(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_842(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_843(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_844(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_845(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_846(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_847(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_848(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_849(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_850(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_851(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_852(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_853(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_854(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_855(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_856(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_857(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_858(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_859(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_860(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_861(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_862(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_863(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_864(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_865(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_866(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_867(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_868(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_869(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_870(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_871(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_872(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_873(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_874(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_875(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_876(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_877(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_878(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_879(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_880(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_881(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_882(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_883(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_884(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_885(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_886(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_887(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_888(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_889(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_890(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_891(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_892(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_893(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_894(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_895(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_896(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_897(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_898(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_899(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_900(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_901(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
}
|
TODO: should increase instead
|
function approve_827(address spender, uint value) public returns (bool ok) {
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
| 6,454,540
|
pragma solidity 0.4.24;
// pragma experimental ABIEncoderV2;
import "./LibMath.sol";
import "./FieldP384.sol";
import "./FieldO384.sol";
// NIST-P384 / secp384r1 curve
contract Curve384 is FieldP384, FieldO384 {
struct C384Elm {
uint256 xhi;
uint256 xlo;
uint256 yhi;
uint256 ylo;
}
// Curve parameters
uint256 constant cahi = 0xffffffffffffffffffffffffffffffff;
uint256 constant calo = 0xfffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc;
uint256 constant cbhi = 0xb3312fa7e23ee7e4988e056be3f82d19;
uint256 constant cblo = 0x181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef;
// Generator
uint256 constant gxhi = 0xaa87ca22be8b05378eb1c71ef320ad74;
uint256 constant gxlo = 0x6e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7;
uint256 constant gyhi = 0x3617de4a96262c6f5d9e98bf9292dc29;
uint256 constant gylo = 0xf8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f;
// Assignment: a' = b
function cset(C384Elm memory a, C384Elm memory b)
internal pure
{
a.xhi = b.xhi;
a.xlo = b.xlo;
a.yhi = b.yhi;
a.ylo = b.ylo;
}
// In place addition: a' = a + b
function cadd(C384Elm memory a, C384Elm memory b)
internal view
{
// 817 010 gas
uint256 lhi;
uint256 llo;
uint256 thi;
uint256 tlo;
// l = (ay - by) / (ax - bx)
(lhi, llo) = fsub(a.yhi, a.ylo, b.yhi, b.ylo);
(thi, tlo) = fsub(a.xhi, a.xlo, b.xhi, b.xlo);
(thi, tlo) = finv(thi, tlo);
(lhi, llo) = fmul(lhi, llo, thi, tlo);
// x = l * l - ax - bx
(thi, tlo) = fsqr(lhi, llo);
(thi, tlo) = fsub(thi, tlo, a.xhi, a.xlo);
(thi, tlo) = fsub(thi, tlo, b.xhi, b.xlo);
a.xhi = thi;
a.xlo = tlo;
// y = l * (bx - x) - by
(thi, tlo) = fsub(b.xhi, b.xlo, a.xhi, a.xlo);
(thi, tlo) = fmul(thi, tlo, lhi, llo);
(thi, tlo) = fsub(thi, tlo, b.yhi, b.ylo);
a.yhi = thi;
a.ylo = tlo;
}
// In place double: a' = a + a
function cdbl(C384Elm memory a)
internal view
{
// 1 490 576 gas
uint256 lhi;
uint256 llo;
uint256 thi;
uint256 tlo;
uint256 xhi;
uint256 xlo;
// l = (3 * ax * ax + ca) / (2 * ay)
(lhi, llo) = fmul(0, 3, a.xhi, a.xlo);
(lhi, llo) = fmul(lhi, llo, a.xhi, a.xlo);
(lhi, llo) = fadd(lhi, llo, cahi, calo);
(thi, tlo) = fadd(a.yhi, a.ylo, a.yhi, a.ylo);
(thi, tlo) = finv(thi, tlo);
(lhi, llo) = fmul(lhi, llo, thi, tlo);
// x = l * l - ax - ax
(thi, tlo) = fsqr(lhi, llo);
(thi, tlo) = fsub(thi, tlo, a.xhi, a.xlo);
(thi, tlo) = fsub(thi, tlo, a.xhi, a.xlo);
xhi = thi;
xlo = tlo;
// y = l * (ax - x) - ay
(thi, tlo) = fsub(a.xhi, a.xlo, xhi, xlo);
(thi, tlo) = fmul(thi, tlo, lhi, llo);
(thi, tlo) = fsub(thi, tlo, a.yhi, a.ylo);
a.xhi = xhi;
a.xlo = xlo;
a.yhi = thi;
a.ylo = tlo;
}
// In place multiply a' = a * r
function cmul(C384Elm memory a, uint256 rhi, uint256 rlo)
internal view
{
bool running = false;
C384Elm memory r;
while(rhi != 0 || rlo != 0) {
if (rlo & 1 == 1) {
if (running) {
cadd(r, a);
} else {
cset(r, a);
running = true;
}
}
// a = a + a
cdbl(a);
// r >>= 2
assembly {
rlo := div(rlo, 2)
rlo := or(rlo, mul(rhi, 0x8000000000000000000000000000000000000000000000000000000000000000))
rhi := div(rhi, 2)
}
}
cset(a, r);
}
function verify(
C384Elm memory pub,
uint256 m,
uint256 rhi, uint256 rlo,
uint256 shi, uint256 slo)
internal view
returns (bool)
{
uint256 uhi;
uint256 ulo;
uint256 vhi;
uint256 vlo;
C384Elm memory g = C384Elm({
xhi: gxhi,
xlo: gxlo,
yhi: gyhi,
ylo: gylo
});
(shi, slo) = oinv(shi, slo);
(uhi, ulo) = omul(0, m, shi, slo);
(vhi, vlo) = omul(rhi, rlo, shi, slo);
cmul(g, uhi, ulo);
cmul(pub, vhi, vlo);
cadd(g, pub);
return g.xhi == rhi && g.xlo == rlo;
}
C384Elm[384] generatorTable;
C384Elm[384] pubkeyTable;
function precomputeGen()
public
{
C384Elm memory g = C384Elm({
xhi: gxhi,
xlo: gxlo,
yhi: gyhi,
ylo: gylo
});
for(uint256 i = 0; i < 383; i++) {
generatorTable[i] = g;
cdbl(g);
}
generatorTable[383] = g;
}
function precomputePub(
uint256 xhi, uint256 xlo,
uint256 yhi, uint256 ylo)
public
{
C384Elm memory p = C384Elm({
xhi: xhi,
xlo: xlo,
yhi: yhi,
ylo: ylo
});
for(uint256 i = 0; i < 383; i++) {
pubkeyTable[i] = p;
cdbl(p);
}
pubkeyTable[383] = p;
}
function cmulgen(C384Elm memory r, uint256 rhi, uint256 rlo)
internal view
{
bool running = false;
uint256 i = 0;
while(rhi != 0 || rlo != 0) {
if (rlo & 1 == 1) {
if (running) {
cadd(r, generatorTable[i]);
} else {
cset(r, generatorTable[i]);
running = true;
}
}
i++;
// r >>= 2
assembly {
rlo := div(rlo, 2)
rlo := or(rlo, mul(rhi, 0x8000000000000000000000000000000000000000000000000000000000000000))
rhi := div(rhi, 2)
}
}
}
function cmulpub(C384Elm memory r, uint256 rhi, uint256 rlo)
internal view
{
bool running = false;
uint256 i = 0;
while(rhi != 0 || rlo != 0) {
if (rlo & 1 == 1) {
if (running) {
cadd(r, pubkeyTable[i]);
} else {
cset(r, pubkeyTable[i]);
running = true;
}
}
i++;
// r >>= 2
assembly {
rlo := div(rlo, 2)
rlo := or(rlo, mul(rhi, 0x8000000000000000000000000000000000000000000000000000000000000000))
rhi := div(rhi, 2)
}
}
}
function verify_fast(
uint256 m,
uint256 rhi, uint256 rlo,
uint256 shi, uint256 slo)
internal view
returns (bool)
{
uint256 uhi;
uint256 ulo;
uint256 vhi;
uint256 vlo;
(shi, slo) = oinv(shi, slo);
(uhi, ulo) = omul(0, m, shi, slo);
(vhi, vlo) = omul(rhi, rlo, shi, slo);
C384Elm memory gen;
C384Elm memory pub;
cmulgen(gen, uhi, ulo);
cmulpub(pub, vhi, vlo);
cadd(gen, pub);
return gen.xhi == rhi && gen.xlo == rlo;
}
function double(
C384Elm a)
internal view
returns (C384Elm)
{
cdbl(a);
return a;
}
function test_fadd()
{
uint256 xhi = 0xc84a6e6ec1e7f30f5c812eeba420f769;
uint256 xlo = 0xb78d377301367565d6c4579d1bd222dbf64ea76464731482fd32a61ebde26432;
uint256 yhi = 0xd0d9d4f899b00456516b647c5e9b7ed;
uint256 ylo = 0x2c538d7878e63e8da0603396b4cbd9494d42f691141f9e2e5927cf88aac0c63;
uint256 hi;
uint256 lo;
(hi, lo) = fadd(xhi, xlo, yhi, ylo);
assert(hi == 0xd5580bbe4b82f354c197e5336a0aaf56);
assert(lo == 0xba52704a88c4d94eb0ca5ad6871ee0708b22d6cd75b50e65e2c52317488e7095);
}
function test_fsub()
{
uint256 xhi = 0x3e501df64c8d7065d58eac499351e2a;
uint256 xlo = 0xfcdc74fda6bd4980919ca5dcf51075e51e36e9442aba748d8d9931e0f1332bd6;
uint256 yhi = 0x49451a30e75e7a6a7f48519b72a60e4f;
uint256 ylo = 0xf737d5a207bc2e493b8455c10652357e19a1044de6e3c1d680f328cb7015f4ee;
uint256 hi;
uint256 lo;
(hi, lo) = fsub(xhi, xlo, yhi, ylo);
assert(hi == 0xba9fe7ae7d6a5c9bde109929268f0fdb);
assert(lo == 0x5a49f5b9f011b375618501beebe40660495e4f543d6b2b70ca60916811d36e7);
}
function test_fmul()
{
uint256 xhi = 0xc84a6e6ec1e7f30f5c812eeba420f769;
uint256 xlo = 0xb78d377301367565d6c4579d1bd222dbf64ea76464731482fd32a61ebde26432;
uint256 yhi = 0xd0d9d4f899b00456516b647c5e9b7ed;
uint256 ylo = 0x02c538d7878e63e8da0603396b4cbd9494d42f691141f9e2e5927cf88aac0c63;
uint256 hi;
uint256 lo;
(hi, lo) = fmul(xhi, xlo, yhi, ylo);
assert(hi == 0x5de8b2b22ecdf6790f0c7de8ea01bdd6);
assert(lo == 0xfb8446353273f6053dd29c5ef32974403861d4b388cefccf2e01f63f53b6ffe0);
}
function test_fmul2()
{
uint256 xhi = 0x58df4b4c45b7d92e15838cc2ec62e63d;
uint256 xlo = 0x26a7a65903a36031844d06d753766895e2ebf62f2d593d88f797f25a39a72c98;
uint256 yhi = 0xc84a6e6ec1e7f30f5c812eeba420f769;
uint256 ylo = 0xb78d377301367565d6c4579d1bd222dbf64ea76464731482fd32a61ebde26432;
uint256 hi;
uint256 lo;
(hi, lo) = fmul(xhi, xlo, yhi, ylo);
assert(hi == 0x858564b53562cbd97f41a5389d7e6673);
assert(lo == 0x41d0469bbe77677a1ec703fcfcf7fe3f1d0c7b85bf517be09e3b5d480678f3be);
}
function test_finv()
{
uint256 xhi = 0x3e501df64c8d7065d58eac499351e2a;
uint256 xlo = 0xfcdc74fda6bd4980919ca5dcf51075e51e36e9442aba748d8d9931e0f1332bd6;
uint256 hi;
uint256 lo;
(hi, lo) = finv(xhi, xlo);
assert(hi == 0xba2909a8e60a55d7a0caf129a18c6c6a);
assert(lo == 0xa41434c431646bb4a928e76ad732152f35eb59e6df429de7323e5813809f03dc);
}
function test_cadd()
{
C384Elm memory a = C384Elm({
xhi:0xc84a6e6ec1e7f30f5c812eeba420f769,
xlo:0xb78d377301367565d6c4579d1bd222dbf64ea76464731482fd32a61ebde26432,
yhi:0xd0d9d4f899b00456516b647c5e9b7ed,
ylo:0x2c538d7878e63e8da0603396b4cbd9494d42f691141f9e2e5927cf88aac0c63
});
C384Elm memory b = C384Elm({
xhi:0xaa87ca22be8b05378eb1c71ef320ad74,
xlo:0x6e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7,
yhi:0x3617de4a96262c6f5d9e98bf9292dc29,
ylo:0xf8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f
});
cadd(a, b);
assert(a.xhi == 0x17dfbde58f77ce2cf0bb835b5eaeb01c);
assert(a.xlo == 0x50dc4050bfeb273cd1b1e7919e4c6101cc3464fdab6327de6bbabd9c33cb87f8);
assert(a.yhi == 0xed3036644cffedab5c397b740906e3c0);
assert(a.ylo == 0xf77b491250488f74577a9f5033fb5fc8de2063466c7a0c395e0e6bc2c91e1a6f);
}
function test_cdbl()
{
C384Elm memory a = C384Elm({
xhi:0xc84a6e6ec1e7f30f5c812eeba420f769,
xlo:0xb78d377301367565d6c4579d1bd222dbf64ea76464731482fd32a61ebde26432,
yhi:0xd0d9d4f899b00456516b647c5e9b7ed,
ylo:0x2c538d7878e63e8da0603396b4cbd9494d42f691141f9e2e5927cf88aac0c63
});
cdbl(a);
assert(a.xhi == 0x17136874b0f7adaaf3c5a9fac85c689e);
assert(a.xlo == 0x3bbae87a0d2e974e226bcbc8007df64e584769a9fbb8ddcb1a0ae09e90a043c3);
assert(a.yhi == 0xff058ae937fa8b0be1479de0629f1a10);
assert(a.ylo == 0x9af355e0dc60f1416906e178f0174517a4d330f7aa1176ffcbd8a47f226f8a10);
}
function test_cmul()
{
C384Elm memory a = C384Elm({
xhi:0xc84a6e6ec1e7f30f5c812eeba420f769,
xlo:0xb78d377301367565d6c4579d1bd222dbf64ea76464731482fd32a61ebde26432,
yhi:0xd0d9d4f899b00456516b647c5e9b7ed,
ylo:0x2c538d7878e63e8da0603396b4cbd9494d42f691141f9e2e5927cf88aac0c63
});
uint256 rhi = 0xeeb9131427fd0f0b7195733c60dd8a99;
uint256 rlo = 0x822e6250b731e570244afe1053226cc83bcfb2a4280b6f2a81f2a723f62a457e;
cmul(a, rhi, rlo);
assert(a.xhi == 0x6744cd0397ec1b44cd58bb28f842557d);
assert(a.xlo == 0x135fa346d9706879ce0cba91105172106df49ea8d38529cbbce95a776491e482);
assert(a.yhi == 0x376ea46200e2a971cfd1b26798bd5ef6);
assert(a.ylo == 0x95f9eb9240e1ec929ee71a46ae57b52e60d75640646df19053d997896807c78d);
}
function test_verify()
{
C384Elm memory a = C384Elm({
xhi:0xc84a6e6ec1e7f30f5c812eeba420f769,
xlo:0xb78d377301367565d6c4579d1bd222dbf64ea76464731482fd32a61ebde26432,
yhi:0xd0d9d4f899b00456516b647c5e9b7ed,
ylo:0x2c538d7878e63e8da0603396b4cbd9494d42f691141f9e2e5927cf88aac0c63
});
uint256 m = 0x413140d54372f9baf481d4c54e2d5c7bcf28fd6087000280e07976121dd54af2;
uint256 rhi = 0xeeb9131427fd0f0b7195733c60dd8a99;
uint256 rlo = 0x822e6250b731e570244afe1053226cc83bcfb2a4280b6f2a81f2a723f62a457e;
uint256 shi = 0xee281a7e5d0ea6a14e00c1759f79fddb;
uint256 slo = 0xd91f3994cae97f886b1f2615c6a51839f13e1b21becd3d21accaccaceed2725f;
bool result = verify(a, m, rhi, rlo, shi, slo);
assert(result == true);
}
function test_verify_neg()
{
C384Elm memory a = C384Elm({
xhi:0xc84a6e6ec1e7f30f5c812eeba420f769,
xlo:0xb78d377301367565d6c4579d1bd222dbf64ea76464731482fd32a61ebde26432,
yhi:0xd0d9d4f899b00456516b647c5e9b7ed,
ylo:0x2c538d7878e63e8da0603396b4cbd9494d42f691141f9e2e5927cf88aac0c63
});
uint256 m = 0x413140d54372f9baf481d4c54e2d5c7bcf28fd6087000280e07976121dd54af2;
uint256 rhi = 0xeeb9131427fd0f0b7195733c60dd8a99;
uint256 rlo = 0x822e6250b731e570244afe1053226cc83bcfb2a4280b6f2a81f2a723f62a457e;
uint256 shi = 0xee281a7e5d0ea6a14e00c1759f79fddb;
uint256 slo = 0xd91f3994cae97f886b1f2615c6a51839f13e1b21becd3d21accaccaceed2725f;
bool result = verify(a, m, shi, slo, rhi, rlo);
assert(result == false);
}
function test_verify_fast()
{
uint256 m = 0x413140d54372f9baf481d4c54e2d5c7bcf28fd6087000280e07976121dd54af2;
uint256 rhi = 0xeeb9131427fd0f0b7195733c60dd8a99;
uint256 rlo = 0x822e6250b731e570244afe1053226cc83bcfb2a4280b6f2a81f2a723f62a457e;
uint256 shi = 0xee281a7e5d0ea6a14e00c1759f79fddb;
uint256 slo = 0xd91f3994cae97f886b1f2615c6a51839f13e1b21becd3d21accaccaceed2725f;
bool result = verify_fast(m, rhi, rlo, shi, slo);
assert(result == true);
}
}
|
In place multiply a' = a r r >>= 2
|
function cmul(C384Elm memory a, uint256 rhi, uint256 rlo)
internal view
{
bool running = false;
C384Elm memory r;
while(rhi != 0 || rlo != 0) {
if (rlo & 1 == 1) {
if (running) {
cadd(r, a);
cset(r, a);
running = true;
}
}
assembly {
rlo := div(rlo, 2)
rlo := or(rlo, mul(rhi, 0x8000000000000000000000000000000000000000000000000000000000000000))
rhi := div(rhi, 2)
}
}
cset(a, r);
}
| 1,035,815
|
/**
*Submitted for verification at Etherscan.io on 2020-11-15
*/
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.4.24;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol
pragma solidity ^0.4.24;
/**
* @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() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
}
// File: openzeppelin-solidity/contracts/access/rbac/Roles.sol
pragma solidity ^0.4.24;
/**
* @title Roles
* @author Francisco Giordano (@frangio)
* @dev Library for managing addresses assigned to a Role.
* See RBAC.sol for example usage.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an address access to this role
*/
function add(Role storage _role, address _addr)
internal
{
_role.bearer[_addr] = true;
}
/**
* @dev remove an address' access to this role
*/
function remove(Role storage _role, address _addr)
internal
{
_role.bearer[_addr] = false;
}
/**
* @dev check if an address has this role
* // reverts
*/
function check(Role storage _role, address _addr)
internal
view
{
require(has(_role, _addr));
}
/**
* @dev check if an address has this role
* @return bool
*/
function has(Role storage _role, address _addr)
internal
view
returns (bool)
{
return _role.bearer[_addr];
}
}
// File: openzeppelin-solidity/contracts/access/rbac/RBAC.sol
pragma solidity ^0.4.24;
/**
* @title RBAC (Role-Based Access Control)
* @author Matt Condon (@Shrugs)
* @dev Stores and provides setters and getters for roles and addresses.
* Supports unlimited numbers of roles and addresses.
* See //contracts/mocks/RBACMock.sol for an example of usage.
* This RBAC method uses strings to key roles. It may be beneficial
* for you to write your own implementation of this interface using Enums or similar.
*/
contract RBAC {
using Roles for Roles.Role;
mapping (string => Roles.Role) private roles;
event RoleAdded(address indexed operator, string role);
event RoleRemoved(address indexed operator, string role);
/**
* @dev reverts if addr does not have role
* @param _operator address
* @param _role the name of the role
* // reverts
*/
function checkRole(address _operator, string _role)
public
view
{
roles[_role].check(_operator);
}
/**
* @dev determine if addr has role
* @param _operator address
* @param _role the name of the role
* @return bool
*/
function hasRole(address _operator, string _role)
public
view
returns (bool)
{
return roles[_role].has(_operator);
}
/**
* @dev add a role to an address
* @param _operator address
* @param _role the name of the role
*/
function addRole(address _operator, string _role)
internal
{
roles[_role].add(_operator);
emit RoleAdded(_operator, _role);
}
/**
* @dev remove a role from an address
* @param _operator address
* @param _role the name of the role
*/
function removeRole(address _operator, string _role)
internal
{
roles[_role].remove(_operator);
emit RoleRemoved(_operator, _role);
}
/**
* @dev modifier to scope access to a single role (uses msg.sender as addr)
* @param _role the name of the role
* // reverts
*/
modifier onlyRole(string _role)
{
checkRole(msg.sender, _role);
_;
}
/**
* @dev modifier to scope access to a set of roles (uses msg.sender as addr)
* @param _roles the names of the roles to scope access to
* // reverts
*
* @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this
* see: https://github.com/ethereum/solidity/issues/2467
*/
// modifier onlyRoles(string[] _roles) {
// bool hasAnyRole = false;
// for (uint8 i = 0; i < _roles.length; i++) {
// if (hasRole(msg.sender, _roles[i])) {
// hasAnyRole = true;
// break;
// }
// }
// require(hasAnyRole);
// _;
// }
}
// File: openzeppelin-solidity/contracts/access/Whitelist.sol
pragma solidity ^0.4.24;
/**
* @title Whitelist
* @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions.
* This simplifies the implementation of "user permissions".
*/
contract Whitelist is Ownable, RBAC {
string public constant ROLE_WHITELISTED = "whitelist";
/**
* @dev Throws if operator is not whitelisted.
* @param _operator address
*/
modifier onlyIfWhitelisted(address _operator) {
checkRole(_operator, ROLE_WHITELISTED);
_;
}
/**
* @dev add an address to the whitelist
* @param _operator address
* @return true if the address was added to the whitelist, false if the address was already in the whitelist
*/
function addAddressToWhitelist(address _operator)
public
onlyOwner
{
addRole(_operator, ROLE_WHITELISTED);
}
/**
* @dev getter to determine if address is in whitelist
*/
function whitelist(address _operator)
public
view
returns (bool)
{
return hasRole(_operator, ROLE_WHITELISTED);
}
/**
* @dev add addresses to the whitelist
* @param _operators addresses
* @return true if at least one address was added to the whitelist,
* false if all addresses were already in the whitelist
*/
function addAddressesToWhitelist(address[] _operators)
public
onlyOwner
{
for (uint256 i = 0; i < _operators.length; i++) {
addAddressToWhitelist(_operators[i]);
}
}
/**
* @dev remove an address from the whitelist
* @param _operator address
* @return true if the address was removed from the whitelist,
* false if the address wasn't in the whitelist in the first place
*/
function removeAddressFromWhitelist(address _operator)
public
onlyOwner
{
removeRole(_operator, ROLE_WHITELISTED);
}
/**
* @dev remove addresses from the whitelist
* @param _operators addresses
* @return true if at least one address was removed from the whitelist,
* false if all addresses weren't in the whitelist in the first place
*/
function removeAddressesFromWhitelist(address[] _operators)
public
onlyOwner
{
for (uint256 i = 0; i < _operators.length; i++) {
removeAddressFromWhitelist(_operators[i]);
}
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
// File: contracts/v2/ReentrancyGuard.sol
pragma solidity ^0.4.24;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
contract ReentrancyGuard {
bool private _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;
}
}
// File: contracts/v2/marketplace/TokenMarketplaceV2.sol
pragma solidity ^0.4.24;
interface IKODAV2Methods {
function ownerOf(uint256 _tokenId) external view returns (address _owner);
function exists(uint256 _tokenId) external view returns (bool _exists);
function editionOfTokenId(uint256 _tokenId) external view returns (uint256 tokenId);
function artistCommission(uint256 _tokenId) external view returns (address _artistAccount, uint256 _artistCommission);
function editionOptionalCommission(uint256 _tokenId) external view returns (uint256 _rate, address _recipient);
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external;
}
// Based on ITokenMarketplace.sol
contract TokenMarketplaceV2 is Whitelist, Pausable, ReentrancyGuard {
using SafeMath for uint256;
event UpdatePlatformPercentageFee(uint256 _oldPercentage, uint256 _newPercentage);
event UpdateRoyaltyPercentageFee(uint256 _oldPercentage, uint256 _newPercentage);
event UpdateMinBidAmount(uint256 minBidAmount);
event TokenListed(
uint256 indexed _tokenId,
address indexed _seller,
uint256 _price
);
event TokenDeListed(
uint256 indexed _tokenId
);
event TokenPurchased(
uint256 indexed _tokenId,
address indexed _buyer,
address indexed _seller,
uint256 _price
);
event BidPlaced(
uint256 indexed _tokenId,
address indexed _currentOwner,
address indexed _bidder,
uint256 _amount
);
event BidWithdrawn(
uint256 indexed _tokenId,
address indexed _bidder
);
event BidAccepted(
uint256 indexed _tokenId,
address indexed _currentOwner,
address indexed _bidder,
uint256 _amount
);
event BidRejected(
uint256 indexed _tokenId,
address indexed _currentOwner,
address indexed _bidder,
uint256 _amount
);
event AuctionEnabled(
uint256 indexed _tokenId,
address indexed _auctioneer
);
event AuctionDisabled(
uint256 indexed _tokenId,
address indexed _auctioneer
);
event ListingEnabled(
uint256 indexed _tokenId
);
event ListingDisabled(
uint256 indexed _tokenId
);
struct Offer {
address bidder;
uint256 offer;
}
struct Listing {
uint256 price;
address seller;
}
// Min increase in bid/list amount
uint256 public minBidAmount = 0.01 ether;
// Interface into the KODA world
IKODAV2Methods public kodaAddress;
// KO account which can receive commission
address public koCommissionAccount;
uint256 public artistRoyaltyPercentage = 100;
uint256 public platformFeePercentage = 25;
// Token ID to Offer mapping
mapping(uint256 => Offer) public offers;
// Token ID to Listing
mapping(uint256 => Listing) public listings;
// Explicitly disable sales for specific tokens
mapping(uint256 => bool) public disabledTokens;
// Explicitly disable listings for specific tokens
mapping(uint256 => bool) public disabledListings;
///////////////
// Modifiers //
///////////////
modifier onlyWhenOfferOwner(uint256 _tokenId) {
require(offers[_tokenId].bidder == msg.sender, "Not offer maker");
_;
}
modifier onlyWhenTokenExists(uint256 _tokenId) {
require(kodaAddress.exists(_tokenId), "Token does not exist");
_;
}
modifier onlyWhenBidOverMinAmount(uint256 _tokenId) {
require(msg.value >= offers[_tokenId].offer.add(minBidAmount), "Offer not enough");
_;
}
modifier onlyWhenTokenAuctionEnabled(uint256 _tokenId) {
require(!disabledTokens[_tokenId], "Token not enabled for offers");
_;
}
/////////////////
// Constructor //
/////////////////
// Set the caller as the default KO account
constructor(IKODAV2Methods _kodaAddress, address _koCommissionAccount) public {
kodaAddress = _kodaAddress;
koCommissionAccount = _koCommissionAccount;
super.addAddressToWhitelist(msg.sender);
}
//////////////////////////
// User Bidding Actions //
//////////////////////////
function placeBid(uint256 _tokenId)
public
payable
whenNotPaused
nonReentrant
onlyWhenTokenExists(_tokenId)
onlyWhenBidOverMinAmount(_tokenId)
onlyWhenTokenAuctionEnabled(_tokenId)
{
require(!isContract(msg.sender), "Unable to place a bid as a contract");
_refundHighestBidder(_tokenId);
offers[_tokenId] = Offer({bidder : msg.sender, offer : msg.value});
address currentOwner = kodaAddress.ownerOf(_tokenId);
emit BidPlaced(_tokenId, currentOwner, msg.sender, msg.value);
}
function withdrawBid(uint256 _tokenId)
public
whenNotPaused
nonReentrant
onlyWhenTokenExists(_tokenId)
onlyWhenOfferOwner(_tokenId)
{
_refundHighestBidder(_tokenId);
emit BidWithdrawn(_tokenId, msg.sender);
}
function rejectBid(uint256 _tokenId)
public
whenNotPaused
nonReentrant
{
address currentOwner = kodaAddress.ownerOf(_tokenId);
require(currentOwner == msg.sender, "Not token owner");
uint256 currentHighestBiddersAmount = offers[_tokenId].offer;
require(currentHighestBiddersAmount > 0, "No offer open");
address currentHighestBidder = offers[_tokenId].bidder;
_refundHighestBidder(_tokenId);
emit BidRejected(_tokenId, currentOwner, currentHighestBidder, currentHighestBiddersAmount);
}
function acceptBid(uint256 _tokenId, uint256 _acceptedAmount)
public
whenNotPaused
nonReentrant
{
address currentOwner = kodaAddress.ownerOf(_tokenId);
require(currentOwner == msg.sender, "Not token owner");
Offer storage offer = offers[_tokenId];
uint256 winningOffer = offer.offer;
// Check valid offer and offer not replaced whilst inflight
require(winningOffer > 0 && _acceptedAmount >= winningOffer, "Offer amount not satisfied");
address winningBidder = offer.bidder;
delete offers[_tokenId];
// Get edition no.
uint256 editionNumber = kodaAddress.editionOfTokenId(_tokenId);
_handleFunds(editionNumber, winningOffer, currentOwner);
kodaAddress.safeTransferFrom(msg.sender, winningBidder, _tokenId);
emit BidAccepted(_tokenId, currentOwner, winningBidder, winningOffer);
}
function _refundHighestBidder(uint256 _tokenId) internal {
// Get current highest bidder
address currentHighestBidder = offers[_tokenId].bidder;
if (currentHighestBidder != address(0)) {
// Get current highest bid amount
uint256 currentHighestBiddersAmount = offers[_tokenId].offer;
if (currentHighestBiddersAmount > 0) {
// Clear out highest bidder
delete offers[_tokenId];
// Refund it
currentHighestBidder.transfer(currentHighestBiddersAmount);
}
}
}
//////////////////////////
// User Listing Actions //
//////////////////////////
function listToken(uint256 _tokenId, uint256 _listingPrice)
public
whenNotPaused {
require(!disabledListings[_tokenId], "Listing disabled");
// Check ownership before listing
address tokenOwner = kodaAddress.ownerOf(_tokenId);
require(tokenOwner == msg.sender, "Not token owner");
// Check price over min bid
require(_listingPrice >= minBidAmount, "Listing price not enough");
// List the token
listings[_tokenId] = Listing({
price : _listingPrice,
seller : msg.sender
});
emit TokenListed(_tokenId, msg.sender, _listingPrice);
}
function delistToken(uint256 _tokenId)
public
whenNotPaused {
// check listing found
require(listings[_tokenId].seller != address(0), "No listing found");
// check owner is msg.sender
require(kodaAddress.ownerOf(_tokenId) == msg.sender, "Only the current owner can delist");
_delistToken(_tokenId);
}
function buyToken(uint256 _tokenId)
public
payable
nonReentrant
whenNotPaused {
Listing storage listing = listings[_tokenId];
// check token is listed
require(listing.seller != address(0), "No listing found");
// check current owner is the lister as it may have changed hands
address currentOwner = kodaAddress.ownerOf(_tokenId);
require(listing.seller == currentOwner, "Listing not valid, token owner has changed");
// check listing satisfied
uint256 listingPrice = listing.price;
require(msg.value == listingPrice, "List price not satisfied");
// Get edition no.
uint256 editionNumber = kodaAddress.editionOfTokenId(_tokenId);
// refund any open offers on it
Offer storage offer = offers[_tokenId];
_refundHighestBidder(_tokenId);
// split funds
_handleFunds(editionNumber, listingPrice, currentOwner);
// transfer token to buyer
kodaAddress.safeTransferFrom(currentOwner, msg.sender, _tokenId);
// de-list the token
_delistToken(_tokenId);
// Fire confirmation event
emit TokenPurchased(_tokenId, msg.sender, currentOwner, listingPrice);
}
function _delistToken(uint256 _tokenId) private {
delete listings[_tokenId];
emit TokenDeListed(_tokenId);
}
////////////////////
// Funds handling //
////////////////////
function _handleFunds(uint256 _editionNumber, uint256 _offer, address _currentOwner) internal {
// Get existing artist commission
(address artistAccount, uint256 artistCommissionRate) = kodaAddress.artistCommission(_editionNumber);
// Get existing optional commission
(uint256 optionalCommissionRate, address optionalCommissionRecipient) = kodaAddress.editionOptionalCommission(_editionNumber);
_splitFunds(artistAccount, artistCommissionRate, optionalCommissionRecipient, optionalCommissionRate, _offer, _currentOwner);
}
function _splitFunds(
address _artistAccount,
uint256 _artistCommissionRate,
address _optionalCommissionRecipient,
uint256 _optionalCommissionRate,
uint256 _offer,
address _currentOwner
) internal {
// Work out total % of royalties to payout = creator royalties + KO commission
uint256 totalCommissionPercentageToPay = platformFeePercentage.add(artistRoyaltyPercentage);
// Send current owner majority share of the offer
uint256 totalToSendToOwner = _offer.sub(
_offer.div(1000).mul(totalCommissionPercentageToPay)
);
_currentOwner.transfer(totalToSendToOwner);
// Send % to KO
uint256 koCommission = _offer.div(1000).mul(platformFeePercentage);
koCommissionAccount.transfer(koCommission);
// Send to seller minus royalties and commission
uint256 remainingRoyalties = _offer.sub(koCommission).sub(totalToSendToOwner);
if (_optionalCommissionRecipient == address(0)) {
// After KO and Seller - send the rest to the original artist
_artistAccount.transfer(remainingRoyalties);
} else {
_handleOptionalSplits(_artistAccount, _artistCommissionRate, _optionalCommissionRecipient, _optionalCommissionRate, remainingRoyalties);
}
}
function _handleOptionalSplits(
address _artistAccount,
uint256 _artistCommissionRate,
address _optionalCommissionRecipient,
uint256 _optionalCommissionRate,
uint256 _remainingRoyalties
) internal {
uint256 _totalCollaboratorsRate = _artistCommissionRate.add(_optionalCommissionRate);
uint256 _scaledUpCommission = _artistCommissionRate.mul(10 ** 18);
// work out % of royalties total to split e.g. 43 / 85 = 50.5882353%
uint256 primaryArtistPercentage = _scaledUpCommission.div(_totalCollaboratorsRate);
uint256 totalPrimaryRoyaltiesToArtist = _remainingRoyalties.mul(primaryArtistPercentage).div(10 ** 18);
_artistAccount.transfer(totalPrimaryRoyaltiesToArtist);
uint256 remainingRoyaltiesToCollaborator = _remainingRoyalties.sub(totalPrimaryRoyaltiesToArtist);
_optionalCommissionRecipient.transfer(remainingRoyaltiesToCollaborator);
}
///////////////////
// Query Methods //
///////////////////
function tokenOffer(uint256 _tokenId) external view returns (address _bidder, uint256 _offer, address _owner, bool _enabled, bool _paused) {
Offer memory offer = offers[_tokenId];
return (
offer.bidder,
offer.offer,
kodaAddress.ownerOf(_tokenId),
!disabledTokens[_tokenId],
paused
);
}
function determineSaleValues(uint256 _tokenId) external view returns (uint256 _sellerTotal, uint256 _platformFee, uint256 _royaltyFee) {
Offer memory offer = offers[_tokenId];
uint256 offerValue = offer.offer;
uint256 fee = offerValue.div(1000).mul(platformFeePercentage);
uint256 royalties = offerValue.div(1000).mul(artistRoyaltyPercentage);
return (
offer.offer.sub(fee).sub(royalties),
fee,
royalties
);
}
function tokenListingDetails(uint256 _tokenId) external view returns (uint256 _price, address _lister, address _currentOwner) {
Listing memory listing = listings[_tokenId];
return (
listing.price,
listing.seller,
kodaAddress.ownerOf(_tokenId)
);
}
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;
}
///////////////////
// Admin Actions //
///////////////////
function disableAuction(uint256 _tokenId)
public
onlyIfWhitelisted(msg.sender)
{
_refundHighestBidder(_tokenId);
disabledTokens[_tokenId] = true;
emit AuctionDisabled(_tokenId, msg.sender);
}
function enableAuction(uint256 _tokenId)
public
onlyIfWhitelisted(msg.sender)
{
_refundHighestBidder(_tokenId);
disabledTokens[_tokenId] = false;
emit AuctionEnabled(_tokenId, msg.sender);
}
function disableListing(uint256 _tokenId)
public
onlyIfWhitelisted(msg.sender)
{
_delistToken(_tokenId);
disabledListings[_tokenId] = true;
emit ListingDisabled(_tokenId);
}
function enableListing(uint256 _tokenId)
public
onlyIfWhitelisted(msg.sender)
{
disabledListings[_tokenId] = false;
emit ListingEnabled(_tokenId);
}
function setMinBidAmount(uint256 _minBidAmount) onlyIfWhitelisted(msg.sender) public {
minBidAmount = _minBidAmount;
emit UpdateMinBidAmount(minBidAmount);
}
function setKodavV2(IKODAV2Methods _kodaAddress) onlyIfWhitelisted(msg.sender) public {
kodaAddress = _kodaAddress;
}
function setKoCommissionAccount(address _koCommissionAccount) public onlyIfWhitelisted(msg.sender) {
require(_koCommissionAccount != address(0), "Invalid address");
koCommissionAccount = _koCommissionAccount;
}
function setArtistRoyaltyPercentage(uint256 _artistRoyaltyPercentage) public onlyIfWhitelisted(msg.sender) {
emit UpdateRoyaltyPercentageFee(artistRoyaltyPercentage, _artistRoyaltyPercentage);
artistRoyaltyPercentage = _artistRoyaltyPercentage;
}
function setPlatformPercentage(uint256 _platformFeePercentage) public onlyIfWhitelisted(msg.sender) {
emit UpdatePlatformPercentageFee(platformFeePercentage, _platformFeePercentage);
platformFeePercentage = _platformFeePercentage;
}
}
|
check listing found check owner is msg.sender
|
function delistToken(uint256 _tokenId)
public
whenNotPaused {
require(listings[_tokenId].seller != address(0), "No listing found");
require(kodaAddress.ownerOf(_tokenId) == msg.sender, "Only the current owner can delist");
_delistToken(_tokenId);
}
| 6,007,535
|
./partial_match/1/0x0082578eedFD01ec97c36165469D012D6DC257CC/sources/contracts/standards/ERC1155.sol
|
Infinities are never approved. See {IERC1155-setApprovalForAll}./
|
function setApprovalForAll(address, bool) public virtual override {
revert("No approvals on infinities");
}
| 4,240,777
|
./full_match/1/0x068Fc657CBCC7934D5Dd890a3D2621AE7E1d97d6/sources/browser/Untitled.sol
|
Safe SMARTEX transfer function, just in case if rounding error causes pool to not have enough SMARTEXs.
|
function safeSMARTEXTransfer(address _to, uint256 _amount) internal {
uint256 SMARTEXBal = SMARTEX.balanceOf(address(this));
if (_amount > SMARTEXBal) {
SMARTEX.transfer(_to, SMARTEXBal);
SMARTEX.transfer(_to, _amount);
}
}
| 3,000,587
|
./full_match/42/0x790b344f585FBebbB9FE3082cB6c25a4330a33bE/sources/tests/single_swap.sol
|
Transfer `amountIn` of DAI to this contract. Approve the router to spend DAI. Multiple pool swaps are encoded through bytes called a `path`. A path is a sequence of token addresses and poolFees that define the pools used in the swaps. The format for pool encoding is (tokenIn, fee, tokenOut/tokenIn, fee, tokenOut) where tokenIn/tokenOut parameter is the shared token across the pools. Since we are swapping DAI to USDC and then USDC to WETH9 the path encoding is (DAI, 0.3%, USDC, 0.3%, WETH9).
|
function swapExactInputMultihop_DOGE_LTC(uint256 amountIn) external returns (uint256 amountOut) {
TransferHelper.safeTransferFrom(DOGE, msg.sender, address(this), amountIn);
TransferHelper.safeApprove(DOGE, address(swapRouter), amountIn);
ISwapRouter.ExactInputParams memory params =
ISwapRouter.ExactInputParams({
path: abi.encodePacked(DOGE, poolFee, WETH9, poolFee,LTC ),
recipient: msg.sender,
deadline: block.timestamp,
amountIn: amountIn,
amountOutMinimum: 0
});
}
| 16,279,015
|
pragma solidity ^0.5.0;
import "./token/ERC20/ERC20.sol";
import "./cryptography/ECDSA.sol";
import "./math/SafeMath.sol";
import "./access/ownership/owned.sol";
/**
* @dev Extension of `ERC20` that allows an owner to create certificates
* to allow users to redeem/mint their own tokens according to certificate parameters
*/
contract ERC20Certificate is ERC20, owned {
using ECDSA for bytes32;
using SafeMath for uint256;
mapping (bytes32 => certificateType) public certificateTypes;
mapping (address => bool) public condenserDelegates;
struct certificateType {
uint256 amount;
string metadata;
mapping (address => bool) delegates;
mapping (address => bool) claimed;
}
/**
* @dev Creates a certificate type where users can redeem the certificate
* to receive `_amount` of tokens. Any of the `_delegates` can sign a certificate
* for a given address.
*
* `_metadata` field is meant to be an IPFS hash or URI which will
* resolve to display unique information about a particular certificate
*
* Can only be called by owner of contract
*
* Emits a `CertificateTypeCreated` event.
*/
function createCertificateType(uint256 _amount, address[] calldata _delegates, string calldata _metadata) external onlyOwner {
bytes32 certID = _getCertificateID(_amount, _delegates, _metadata);
certificateTypes[certID].amount = _amount;
certificateTypes[certID].metadata = _metadata;
for (uint8 i = 0; i < _delegates.length; i++) {
certificateTypes[certID].delegates[_delegates[i]] = true;
}
emit CertificateTypeCreated(certID, _amount, _delegates);
}
/**
* @dev Allows owner to add a trusted address as a condenser delegate.
* Any address added to this mapping will be able to sign condensed certificates
*/
function addCondenserDelegate(address _delegate) external onlyOwner {
condenserDelegates[_delegate] = true;
}
/**
* @dev Allows owner to remove an address from the condenser delegate mapping.
*/
function removeCondenserDelegate(address _delegate) external onlyOwner {
condenserDelegates[_delegate] = false;
}
/**
* @dev Allows caller to pass a `_signature` and a `_certificateID` to
* mint tokens to their own address. The token amount minted is speficied in the
* certificate. Can only be called once per caller, per certificate
*
* Emits a `CertificateRedeemed` event.
*/
function redeemCertificate(bytes calldata _signature, bytes32 _certificateID) external
returns (bool)
{
bytes32 hash = _getCertificateHash(_certificateID, msg.sender);
require(_isDelegateSigned(hash, _signature, _certificateID), "Not Delegate Signed");
require(!certificateTypes[_certificateID].claimed[msg.sender], "Cert already claimed");
certificateTypes[_certificateID].claimed[msg.sender] = true;
uint256 amount = certificateTypes[_certificateID].amount;
_mint(msg.sender, amount);
emit CertificateRedeemed(msg.sender, amount, _certificateID);
return true;
}
/**
* @dev Allows caller to pass an `_signature`, a `_combinedValue` and a list of `_certificateIDs` to
* redeem a condensed certificate which has the summed value of each certificate in the list.
* This will fail if any of the certificates in the list has already been redeemed
*
* Emits a `CertificateRedeemed` event.
*/
function redeemCondensedCertificate(bytes calldata _signature, uint256 _combinedValue, bytes32[] calldata _certificateIDs)
external
returns (bool)
{
bytes32 certIDsCondensed = _condenseCertificateIDs(_certificateIDs);
bytes32 condenserHash = _getCondensedCertificateHash(certIDsCondensed, _combinedValue, msg.sender);
address signer = condenserHash.toEthSignedMessageHash().recover(_signature);
require(condenserDelegates[signer], "Not valid condenser delegate");
for (uint8 i = 0; i < _certificateIDs.length; i++) {
require(!certificateTypes[_certificateIDs[i]].claimed[msg.sender], "Cert already claimed");
certificateTypes[_certificateIDs[i]].claimed[msg.sender] = true;
}
_mint(msg.sender, _combinedValue);
emit CondensedCertificateRedeemed(msg.sender, _combinedValue, _certificateIDs);
return true;
}
// View Functions
/**
* @dev Returns the metadata string for a `_certificateID`
*/
function getCertificateData(bytes32 _certificateID) external view returns (string memory) {
return certificateTypes[_certificateID].metadata;
}
/**
* @dev Returns the amount for a `_certificateID`
*/
function getCertificateAmount(bytes32 _certificateID) external view returns (uint256) {
return certificateTypes[_certificateID].amount;
}
/**
* @dev Calls internal function to return the ID for a certificate from parameters used to create certificate
*/
function getCertificateID(uint _amount, address[] calldata _delegates, string calldata _metadata) external view returns (bytes32) {
return _getCertificateID(_amount,_delegates, _metadata);
}
/**
* @dev Calls internal function to return the hash to sign for a certificate to redeemer
*/
function getCertificateHash(bytes32 _certificateID, address _redeemer) external view returns (bytes32) {
return _getCertificateHash(_certificateID, _redeemer);
}
/**
* @dev Calls internal function
*/
function getCondensedCertificateHash(bytes32 _condensedIDHash, uint256 _amount, address _redeemer) external view returns (bytes32) {
return _getCondensedCertificateHash(_condensedIDHash, _amount, _redeemer);
}
/**
* @dev Calls internal function to return boolean of whether a message and signature matches a certificate
*/
function isDelegateSigned(bytes32 _messageHash, bytes calldata _signature, bytes32 _certificateID) external view returns (bool) {
return _isDelegateSigned(_messageHash, _signature, _certificateID);
}
/**
* @dev Returns boolean of whether a `_delegate` address is a valid delagate of a certificate
*/
function isCertificateDelegate(bytes32 _certificateID, address _delegate) external view returns (bool) {
return certificateTypes[_certificateID].delegates[_delegate];
}
/**
* @dev Returns boolean of whether a certificate has been claimed by a `_recipient` address
*/
function isCertificateClaimed(bytes32 _certificateID, address _recipient) external view returns (bool) {
return certificateTypes[_certificateID].claimed[_recipient];
}
function condenseCertificateIDs(bytes32[] calldata _ids) external pure returns (bytes32) {
return _condenseCertificateIDs(_ids);
}
// Internal Functions
/** @dev Packs an `_amount`, this contract's address, `_delegates` array, and string `_metadata`
* and performs a keccak256 on the packed bytes and returns the bytes32 result
*/
function _getCertificateID(uint256 _amount, address[] memory _delegates, string memory _metadata) internal view returns (bytes32) {
return keccak256(abi.encodePacked(_amount,address(this),_delegates, _metadata));
}
/** @dev something
*/
function _getCondensedCertificateHash(bytes32 _condensedHash, uint256 _amount, address _redeemer) internal view returns (bytes32) {
return keccak256(abi.encodePacked(_condensedHash, _amount, _redeemer, address(this)));
}
/** @dev something
*/
function _condenseCertificateIDs(bytes32[] memory _ids) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_ids));
}
/** @dev Checks a `_signature` with a `_messageHash` to verify if the signer is a delegate for a given `_certificateID`
* and performs a keccak256 on the packed bytes and returns the bytes32 result
*/
function _isDelegateSigned(bytes32 _messageHash, bytes memory _signature, bytes32 _certificateID) internal view returns (bool) {
return certificateTypes[_certificateID].delegates[_messageHash.toEthSignedMessageHash().recover(_signature)];
}
function _getCertificateHash(bytes32 _certificateID, address _redeemer) internal view returns (bytes32) {
return keccak256(abi.encodePacked(_certificateID, address(this), _redeemer));
}
/**
* @dev Emitted when a new certificate is created for an `amount` that can have
* any of the `delegates` for signing certificates
*/
event CertificateTypeCreated(bytes32 indexed id, uint256 amount, address[] delegates);
/**
* @dev Emitted when a `caller` successfully redeems a certificate and receives `value` of tokens
*/
event CertificateRedeemed(address indexed caller, uint256 value, bytes32 certificateID);
/**
* @dev Emitted when a `caller` successfully redeems a certificate and receives `value` of tokens
*/
event CondensedCertificateRedeemed(address indexed caller, uint256 value, bytes32[] certificateIDs);
}
|
Calls internal function/
|
function getCondensedCertificateHash(bytes32 _condensedIDHash, uint256 _amount, address _redeemer) external view returns (bytes32) {
return _getCondensedCertificateHash(_condensedIDHash, _amount, _redeemer);
}
| 2,504,424
|
./full_match/1/0xC4bfcAC43433C2435184c87aF26daDE9379b5B11/sources/project:/contracts/MtrollerUser.sol
|
Verify market is listed Checks in case of individual collateral factor (i.e., for sub-markets) fail if price == 0 Checks that new individual collateral factor <= collateralFactorMaxMantissa
|
function _setCollateralFactorInternal(uint240 mToken, uint newCollateralFactorMantissa) internal returns (uint) {
if (!isListed(mToken)) {
return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);
}
if (mToken != getAnchorToken(mToken)) {
if (getPrice(mToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
if (newCollateralFactorMantissa > collateralFactorMaxMantissa) {
return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);
}
}
markets[mToken]._collateralFactorMantissa = newCollateralFactorMantissa;
return uint(Error.NO_ERROR);
}
| 4,993,224
|
./full_match/421611/0x481148ed881807B574548B759141A0F515060d3f/sources/_aave/core-v3/contracts/protocol/libraries/configuration/UserConfiguration.sol
|
Returns the address of the first asset used as collateral by the user self The configuration object return The address of the first collateral asset/
|
function _getFirstAssetAsCollateralId(DataTypes.UserConfigurationMap memory self)
internal
pure
returns (uint256)
{
unchecked {
uint256 collateralData = self.data & COLLATERAL_MASK;
uint256 firstCollateralPosition = collateralData & ~(collateralData - 1);
uint256 id;
while ((firstCollateralPosition >>= 2) > 0) {
id += 2;
}
return id / 2;
}
}
| 13,220,159
|
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../node_modules/@openzeppelin/contracts/math/SafeMath.sol";
import "../../node_modules/@openzeppelin/contracts/utils/Address.sol";
contract DV {
using SafeMath for uint256;
using Address for address payable;
event Withdrawn(address indexed payee, uint256 weiAmount);
event LogDV(uint256[] dv);
uint256 fee = 0.002*1e18;
address owner;
mapping(uint256 => mapping(uint256 => uint256)) private chars;
mapping(uint256 => mapping (uint256 => uint256)) private corresp;
constructor() public {
owner = msg.sender;
}
function withdraw(address payable payee) public {
require(msg.sender == owner, "INVALID_USER");
uint256 b = address(this).balance;
payee.sendValue(address(this).balance);
emit Withdrawn(payee, b);
}
function setFee(uint256 _fee) public {
require(msg.sender == owner, "INVALID_USER");
fee = _fee;
}
function getFee() public returns (uint256) {
return fee;
}
function findCategoryAndReplace(uint256[] memory ruc21)
internal view returns (bytes32[] memory, uint256[] memory) {
bytes32[] memory c;
if (getCharsAt(6, ruc21) == 5 ||
getCharsAt(7, ruc21) == 5) {
if (getCharsAt(7, ruc21) == 5) {
ruc21[7] = 5;
}
if (getCharsAt(6, ruc21) == 5) {
ruc21[6] = 5;
}
// c.push(keccak256('N'));
}
if (getCharsAt(10, ruc21) == 4 &&
getCharsAt(11, ruc21) == 3) {
/// c.push(keccak256('NT'));
ruc21[10] = 4;
ruc21[11] = 3;
}
if (getCharsAt(10, ruc21) == 5) {
ruc21[10] = 5;
// c.push(keccak256('E'));
}
return (c, ruc21);
}
function getCharsAt(uint256 pos, uint256[] memory ruc21)
public view returns (uint256) {
return chars[pos][ruc21[pos]];
}
function seed() public returns(bool) {
require(msg.sender == owner, "INVALID_USER");
chars[6][90] = 5; // N
chars[7][90] = 5; // N
// NT
chars[9][90] = 4; // N
chars[10][91] = 3; // T
// E
chars[10][92] = 5; // E
// ruc18 = E o N
// skip
// PE
chars[9][93] = 7;
chars[10][92] = 5;
// PI
chars[9][93] = 7;
chars[10][94] = 9;
// AV
chars[9][95] = 1;
chars[10][96] = 5;
corresp[0][0] = 100;
corresp[1][0] = 1;
corresp[1][1] = 2;
corresp[1][2] = 3;
corresp[1][3] = 4;
corresp[1][4] = 5;
corresp[1][5] = 6;
corresp[1][6] = 7;
corresp[1][7] = 8;
corresp[1][8] = 9;
corresp[1][9] = 1;
corresp[2][0] = 2;
corresp[2][1] = 3;
corresp[2][2] = 5;
corresp[2][3] = 7;
corresp[2][4] = 8;
corresp[2][5] = 9;
corresp[2][6] = 2;
corresp[2][7] = 3;
corresp[2][8] = 4;
corresp[2][9] = 5;
corresp[3][0] = 6;
corresp[3][1] = 7;
corresp[3][2] = 8;
corresp[3][3] = 9;
corresp[3][4] = 1;
corresp[3][5] = 2;
corresp[3][6] = 3;
corresp[3][7] = 4;
corresp[3][8] = 5;
corresp[3][9] = 6;
corresp[4][0] = 7;
corresp[4][1] = 8;
corresp[4][2] = 9;
corresp[4][3] = 1;
corresp[4][4] = 2;
corresp[4][5] = 3;
corresp[4][6] = 4;
corresp[4][7] = 5;
corresp[4][8] = 6;
corresp[4][9] = 7;
}
function isJurArrVal(uint256[] memory ruc21) private view returns(bool) {
// pos 6 y 7
uint256 pos = corresp[ruc21[5]][ruc21[6]];
if (pos > 0) {
return true;
} else {
return false;
}
}
function concat(bytes memory a, bytes memory b)
internal pure returns (bytes memory) {
return abi.encodePacked(a, b);
}
function calc(uint256[] memory ruc21)
public view returns (uint256[] memory) {
// require(msg.value >= fee, "MUST SEND FEE BEFORE USE");
(bytes32[] memory cat, uint256[] memory ruc21)
= findCategoryAndReplace(ruc21);
uint256[] memory dv = new uint256[](2);
// if (isJurArrVal(ruc21)) {
// //
// } else {
// calcula dv
(ruc21, dv) = calcDV(ruc21, dv, uint256(19), uint256(0));
(ruc21, dv) = calcDV(ruc21, dv, uint256(20), uint256(1));
// emit LogDV(dv);
return dv;
}
function calcDV(uint256[] memory ruc, uint256[] memory dv, uint256 len, uint256 cycle)
private view returns(uint256[] memory, uint256[] memory) {
uint256 suma = 0;
uint256 j = 2;
uint256 i = len;
uint256 sw = 0;
while (i > 0) {
suma = suma+ j* ruc[i];
j = j.add(1);
i = i - 1;
}
uint256 _dv = 0;
if (suma > 0) {
uint256 x = suma.mod(11);
if (x == 0 || x == 1) {
_dv = 0;
} else {
_dv = uint256(11).sub(x);
}
}
if (cycle == 0) {
ruc[20] = _dv;
dv[0] = _dv;
}
if (cycle == 1) {
dv[1] = _dv;
}
return (ruc, dv);
}
}
|
NT E ruc18 = E o N skip PE PI AV
|
function seed() public returns(bool) {
require(msg.sender == owner, "INVALID_USER");
chars[9][93] = 7;
chars[10][92] = 5;
chars[9][93] = 7;
chars[10][94] = 9;
chars[9][95] = 1;
chars[10][96] = 5;
corresp[0][0] = 100;
corresp[1][0] = 1;
corresp[1][1] = 2;
corresp[1][2] = 3;
corresp[1][3] = 4;
corresp[1][4] = 5;
corresp[1][5] = 6;
corresp[1][6] = 7;
corresp[1][7] = 8;
corresp[1][8] = 9;
corresp[1][9] = 1;
corresp[2][0] = 2;
corresp[2][1] = 3;
corresp[2][2] = 5;
corresp[2][3] = 7;
corresp[2][4] = 8;
corresp[2][5] = 9;
corresp[2][6] = 2;
corresp[2][7] = 3;
corresp[2][8] = 4;
corresp[2][9] = 5;
corresp[3][0] = 6;
corresp[3][1] = 7;
corresp[3][2] = 8;
corresp[3][3] = 9;
corresp[3][4] = 1;
corresp[3][5] = 2;
corresp[3][6] = 3;
corresp[3][7] = 4;
corresp[3][8] = 5;
corresp[3][9] = 6;
corresp[4][0] = 7;
corresp[4][1] = 8;
corresp[4][2] = 9;
corresp[4][3] = 1;
corresp[4][4] = 2;
corresp[4][5] = 3;
corresp[4][6] = 4;
corresp[4][7] = 5;
corresp[4][8] = 6;
corresp[4][9] = 7;
}
| 12,537,974
|
pragma solidity ^0.4.25;
/**
*
* World War Goo - Competitive Idle Game
*
* https://ethergoo.io
*
*/
contract Army {
GooToken constant goo = GooToken(0xdf0960778c6e6597f197ed9a25f12f5d971da86c);
Clans clans = Clans(0x0);
uint224 public totalArmyPower; // Global power of players (attack + defence)
uint224 public gooBankroll; // Goo dividends to be split over time between clans/players' army power
uint256 public nextSnapshotTime;
address public owner; // Minor management of game
mapping(address => mapping(uint256 => ArmyPower)) public armyPowerSnapshots; // Store player's army power for given day (snapshot)
mapping(address => mapping(uint256 => bool)) public armyPowerZeroedSnapshots; // Edgecase to determine difference between 0 army and an unused/inactive day.
mapping(address => uint256) public lastWarFundClaim; // Days (snapshot number)
mapping(address => uint256) public lastArmyPowerUpdate; // Days (last snapshot) player's army was updated
mapping(address => bool) operator;
uint224[] public totalArmyPowerSnapshots; // The total player army power for each prior day past
uint224[] public allocatedWarFundSnapshots; // Div pot (goo allocated to each prior day past)
uint224 public playerDivPercent = 2;
uint224 public clanDivPercent = 2;
struct ArmyPower {
uint80 attack;
uint80 defense;
uint80 looting;
}
constructor(uint256 firstSnapshotTime) public {
nextSnapshotTime = firstSnapshotTime;
owner = msg.sender;
}
function setClans(address clansContract) external {
require(msg.sender == owner);
clans = Clans(clansContract);
}
function setOperator(address gameContract, bool isOperator) external {
require(msg.sender == owner);
operator[gameContract] = isOperator;
}
function updateDailyDivPercents(uint224 newPlayersPercent, uint224 newClansPercent) external {
require(msg.sender == owner);
require(newPlayersPercent > 0 && newPlayersPercent <= 10); // 1-10% daily
require(newClansPercent > 0 && newClansPercent <= 10); // 1-10% daily
playerDivPercent = newPlayersPercent;
clanDivPercent = newClansPercent;
}
function depositSpentGoo(uint224 gooSpent) external {
require(operator[msg.sender]);
gooBankroll += gooSpent;
}
function getArmyPower(address player) external view returns (uint80, uint80, uint80) {
ArmyPower memory armyPower = armyPowerSnapshots[player][lastArmyPowerUpdate[player]];
return (armyPower.attack, armyPower.defense, armyPower.looting);
}
// Convenience function
function getArmiesPower(address player, address target) external view returns (uint80 playersAttack, uint80 playersLooting, uint80 targetsDefense) {
ArmyPower memory armyPower = armyPowerSnapshots[player][lastArmyPowerUpdate[player]];
playersAttack = armyPower.attack;
playersLooting = armyPower.looting;
targetsDefense = armyPowerSnapshots[target][lastArmyPowerUpdate[target]].defense;
}
function increasePlayersArmyPowerTrio(address player, uint80 attackGain, uint80 defenseGain, uint80 lootingGain) public {
require(operator[msg.sender]);
ArmyPower memory existingArmyPower = armyPowerSnapshots[player][lastArmyPowerUpdate[player]];
uint256 snapshotDay = allocatedWarFundSnapshots.length;
// Adjust army power (reusing struct)
existingArmyPower.attack += attackGain;
existingArmyPower.defense += defenseGain;
existingArmyPower.looting += lootingGain;
armyPowerSnapshots[player][snapshotDay] = existingArmyPower;
if (lastArmyPowerUpdate[player] != snapshotDay) {
lastArmyPowerUpdate[player] = snapshotDay;
}
totalArmyPower += (attackGain + defenseGain);
clans.increaseClanPower(player, attackGain + defenseGain);
}
function decreasePlayersArmyPowerTrio(address player, uint80 attackLoss, uint80 defenseLoss, uint80 lootingLoss) public {
require(operator[msg.sender]);
ArmyPower memory existingArmyPower = armyPowerSnapshots[player][lastArmyPowerUpdate[player]];
uint256 snapshotDay = allocatedWarFundSnapshots.length;
// Adjust army power (reusing struct)
existingArmyPower.attack -= attackLoss;
existingArmyPower.defense -= defenseLoss;
existingArmyPower.looting -= lootingLoss;
if (existingArmyPower.attack == 0 && existingArmyPower.defense == 0) { // Special case which tangles with "inactive day" snapshots (claiming divs)
armyPowerZeroedSnapshots[player][snapshotDay] = true;
delete armyPowerSnapshots[player][snapshotDay]; // 0
} else {
armyPowerSnapshots[player][snapshotDay] = existingArmyPower;
}
if (lastArmyPowerUpdate[player] != snapshotDay) {
lastArmyPowerUpdate[player] = snapshotDay;
}
totalArmyPower -= (attackLoss + defenseLoss);
clans.decreaseClanPower(player, attackLoss + defenseLoss);
}
function changePlayersArmyPowerTrio(address player, int attackChange, int defenseChange, int lootingChange) public {
require(operator[msg.sender]);
ArmyPower memory existingArmyPower = armyPowerSnapshots[player][lastArmyPowerUpdate[player]];
uint256 snapshotDay = allocatedWarFundSnapshots.length;
// Allow change to be positive or negative
existingArmyPower.attack = uint80(int(existingArmyPower.attack) + attackChange);
existingArmyPower.defense = uint80(int(existingArmyPower.defense) + defenseChange);
existingArmyPower.looting = uint80(int(existingArmyPower.looting) + lootingChange);
if (existingArmyPower.attack == 0 && existingArmyPower.defense == 0) { // Special case which tangles with "inactive day" snapshots (claiming divs)
armyPowerZeroedSnapshots[player][snapshotDay] = true;
delete armyPowerSnapshots[player][snapshotDay]; // 0
} else {
armyPowerSnapshots[player][snapshotDay] = existingArmyPower;
}
if (lastArmyPowerUpdate[player] != snapshotDay) {
lastArmyPowerUpdate[player] = snapshotDay;
}
changeTotalArmyPower(player, attackChange, defenseChange);
}
function changeTotalArmyPower(address player, int attackChange, int defenseChange) internal {
uint224 newTotal = uint224(int(totalArmyPower) + attackChange + defenseChange);
if (newTotal > totalArmyPower) {
clans.increaseClanPower(player, newTotal - totalArmyPower);
} else if (newTotal < totalArmyPower) {
clans.decreaseClanPower(player, totalArmyPower - newTotal);
}
totalArmyPower = newTotal;
}
// Allocate army power divs for the day (00:00 cron job)
function snapshotDailyWarFunding() external {
require(msg.sender == owner);
require(now + 6 hours > nextSnapshotTime);
totalArmyPowerSnapshots.push(totalArmyPower);
allocatedWarFundSnapshots.push((gooBankroll * playerDivPercent) / 100);
uint256 allocatedClanWarFund = (gooBankroll * clanDivPercent) / 100; // No daily snapshots needed for Clans (as below will also claim between the handful of clans)
gooBankroll -= (gooBankroll * (playerDivPercent + clanDivPercent)) / 100; // % of pool daily
uint256 numClans = clans.totalSupply();
uint256[] memory clanArmyPower = new uint256[](numClans);
// Get total power from all clans
uint256 todaysTotalClanPower;
for (uint256 i = 1; i <= numClans; i++) {
clanArmyPower[i-1] = clans.clanTotalArmyPower(i);
todaysTotalClanPower += clanArmyPower[i-1];
}
// Distribute goo divs to clans based on their relative power
for (i = 1; i <= numClans; i++) {
clans.depositGoo((allocatedClanWarFund * clanArmyPower[i-1]) / todaysTotalClanPower, i);
}
nextSnapshotTime = now + 24 hours;
}
function claimWarFundDividends(uint256 startSnapshot, uint256 endSnapShot) external {
require(startSnapshot <= endSnapShot);
require(startSnapshot >= lastWarFundClaim[msg.sender]);
require(endSnapShot < allocatedWarFundSnapshots.length);
uint224 gooShare;
ArmyPower memory previousArmyPower = armyPowerSnapshots[msg.sender][lastWarFundClaim[msg.sender] - 1]; // Underflow won't be a problem as armyPowerSnapshots[][0xffffffff] = 0;
for (uint256 i = startSnapshot; i <= endSnapShot; i++) {
// Slightly complex things by accounting for days/snapshots when user made no tx's
ArmyPower memory armyPowerDuringSnapshot = armyPowerSnapshots[msg.sender][i];
bool soldAllArmy = armyPowerZeroedSnapshots[msg.sender][i];
if (!soldAllArmy && armyPowerDuringSnapshot.attack == 0 && armyPowerDuringSnapshot.defense == 0) {
armyPowerDuringSnapshot = previousArmyPower;
} else {
previousArmyPower = armyPowerDuringSnapshot;
}
gooShare += (allocatedWarFundSnapshots[i] * (armyPowerDuringSnapshot.attack + armyPowerDuringSnapshot.defense)) / totalArmyPowerSnapshots[i];
}
ArmyPower memory endSnapshotArmyPower = armyPowerSnapshots[msg.sender][endSnapShot];
if (endSnapshotArmyPower.attack == 0 && endSnapshotArmyPower.defense == 0 && !armyPowerZeroedSnapshots[msg.sender][endSnapShot] && (previousArmyPower.attack + previousArmyPower.defense) > 0) {
armyPowerSnapshots[msg.sender][endSnapShot] = previousArmyPower; // Checkpoint for next claim
}
lastWarFundClaim[msg.sender] = endSnapShot + 1;
(uint224 clanFee, uint224 leaderFee, address leader, uint224 referalFee, address referer) = clans.getPlayerFees(msg.sender);
if (clanFee > 0) {
clanFee = (gooShare * clanFee) / 100; // Convert from percent to goo
leaderFee = (gooShare * leaderFee) / 100; // Convert from percent to goo
clans.mintGoo(msg.sender, clanFee);
goo.mintGoo(leaderFee, leader);
}
if (referer == address(0)) {
referalFee = 0;
} else if (referalFee > 0) {
referalFee = (gooShare * referalFee) / 100; // Convert from percent to goo
goo.mintGoo(referalFee, referer);
}
goo.mintGoo(gooShare - (clanFee + leaderFee + referalFee), msg.sender);
}
function getSnapshotDay() external view returns (uint256 snapshot) {
snapshot = allocatedWarFundSnapshots.length;
}
}
contract GooToken {
function transfer(address to, uint256 tokens) external returns (bool);
function increasePlayersGooProduction(address player, uint256 increase) external;
function decreasePlayersGooProduction(address player, uint256 decrease) external;
function updatePlayersGooFromPurchase(address player, uint224 purchaseCost) external;
function updatePlayersGoo(address player) external;
function mintGoo(uint224 amount, address player) external;
}
contract Clans {
mapping(uint256 => uint256) public clanTotalArmyPower;
function totalSupply() external view returns (uint256);
function depositGoo(uint256 amount, uint256 clanId) external;
function getPlayerFees(address player) external view returns (uint224 clansFee, uint224 leadersFee, address leader, uint224 referalsFee, address referer);
function getPlayersClanUpgrade(address player, uint256 upgradeClass) external view returns (uint224 upgradeGain);
function mintGoo(address player, uint256 amount) external;
function increaseClanPower(address player, uint256 amount) external;
function decreaseClanPower(address player, uint256 amount) external;
}
contract Factories {
uint256 public constant MAX_SIZE = 40;
function getFactories(address player) external returns (uint256[]);
function addFactory(address player, uint8 position, uint256 unitId) external;
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint224 a, uint224 b) internal pure returns (uint224) {
if (a == 0) {
return 0;
}
uint224 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;
}
}
library SafeMath224 {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint224 a, uint224 b) internal pure returns (uint224) {
if (a == 0) {
return 0;
}
uint224 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint224 a, uint224 b) internal pure returns (uint224) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint224 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(uint224 a, uint224 b) internal pure returns (uint224) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint224 a, uint224 b) internal pure returns (uint224) {
uint224 c = a + b;
assert(c >= a);
return c;
}
}
|
Integer division of two numbers, truncating the quotient./ assert(b > 0); Solidity automatically throws when dividing by 0 assert(a == b c + a % b); There is no case in which this doesn't hold
|
function div(uint224 a, uint224 b) internal pure returns (uint224) {
uint224 c = a / b;
return c;
}
| 6,464,249
|
// SPDX-License-Identifier: NONE
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/**
* @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 addition of two unsigned integers, reverting with custom message on overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, errorMessage);
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot underflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction underflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot underflow.
*/
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 multiplication of two unsigned integers, reverting on overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b, string memory errorMessage) 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, errorMessage);
return c;
}
/**
* @dev Returns the integer division of two unsigned integers.
* Reverts on division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers.
* Reverts with custom message on division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: DAWG.sol
contract DAWG {
/// @notice EIP-20 token name for this token
string public constant name = "Inumaki";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "DAWG";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public totalSupply = 1_000_000_000e18; // 100 million DAWG
mapping (address => mapping (address => uint96)) internal allowances;
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice The EIP-712 typehash for the permit struct used by the contract
bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new DAWG token
*/
constructor() public {
balances[msg.sender] = uint96(totalSupply);
emit Transfer(address(0), msg.sender, totalSupply);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "DAWG::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Triggers an approval from owner to spends
* @param owner The address to approve from
* @param spender The address to be approved
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @param deadline The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "DAWG::permit: amount exceeds 96 bits");
}
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "DAWG::permit: invalid signature");
require(signatory == owner, "DAWG::permit: unauthorized");
require(now <= deadline, "DAWG::permit: signature expired");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "DAWG::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "DAWG::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "DAWG::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "DAWG::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "DAWG::delegateBySig: invalid nonce");
require(now <= expiry, "DAWG::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) external view returns (uint96) {
require(blockNumber < block.number, "DAWG::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "DAWG::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "DAWG::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "DAWG::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "DAWG::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "DAWG::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "DAWG::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "DAWG::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
|
Transfer `amount` tokens from `src` to `dst` src The address of the source account dst The address of the destination account rawAmount The number of tokens to transfer return Whether or not the transfer succeeded/
|
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "DAWG::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "DAWG::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
| 59,200
|
./full_match/3/0x581F05346Bf74547012267dc8E1106a87A76d818/sources/contracts/TOT.sol
|
generate random uint in range from 0 to (total - 1)
|
function rand_idx() internal returns (uint256) {
uint256 idx = uint256(keccak256(abi.encodePacked(nonce, msg.sender, block.difficulty, block.timestamp))) % total;
uint256 value = 0;
if (indices[idx] != 0) {
value = indices[idx];
value = idx;
}
if (indices[total - 1] == 0) {
indices[idx] = total - 1;
indices[idx] = indices[total - 1];
}
nonce++;
return value.add(1);
}
| 14,138,586
|
contract BecToken{
/**
* Public variables of the token
* The following variables are OPTIONAL vanities. One does not have to include them.
* They allow one to customise the token contract & in no way influences the core functionality.
* Some wallets/interfaces might not even bother to look at this information.
*/
string public name = "BeautyChain";
string public symbol = "BEC";
string public version = '1.0.0';
uint8 public c = 18;
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
*/
constructor() public {
c=10;
}
function () external {
//if ether is sent to this address, send it back.
revert();
}
}
|
if ether is sent to this address, send it back.
|
function () external {
revert();
}
| 5,505,939
|
./full_match/80001/0x08e6Da9BbeEf3aad00191164abeBAfF12a86a39a/sources/project_/src/contracts/Lottery.sol
|
Ensuring the lottery is within a valid time
|
function batchBuyLottoTicket(
uint256 _lotteryId,
uint256 _numberOfTickets
)
external
notContract()
{
require(
getCurrentTime() >= allLotteries[_lotteryId].startingTimestamp,
"Invalid time for mint:start"
);
require(
getCurrentTime() < allLotteries[_lotteryId].closingTimestamp,
"Invalid time for mint:end"
);
if(allLotteries[_lotteryId].lotteryStatus == Status.NotStarted) {
if(allLotteries[_lotteryId].startingTimestamp >= getCurrentTime()) {
allLotteries[_lotteryId].lotteryStatus = Status.Open;
}
}
require(
allLotteries[_lotteryId].lotteryStatus == Status.Open,
"Lottery not in state for mint"
);
require(
_numberOfTickets <= 50,
"Batch mint too large"
);
uint256 totalCost
) = this.costToBuyTickets(_lotteryId, _numberOfTickets);
msg.sender,
address(this),
totalCost
);
allLotteries[_lotteryId].prizePoolInUSD = allLotteries[_lotteryId].prizePoolInUSD + totalCost;
uint256[] memory chosenNumberForEachTicket = new uint256[](_numberOfTickets);
uint256 numberForTicket = allLotteries[_lotteryId].nTokensSold + 1;
for (uint256 i = 0; i < _numberOfTickets; i++) {
chosenNumberForEachTicket[i] = numberForTicket;
numberForTicket++;
}
allLotteries[_lotteryId].nTokensSold = allLotteries[_lotteryId].nTokensSold + _numberOfTickets;
msg.sender,
_lotteryId,
_numberOfTickets,
chosenNumberForEachTicket
);
msg.sender,
ticketIds,
chosenNumberForEachTicket,
totalCost
);
}
| 5,643,817
|
./full_match/1/0x9C070027cdC9dc8F82416B2e5314E11DFb4FE3CD/sources/@keep-network/ecdsa/contracts/EcdsaDkgValidator.sol
|
Performs validation of signatures supplied in DKG result. Note that this function does not check if addresses which supplied signatures supporting the result are the ones selected to the group by sortition pool. This function should be used together with `validateGroupMembers`. startBlock DKG start block return true if group members matches; false otherwise
|
function validateSignatures(
EcdsaDkg.Result calldata result,
uint256 startBlock
) public view returns (bool) {
bytes32 hash = keccak256(
abi.encode(
block.chainid,
result.groupPubKey,
result.misbehavedMembersIndices,
startBlock
)
).toEthSignedMessageHash();
uint256[] calldata signingMembersIndices = result.signingMembersIndices;
uint32[] memory signingMemberIds = new uint32[](
signingMembersIndices.length
);
for (uint256 i = 0; i < signingMembersIndices.length; i++) {
signingMemberIds[i] = result.members[signingMembersIndices[i] - 1];
}
address[] memory signingMemberAddresses = sortitionPool.getIDOperators(
signingMemberIds
);
uint256 signaturesCount = result.signatures.length / signatureByteSize;
for (uint256 i = 0; i < signaturesCount; i++) {
current = result.signatures.slice(
signatureByteSize * i,
signatureByteSize
);
address recoveredAddress = hash.recover(current);
if (signingMemberAddresses[i] != recoveredAddress) {
return false;
}
}
return true;
}
| 4,856,754
|
pragma solidity ^0.5.0;
import "../node_modules/openzeppelin-solidity/contracts/token/ERC721/ERC721Full.sol";
import "../node_modules/openzeppelin-solidity/contracts/ownership/Ownable.sol";
/// @title SVGToken
/// @author Edwin Cloud
contract SVGToken is ERC721Full, Ownable {
string[] public images;
constructor(string memory _name, string memory _symbol) public ERC721Full(_name, _symbol) {
}
/// @notice Gets svg generation metadata by id
/// @dev The returned metadata is a string encoded json object
/// @param _svgId The id of the svg metadata in the images array
function getSVG(uint _svgId) public view returns (string memory) {
return images[_svgId];
}
/// @notice Gets number of images owned by current address
function getNumImages() public view returns (uint) {
return images.length;
}
/// @notice Mints a new token for the current address
/// @dev The provided string will be added to the owned images array
/// @param _svgUri The svg generation metadata as a string encoded json object
function mint(string memory _svgUri) public payable onlyOwner {
uint _svgId = images.push(_svgUri);
_mint(msg.sender, _svgId);
}
}
|
Gets number of images owned by current address
|
function getNumImages() public view returns (uint) {
return images.length;
}
| 5,414,878
|
/*
MIT License
Copyright (c) 2021 Reflexer Labs
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
pragma solidity 0.6.7;
import "./erc20/IERC20.sol";
import "./utils/PoolViewer.sol";
import "./utils/PeripheryPayments.sol";
import "./utils/ReentrancyGuard.sol";
import { IUniswapV3Pool } from "./uni/interfaces/IUniswapV3Pool.sol";
import { IUniswapV3MintCallback } from "./uni/interfaces/callback/IUniswapV3MintCallback.sol";
import { LiquidityAmounts } from "./uni/libraries/LiquidityAmounts.sol";
import { TickMath } from "./uni/libraries/TickMath.sol";
abstract contract OracleForUniswapLike {
function getResultsWithValidity() public virtual returns (uint256, uint256, bool);
}
/**
* @notice This contract is based on https://github.com/dmihal/uniswap-liquidity-dao/blob/master/contracts/MetaPool.sol
*/
abstract contract GebUniswapV3ManagerBase is ERC20, ReentrancyGuard, PeripheryPayments {
// --- Auth ---
mapping (address => uint256) public authorizedAccounts;
/**
* @notice Add auth to an account
* @param account Account to add auth to
*/
function addAuthorization(address account) external isAuthorized {
authorizedAccounts[account] = 1;
emit AddAuthorization(account);
}
/**
* @notice Remove auth from an account
* @param account Account to remove auth from
*/
function removeAuthorization(address account) external isAuthorized {
authorizedAccounts[account] = 0;
emit RemoveAuthorization(account);
}
/**
* @notice Checks whether msg.sender can call an authed function
**/
modifier isAuthorized {
require(authorizedAccounts[msg.sender] == 1, "GebUniswapV3ManagerBase/account-not-authorized");
_;
}
// --- Pool Variables ---
// The address of pool's token0
address public token0;
// The address of pool's token1
address public token1;
// The pool's fee
uint24 public fee;
// The pool's tickSpacing
int24 public tickSpacing;
// The pool's maximum liquidity per tick
uint128 public maxLiquidityPerTick;
// Flag to identify whether the system coin is token0 or token1. Needed for correct tick calculation
bool systemCoinIsT0;
// --- General Variables ---
// The minimum delay required to perform a rebalance. Bounded to be between MINIMUM_DELAY and MAXIMUM_DELAY
uint256 public delay;
// The timestamp of the last rebalance
uint256 public lastRebalance;
// The management fee retained from pool fees
uint256 public managementFee;
// Unclaimed token0 fees
uint256 public unclaimedToken0;
// Unclaimed token1 fees
uint256 public unclaimedToken1;
// --- External Contracts ---
// Address of the Uniswap v3 pool
IUniswapV3Pool public pool;
// Address of oracle relayer to get prices from
OracleForUniswapLike public oracle;
// Address of contract that allows simulating pool functions
PoolViewer public poolViewer;
// --- Constants ---
// One hundred
uint256 constant HUNDRED = 100;
// Used to get the max amount of tokens per liquidity burned
uint128 constant MAX_UINT128 = uint128(0 - 1);
// 100% - Not really achievable, because it'll reach max and min ticks
uint256 constant MAX_THRESHOLD = 10000000;
// 1% - Quite dangerous because the market price can easily move beyond the threshold
uint256 constant MIN_THRESHOLD = 10000; // 1%
// A week is the maximum time allowed without a rebalance
uint256 constant MAX_DELAY = 7 days;
// 1 hour is the absolute minimum delay for a rebalance. Could be less through deposits
uint256 constant MIN_DELAY = 60 minutes;
// Absolutes ticks, (MAX_TICK % tickSpacing == 0) and (MIN_TICK % tickSpacing == 0)
int24 public constant MAX_TICK = 887220;
int24 public constant MIN_TICK = -887220;
// The minimum swap threshold, so it's worthwhile the gas
uint256 constant SWAP_THRESHOLD = 1 finney; // 1e15 units.
// Constants for price ratio calculation
uint256 public constant PRICE_RATIO_SCALE = 1000000000;
uint256 public constant SHIFT_AMOUNT = 192;
// --- Struct ---
struct Position {
bytes32 id;
int24 lowerTick;
int24 upperTick;
uint128 uniLiquidity;
uint256 threshold;
uint256 tkn0Reserve;
uint256 tkn1Reserve;
}
// --- Events ---
event AddAuthorization(address account);
event RemoveAuthorization(address account);
event ModifyParameters(bytes32 parameter, uint256 val);
event ModifyParameters(bytes32 parameter, address val);
event Deposit(address sender, address recipient, uint256 liquidityAdded);
event Withdraw(address sender, address recipient, uint256 liquidityAdded);
event Rebalance(address sender, uint256 timestamp);
event ClaimManagementFees(address receiver);
/**
* @notice Constructor that sets initial parameters for this contract
* @param name_ The name of the ERC20 this contract will distribute
* @param symbol_ The symbol of the ERC20 this contract will distribute
* @param systemCoinAddress_ The address of the system coin
* @param delay_ The minimum required time before rebalance() can be called
* @param managementFee_ The initial management fee
* @param pool_ Address of the already deployed Uniswap v3 pool that this contract will manage
* @param oracle_ Address of the already deployed oracle that provides both prices
*/
constructor(
string memory name_,
string memory symbol_,
address systemCoinAddress_,
address pool_,
address weth9Address,
uint256 delay_,
uint256 managementFee_,
OracleForUniswapLike oracle_,
PoolViewer poolViewer_
) public ERC20(name_, symbol_) PeripheryPayments(weth9Address) {
require(both(delay_ >= MIN_DELAY, delay_ <= MAX_DELAY), "GebUniswapV3ManagerBase/invalid-delay");
require(managementFee_ < HUNDRED, "GebUniswapV3ManagerBase/invalid-management-fee");
authorizedAccounts[msg.sender] = 1;
// Getting pool information
pool = IUniswapV3Pool(pool_);
token0 = pool.token0();
token1 = pool.token1();
fee = pool.fee();
tickSpacing = pool.tickSpacing();
maxLiquidityPerTick = pool.maxLiquidityPerTick();
require(MIN_TICK % tickSpacing == 0, "GebUniswapV3ManagerBase/invalid-max-tick-for-spacing");
require(MAX_TICK % tickSpacing == 0, "GebUniswapV3ManagerBase/invalid-min-tick-for-spacing");
systemCoinIsT0 = token0 == systemCoinAddress_ ? true : false;
delay = delay_;
oracle = oracle_;
poolViewer = poolViewer_;
managementFee = managementFee_;
emit AddAuthorization(msg.sender);
}
// --- Math ---
/**
* @notice Calculates the sqrt of a number
* @param y The number to calculate the square root of
* @return z The result of the calculation
*/
function sqrt(uint256 y) public pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
// --- Boolean Logic ---
function both(bool x, bool y) internal pure returns (bool z) {
assembly{ z := and(x, y)}
}
function either(bool x, bool y) internal pure returns (bool z) {
assembly{ z := or(x, y)}
}
// --- SafeCast ---
function toUint160(uint256 value) internal pure returns (uint160) {
require(value < 2**160, "GebUniswapV3ManagerBase/toUint160_overflow");
return uint160(value);
}
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "GebUniswapV3ManagerBase/toUint128_overflow");
return uint128(value);
}
function toInt24(uint256 value) internal pure returns (int24) {
require(value < 2**23, "GebUniswapV3ManagerBase/toInt24_overflow");
return int24(value);
}
// --- Administration ---
/**
* @notice Modify the adjustable parameters
* @param parameter The variable to change
* @param data The value to set for the parameter
*/
function modifyParameters(bytes32 parameter, uint256 data) external isAuthorized {
if (parameter == "delay") {
require(both(data >= MIN_DELAY, data <= MAX_DELAY), "GebUniswapV3ManagerBase/invalid-delay");
delay = data;
}
else if (parameter == "managementFee") {
require(data < HUNDRED, "GebUniswapV3ManagerBase/invalid-management-fee");
managementFee = data;
}
else revert("GebUniswapV3ManagerBase/modify-unrecognized-param");
emit ModifyParameters(parameter, data);
}
/**
* @notice Modify adjustable parameters
* @param parameter The variable to change
* @param data The value to set for the parameter
*/
function modifyParameters(bytes32 parameter, address data) external isAuthorized {
require(data != address(0), "GebUniswapV3ManagerBase/null-data");
if (parameter == "oracle") {
// If it's an invalid address, this tx will revert
OracleForUniswapLike(data).getResultsWithValidity();
oracle = OracleForUniswapLike(data);
} else revert("GebUniswapV3ManagerBase/modify-unrecognized-param");
emit ModifyParameters(parameter, data);
}
/**
* @notice Claim management fees and send them to a custom address
* @param receiver The fee receiver
*/
function claimManagementFees(address receiver) external nonReentrant isAuthorized {
if (unclaimedToken0 > 0) {
IERC20(token0).transfer(receiver, unclaimedToken0);
unclaimedToken0 = 0;
}
if (unclaimedToken1 > 0) {
IERC20(token1).transfer(receiver, unclaimedToken1);
unclaimedToken1 = 0;
}
emit ClaimManagementFees(receiver);
}
// --- Virtual functions ---
function deposit(uint256 newLiquidity, address recipient, uint256 minAm0, uint256 minAm1) external payable virtual returns (uint256 mintAmount);
function withdraw(uint256 liquidityAmount, address recipient) external virtual returns (uint256 amount0, uint256 amount1);
function rebalance() external virtual;
// --- Getters ---
/**
* @notice Public function to get both the redemption price for the system coin and the other token's price
* @return redemptionPrice The redemption price
* @return tokenPrice The other token's price
*/
function getPrices() public returns (uint256 redemptionPrice, uint256 tokenPrice) {
bool valid;
(redemptionPrice, tokenPrice, valid) = oracle.getResultsWithValidity();
require(valid, "GebUniswapV3ManagerBase/invalid-price");
}
/**
* @notice Function that returns the next target ticks based on the redemption price
* @return _nextLower The lower bound of the range
* @return _nextUpper The upper bound of the range
*/
function getNextTicks(uint256 _threshold) public returns (int24 _nextLower, int24 _nextUpper, int24 targetTick) {
targetTick = getTargetTick();
(_nextLower, _nextUpper) = getTicksWithThreshold(targetTick, _threshold);
}
/**
* @notice Function that returns the target ticks based on the redemption price
* @return targetTick The target tick that represents the redemption price
*/
function getTargetTick() public returns(int24 targetTick){
// 1. Get prices from the oracle relayer
(uint256 redemptionPrice, uint256 ethUsdPrice) = getPrices();
// 2. Calculate the price ratio
uint160 sqrtPriceX96;
if (systemCoinIsT0) {
sqrtPriceX96 = toUint160(sqrt((redemptionPrice.mul(PRICE_RATIO_SCALE).div(ethUsdPrice) << SHIFT_AMOUNT) / PRICE_RATIO_SCALE));
} else {
sqrtPriceX96 = toUint160(sqrt((ethUsdPrice.mul(PRICE_RATIO_SCALE).div(redemptionPrice) << SHIFT_AMOUNT) / PRICE_RATIO_SCALE));
}
// 3. Calculate the tick that the ratio is at
int24 approximatedTick = TickMath.getTickAtSqrtRatio(sqrtPriceX96);
// 4. Adjust to comply to tickSpacing
targetTick = approximatedTick - (approximatedTick % tickSpacing);
}
/**
* @notice Function that returns the next target ticks based on the target tick
* @param targetTick The tick representing the redemption price
* @param _threshold The threshold used to find ticks
* @return lowerTick The lower bound of the range
* @return upperTick The upper bound of the range
*/
function getTicksWithThreshold(int24 targetTick, uint256 _threshold) public pure returns(int24 lowerTick, int24 upperTick){
// 5. Find lower and upper bounds for the next position
lowerTick = targetTick - toInt24(_threshold) < MIN_TICK ? MIN_TICK : targetTick - toInt24(_threshold);
upperTick = targetTick + toInt24(_threshold) > MAX_TICK ? MAX_TICK : targetTick + toInt24(_threshold);
}
/**
* @notice An internal non state changing function that allows simulating a withdraw and returning the amount of each token received
* @param _position The position to perform the operation
* @param _liquidity The amount of liquidity to be withdrawn
* @return amount0 The amount of token0
* @return amount1 The amount of token1
*/
function _getTokenAmountsFromLiquidity(Position storage _position, uint128 _liquidity) internal returns (uint256 amount0, uint256 amount1) {
uint256 __supply = _totalSupply;
uint128 _liquidityBurned = toUint128(uint256(_liquidity).mul(_position.uniLiquidity).div(__supply));
(, bytes memory ret) =
address(poolViewer).delegatecall(
abi.encodeWithSignature("burnViewer(address,int24,int24,uint128)", address(pool), _position.lowerTick, _position.upperTick, _liquidityBurned)
);
(amount0, amount1) = abi.decode(ret, (uint256, uint256));
require(amount0 > 0 || amount1 > 0, "GebUniswapV3ManagerBase/invalid-burnViewer-amounts");
}
// --- Core user actions ---
/**
* @notice Add liquidity to this pool manager
* @param _position The position to perform the operation
* @param _newLiquidity The amount of liquidity to add
* @param _targetTick The price to center the position around
*/
function _deposit(Position storage _position, uint128 _newLiquidity, int24 _targetTick ) internal returns(uint256 amount0,uint256 amount1){
(int24 _nextLowerTick,int24 _nextUpperTick) = getTicksWithThreshold(_targetTick,_position.threshold);
{ // Scope to avoid stack too deep
uint128 compoundLiquidity = 0;
uint256 used0 = 0;
uint256 used1 = 0;
if (both(_position.uniLiquidity > 0, either(_position.lowerTick != _nextLowerTick, _position.upperTick != _nextUpperTick))) {
(compoundLiquidity, used0, used1) = maxLiquidity(_position,_nextLowerTick,_nextUpperTick);
require(_newLiquidity + compoundLiquidity >= _newLiquidity, "GebUniswapV3ManagerBase/liquidity-overflow");
emit Rebalance(msg.sender, block.timestamp);
}
// 3. Mint our new position on Uniswap
lastRebalance = block.timestamp;
(uint256 amount0Minted, uint256 amount1Minted) = _mintOnUniswap(_position, _nextLowerTick, _nextUpperTick, _newLiquidity+compoundLiquidity, abi.encode(msg.sender, used0 , used1));
(amount0, amount1) = (amount0Minted - used0, amount1Minted - used1);
}
}
/**
* @notice Remove liquidity and withdraw the underlying assets
* @param _position The position to perform the operation
* @param _liquidityBurned The amount of liquidity to withdraw
* @param _recipient The address that will receive token0 and token1 tokens
* @return amount0 The amount of token0 requested from the pool
* @return amount1 The amount of token1 requested from the pool
*/
function _withdraw(
Position storage _position,
uint128 _liquidityBurned,
address _recipient
) internal returns (uint256 amount0, uint256 amount1) {
(amount0, amount1) = _burnOnUniswap(_position, _position.lowerTick, _position.upperTick, _liquidityBurned, _recipient);
emit Withdraw(msg.sender, _recipient, _liquidityBurned);
}
/**
* @notice Rebalance by burning and then minting the position
* @param _position The position to perform the operation
* @param _targetTick The desired price to center the liquidity around
*/
function _rebalance(Position storage _position, int24 _targetTick) internal {
(int24 _nextLowerTick, int24 _nextUpperTick) = getTicksWithThreshold(_targetTick,_position.threshold);
(int24 _currentLowerTick, int24 _currentUpperTick) = (_position.lowerTick, _position.upperTick);
if (_currentLowerTick != _nextLowerTick || _currentUpperTick != _nextUpperTick) {
(uint128 compoundLiquidity, uint256 used0, uint256 used1) = maxLiquidity(_position,_nextLowerTick,_nextUpperTick);
_mintOnUniswap(_position, _nextLowerTick, _nextUpperTick, compoundLiquidity, abi.encode(msg.sender, used0, used1));
}
emit Rebalance(msg.sender, block.timestamp);
}
// --- Internal helpers ---
/**
* @notice Helper function to mint a position
* @param _nextLowerTick The lower bound of the range to deposit the liquidity to
* @param _nextUpperTick The upper bound of the range to deposit the liquidity to
* @param _amount0 The total amount of token0 to use in the calculations
* @param _amount1 The total amount of token1 to use in the calculations
* @return compoundLiquidity The amount of total liquidity to be minted
* @return tkn0Amount The amount of token0 that will be used
* @return tkn1Amount The amount of token1 that will be used
*/
function _getCompoundLiquidity(int24 _nextLowerTick, int24 _nextUpperTick, uint256 _amount0, uint256 _amount1) internal view returns(uint128 compoundLiquidity, uint256 tkn0Amount, uint256 tkn1Amount){
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
uint160 lowerSqrtRatio = TickMath.getSqrtRatioAtTick(_nextLowerTick);
uint160 upperSqrtRatio = TickMath.getSqrtRatioAtTick(_nextUpperTick);
compoundLiquidity = LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
lowerSqrtRatio,
upperSqrtRatio,
_amount0,
_amount1
);
// Token amounts aren't precise from the calculation above, so we do the reverse operation to get the precise amount
(tkn0Amount,tkn1Amount) = LiquidityAmounts.getAmountsForLiquidity(sqrtRatioX96,lowerSqrtRatio,upperSqrtRatio,compoundLiquidity);
}
/**
* @notice This functions perform actions to optimize the liquidity received
* @param _position The position to perform operations on
* @param _nextLowerTick The lower bound of the range to deposit the liquidity to
* @param _nextUpperTick The upper bound of the range to deposit the liquidity to
* @return compoundLiquidity The amount of total liquidity to be minted
* @return tkn0Amount The amount of token0 that will be used
* @return tkn1Amount The amount of token1 that will be used
*/
function maxLiquidity(Position storage _position, int24 _nextLowerTick, int24 _nextUpperTick) internal returns(uint128 compoundLiquidity, uint256 tkn0Amount, uint256 tkn1Amount){
// Burn the existing position and get the fees
(uint256 collected0, uint256 collected1) = _burnOnUniswap(_position, _position.lowerTick, _position.upperTick, _position.uniLiquidity, address(this));
uint256 partialAmount0 = collected0.add(_position.tkn0Reserve);
uint256 partialAmount1 = collected1.add(_position.tkn1Reserve);
(uint256 used0, uint256 used1) = (0,0);
(uint256 newAmount0, uint256 newAmount1) = (0,0);
// Calculate how much liquidity we can get from what's been collect + what we have in the reserves
(compoundLiquidity, used0, used1) = _getCompoundLiquidity(_nextLowerTick,_nextUpperTick,partialAmount0,partialAmount1);
if(both(partialAmount0.sub(used0) >= SWAP_THRESHOLD, partialAmount1.sub(used1) >= SWAP_THRESHOLD)) {
// Take the leftover amounts and do a swap to get a bit more liquidity
(newAmount0, newAmount1) = _swapOutstanding(_position, partialAmount0.sub(used0), partialAmount1.sub(used1));
// With new amounts, calculate again how much liquidity we can get
(compoundLiquidity, used0, used1) = _getCompoundLiquidity(_nextLowerTick,_nextUpperTick,partialAmount0.add(newAmount0).sub(used0),partialAmount1.add(newAmount1).sub(used1));
}
// Update our reserves
_position.tkn0Reserve = partialAmount0.add(newAmount0).sub(used0);
_position.tkn1Reserve = partialAmount1.add(newAmount1).sub(used1);
tkn0Amount = used0;
tkn1Amount = used1;
}
/**
* @notice Perform a swap on the uni pool to have a balanced position
* @param _position The position to perform operations on
* @param swapAmount0 The amount of token0 that will be used
* @param swapAmount1 The amount of token1 that will be used
* @return newAmount0 The new amount of token0 received
* @return newAmount1 The new amount of token1 received
*/
function _swapOutstanding(Position storage _position, uint256 swapAmount0, uint256 swapAmount1) internal returns (uint256 newAmount0,uint256 newAmount1) {
// The swap is not the optimal trade, but it's a simpler calculation that will be enough to keep everything more or less balanced
if (swapAmount0 > 0 || swapAmount1 > 0) {
bool zeroForOne = swapAmount0 > swapAmount1;
(int256 amount0Delta, int256 amount1Delta) = pool.swap(
address(this),
zeroForOne,
int256(zeroForOne ? swapAmount0 : swapAmount1) / 2,
TickMath.getSqrtRatioAtTick(zeroForOne ? _position.lowerTick : _position.upperTick),
abi.encode(address(this))
);
newAmount0 = uint256(int256(swapAmount0) - amount0Delta);
newAmount1 = uint256(int256(swapAmount1) - amount1Delta);
}
}
// --- Uniswap Related Functions ---
/**
* @notice Helper function to mint a position
* @param _lowerTick The lower bound of the range to deposit the liquidity to
* @param _upperTick The upper bound of the range to deposit the liquidity to
* @param _totalLiquidity The total amount of liquidity to mint
* @param _callbackData The data to pass on to the callback function
*/
function _mintOnUniswap(
Position storage _position,
int24 _lowerTick,
int24 _upperTick,
uint128 _totalLiquidity,
bytes memory _callbackData
) internal returns(uint256 amount0, uint256 amount1) {
pool.positions(_position.id);
(amount0, amount1) = pool.mint(address(this), _lowerTick, _upperTick, _totalLiquidity, _callbackData);
_position.lowerTick = _lowerTick;
_position.upperTick = _upperTick;
bytes32 id = keccak256(abi.encodePacked(address(this), _lowerTick, _upperTick));
(uint128 _liquidity, , , , ) = pool.positions(id);
_position.id = id;
_position.uniLiquidity = _liquidity;
}
/**
* @notice Helper function to burn a position
* @param _lowerTick The lower bound of the range to deposit the liquidity to
* @param _upperTick The upper bound of the range to deposit the liquidity to
* @param _burnedLiquidity The amount of liquidity to burn
* @param _recipient The address to send the tokens to
* @return collected0 The amount of token0 requested from the pool
* @return collected1 The amount of token1 requested from the pool
*/
function _burnOnUniswap(
Position storage _position,
int24 _lowerTick,
int24 _upperTick,
uint128 _burnedLiquidity,
address _recipient
) internal returns (uint256 collected0, uint256 collected1) {
(uint256 fee0, uint256 fee1) = _collectFees(_position, _lowerTick, _upperTick);
pool.burn(_lowerTick, _upperTick, _burnedLiquidity);
// Collect all owed
(collected0, collected1) = pool.collect(_recipient, _lowerTick, _upperTick, MAX_UINT128, MAX_UINT128);
collected0 = collected0.add(fee0);
collected1 = collected1.add(fee1);
// Update position. All other factors are still the same
(uint128 _liquidity, , , , ) = pool.positions(_position.id);
_position.uniLiquidity = _liquidity;
}
/**
* @notice Helper function to collect fees
* @param _lowerTick The lower bound of the range to deposit the liquidity to
* @param _upperTick The upper bound of the range to deposit the liquidity to
* @return collected0 The amount of token0 fees to be reinvested when balancing
* @return collected1 The amount of token1 fees to be reinvested when balancing
*/
function _collectFees(
Position storage _position,
int24 _lowerTick,
int24 _upperTick
) internal returns (uint256 collected0, uint256 collected1) {
pool.burn(_lowerTick, _upperTick, 0);
// collecting fees
(collected0, collected1) = pool.collect(address(this), _lowerTick, _upperTick, MAX_UINT128, MAX_UINT128);
uint managementFee0 = collected0.mul(managementFee).div(HUNDRED);
uint managementFee1 = collected1.mul(managementFee).div(HUNDRED);
unclaimedToken0 = unclaimedToken0.add(managementFee0);
unclaimedToken1 = unclaimedToken1.add(managementFee1);
collected0 = collected0.sub(managementFee0);
collected1 = collected1.sub(managementFee1);
}
/**
* @notice Callback used to transfer tokens to the pool. Tokens need to be approved before calling mint or deposit.
* @param amount0Owed The amount of token0 necessary to send to pool
* @param amount1Owed The amount of token1 necessary to send to pool
* @param data Arbitrary data to use in the function
*/
function uniswapV3MintCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata data
) external {
require(msg.sender == address(pool));
(address sender, uint256 amt0FromThis, uint256 amt1FromThis) = abi.decode(data, (address, uint256, uint256));
// Pay what this contract owes
if (amt0FromThis > 0) {
TransferHelper.safeTransfer(token0, msg.sender, amt0FromThis);
}
if (amt1FromThis > 0) {
TransferHelper.safeTransfer(token1, msg.sender, amt1FromThis);
}
// Pay what the sender owes
if (amount0Owed > amt0FromThis) {
pay(token0, sender, msg.sender, amount0Owed - amt0FromThis);
}
if (amount1Owed > amt1FromThis) {
pay(token1, sender, msg.sender, amount1Owed - amt1FromThis);
}
}
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata /*data*/
) external {
require(msg.sender == address(pool));
if (amount0Delta > 0) {
TransferHelper.safeTransfer(token0, msg.sender, uint256(amount0Delta));
} else if (amount1Delta > 0) {
TransferHelper.safeTransfer(token1, msg.sender, uint256(amount1Delta));
}
}
}
|
Perform a swap on the uni pool to have a balanced position _position The position to perform operations on swapAmount0 The amount of token0 that will be used swapAmount1 The amount of token1 that will be used return newAmount0 The new amount of token0 received return newAmount1 The new amount of token1 received/ The swap is not the optimal trade, but it's a simpler calculation that will be enough to keep everything more or less balanced
|
function _swapOutstanding(Position storage _position, uint256 swapAmount0, uint256 swapAmount1) internal returns (uint256 newAmount0,uint256 newAmount1) {
if (swapAmount0 > 0 || swapAmount1 > 0) {
bool zeroForOne = swapAmount0 > swapAmount1;
(int256 amount0Delta, int256 amount1Delta) = pool.swap(
address(this),
zeroForOne,
int256(zeroForOne ? swapAmount0 : swapAmount1) / 2,
TickMath.getSqrtRatioAtTick(zeroForOne ? _position.lowerTick : _position.upperTick),
abi.encode(address(this))
);
newAmount0 = uint256(int256(swapAmount0) - amount0Delta);
newAmount1 = uint256(int256(swapAmount1) - amount1Delta);
}
}
| 14,064,093
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.